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
125/// GetConversionRank - Retrieve the implicit conversion rank
126/// corresponding to the given implicit conversion kind.
128 static const ImplicitConversionRank Rank[] = {
155 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
156 // it was omitted by the patch that added
157 // ICK_Zero_Event_Conversion
158 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
159 // it was omitted by the patch that added
160 // ICK_Zero_Queue_Conversion
169 };
170 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
171 return Rank[(int)Kind];
172}
173
192
193/// GetImplicitConversionName - Return the name of this kind of
194/// implicit conversion.
196 static const char *const Name[] = {
197 "No conversion",
198 "Lvalue-to-rvalue",
199 "Array-to-pointer",
200 "Function-to-pointer",
201 "Function pointer conversion",
202 "Qualification",
203 "Integral promotion",
204 "Floating point promotion",
205 "Complex promotion",
206 "Integral conversion",
207 "Floating conversion",
208 "Complex conversion",
209 "Floating-integral conversion",
210 "Pointer conversion",
211 "Pointer-to-member conversion",
212 "Boolean conversion",
213 "Compatible-types conversion",
214 "Derived-to-base conversion",
215 "Vector conversion",
216 "SVE Vector conversion",
217 "RVV Vector conversion",
218 "Vector splat",
219 "Complex-real conversion",
220 "Block Pointer conversion",
221 "Transparent Union Conversion",
222 "Writeback conversion",
223 "OpenCL Zero Event Conversion",
224 "OpenCL Zero Queue Conversion",
225 "C specific type conversion",
226 "Incompatible pointer conversion",
227 "Fixed point conversion",
228 "HLSL vector truncation",
229 "HLSL matrix truncation",
230 "Non-decaying array conversion",
231 "HLSL vector splat",
232 "HLSL matrix splat",
233 };
234 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
235 return Name[Kind];
236}
237
238/// StandardConversionSequence - Set the standard conversion
239/// sequence to the identity conversion.
257
258/// getRank - Retrieve the rank of this standard conversion sequence
259/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
260/// implicit conversions.
273
274/// isPointerConversionToBool - Determines whether this conversion is
275/// a conversion of a pointer or pointer-to-member to bool. This is
276/// used as part of the ranking of standard conversion sequences
277/// (C++ 13.3.3.2p4).
279 // Note that FromType has not necessarily been transformed by the
280 // array-to-pointer or function-to-pointer implicit conversions, so
281 // check for their presence as well as checking whether FromType is
282 // a pointer.
283 if (getToType(1)->isBooleanType() &&
284 (getFromType()->isPointerType() ||
285 getFromType()->isMemberPointerType() ||
286 getFromType()->isObjCObjectPointerType() ||
287 getFromType()->isBlockPointerType() ||
289 return true;
290
291 return false;
292}
293
294/// isPointerConversionToVoidPointer - Determines whether this
295/// conversion is a conversion of a pointer to a void pointer. This is
296/// used as part of the ranking of standard conversion sequences (C++
297/// 13.3.3.2p4).
298bool
301 QualType FromType = getFromType();
302 QualType ToType = getToType(1);
303
304 // Note that FromType has not necessarily been transformed by the
305 // array-to-pointer implicit conversion, so check for its presence
306 // and redo the conversion to get a pointer.
308 FromType = Context.getArrayDecayedType(FromType);
309
310 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
311 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
312 return ToPtrType->getPointeeType()->isVoidType();
313
314 return false;
315}
316
317/// Skip any implicit casts which could be either part of a narrowing conversion
318/// or after one in an implicit conversion.
320 const Expr *Converted) {
321 // We can have cleanups wrapping the converted expression; these need to be
322 // preserved so that destructors run if necessary.
323 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
324 Expr *Inner =
325 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
326 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
327 EWC->getObjects());
328 }
329
330 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
331 switch (ICE->getCastKind()) {
332 case CK_NoOp:
333 case CK_IntegralCast:
334 case CK_IntegralToBoolean:
335 case CK_IntegralToFloating:
336 case CK_BooleanToSignedIntegral:
337 case CK_FloatingToIntegral:
338 case CK_FloatingToBoolean:
339 case CK_FloatingCast:
340 Converted = ICE->getSubExpr();
341 continue;
342
343 default:
344 return Converted;
345 }
346 }
347
348 return Converted;
349}
350
351/// Check if this standard conversion sequence represents a narrowing
352/// conversion, according to C++11 [dcl.init.list]p7.
353///
354/// \param Ctx The AST context.
355/// \param Converted The result of applying this standard conversion sequence.
356/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
357/// value of the expression prior to the narrowing conversion.
358/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
359/// type of the expression prior to the narrowing conversion.
360/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
361/// from floating point types to integral types should be ignored.
363 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
364 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
365 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
366 "narrowing check outside C++");
367
368 // C++11 [dcl.init.list]p7:
369 // A narrowing conversion is an implicit conversion ...
370 QualType FromType = getToType(0);
371 QualType ToType = getToType(1);
372
373 // A conversion to an enumeration type is narrowing if the conversion to
374 // the underlying type is narrowing. This only arises for expressions of
375 // the form 'Enum{init}'.
376 if (const auto *ED = ToType->getAsEnumDecl())
377 ToType = ED->getIntegerType();
378
379 switch (Second) {
380 // 'bool' is an integral type; dispatch to the right place to handle it.
382 if (FromType->isRealFloatingType())
383 goto FloatingIntegralConversion;
385 goto IntegralConversion;
386 // -- from a pointer type or pointer-to-member type to bool, or
387 return NK_Type_Narrowing;
388
389 // -- from a floating-point type to an integer type, or
390 //
391 // -- from an integer type or unscoped enumeration type to a floating-point
392 // type, except where the source is a constant expression and the actual
393 // value after conversion will fit into the target type and will produce
394 // the original value when converted back to the original type, or
396 FloatingIntegralConversion:
397 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
398 return NK_Type_Narrowing;
399 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
400 ToType->isRealFloatingType()) {
401 if (IgnoreFloatToIntegralConversion)
402 return NK_Not_Narrowing;
403 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
404 assert(Initializer && "Unknown conversion expression");
405
406 // If it's value-dependent, we can't tell whether it's narrowing.
407 if (Initializer->isValueDependent())
409
410 if (std::optional<llvm::APSInt> IntConstantValue =
411 Initializer->getIntegerConstantExpr(Ctx)) {
412 // Convert the integer to the floating type.
413 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
414 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
415 llvm::APFloat::rmNearestTiesToEven);
416 // And back.
417 llvm::APSInt ConvertedValue = *IntConstantValue;
418 bool ignored;
419 llvm::APFloat::opStatus Status = Result.convertToInteger(
420 ConvertedValue, llvm::APFloat::rmTowardZero, &ignored);
421 // If the converted-back integer has unspecified value, or if the
422 // resulting value is different, this was a narrowing conversion.
423 if (Status == llvm::APFloat::opInvalidOp ||
424 *IntConstantValue != ConvertedValue) {
425 ConstantValue = APValue(*IntConstantValue);
426 ConstantType = Initializer->getType();
428 }
429 } else {
430 // Variables are always narrowings.
432 }
433 }
434 return NK_Not_Narrowing;
435
436 // -- from long double to double or float, or from double to float, except
437 // where the source is a constant expression and the actual value after
438 // conversion is within the range of values that can be represented (even
439 // if it cannot be represented exactly), or
441 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
442 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
443 // FromType is larger than ToType.
444 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
445
446 // If it's value-dependent, we can't tell whether it's narrowing.
447 if (Initializer->isValueDependent())
449
451 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
452 ((Ctx.getLangOpts().CPlusPlus &&
453 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)))) {
454 // Constant!
455 if (Ctx.getLangOpts().C23)
456 ConstantValue = R.Val;
457 assert(ConstantValue.isFloat());
458 llvm::APFloat FloatVal = ConstantValue.getFloat();
459 // Convert the source value into the target type.
460 bool ignored;
461 llvm::APFloat Converted = FloatVal;
462 llvm::APFloat::opStatus ConvertStatus =
463 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
464 llvm::APFloat::rmNearestTiesToEven, &ignored);
465 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
466 llvm::APFloat::rmNearestTiesToEven, &ignored);
467 if (Ctx.getLangOpts().C23) {
468 if (FloatVal.isNaN() && Converted.isNaN() &&
469 !FloatVal.isSignaling() && !Converted.isSignaling()) {
470 // Quiet NaNs are considered the same value, regardless of
471 // payloads.
472 return NK_Not_Narrowing;
473 }
474 // For normal values, check exact equality.
475 if (!Converted.bitwiseIsEqual(FloatVal)) {
476 ConstantType = Initializer->getType();
478 }
479 } else {
480 // If there was no overflow, the source value is within the range of
481 // values that can be represented.
482 if (ConvertStatus & llvm::APFloat::opOverflow) {
483 ConstantType = Initializer->getType();
485 }
486 }
487 } else {
489 }
490 }
491 return NK_Not_Narrowing;
492
493 // -- from an integer type or unscoped enumeration type to an integer type
494 // that cannot represent all the values of the original type, except where
495 // (CWG2627) -- the source is a bit-field whose width w is less than that
496 // of its type (or, for an enumeration type, its underlying type) and the
497 // target type can represent all the values of a hypothetical extended
498 // integer type with width w and with the same signedness as the original
499 // type or
500 // -- the source is a constant expression and the actual value after
501 // conversion will fit into the target type and will produce the original
502 // value when converted back to the original type.
504 IntegralConversion: {
505 assert(FromType->isIntegralOrUnscopedEnumerationType());
506 assert(ToType->isIntegralOrUnscopedEnumerationType());
507 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
508 unsigned FromWidth = Ctx.getIntWidth(FromType);
509 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
510 const unsigned ToWidth = Ctx.getIntWidth(ToType);
511
512 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
513 bool ToSigned, unsigned ToWidth) {
514 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
515 !(FromSigned && !ToSigned);
516 };
517
518 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
519 return NK_Not_Narrowing;
520
521 // Not all values of FromType can be represented in ToType.
522 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
523
524 bool DependentBitField = false;
525 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
526 if (BitField->getBitWidth()->isValueDependent())
527 DependentBitField = true;
528 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
529 BitFieldWidth < FromWidth) {
530 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
531 return NK_Not_Narrowing;
532
533 // The initializer will be truncated to the bit-field width
534 FromWidth = BitFieldWidth;
535 }
536 }
537
538 // If it's value-dependent, we can't tell whether it's narrowing.
539 if (Initializer->isValueDependent())
541
542 std::optional<llvm::APSInt> OptInitializerValue =
543 Initializer->getIntegerConstantExpr(Ctx);
544 if (!OptInitializerValue) {
545 // If the bit-field width was dependent, it might end up being small
546 // enough to fit in the target type (unless the target type is unsigned
547 // and the source type is signed, in which case it will never fit)
548 if (DependentBitField && !(FromSigned && !ToSigned))
550
551 // Otherwise, such a conversion is always narrowing
553 }
554 llvm::APSInt &InitializerValue = *OptInitializerValue;
555 bool Narrowing = false;
556 if (FromWidth < ToWidth) {
557 // Negative -> unsigned is narrowing. Otherwise, more bits is never
558 // narrowing.
559 if (InitializerValue.isSigned() && InitializerValue.isNegative())
560 Narrowing = true;
561 } else {
562 // Add a bit to the InitializerValue so we don't have to worry about
563 // signed vs. unsigned comparisons.
564 InitializerValue =
565 InitializerValue.extend(InitializerValue.getBitWidth() + 1);
566 // Convert the initializer to and from the target width and signed-ness.
567 llvm::APSInt ConvertedValue = InitializerValue;
568 ConvertedValue = ConvertedValue.trunc(ToWidth);
569 ConvertedValue.setIsSigned(ToSigned);
570 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
571 ConvertedValue.setIsSigned(InitializerValue.isSigned());
572 // If the result is different, this was a narrowing conversion.
573 if (ConvertedValue != InitializerValue)
574 Narrowing = true;
575 }
576 if (Narrowing) {
577 ConstantType = Initializer->getType();
578 ConstantValue = APValue(InitializerValue);
580 }
581
582 return NK_Not_Narrowing;
583 }
584 case ICK_Complex_Real:
585 if (FromType->isComplexType() && !ToType->isComplexType())
586 return NK_Type_Narrowing;
587 return NK_Not_Narrowing;
588
590 if (Ctx.getLangOpts().C23) {
591 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
593 if (Initializer->EvaluateAsRValue(R, Ctx)) {
594 ConstantValue = R.Val;
595 assert(ConstantValue.isFloat());
596 llvm::APFloat FloatVal = ConstantValue.getFloat();
597 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
598 // value, the unqualified versions of the type of the initializer and
599 // the corresponding real type of the object declared shall be
600 // compatible.
601 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
602 ConstantType = Initializer->getType();
604 }
605 }
606 }
607 return NK_Not_Narrowing;
608 default:
609 // Other kinds of conversions are not narrowings.
610 return NK_Not_Narrowing;
611 }
612}
613
614/// dump - Print this standard conversion sequence to standard
615/// error. Useful for debugging overloading issues.
616LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
617 raw_ostream &OS = llvm::errs();
618 bool PrintedSomething = false;
619 if (First != ICK_Identity) {
621 PrintedSomething = true;
622 }
623
624 if (Second != ICK_Identity) {
625 if (PrintedSomething) {
626 OS << " -> ";
627 }
629
630 if (CopyConstructor) {
631 OS << " (by copy constructor)";
632 } else if (DirectBinding) {
633 OS << " (direct reference binding)";
634 } else if (ReferenceBinding) {
635 OS << " (reference binding)";
636 }
637 PrintedSomething = true;
638 }
639
640 if (Third != ICK_Identity) {
641 if (PrintedSomething) {
642 OS << " -> ";
643 }
645 PrintedSomething = true;
646 }
647
648 if (!PrintedSomething) {
649 OS << "No conversions required";
650 }
651}
652
653/// dump - Print this user-defined conversion sequence to standard
654/// error. Useful for debugging overloading issues.
656 raw_ostream &OS = llvm::errs();
657 if (Before.First || Before.Second || Before.Third) {
658 Before.dump();
659 OS << " -> ";
660 }
662 OS << '\'' << *ConversionFunction << '\'';
663 else
664 OS << "aggregate initialization";
665 if (After.First || After.Second || After.Third) {
666 OS << " -> ";
667 After.dump();
668 }
669}
670
671/// dump - Print this implicit conversion sequence to standard
672/// error. Useful for debugging overloading issues.
674 raw_ostream &OS = llvm::errs();
676 OS << "Worst list element conversion: ";
677 switch (ConversionKind) {
679 OS << "Standard conversion: ";
680 Standard.dump();
681 break;
683 OS << "User-defined conversion: ";
684 UserDefined.dump();
685 break;
687 OS << "Ellipsis conversion";
688 break;
690 OS << "Ambiguous conversion";
691 break;
692 case BadConversion:
693 OS << "Bad conversion";
694 break;
695 }
696
697 OS << "\n";
698}
699
703
705 conversions().~ConversionSet();
706}
707
708void
714
715namespace {
716 // Structure used by DeductionFailureInfo to store
717 // template argument information.
718 struct DFIArguments {
719 TemplateArgument FirstArg;
720 TemplateArgument SecondArg;
721 };
722 // Structure used by DeductionFailureInfo to store
723 // template parameter and template argument information.
724 struct DFIParamWithArguments : DFIArguments {
725 TemplateParameter Param;
726 };
727 // Structure used by DeductionFailureInfo to store template argument
728 // information and the index of the problematic call argument.
729 struct DFIDeducedMismatchArgs : DFIArguments {
730 TemplateArgumentList *TemplateArgs;
731 unsigned CallArgIndex;
732 };
733 // Structure used by DeductionFailureInfo to store information about
734 // unsatisfied constraints.
735 struct CNSInfo {
736 TemplateArgumentList *TemplateArgs;
737 ConstraintSatisfaction Satisfaction;
738 };
739}
740
741/// Convert from Sema's representation of template deduction information
742/// to the form used in overload-candidate information.
746 TemplateDeductionInfo &Info) {
748 Result.Result = static_cast<unsigned>(TDK);
749 Result.HasDiagnostic = false;
750 switch (TDK) {
757 Result.Data = nullptr;
758 break;
759
762 Result.Data = Info.Param.getOpaqueValue();
763 break;
764
767 // FIXME: Should allocate from normal heap so that we can free this later.
768 auto *Saved = new (Context) DFIDeducedMismatchArgs;
769 Saved->FirstArg = Info.FirstArg;
770 Saved->SecondArg = Info.SecondArg;
771 Saved->TemplateArgs = Info.takeSugared();
772 Saved->CallArgIndex = Info.CallArgIndex;
773 Result.Data = Saved;
774 break;
775 }
776
778 // FIXME: Should allocate from normal heap so that we can free this later.
779 DFIArguments *Saved = new (Context) DFIArguments;
780 Saved->FirstArg = Info.FirstArg;
781 Saved->SecondArg = Info.SecondArg;
782 Result.Data = Saved;
783 break;
784 }
785
787 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
790 // FIXME: Should allocate from normal heap so that we can free this later.
791 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
792 Saved->Param = Info.Param;
793 Saved->FirstArg = Info.FirstArg;
794 Saved->SecondArg = Info.SecondArg;
795 Result.Data = Saved;
796 break;
797 }
798
800 Result.Data = Info.takeSugared();
801 if (Info.hasSFINAEDiagnostic()) {
805 Result.HasDiagnostic = true;
806 }
807 break;
808
810 CNSInfo *Saved = new (Context) CNSInfo;
811 Saved->TemplateArgs = Info.takeSugared();
812 Saved->Satisfaction = std::move(Info.AssociatedConstraintsSatisfaction);
813 Result.Data = Saved;
814 break;
815 }
816
820 llvm_unreachable("not a deduction failure");
821 }
822
823 return Result;
824}
825
827 switch (static_cast<TemplateDeductionResult>(Result)) {
837 break;
838
845 // FIXME: Destroy the data?
846 Data = nullptr;
847 break;
848
850 // FIXME: Destroy the template argument list?
851 Data = nullptr;
853 Diag->~PartialDiagnosticAt();
854 HasDiagnostic = false;
855 }
856 break;
857
859 // FIXME: Destroy the template argument list?
860 static_cast<CNSInfo *>(Data)->Satisfaction.~ConstraintSatisfaction();
861 Data = nullptr;
863 Diag->~PartialDiagnosticAt();
864 HasDiagnostic = false;
865 }
866 break;
867
868 // Unhandled
871 break;
872 }
873}
874
876 if (HasDiagnostic)
877 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
878 return nullptr;
879}
880
914
950
982
1014
1016 switch (static_cast<TemplateDeductionResult>(Result)) {
1019 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1020
1021 default:
1022 return std::nullopt;
1023 }
1024}
1025
1027 const FunctionDecl *Y) {
1028 if (!X || !Y)
1029 return false;
1030 if (X->getNumParams() != Y->getNumParams())
1031 return false;
1032 // FIXME: when do rewritten comparison operators
1033 // with explicit object parameters correspond?
1034 // https://cplusplus.github.io/CWG/issues/2797.html
1035 for (unsigned I = 0; I < X->getNumParams(); ++I)
1036 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1037 Y->getParamDecl(I)->getType()))
1038 return false;
1039 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1040 auto *FTY = Y->getDescribedFunctionTemplate();
1041 if (!FTY)
1042 return false;
1043 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1044 FTY->getTemplateParameters()))
1045 return false;
1046 }
1047 return true;
1048}
1049
1051 Expr *FirstOperand, FunctionDecl *EqFD) {
1052 assert(EqFD->getOverloadedOperator() ==
1053 OverloadedOperatorKind::OO_EqualEqual);
1054 // C++2a [over.match.oper]p4:
1055 // A non-template function or function template F named operator== is a
1056 // rewrite target with first operand o unless a search for the name operator!=
1057 // in the scope S from the instantiation context of the operator expression
1058 // finds a function or function template that would correspond
1059 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1060 // scope of the class type of o if F is a class member, and the namespace
1061 // scope of which F is a member otherwise. A function template specialization
1062 // named operator== is a rewrite target if its function template is a rewrite
1063 // target.
1065 OverloadedOperatorKind::OO_ExclaimEqual);
1066 if (isa<CXXMethodDecl>(EqFD)) {
1067 // If F is a class member, search scope is class type of first operand.
1068 QualType RHS = FirstOperand->getType();
1069 auto *RHSRec = RHS->getAsCXXRecordDecl();
1070 if (!RHSRec)
1071 return true;
1072 LookupResult Members(S, NotEqOp, OpLoc,
1074 S.LookupQualifiedName(Members, RHSRec);
1075 Members.suppressAccessDiagnostics();
1076 for (NamedDecl *Op : Members)
1077 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1078 return false;
1079 return true;
1080 }
1081 // Otherwise the search scope is the namespace scope of which F is a member.
1082 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1083 auto *NotEqFD = Op->getAsFunction();
1084 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1085 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1086 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1088 cast<Decl>(Op->getLexicalDeclContext())))
1089 return false;
1090 }
1091 return true;
1092}
1093
1095 OverloadedOperatorKind Op) const {
1097 return false;
1098 return Op == OO_EqualEqual || Op == OO_Spaceship;
1099}
1100
1102 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) const {
1103 auto Op = FD->getOverloadedOperator();
1104 if (!allowsReversed(Op))
1105 return false;
1106 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1107 assert(OriginalArgs.size() == 2);
1109 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1110 return false;
1111 }
1112 // Don't bother adding a reversed candidate that can never be a better
1113 // match than the non-reversed version.
1114 return FD->getNumNonObjectParams() != 2 ||
1116 FD->getParamDecl(1)->getType()) ||
1117 FD->hasAttr<EnableIfAttr>();
1118}
1119
1120void OverloadCandidateSet::destroyCandidates() {
1121 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1122 for (auto &C : i->Conversions)
1123 C.~ImplicitConversionSequence();
1124 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1125 i->DeductionFailure.Destroy();
1126 }
1127}
1128
1130 destroyCandidates();
1131 SlabAllocator.Reset();
1132 NumInlineBytesUsed = 0;
1133 Candidates.clear();
1134 Functions.clear();
1135 Kind = CSK;
1136 FirstDeferredCandidate = nullptr;
1137 DeferredCandidatesCount = 0;
1138 HasDeferredTemplateConstructors = false;
1139 ResolutionByPerfectCandidateIsDisabled = false;
1140}
1141
1142namespace {
1143 class UnbridgedCastsSet {
1144 struct Entry {
1145 Expr **Addr;
1146 Expr *Saved;
1147 };
1148 SmallVector<Entry, 2> Entries;
1149
1150 public:
1151 void save(Sema &S, Expr *&E) {
1152 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1153 Entry entry = { &E, E };
1154 Entries.push_back(entry);
1155 E = S.ObjC().stripARCUnbridgedCast(E);
1156 }
1157
1158 void restore() {
1159 for (SmallVectorImpl<Entry>::iterator
1160 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1161 *i->Addr = i->Saved;
1162 }
1163 };
1164}
1165
1166/// checkPlaceholderForOverload - Do any interesting placeholder-like
1167/// preprocessing on the given expression.
1168///
1169/// \param unbridgedCasts a collection to which to add unbridged casts;
1170/// without this, they will be immediately diagnosed as errors
1171///
1172/// Return true on unrecoverable error.
1173static bool
1175 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1176 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1177 // We can't handle overloaded expressions here because overload
1178 // resolution might reasonably tweak them.
1179 if (placeholder->getKind() == BuiltinType::Overload) return false;
1180
1181 // If the context potentially accepts unbridged ARC casts, strip
1182 // the unbridged cast and add it to the collection for later restoration.
1183 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1184 unbridgedCasts) {
1185 unbridgedCasts->save(S, E);
1186 return false;
1187 }
1188
1189 // Go ahead and check everything else.
1190 ExprResult result = S.CheckPlaceholderExpr(E);
1191 if (result.isInvalid())
1192 return true;
1193
1194 E = result.get();
1195 return false;
1196 }
1197
1198 // Nothing to do.
1199 return false;
1200}
1201
1202/// checkArgPlaceholdersForOverload - Check a set of call operands for
1203/// placeholders.
1205 UnbridgedCastsSet &unbridged) {
1206 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1207 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1208 return true;
1209
1210 return false;
1211}
1212
1214 const LookupResult &Old, NamedDecl *&Match,
1215 bool NewIsUsingDecl) {
1216 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1217 I != E; ++I) {
1218 NamedDecl *OldD = *I;
1219
1220 bool OldIsUsingDecl = false;
1221 if (isa<UsingShadowDecl>(OldD)) {
1222 OldIsUsingDecl = true;
1223
1224 // We can always introduce two using declarations into the same
1225 // context, even if they have identical signatures.
1226 if (NewIsUsingDecl) continue;
1227
1228 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1229 }
1230
1231 // A using-declaration does not conflict with another declaration
1232 // if one of them is hidden.
1233 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1234 continue;
1235
1236 // If either declaration was introduced by a using declaration,
1237 // we'll need to use slightly different rules for matching.
1238 // Essentially, these rules are the normal rules, except that
1239 // function templates hide function templates with different
1240 // return types or template parameter lists.
1241 bool UseMemberUsingDeclRules =
1242 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1243 !New->getFriendObjectKind();
1244
1245 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1246 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1247 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1249 continue;
1250 }
1251
1252 if (!isa<FunctionTemplateDecl>(OldD) &&
1253 !shouldLinkPossiblyHiddenDecl(*I, New))
1254 continue;
1255
1256 Match = *I;
1257 return OverloadKind::Match;
1258 }
1259
1260 // Builtins that have custom typechecking or have a reference should
1261 // not be overloadable or redeclarable.
1262 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1263 Match = *I;
1265 }
1266 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1267 // We can overload with these, which can show up when doing
1268 // redeclaration checks for UsingDecls.
1269 assert(Old.getLookupKind() == LookupUsingDeclName);
1270 } else if (isa<TagDecl>(OldD)) {
1271 // We can always overload with tags by hiding them.
1272 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1273 // Optimistically assume that an unresolved using decl will
1274 // overload; if it doesn't, we'll have to diagnose during
1275 // template instantiation.
1276 //
1277 // Exception: if the scope is dependent and this is not a class
1278 // member, the using declaration can only introduce an enumerator.
1279 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1280 Match = *I;
1282 }
1283 } else {
1284 // (C++ 13p1):
1285 // Only function declarations can be overloaded; object and type
1286 // declarations cannot be overloaded.
1287 Match = *I;
1289 }
1290 }
1291
1292 // C++ [temp.friend]p1:
1293 // For a friend function declaration that is not a template declaration:
1294 // -- if the name of the friend is a qualified or unqualified template-id,
1295 // [...], otherwise
1296 // -- if the name of the friend is a qualified-id and a matching
1297 // non-template function is found in the specified class or namespace,
1298 // the friend declaration refers to that function, otherwise,
1299 // -- if the name of the friend is a qualified-id and a matching function
1300 // template is found in the specified class or namespace, the friend
1301 // declaration refers to the deduced specialization of that function
1302 // template, otherwise
1303 // -- the name shall be an unqualified-id [...]
1304 // If we get here for a qualified friend declaration, we've just reached the
1305 // third bullet. If the type of the friend is dependent, skip this lookup
1306 // until instantiation.
1307 if (New->getFriendObjectKind() && New->getQualifier() &&
1308 !New->getDescribedFunctionTemplate() &&
1309 !New->getDependentSpecializationInfo() &&
1310 !New->getType()->isDependentType()) {
1311 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1312 TemplateSpecResult.addAllDecls(Old);
1313 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1314 /*QualifiedFriend*/true)) {
1315 New->setInvalidDecl();
1317 }
1318
1319 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1320 return OverloadKind::Match;
1321 }
1322
1324}
1325
1326template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1327 assert(D && "function decl should not be null");
1328 if (auto *A = D->getAttr<AttrT>())
1329 return !A->isImplicit();
1330 return false;
1331}
1332
1334 FunctionDecl *Old,
1335 bool UseMemberUsingDeclRules,
1336 bool ConsiderCudaAttrs,
1337 bool UseOverrideRules = false) {
1338 // C++ [basic.start.main]p2: This function shall not be overloaded.
1339 if (New->isMain())
1340 return false;
1341
1342 // MSVCRT user defined entry points cannot be overloaded.
1343 if (New->isMSVCRTEntryPoint())
1344 return false;
1345
1346 NamedDecl *OldDecl = Old;
1347 NamedDecl *NewDecl = New;
1349 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1350
1351 // C++ [temp.fct]p2:
1352 // A function template can be overloaded with other function templates
1353 // and with normal (non-template) functions.
1354 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1355 return true;
1356
1357 // Is the function New an overload of the function Old?
1358 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1359 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1360
1361 // Compare the signatures (C++ 1.3.10) of the two functions to
1362 // determine whether they are overloads. If we find any mismatch
1363 // in the signature, they are overloads.
1364
1365 // If either of these functions is a K&R-style function (no
1366 // prototype), then we consider them to have matching signatures.
1367 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1369 return false;
1370
1371 const auto *OldType = cast<FunctionProtoType>(OldQType);
1372 const auto *NewType = cast<FunctionProtoType>(NewQType);
1373
1374 // The signature of a function includes the types of its
1375 // parameters (C++ 1.3.10), which includes the presence or absence
1376 // of the ellipsis; see C++ DR 357).
1377 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1378 return true;
1379
1380 // For member-like friends, the enclosing class is part of the signature.
1381 if ((New->isMemberLikeConstrainedFriend() ||
1383 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1384 return true;
1385
1386 // Compare the parameter lists.
1387 // This can only be done once we have establish that friend functions
1388 // inhabit the same context, otherwise we might tried to instantiate
1389 // references to non-instantiated entities during constraint substitution.
1390 // GH78101.
1391 if (NewTemplate) {
1392 OldDecl = OldTemplate;
1393 NewDecl = NewTemplate;
1394 // C++ [temp.over.link]p4:
1395 // The signature of a function template consists of its function
1396 // signature, its return type and its template parameter list. The names
1397 // of the template parameters are significant only for establishing the
1398 // relationship between the template parameters and the rest of the
1399 // signature.
1400 //
1401 // We check the return type and template parameter lists for function
1402 // templates first; the remaining checks follow.
1403 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1404 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1405 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1406 bool SameReturnType = SemaRef.Context.hasSameType(
1407 Old->getDeclaredReturnType(), New->getDeclaredReturnType());
1408 // FIXME(GH58571): Match template parameter list even for non-constrained
1409 // template heads. This currently ensures that the code prior to C++20 is
1410 // not newly broken.
1411 bool ConstraintsInTemplateHead =
1414 // C++ [namespace.udecl]p11:
1415 // The set of declarations named by a using-declarator that inhabits a
1416 // class C does not include member functions and member function
1417 // templates of a base class that "correspond" to (and thus would
1418 // conflict with) a declaration of a function or function template in
1419 // C.
1420 // Comparing return types is not required for the "correspond" check to
1421 // decide whether a member introduced by a shadow declaration is hidden.
1422 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1423 !SameTemplateParameterList)
1424 return true;
1425 if (!UseMemberUsingDeclRules &&
1426 (!SameTemplateParameterList || !SameReturnType))
1427 return true;
1428 }
1429
1430 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1431 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1432
1433 int OldParamsOffset = 0;
1434 int NewParamsOffset = 0;
1435
1436 // When determining if a method is an overload from a base class, act as if
1437 // the implicit object parameter are of the same type.
1438
1439 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1441 auto ThisType = M->getFunctionObjectParameterReferenceType();
1442 if (ThisType.isConstQualified())
1443 Q.removeConst();
1444 return Q;
1445 }
1446
1447 // We do not allow overloading based off of '__restrict'.
1448 Q.removeRestrict();
1449
1450 // We may not have applied the implicit const for a constexpr member
1451 // function yet (because we haven't yet resolved whether this is a static
1452 // or non-static member function). Add it now, on the assumption that this
1453 // is a redeclaration of OldMethod.
1454 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1455 (M->isConstexpr() || M->isConsteval()) &&
1456 !isa<CXXConstructorDecl>(NewMethod))
1457 Q.addConst();
1458 return Q;
1459 };
1460
1461 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1462 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1463 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1464
1465 if (OldMethod->isExplicitObjectMemberFunction()) {
1466 BS.Quals.removeVolatile();
1467 DS.Quals.removeVolatile();
1468 }
1469
1470 return BS.Quals == DS.Quals;
1471 };
1472
1473 auto CompareType = [&](QualType Base, QualType D) {
1474 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1475 auto DS = D.getNonReferenceType().getCanonicalType().split();
1476
1477 if (!AreQualifiersEqual(BS, DS))
1478 return false;
1479
1480 if (OldMethod->isImplicitObjectMemberFunction() &&
1481 OldMethod->getParent() != NewMethod->getParent()) {
1482 CanQualType ParentType =
1483 SemaRef.Context.getCanonicalTagType(OldMethod->getParent());
1484 if (ParentType.getTypePtr() != BS.Ty)
1485 return false;
1486 BS.Ty = DS.Ty;
1487 }
1488
1489 // FIXME: should we ignore some type attributes here?
1490 if (BS.Ty != DS.Ty)
1491 return false;
1492
1493 if (Base->isLValueReferenceType())
1494 return D->isLValueReferenceType();
1495 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1496 };
1497
1498 // If the function is a class member, its signature includes the
1499 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1500 auto DiagnoseInconsistentRefQualifiers = [&]() {
1501 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1502 return false;
1503 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1504 return false;
1505 if (OldMethod->isExplicitObjectMemberFunction() ||
1506 NewMethod->isExplicitObjectMemberFunction())
1507 return false;
1508 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1509 NewMethod->getRefQualifier() == RQ_None)) {
1510 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1511 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1512 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1513 return true;
1514 }
1515 return false;
1516 };
1517
1518 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1519 OldParamsOffset++;
1520 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1521 NewParamsOffset++;
1522
1523 if (OldType->getNumParams() - OldParamsOffset !=
1524 NewType->getNumParams() - NewParamsOffset ||
1526 {OldType->param_type_begin() + OldParamsOffset,
1527 OldType->param_type_end()},
1528 {NewType->param_type_begin() + NewParamsOffset,
1529 NewType->param_type_end()},
1530 nullptr)) {
1531 return true;
1532 }
1533
1534 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1535 !NewMethod->isStatic()) {
1536 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1537 const CXXMethodDecl *New) {
1538 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1539 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1540
1541 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1542 return F->getRefQualifier() == RQ_None &&
1543 !F->isExplicitObjectMemberFunction();
1544 };
1545
1546 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1547 CompareType(OldObjectType.getNonReferenceType(),
1548 NewObjectType.getNonReferenceType()))
1549 return true;
1550 return CompareType(OldObjectType, NewObjectType);
1551 }(OldMethod, NewMethod);
1552
1553 if (!HaveCorrespondingObjectParameters) {
1554 if (DiagnoseInconsistentRefQualifiers())
1555 return true;
1556 // CWG2554
1557 // and, if at least one is an explicit object member function, ignoring
1558 // object parameters
1559 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1560 !OldMethod->isExplicitObjectMemberFunction()))
1561 return true;
1562 }
1563 }
1564
1565 if (!UseOverrideRules &&
1566 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1567 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1568 OldRC = Old->getTrailingRequiresClause();
1569 if (!NewRC != !OldRC)
1570 return true;
1571 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1572 return true;
1573 if (NewRC &&
1574 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC.ConstraintExpr,
1575 NewDecl, NewRC.ConstraintExpr))
1576 return true;
1577 }
1578
1579 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1580 NewMethod->isImplicitObjectMemberFunction()) {
1581 if (DiagnoseInconsistentRefQualifiers())
1582 return true;
1583 }
1584
1585 // Though pass_object_size is placed on parameters and takes an argument, we
1586 // consider it to be a function-level modifier for the sake of function
1587 // identity. Either the function has one or more parameters with
1588 // pass_object_size or it doesn't.
1591 return true;
1592
1593 // enable_if attributes are an order-sensitive part of the signature.
1595 NewI = New->specific_attr_begin<EnableIfAttr>(),
1596 NewE = New->specific_attr_end<EnableIfAttr>(),
1597 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1598 OldE = Old->specific_attr_end<EnableIfAttr>();
1599 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1600 if (NewI == NewE || OldI == OldE)
1601 return true;
1602 llvm::FoldingSetNodeID NewID, OldID;
1603 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1604 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1605 if (NewID != OldID)
1606 return true;
1607 }
1608
1609 // At this point, it is known that the two functions have the same signature.
1610 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1611 // Don't allow overloading of destructors. (In theory we could, but it
1612 // would be a giant change to clang.)
1614 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1615 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1616 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1617 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1618 "Unexpected invalid target.");
1619
1620 // Allow overloading of functions with same signature and different CUDA
1621 // target attributes.
1622 if (NewTarget != OldTarget) {
1623 // Special case: non-constexpr function is allowed to override
1624 // constexpr virtual function
1625 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1626 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1631 return false;
1632 }
1633 return true;
1634 }
1635 }
1636 }
1637 }
1638
1639 // The signatures match; this is not an overload.
1640 return false;
1641}
1642
1644 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1645 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1646 ConsiderCudaAttrs);
1647}
1648
1650 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1651 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1652 /*UseMemberUsingDeclRules=*/false,
1653 /*ConsiderCudaAttrs=*/true,
1654 /*UseOverrideRules=*/true);
1655}
1656
1657/// Tries a user-defined conversion from From to ToType.
1658///
1659/// Produces an implicit conversion sequence for when a standard conversion
1660/// is not an option. See TryImplicitConversion for more information.
1663 bool SuppressUserConversions,
1664 AllowedExplicit AllowExplicit,
1665 bool InOverloadResolution,
1666 bool CStyle,
1667 bool AllowObjCWritebackConversion,
1668 bool AllowObjCConversionOnExplicit) {
1670
1671 if (SuppressUserConversions) {
1672 // We're not in the case above, so there is no conversion that
1673 // we can perform.
1675 return ICS;
1676 }
1677
1678 // Attempt user-defined conversion.
1679 OverloadCandidateSet Conversions(From->getExprLoc(),
1681 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1682 Conversions, AllowExplicit,
1683 AllowObjCConversionOnExplicit)) {
1684 case OR_Success:
1685 case OR_Deleted:
1686 ICS.setUserDefined();
1687 // C++ [over.ics.user]p4:
1688 // A conversion of an expression of class type to the same class
1689 // type is given Exact Match rank, and a conversion of an
1690 // expression of class type to a base class of that type is
1691 // given Conversion rank, in spite of the fact that a copy
1692 // constructor (i.e., a user-defined conversion function) is
1693 // called for those cases.
1695 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1696 QualType FromType;
1697 SourceLocation FromLoc;
1698 // C++11 [over.ics.list]p6, per DR2137:
1699 // C++17 [over.ics.list]p6:
1700 // If C is not an initializer-list constructor and the initializer list
1701 // has a single element of type cv U, where U is X or a class derived
1702 // from X, the implicit conversion sequence has Exact Match rank if U is
1703 // X, or Conversion rank if U is derived from X.
1704 bool FromListInit = false;
1705 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1706 InitList && InitList->getNumInits() == 1 &&
1708 const Expr *SingleInit = InitList->getInit(0);
1709 FromType = SingleInit->getType();
1710 FromLoc = SingleInit->getBeginLoc();
1711 FromListInit = true;
1712 } else {
1713 FromType = From->getType();
1714 FromLoc = From->getBeginLoc();
1715 }
1716 QualType FromCanon =
1718 QualType ToCanon
1720 if ((FromCanon == ToCanon ||
1721 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1722 // Turn this into a "standard" conversion sequence, so that it
1723 // gets ranked with standard conversion sequences.
1725 ICS.setStandard();
1727 ICS.Standard.setFromType(FromType);
1728 ICS.Standard.setAllToTypes(ToType);
1729 ICS.Standard.FromBracedInitList = FromListInit;
1732 if (ToCanon != FromCanon)
1734 }
1735 }
1736 break;
1737
1738 case OR_Ambiguous:
1739 ICS.setAmbiguous();
1740 ICS.Ambiguous.setFromType(From->getType());
1741 ICS.Ambiguous.setToType(ToType);
1742 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1743 Cand != Conversions.end(); ++Cand)
1744 if (Cand->Best)
1745 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1746 break;
1747
1748 // Fall through.
1751 break;
1752 }
1753
1754 return ICS;
1755}
1756
1757/// TryImplicitConversion - Attempt to perform an implicit conversion
1758/// from the given expression (Expr) to the given type (ToType). This
1759/// function returns an implicit conversion sequence that can be used
1760/// to perform the initialization. Given
1761///
1762/// void f(float f);
1763/// void g(int i) { f(i); }
1764///
1765/// this routine would produce an implicit conversion sequence to
1766/// describe the initialization of f from i, which will be a standard
1767/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1768/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1769//
1770/// Note that this routine only determines how the conversion can be
1771/// performed; it does not actually perform the conversion. As such,
1772/// it will not produce any diagnostics if no conversion is available,
1773/// but will instead return an implicit conversion sequence of kind
1774/// "BadConversion".
1775///
1776/// If @p SuppressUserConversions, then user-defined conversions are
1777/// not permitted.
1778/// If @p AllowExplicit, then explicit user-defined conversions are
1779/// permitted.
1780///
1781/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1782/// writeback conversion, which allows __autoreleasing id* parameters to
1783/// be initialized with __strong id* or __weak id* arguments.
1784static ImplicitConversionSequence
1786 bool SuppressUserConversions,
1787 AllowedExplicit AllowExplicit,
1788 bool InOverloadResolution,
1789 bool CStyle,
1790 bool AllowObjCWritebackConversion,
1791 bool AllowObjCConversionOnExplicit) {
1793 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1794 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1795 ICS.setStandard();
1796 return ICS;
1797 }
1798
1799 if (!S.getLangOpts().CPlusPlus) {
1801 return ICS;
1802 }
1803
1804 // C++ [over.ics.user]p4:
1805 // A conversion of an expression of class type to the same class
1806 // type is given Exact Match rank, and a conversion of an
1807 // expression of class type to a base class of that type is
1808 // given Conversion rank, in spite of the fact that a copy/move
1809 // constructor (i.e., a user-defined conversion function) is
1810 // called for those cases.
1811 QualType FromType = From->getType();
1812 if (ToType->isRecordType() &&
1813 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1814 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1815 ICS.setStandard();
1817 ICS.Standard.setFromType(FromType);
1818 ICS.Standard.setAllToTypes(ToType);
1819
1820 // We don't actually check at this point whether there is a valid
1821 // copy/move constructor, since overloading just assumes that it
1822 // exists. When we actually perform initialization, we'll find the
1823 // appropriate constructor to copy the returned object, if needed.
1824 ICS.Standard.CopyConstructor = nullptr;
1825
1826 // Determine whether this is considered a derived-to-base conversion.
1827 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1829
1830 return ICS;
1831 }
1832
1833 if (S.getLangOpts().HLSL) {
1834 // Handle conversion of the HLSL resource types.
1835 const Type *FromTy = FromType->getUnqualifiedDesugaredType();
1836 if (FromTy->isHLSLAttributedResourceType()) {
1837 // Attributed resource types can convert to other attributed
1838 // resource types with the same attributes and contained types,
1839 // or to __hlsl_resource_t without any attributes.
1840 bool CanConvert = false;
1841 const Type *ToTy = ToType->getUnqualifiedDesugaredType();
1842 if (ToTy->isHLSLAttributedResourceType()) {
1843 auto *ToResType = cast<HLSLAttributedResourceType>(ToTy);
1844 auto *FromResType = cast<HLSLAttributedResourceType>(FromTy);
1845 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1846 FromResType->getWrappedType()) &&
1847 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1848 FromResType->getContainedType()) &&
1849 ToResType->getAttrs() == FromResType->getAttrs())
1850 CanConvert = true;
1851 } else if (ToTy->isHLSLResourceType()) {
1852 CanConvert = true;
1853 }
1854 if (CanConvert) {
1855 ICS.setStandard();
1857 ICS.Standard.setFromType(FromType);
1858 ICS.Standard.setAllToTypes(ToType);
1859 return ICS;
1860 }
1861 }
1862 }
1863
1864 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1865 AllowExplicit, InOverloadResolution, CStyle,
1866 AllowObjCWritebackConversion,
1867 AllowObjCConversionOnExplicit);
1868}
1869
1870ImplicitConversionSequence
1872 bool SuppressUserConversions,
1873 AllowedExplicit AllowExplicit,
1874 bool InOverloadResolution,
1875 bool CStyle,
1876 bool AllowObjCWritebackConversion) {
1877 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1878 AllowExplicit, InOverloadResolution, CStyle,
1879 AllowObjCWritebackConversion,
1880 /*AllowObjCConversionOnExplicit=*/false);
1881}
1882
1884 AssignmentAction Action,
1885 bool AllowExplicit) {
1886 if (checkPlaceholderForOverload(*this, From))
1887 return ExprError();
1888
1889 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1890 bool AllowObjCWritebackConversion =
1891 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1892 Action == AssignmentAction::Sending);
1893 if (getLangOpts().ObjC)
1894 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1895 From->getType(), From);
1897 *this, From, ToType,
1898 /*SuppressUserConversions=*/false,
1899 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1900 /*InOverloadResolution=*/false,
1901 /*CStyle=*/false, AllowObjCWritebackConversion,
1902 /*AllowObjCConversionOnExplicit=*/false);
1903 return PerformImplicitConversion(From, ToType, ICS, Action);
1904}
1905
1907 QualType &ResultTy) const {
1908 bool Changed = IsFunctionConversion(FromType, ToType);
1909 if (Changed)
1910 ResultTy = ToType;
1911 return Changed;
1912}
1913
1914bool Sema::IsFunctionConversion(QualType FromType, QualType ToType) const {
1915 if (Context.hasSameUnqualifiedType(FromType, ToType))
1916 return false;
1917
1918 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1919 // or F(t noexcept) -> F(t)
1920 // where F adds one of the following at most once:
1921 // - a pointer
1922 // - a member pointer
1923 // - a block pointer
1924 // Changes here need matching changes in FindCompositePointerType.
1925 CanQualType CanTo = Context.getCanonicalType(ToType);
1926 CanQualType CanFrom = Context.getCanonicalType(FromType);
1927 Type::TypeClass TyClass = CanTo->getTypeClass();
1928 if (TyClass != CanFrom->getTypeClass()) return false;
1929 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1930 if (TyClass == Type::Pointer) {
1931 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1932 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1933 } else if (TyClass == Type::BlockPointer) {
1934 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1935 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1936 } else if (TyClass == Type::MemberPointer) {
1937 auto ToMPT = CanTo.castAs<MemberPointerType>();
1938 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1939 // A function pointer conversion cannot change the class of the function.
1940 if (!declaresSameEntity(ToMPT->getMostRecentCXXRecordDecl(),
1941 FromMPT->getMostRecentCXXRecordDecl()))
1942 return false;
1943 CanTo = ToMPT->getPointeeType();
1944 CanFrom = FromMPT->getPointeeType();
1945 } else {
1946 return false;
1947 }
1948
1949 TyClass = CanTo->getTypeClass();
1950 if (TyClass != CanFrom->getTypeClass()) return false;
1951 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1952 return false;
1953 }
1954
1955 const auto *FromFn = cast<FunctionType>(CanFrom);
1956 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1957
1958 const auto *ToFn = cast<FunctionType>(CanTo);
1959 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1960
1961 bool Changed = false;
1962
1963 // Drop 'noreturn' if not present in target type.
1964 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1965 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1966 Changed = true;
1967 }
1968
1969 const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn);
1970 const auto *ToFPT = dyn_cast<FunctionProtoType>(ToFn);
1971
1972 if (FromFPT && ToFPT) {
1973 if (FromFPT->hasCFIUncheckedCallee() != ToFPT->hasCFIUncheckedCallee()) {
1974 QualType NewTy = Context.getFunctionType(
1975 FromFPT->getReturnType(), FromFPT->getParamTypes(),
1976 FromFPT->getExtProtoInfo().withCFIUncheckedCallee(
1977 ToFPT->hasCFIUncheckedCallee()));
1978 FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());
1979 FromFn = FromFPT;
1980 Changed = true;
1981 }
1982 }
1983
1984 // Drop 'noexcept' if not present in target type.
1985 if (FromFPT && ToFPT) {
1986 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1987 FromFn = cast<FunctionType>(
1988 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1989 EST_None)
1990 .getTypePtr());
1991 Changed = true;
1992 }
1993
1994 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1995 // only if the ExtParameterInfo lists of the two function prototypes can be
1996 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1998 bool CanUseToFPT, CanUseFromFPT;
1999 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
2000 CanUseFromFPT, NewParamInfos) &&
2001 CanUseToFPT && !CanUseFromFPT) {
2002 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2003 ExtInfo.ExtParameterInfos =
2004 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2005 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
2006 FromFPT->getParamTypes(), ExtInfo);
2007 FromFn = QT->getAs<FunctionType>();
2008 Changed = true;
2009 }
2010
2011 if (Context.hasAnyFunctionEffects()) {
2012 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
2013
2014 // Transparently add/drop effects; here we are concerned with
2015 // language rules/canonicalization. Adding/dropping effects is a warning.
2016 const auto FromFX = FromFPT->getFunctionEffects();
2017 const auto ToFX = ToFPT->getFunctionEffects();
2018 if (FromFX != ToFX) {
2019 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2020 ExtInfo.FunctionEffects = ToFX;
2021 QualType QT = Context.getFunctionType(
2022 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
2023 FromFn = QT->getAs<FunctionType>();
2024 Changed = true;
2025 }
2026 }
2027 }
2028
2029 if (!Changed)
2030 return false;
2031
2032 assert(QualType(FromFn, 0).isCanonical());
2033 if (QualType(FromFn, 0) != CanTo) return false;
2034
2035 return true;
2036}
2037
2038/// Determine whether the conversion from FromType to ToType is a valid
2039/// floating point conversion.
2040///
2041static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2042 QualType ToType) {
2043 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2044 return false;
2045 // FIXME: disable conversions between long double, __ibm128 and __float128
2046 // if their representation is different until there is back end support
2047 // We of course allow this conversion if long double is really double.
2048
2049 // Conversions between bfloat16 and float16 are currently not supported.
2050 if ((FromType->isBFloat16Type() &&
2051 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2052 (ToType->isBFloat16Type() &&
2053 (FromType->isFloat16Type() || FromType->isHalfType())))
2054 return false;
2055
2056 // Conversions between IEEE-quad and IBM-extended semantics are not
2057 // permitted.
2058 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
2059 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2060 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2061 &ToSem == &llvm::APFloat::IEEEquad()) ||
2062 (&FromSem == &llvm::APFloat::IEEEquad() &&
2063 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2064 return false;
2065 return true;
2066}
2067
2069 QualType ToType,
2071 Expr *From) {
2072 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2073 return true;
2074
2075 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2077 return true;
2078 }
2079
2080 if (IsFloatingPointConversion(S, FromType, ToType)) {
2082 return true;
2083 }
2084
2085 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2087 return true;
2088 }
2089
2090 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2092 ToType->isRealFloatingType())) {
2094 return true;
2095 }
2096
2097 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2099 return true;
2100 }
2101
2102 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2103 ToType->isIntegralType(S.Context)) {
2105 return true;
2106 }
2107
2108 return false;
2109}
2110
2111/// Determine whether the conversion from FromType to ToType is a valid
2112/// matrix conversion.
2113///
2114/// \param ICK Will be set to the matrix conversion kind, if this is a matrix
2115/// conversion.
2116static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType,
2118 ImplicitConversionKind &ElConv, Expr *From,
2119 bool InOverloadResolution, bool CStyle) {
2120 // Implicit conversions for matrices are an HLSL feature not present in C/C++.
2121 if (!S.getLangOpts().HLSL)
2122 return false;
2123
2124 auto *ToMatrixType = ToType->getAs<ConstantMatrixType>();
2125 auto *FromMatrixType = FromType->getAs<ConstantMatrixType>();
2126
2127 // If both arguments are matrix, handle possible matrix truncation and
2128 // element conversion.
2129 if (ToMatrixType && FromMatrixType) {
2130 unsigned FromCols = FromMatrixType->getNumColumns();
2131 unsigned ToCols = ToMatrixType->getNumColumns();
2132 if (FromCols < ToCols)
2133 return false;
2134
2135 unsigned FromRows = FromMatrixType->getNumRows();
2136 unsigned ToRows = ToMatrixType->getNumRows();
2137 if (FromRows < ToRows)
2138 return false;
2139
2140 if (FromRows == ToRows && FromCols == ToCols)
2141 ElConv = ICK_Identity;
2142 else
2144
2145 QualType FromElTy = FromMatrixType->getElementType();
2146 QualType ToElTy = ToMatrixType->getElementType();
2147 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2148 return true;
2149 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2150 }
2151
2152 // Matrix splat from any arithmetic type to a matrix.
2153 if (ToMatrixType && FromType->isArithmeticType()) {
2154 ElConv = ICK_HLSL_Matrix_Splat;
2155 QualType ToElTy = ToMatrixType->getElementType();
2156 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK, From);
2158 return true;
2159 }
2160 if (FromMatrixType && !ToMatrixType) {
2162 QualType FromElTy = FromMatrixType->getElementType();
2163 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2164 return true;
2165 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2166 }
2167
2168 return false;
2169}
2170
2171/// Determine whether the conversion from FromType to ToType is a valid
2172/// vector conversion.
2173///
2174/// \param ICK Will be set to the vector conversion kind, if this is a vector
2175/// conversion.
2176static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2178 ImplicitConversionKind &ElConv, Expr *From,
2179 bool InOverloadResolution, bool CStyle) {
2180 // We need at least one of these types to be a vector type to have a vector
2181 // conversion.
2182 if (!ToType->isVectorType() && !FromType->isVectorType())
2183 return false;
2184
2185 // Identical types require no conversions.
2186 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2187 return false;
2188
2189 // HLSL allows implicit truncation of vector types.
2190 if (S.getLangOpts().HLSL) {
2191 auto *ToExtType = ToType->getAs<ExtVectorType>();
2192 auto *FromExtType = FromType->getAs<ExtVectorType>();
2193
2194 // If both arguments are vectors, handle possible vector truncation and
2195 // element conversion.
2196 if (ToExtType && FromExtType) {
2197 unsigned FromElts = FromExtType->getNumElements();
2198 unsigned ToElts = ToExtType->getNumElements();
2199 if (FromElts < ToElts)
2200 return false;
2201 if (FromElts == ToElts)
2202 ElConv = ICK_Identity;
2203 else
2205
2206 QualType FromElTy = FromExtType->getElementType();
2207 QualType ToElTy = ToExtType->getElementType();
2208 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2209 return true;
2210 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2211 }
2212 if (FromExtType && !ToExtType) {
2214 QualType FromElTy = FromExtType->getElementType();
2215 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2216 return true;
2217 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2218 }
2219 // Fallthrough for the case where ToType is a vector and FromType is not.
2220 }
2221
2222 // There are no conversions between extended vector types, only identity.
2223 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2224 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2225 // Implicit conversions require the same number of elements.
2226 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2227 return false;
2228
2229 // Permit implicit conversions from integral values to boolean vectors.
2230 if (ToType->isExtVectorBoolType() &&
2231 FromExtType->getElementType()->isIntegerType()) {
2233 return true;
2234 }
2235 // There are no other conversions between extended vector types.
2236 return false;
2237 }
2238
2239 // Vector splat from any arithmetic type to a vector.
2240 if (FromType->isArithmeticType()) {
2241 if (S.getLangOpts().HLSL) {
2242 ElConv = ICK_HLSL_Vector_Splat;
2243 QualType ToElTy = ToExtType->getElementType();
2244 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK,
2245 From);
2246 }
2247 ICK = ICK_Vector_Splat;
2248 return true;
2249 }
2250 }
2251
2252 if (ToType->isSVESizelessBuiltinType() ||
2253 FromType->isSVESizelessBuiltinType())
2254 if (S.ARM().areCompatibleSveTypes(FromType, ToType) ||
2255 S.ARM().areLaxCompatibleSveTypes(FromType, ToType)) {
2257 return true;
2258 }
2259
2260 if (ToType->isRVVSizelessBuiltinType() ||
2261 FromType->isRVVSizelessBuiltinType())
2262 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2263 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2265 return true;
2266 }
2267
2268 // We can perform the conversion between vector types in the following cases:
2269 // 1)vector types are equivalent AltiVec and GCC vector types
2270 // 2)lax vector conversions are permitted and the vector types are of the
2271 // same size
2272 // 3)the destination type does not have the ARM MVE strict-polymorphism
2273 // attribute, which inhibits lax vector conversion for overload resolution
2274 // only
2275 if (ToType->isVectorType() && FromType->isVectorType()) {
2276 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2277 (S.isLaxVectorConversion(FromType, ToType) &&
2278 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2279 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2280 S.isLaxVectorConversion(FromType, ToType) &&
2281 S.anyAltivecTypes(FromType, ToType) &&
2282 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2283 !InOverloadResolution && !CStyle) {
2284 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2285 << FromType << ToType;
2286 }
2288 return true;
2289 }
2290 }
2291
2292 return false;
2293}
2294
2295static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2296 bool InOverloadResolution,
2297 StandardConversionSequence &SCS,
2298 bool CStyle);
2299
2300/// IsStandardConversion - Determines whether there is a standard
2301/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2302/// expression From to the type ToType. Standard conversion sequences
2303/// only consider non-class types; for conversions that involve class
2304/// types, use TryImplicitConversion. If a conversion exists, SCS will
2305/// contain the standard conversion sequence required to perform this
2306/// conversion and this routine will return true. Otherwise, this
2307/// routine will return false and the value of SCS is unspecified.
2308static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2309 bool InOverloadResolution,
2311 bool CStyle,
2312 bool AllowObjCWritebackConversion) {
2313 QualType FromType = From->getType();
2314
2315 // Standard conversions (C++ [conv])
2317 SCS.IncompatibleObjC = false;
2318 SCS.setFromType(FromType);
2319 SCS.CopyConstructor = nullptr;
2320
2321 // There are no standard conversions for class types in C++, so
2322 // abort early. When overloading in C, however, we do permit them.
2323 if (S.getLangOpts().CPlusPlus &&
2324 (FromType->isRecordType() || ToType->isRecordType()))
2325 return false;
2326
2327 // The first conversion can be an lvalue-to-rvalue conversion,
2328 // array-to-pointer conversion, or function-to-pointer conversion
2329 // (C++ 4p1).
2330
2331 if (FromType == S.Context.OverloadTy) {
2332 DeclAccessPair AccessPair;
2333 if (FunctionDecl *Fn
2334 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2335 AccessPair)) {
2336 // We were able to resolve the address of the overloaded function,
2337 // so we can convert to the type of that function.
2338 FromType = Fn->getType();
2339 SCS.setFromType(FromType);
2340
2341 // we can sometimes resolve &foo<int> regardless of ToType, so check
2342 // if the type matches (identity) or we are converting to bool
2344 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2345 // if the function type matches except for [[noreturn]], it's ok
2346 if (!S.IsFunctionConversion(FromType,
2348 // otherwise, only a boolean conversion is standard
2349 if (!ToType->isBooleanType())
2350 return false;
2351 }
2352
2353 // Check if the "from" expression is taking the address of an overloaded
2354 // function and recompute the FromType accordingly. Take advantage of the
2355 // fact that non-static member functions *must* have such an address-of
2356 // expression.
2357 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2358 if (Method && !Method->isStatic() &&
2359 !Method->isExplicitObjectMemberFunction()) {
2360 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2361 "Non-unary operator on non-static member address");
2362 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2363 == UO_AddrOf &&
2364 "Non-address-of operator on non-static member address");
2365 FromType = S.Context.getMemberPointerType(
2366 FromType, /*Qualifier=*/std::nullopt, Method->getParent());
2367 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2368 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2369 UO_AddrOf &&
2370 "Non-address-of operator for overloaded function expression");
2371 FromType = S.Context.getPointerType(FromType);
2372 }
2373 } else {
2374 return false;
2375 }
2376 }
2377
2378 bool argIsLValue = From->isGLValue();
2379 // To handle conversion from ArrayParameterType to ConstantArrayType
2380 // this block must be above the one below because Array parameters
2381 // do not decay and when handling HLSLOutArgExprs and
2382 // the From expression is an LValue.
2383 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2384 ToType->isConstantArrayType()) {
2385 // HLSL constant array parameters do not decay, so if the argument is a
2386 // constant array and the parameter is an ArrayParameterType we have special
2387 // handling here.
2388 if (ToType->isArrayParameterType()) {
2389 FromType = S.Context.getArrayParameterType(FromType);
2390 } else if (FromType->isArrayParameterType()) {
2391 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2392 FromType = APT->getConstantArrayType(S.Context);
2393 }
2394
2396
2397 // Don't consider qualifiers, which include things like address spaces
2398 if (FromType.getCanonicalType().getUnqualifiedType() !=
2400 return false;
2401
2402 SCS.setAllToTypes(ToType);
2403 return true;
2404 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2405 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2406 // Lvalue-to-rvalue conversion (C++11 4.1):
2407 // A glvalue (3.10) of a non-function, non-array type T can
2408 // be converted to a prvalue.
2409
2411
2412 // C11 6.3.2.1p2:
2413 // ... if the lvalue has atomic type, the value has the non-atomic version
2414 // of the type of the lvalue ...
2415 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2416 FromType = Atomic->getValueType();
2417
2418 // If T is a non-class type, the type of the rvalue is the
2419 // cv-unqualified version of T. Otherwise, the type of the rvalue
2420 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2421 // just strip the qualifiers because they don't matter.
2422 FromType = FromType.getUnqualifiedType();
2423 } else if (FromType->isArrayType()) {
2424 // Array-to-pointer conversion (C++ 4.2)
2426
2427 // An lvalue or rvalue of type "array of N T" or "array of unknown
2428 // bound of T" can be converted to an rvalue of type "pointer to
2429 // T" (C++ 4.2p1).
2430 FromType = S.Context.getArrayDecayedType(FromType);
2431
2432 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2433 // This conversion is deprecated in C++03 (D.4)
2435
2436 // For the purpose of ranking in overload resolution
2437 // (13.3.3.1.1), this conversion is considered an
2438 // array-to-pointer conversion followed by a qualification
2439 // conversion (4.4). (C++ 4.2p2)
2440 SCS.Second = ICK_Identity;
2443 SCS.setAllToTypes(FromType);
2444 return true;
2445 }
2446 } else if (FromType->isFunctionType() && argIsLValue) {
2447 // Function-to-pointer conversion (C++ 4.3).
2449
2450 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2451 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2453 return false;
2454
2455 // An lvalue of function type T can be converted to an rvalue of
2456 // type "pointer to T." The result is a pointer to the
2457 // function. (C++ 4.3p1).
2458 FromType = S.Context.getPointerType(FromType);
2459 } else {
2460 // We don't require any conversions for the first step.
2461 SCS.First = ICK_Identity;
2462 }
2463 SCS.setToType(0, FromType);
2464
2465 // The second conversion can be an integral promotion, floating
2466 // point promotion, integral conversion, floating point conversion,
2467 // floating-integral conversion, pointer conversion,
2468 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2469 // For overloading in C, this can also be a "compatible-type"
2470 // conversion.
2471 bool IncompatibleObjC = false;
2473 ImplicitConversionKind DimensionICK = ICK_Identity;
2474 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2475 // The unqualified versions of the types are the same: there's no
2476 // conversion to do.
2477 SCS.Second = ICK_Identity;
2478 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2479 // Integral promotion (C++ 4.5).
2481 FromType = ToType.getUnqualifiedType();
2482 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2483 // Floating point promotion (C++ 4.6).
2485 FromType = ToType.getUnqualifiedType();
2486 } else if (S.IsComplexPromotion(FromType, ToType)) {
2487 // Complex promotion (Clang extension)
2489 FromType = ToType.getUnqualifiedType();
2490 } else if (ToType->isBooleanType() &&
2491 (FromType->isArithmeticType() ||
2492 FromType->isAnyPointerType() ||
2493 FromType->isBlockPointerType() ||
2494 FromType->isMemberPointerType())) {
2495 // Boolean conversions (C++ 4.12).
2497 FromType = S.Context.BoolTy;
2498 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2499 ToType->isIntegralType(S.Context)) {
2500 // Integral conversions (C++ 4.7).
2502 FromType = ToType.getUnqualifiedType();
2503 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2504 // Complex conversions (C99 6.3.1.6)
2506 FromType = ToType.getUnqualifiedType();
2507 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2508 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2509 // Complex-real conversions (C99 6.3.1.7)
2511 FromType = ToType.getUnqualifiedType();
2512 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2513 // Floating point conversions (C++ 4.8).
2515 FromType = ToType.getUnqualifiedType();
2516 } else if ((FromType->isRealFloatingType() &&
2517 ToType->isIntegralType(S.Context)) ||
2519 ToType->isRealFloatingType())) {
2520
2521 // Floating-integral conversions (C++ 4.9).
2523 FromType = ToType.getUnqualifiedType();
2524 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2526 } else if (AllowObjCWritebackConversion &&
2527 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2529 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2530 FromType, IncompatibleObjC)) {
2531 // Pointer conversions (C++ 4.10).
2533 SCS.IncompatibleObjC = IncompatibleObjC;
2534 FromType = FromType.getUnqualifiedType();
2535 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2536 InOverloadResolution, FromType)) {
2537 // Pointer to member conversions (4.11).
2539 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2540 From, InOverloadResolution, CStyle)) {
2541 SCS.Second = SecondICK;
2542 SCS.Dimension = DimensionICK;
2543 FromType = ToType.getUnqualifiedType();
2544 } else if (IsMatrixConversion(S, FromType, ToType, SecondICK, DimensionICK,
2545 From, InOverloadResolution, CStyle)) {
2546 SCS.Second = SecondICK;
2547 SCS.Dimension = DimensionICK;
2548 FromType = ToType.getUnqualifiedType();
2549 } else if (!S.getLangOpts().CPlusPlus &&
2550 S.Context.typesAreCompatible(ToType, FromType)) {
2551 // Compatible conversions (Clang extension for C function overloading)
2553 FromType = ToType.getUnqualifiedType();
2555 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2557 FromType = ToType;
2558 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2559 CStyle)) {
2560 // tryAtomicConversion has updated the standard conversion sequence
2561 // appropriately.
2562 return true;
2563 } else if (ToType->isEventT() &&
2565 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2567 FromType = ToType;
2568 } else if (ToType->isQueueT() &&
2570 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2572 FromType = ToType;
2573 } else if (ToType->isSamplerT() &&
2576 FromType = ToType;
2577 } else if ((ToType->isFixedPointType() &&
2578 FromType->isConvertibleToFixedPointType()) ||
2579 (FromType->isFixedPointType() &&
2580 ToType->isConvertibleToFixedPointType())) {
2582 FromType = ToType;
2583 } else {
2584 // No second conversion required.
2585 SCS.Second = ICK_Identity;
2586 }
2587 SCS.setToType(1, FromType);
2588
2589 // The third conversion can be a function pointer conversion or a
2590 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2591 bool ObjCLifetimeConversion;
2592 if (S.TryFunctionConversion(FromType, ToType, FromType)) {
2593 // Function pointer conversions (removing 'noexcept') including removal of
2594 // 'noreturn' (Clang extension).
2596 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2597 ObjCLifetimeConversion)) {
2599 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2600 FromType = ToType;
2601 } else {
2602 // No conversion required
2603 SCS.Third = ICK_Identity;
2604 }
2605
2606 // C++ [over.best.ics]p6:
2607 // [...] Any difference in top-level cv-qualification is
2608 // subsumed by the initialization itself and does not constitute
2609 // a conversion. [...]
2610 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2611 QualType CanonTo = S.Context.getCanonicalType(ToType);
2612 if (CanonFrom.getLocalUnqualifiedType()
2613 == CanonTo.getLocalUnqualifiedType() &&
2614 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2615 FromType = ToType;
2616 CanonFrom = CanonTo;
2617 }
2618
2619 SCS.setToType(2, FromType);
2620
2621 if (CanonFrom == CanonTo)
2622 return true;
2623
2624 // If we have not converted the argument type to the parameter type,
2625 // this is a bad conversion sequence, unless we're resolving an overload in C.
2626 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2627 return false;
2628
2629 ExprResult ER = ExprResult{From};
2630 AssignConvertType Conv =
2632 /*Diagnose=*/false,
2633 /*DiagnoseCFAudited=*/false,
2634 /*ConvertRHS=*/false);
2635 ImplicitConversionKind SecondConv;
2636 switch (Conv) {
2638 case AssignConvertType::
2639 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2640 SecondConv = ICK_C_Only_Conversion;
2641 break;
2642 // For our purposes, discarding qualifiers is just as bad as using an
2643 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2644 // qualifiers, as well.
2649 break;
2650 default:
2651 return false;
2652 }
2653
2654 // First can only be an lvalue conversion, so we pretend that this was the
2655 // second conversion. First should already be valid from earlier in the
2656 // function.
2657 SCS.Second = SecondConv;
2658 SCS.setToType(1, ToType);
2659
2660 // Third is Identity, because Second should rank us worse than any other
2661 // conversion. This could also be ICK_Qualification, but it's simpler to just
2662 // lump everything in with the second conversion, and we don't gain anything
2663 // from making this ICK_Qualification.
2664 SCS.Third = ICK_Identity;
2665 SCS.setToType(2, ToType);
2666 return true;
2667}
2668
2669static bool
2671 QualType &ToType,
2672 bool InOverloadResolution,
2674 bool CStyle) {
2675
2676 const RecordType *UT = ToType->getAsUnionType();
2677 if (!UT)
2678 return false;
2679 // The field to initialize within the transparent union.
2680 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2681 if (!UD->hasAttr<TransparentUnionAttr>())
2682 return false;
2683 // It's compatible if the expression matches any of the fields.
2684 for (const auto *it : UD->fields()) {
2685 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2686 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2687 ToType = it->getType();
2688 return true;
2689 }
2690 }
2691 return false;
2692}
2693
2694bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2695 const BuiltinType *To = ToType->getAs<BuiltinType>();
2696 // All integers are built-in.
2697 if (!To) {
2698 return false;
2699 }
2700
2701 // An rvalue of type char, signed char, unsigned char, short int, or
2702 // unsigned short int can be converted to an rvalue of type int if
2703 // int can represent all the values of the source type; otherwise,
2704 // the source rvalue can be converted to an rvalue of type unsigned
2705 // int (C++ 4.5p1).
2706 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2707 !FromType->isEnumeralType()) {
2708 if ( // We can promote any signed, promotable integer type to an int
2709 (FromType->isSignedIntegerType() ||
2710 // We can promote any unsigned integer type whose size is
2711 // less than int to an int.
2712 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2713 return To->getKind() == BuiltinType::Int;
2714 }
2715
2716 return To->getKind() == BuiltinType::UInt;
2717 }
2718
2719 // C++11 [conv.prom]p3:
2720 // A prvalue of an unscoped enumeration type whose underlying type is not
2721 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2722 // following types that can represent all the values of the enumeration
2723 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2724 // unsigned int, long int, unsigned long int, long long int, or unsigned
2725 // long long int. If none of the types in that list can represent all the
2726 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2727 // type can be converted to an rvalue a prvalue of the extended integer type
2728 // with lowest integer conversion rank (4.13) greater than the rank of long
2729 // long in which all the values of the enumeration can be represented. If
2730 // there are two such extended types, the signed one is chosen.
2731 // C++11 [conv.prom]p4:
2732 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2733 // can be converted to a prvalue of its underlying type. Moreover, if
2734 // integral promotion can be applied to its underlying type, a prvalue of an
2735 // unscoped enumeration type whose underlying type is fixed can also be
2736 // converted to a prvalue of the promoted underlying type.
2737 if (const auto *FromED = FromType->getAsEnumDecl()) {
2738 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2739 // provided for a scoped enumeration.
2740 if (FromED->isScoped())
2741 return false;
2742
2743 // We can perform an integral promotion to the underlying type of the enum,
2744 // even if that's not the promoted type. Note that the check for promoting
2745 // the underlying type is based on the type alone, and does not consider
2746 // the bitfield-ness of the actual source expression.
2747 if (FromED->isFixed()) {
2748 QualType Underlying = FromED->getIntegerType();
2749 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2750 IsIntegralPromotion(nullptr, Underlying, ToType);
2751 }
2752
2753 // We have already pre-calculated the promotion type, so this is trivial.
2754 if (ToType->isIntegerType() &&
2755 isCompleteType(From->getBeginLoc(), FromType))
2756 return Context.hasSameUnqualifiedType(ToType, FromED->getPromotionType());
2757
2758 // C++ [conv.prom]p5:
2759 // If the bit-field has an enumerated type, it is treated as any other
2760 // value of that type for promotion purposes.
2761 //
2762 // ... so do not fall through into the bit-field checks below in C++.
2763 if (getLangOpts().CPlusPlus)
2764 return false;
2765 }
2766
2767 // C++0x [conv.prom]p2:
2768 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2769 // to an rvalue a prvalue of the first of the following types that can
2770 // represent all the values of its underlying type: int, unsigned int,
2771 // long int, unsigned long int, long long int, or unsigned long long int.
2772 // If none of the types in that list can represent all the values of its
2773 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2774 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2775 // type.
2776 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2777 ToType->isIntegerType()) {
2778 // Determine whether the type we're converting from is signed or
2779 // unsigned.
2780 bool FromIsSigned = FromType->isSignedIntegerType();
2781 uint64_t FromSize = Context.getTypeSize(FromType);
2782
2783 // The types we'll try to promote to, in the appropriate
2784 // order. Try each of these types.
2785 QualType PromoteTypes[6] = {
2786 Context.IntTy, Context.UnsignedIntTy,
2787 Context.LongTy, Context.UnsignedLongTy ,
2788 Context.LongLongTy, Context.UnsignedLongLongTy
2789 };
2790 for (int Idx = 0; Idx < 6; ++Idx) {
2791 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2792 if (FromSize < ToSize ||
2793 (FromSize == ToSize &&
2794 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2795 // We found the type that we can promote to. If this is the
2796 // type we wanted, we have a promotion. Otherwise, no
2797 // promotion.
2798 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2799 }
2800 }
2801 }
2802
2803 // An rvalue for an integral bit-field (9.6) can be converted to an
2804 // rvalue of type int if int can represent all the values of the
2805 // bit-field; otherwise, it can be converted to unsigned int if
2806 // unsigned int can represent all the values of the bit-field. If
2807 // the bit-field is larger yet, no integral promotion applies to
2808 // it. If the bit-field has an enumerated type, it is treated as any
2809 // other value of that type for promotion purposes (C++ 4.5p3).
2810 // FIXME: We should delay checking of bit-fields until we actually perform the
2811 // conversion.
2812 //
2813 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2814 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2815 // bit-fields and those whose underlying type is larger than int) for GCC
2816 // compatibility.
2817 if (From) {
2818 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2819 std::optional<llvm::APSInt> BitWidth;
2820 if (FromType->isIntegralType(Context) &&
2821 (BitWidth =
2822 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2823 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2824 ToSize = Context.getTypeSize(ToType);
2825
2826 // Are we promoting to an int from a bitfield that fits in an int?
2827 if (*BitWidth < ToSize ||
2828 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2829 return To->getKind() == BuiltinType::Int;
2830 }
2831
2832 // Are we promoting to an unsigned int from an unsigned bitfield
2833 // that fits into an unsigned int?
2834 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2835 return To->getKind() == BuiltinType::UInt;
2836 }
2837
2838 return false;
2839 }
2840 }
2841 }
2842
2843 // An rvalue of type bool can be converted to an rvalue of type int,
2844 // with false becoming zero and true becoming one (C++ 4.5p4).
2845 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2846 return true;
2847 }
2848
2849 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2850 // integral type.
2851 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2852 ToType->isIntegerType())
2853 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2854
2855 return false;
2856}
2857
2859 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2860 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2861 /// An rvalue of type float can be converted to an rvalue of type
2862 /// double. (C++ 4.6p1).
2863 if (FromBuiltin->getKind() == BuiltinType::Float &&
2864 ToBuiltin->getKind() == BuiltinType::Double)
2865 return true;
2866
2867 // C99 6.3.1.5p1:
2868 // When a float is promoted to double or long double, or a
2869 // double is promoted to long double [...].
2870 if (!getLangOpts().CPlusPlus &&
2871 (FromBuiltin->getKind() == BuiltinType::Float ||
2872 FromBuiltin->getKind() == BuiltinType::Double) &&
2873 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2874 ToBuiltin->getKind() == BuiltinType::Float128 ||
2875 ToBuiltin->getKind() == BuiltinType::Ibm128))
2876 return true;
2877
2878 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2879 // or not native half types are enabled.
2880 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2881 (ToBuiltin->getKind() == BuiltinType::Float ||
2882 ToBuiltin->getKind() == BuiltinType::Double))
2883 return true;
2884
2885 // Half can be promoted to float.
2886 if (!getLangOpts().NativeHalfType &&
2887 FromBuiltin->getKind() == BuiltinType::Half &&
2888 ToBuiltin->getKind() == BuiltinType::Float)
2889 return true;
2890 }
2891
2892 return false;
2893}
2894
2896 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2897 if (!FromComplex)
2898 return false;
2899
2900 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2901 if (!ToComplex)
2902 return false;
2903
2904 return IsFloatingPointPromotion(FromComplex->getElementType(),
2905 ToComplex->getElementType()) ||
2906 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2907 ToComplex->getElementType());
2908}
2909
2910/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2911/// the pointer type FromPtr to a pointer to type ToPointee, with the
2912/// same type qualifiers as FromPtr has on its pointee type. ToType,
2913/// if non-empty, will be a pointer to ToType that may or may not have
2914/// the right set of qualifiers on its pointee.
2915///
2916static QualType
2918 QualType ToPointee, QualType ToType,
2919 ASTContext &Context,
2920 bool StripObjCLifetime = false) {
2921 assert((FromPtr->getTypeClass() == Type::Pointer ||
2922 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2923 "Invalid similarly-qualified pointer type");
2924
2925 /// Conversions to 'id' subsume cv-qualifier conversions.
2926 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2927 return ToType.getUnqualifiedType();
2928
2929 QualType CanonFromPointee
2930 = Context.getCanonicalType(FromPtr->getPointeeType());
2931 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2932 Qualifiers Quals = CanonFromPointee.getQualifiers();
2933
2934 if (StripObjCLifetime)
2935 Quals.removeObjCLifetime();
2936
2937 // Exact qualifier match -> return the pointer type we're converting to.
2938 if (CanonToPointee.getLocalQualifiers() == Quals) {
2939 // ToType is exactly what we need. Return it.
2940 if (!ToType.isNull())
2941 return ToType.getUnqualifiedType();
2942
2943 // Build a pointer to ToPointee. It has the right qualifiers
2944 // already.
2945 if (isa<ObjCObjectPointerType>(ToType))
2946 return Context.getObjCObjectPointerType(ToPointee);
2947 return Context.getPointerType(ToPointee);
2948 }
2949
2950 // Just build a canonical type that has the right qualifiers.
2951 QualType QualifiedCanonToPointee
2952 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2953
2954 if (isa<ObjCObjectPointerType>(ToType))
2955 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2956 return Context.getPointerType(QualifiedCanonToPointee);
2957}
2958
2960 bool InOverloadResolution,
2961 ASTContext &Context) {
2962 // Handle value-dependent integral null pointer constants correctly.
2963 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2964 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2966 return !InOverloadResolution;
2967
2968 return Expr->isNullPointerConstant(Context,
2969 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2971}
2972
2974 bool InOverloadResolution,
2975 QualType& ConvertedType,
2976 bool &IncompatibleObjC) {
2977 IncompatibleObjC = false;
2978 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2979 IncompatibleObjC))
2980 return true;
2981
2982 // Conversion from a null pointer constant to any Objective-C pointer type.
2983 if (ToType->isObjCObjectPointerType() &&
2984 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2985 ConvertedType = ToType;
2986 return true;
2987 }
2988
2989 // Blocks: Block pointers can be converted to void*.
2990 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2991 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2992 ConvertedType = ToType;
2993 return true;
2994 }
2995 // Blocks: A null pointer constant can be converted to a block
2996 // pointer type.
2997 if (ToType->isBlockPointerType() &&
2998 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2999 ConvertedType = ToType;
3000 return true;
3001 }
3002
3003 // If the left-hand-side is nullptr_t, the right side can be a null
3004 // pointer constant.
3005 if (ToType->isNullPtrType() &&
3006 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3007 ConvertedType = ToType;
3008 return true;
3009 }
3010
3011 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
3012 if (!ToTypePtr)
3013 return false;
3014
3015 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
3016 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3017 ConvertedType = ToType;
3018 return true;
3019 }
3020
3021 // Beyond this point, both types need to be pointers
3022 // , including objective-c pointers.
3023 QualType ToPointeeType = ToTypePtr->getPointeeType();
3024 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
3025 !getLangOpts().ObjCAutoRefCount) {
3026 ConvertedType = BuildSimilarlyQualifiedPointerType(
3027 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
3028 Context);
3029 return true;
3030 }
3031 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
3032 if (!FromTypePtr)
3033 return false;
3034
3035 QualType FromPointeeType = FromTypePtr->getPointeeType();
3036
3037 // If the unqualified pointee types are the same, this can't be a
3038 // pointer conversion, so don't do all of the work below.
3039 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
3040 return false;
3041
3042 // An rvalue of type "pointer to cv T," where T is an object type,
3043 // can be converted to an rvalue of type "pointer to cv void" (C++
3044 // 4.10p2).
3045 if (FromPointeeType->isIncompleteOrObjectType() &&
3046 ToPointeeType->isVoidType()) {
3047 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3048 ToPointeeType,
3049 ToType, Context,
3050 /*StripObjCLifetime=*/true);
3051 return true;
3052 }
3053
3054 // MSVC allows implicit function to void* type conversion.
3055 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
3056 ToPointeeType->isVoidType()) {
3057 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3058 ToPointeeType,
3059 ToType, Context);
3060 return true;
3061 }
3062
3063 // When we're overloading in C, we allow a special kind of pointer
3064 // conversion for compatible-but-not-identical pointee types.
3065 if (!getLangOpts().CPlusPlus &&
3066 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
3067 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3068 ToPointeeType,
3069 ToType, Context);
3070 return true;
3071 }
3072
3073 // C++ [conv.ptr]p3:
3074 //
3075 // An rvalue of type "pointer to cv D," where D is a class type,
3076 // can be converted to an rvalue of type "pointer to cv B," where
3077 // B is a base class (clause 10) of D. If B is an inaccessible
3078 // (clause 11) or ambiguous (10.2) base class of D, a program that
3079 // necessitates this conversion is ill-formed. The result of the
3080 // conversion is a pointer to the base class sub-object of the
3081 // derived class object. The null pointer value is converted to
3082 // the null pointer value of the destination type.
3083 //
3084 // Note that we do not check for ambiguity or inaccessibility
3085 // here. That is handled by CheckPointerConversion.
3086 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3087 ToPointeeType->isRecordType() &&
3088 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
3089 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
3090 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3091 ToPointeeType,
3092 ToType, Context);
3093 return true;
3094 }
3095
3096 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3097 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
3098 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3099 ToPointeeType,
3100 ToType, Context);
3101 return true;
3102 }
3103
3104 return false;
3105}
3106
3107/// Adopt the given qualifiers for the given type.
3109 Qualifiers TQs = T.getQualifiers();
3110
3111 // Check whether qualifiers already match.
3112 if (TQs == Qs)
3113 return T;
3114
3115 if (Qs.compatiblyIncludes(TQs, Context))
3116 return Context.getQualifiedType(T, Qs);
3117
3118 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
3119}
3120
3122 QualType& ConvertedType,
3123 bool &IncompatibleObjC) {
3124 if (!getLangOpts().ObjC)
3125 return false;
3126
3127 // The set of qualifiers on the type we're converting from.
3128 Qualifiers FromQualifiers = FromType.getQualifiers();
3129
3130 // First, we handle all conversions on ObjC object pointer types.
3131 const ObjCObjectPointerType* ToObjCPtr =
3132 ToType->getAs<ObjCObjectPointerType>();
3133 const ObjCObjectPointerType *FromObjCPtr =
3134 FromType->getAs<ObjCObjectPointerType>();
3135
3136 if (ToObjCPtr && FromObjCPtr) {
3137 // If the pointee types are the same (ignoring qualifications),
3138 // then this is not a pointer conversion.
3139 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
3140 FromObjCPtr->getPointeeType()))
3141 return false;
3142
3143 // Conversion between Objective-C pointers.
3144 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3145 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3146 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3147 if (getLangOpts().CPlusPlus && LHS && RHS &&
3149 FromObjCPtr->getPointeeType(), getASTContext()))
3150 return false;
3151 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3152 ToObjCPtr->getPointeeType(),
3153 ToType, Context);
3154 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3155 return true;
3156 }
3157
3158 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3159 // Okay: this is some kind of implicit downcast of Objective-C
3160 // interfaces, which is permitted. However, we're going to
3161 // complain about it.
3162 IncompatibleObjC = true;
3163 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3164 ToObjCPtr->getPointeeType(),
3165 ToType, Context);
3166 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3167 return true;
3168 }
3169 }
3170 // Beyond this point, both types need to be C pointers or block pointers.
3171 QualType ToPointeeType;
3172 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3173 ToPointeeType = ToCPtr->getPointeeType();
3174 else if (const BlockPointerType *ToBlockPtr =
3175 ToType->getAs<BlockPointerType>()) {
3176 // Objective C++: We're able to convert from a pointer to any object
3177 // to a block pointer type.
3178 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3179 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3180 return true;
3181 }
3182 ToPointeeType = ToBlockPtr->getPointeeType();
3183 }
3184 else if (FromType->getAs<BlockPointerType>() &&
3185 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3186 // Objective C++: We're able to convert from a block pointer type to a
3187 // pointer to any object.
3188 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3189 return true;
3190 }
3191 else
3192 return false;
3193
3194 QualType FromPointeeType;
3195 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3196 FromPointeeType = FromCPtr->getPointeeType();
3197 else if (const BlockPointerType *FromBlockPtr =
3198 FromType->getAs<BlockPointerType>())
3199 FromPointeeType = FromBlockPtr->getPointeeType();
3200 else
3201 return false;
3202
3203 // If we have pointers to pointers, recursively check whether this
3204 // is an Objective-C conversion.
3205 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3206 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3207 IncompatibleObjC)) {
3208 // We always complain about this conversion.
3209 IncompatibleObjC = true;
3210 ConvertedType = Context.getPointerType(ConvertedType);
3211 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3212 return true;
3213 }
3214 // Allow conversion of pointee being objective-c pointer to another one;
3215 // as in I* to id.
3216 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3217 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3218 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3219 IncompatibleObjC)) {
3220
3221 ConvertedType = Context.getPointerType(ConvertedType);
3222 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3223 return true;
3224 }
3225
3226 // If we have pointers to functions or blocks, check whether the only
3227 // differences in the argument and result types are in Objective-C
3228 // pointer conversions. If so, we permit the conversion (but
3229 // complain about it).
3230 const FunctionProtoType *FromFunctionType
3231 = FromPointeeType->getAs<FunctionProtoType>();
3232 const FunctionProtoType *ToFunctionType
3233 = ToPointeeType->getAs<FunctionProtoType>();
3234 if (FromFunctionType && ToFunctionType) {
3235 // If the function types are exactly the same, this isn't an
3236 // Objective-C pointer conversion.
3237 if (Context.getCanonicalType(FromPointeeType)
3238 == Context.getCanonicalType(ToPointeeType))
3239 return false;
3240
3241 // Perform the quick checks that will tell us whether these
3242 // function types are obviously different.
3243 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3244 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3245 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3246 return false;
3247
3248 bool HasObjCConversion = false;
3249 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3250 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3251 // Okay, the types match exactly. Nothing to do.
3252 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3253 ToFunctionType->getReturnType(),
3254 ConvertedType, IncompatibleObjC)) {
3255 // Okay, we have an Objective-C pointer conversion.
3256 HasObjCConversion = true;
3257 } else {
3258 // Function types are too different. Abort.
3259 return false;
3260 }
3261
3262 // Check argument types.
3263 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3264 ArgIdx != NumArgs; ++ArgIdx) {
3265 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3266 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3267 if (Context.getCanonicalType(FromArgType)
3268 == Context.getCanonicalType(ToArgType)) {
3269 // Okay, the types match exactly. Nothing to do.
3270 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3271 ConvertedType, IncompatibleObjC)) {
3272 // Okay, we have an Objective-C pointer conversion.
3273 HasObjCConversion = true;
3274 } else {
3275 // Argument types are too different. Abort.
3276 return false;
3277 }
3278 }
3279
3280 if (HasObjCConversion) {
3281 // We had an Objective-C conversion. Allow this pointer
3282 // conversion, but complain about it.
3283 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3284 IncompatibleObjC = true;
3285 return true;
3286 }
3287 }
3288
3289 return false;
3290}
3291
3293 QualType& ConvertedType) {
3294 QualType ToPointeeType;
3295 if (const BlockPointerType *ToBlockPtr =
3296 ToType->getAs<BlockPointerType>())
3297 ToPointeeType = ToBlockPtr->getPointeeType();
3298 else
3299 return false;
3300
3301 QualType FromPointeeType;
3302 if (const BlockPointerType *FromBlockPtr =
3303 FromType->getAs<BlockPointerType>())
3304 FromPointeeType = FromBlockPtr->getPointeeType();
3305 else
3306 return false;
3307 // We have pointer to blocks, check whether the only
3308 // differences in the argument and result types are in Objective-C
3309 // pointer conversions. If so, we permit the conversion.
3310
3311 const FunctionProtoType *FromFunctionType
3312 = FromPointeeType->getAs<FunctionProtoType>();
3313 const FunctionProtoType *ToFunctionType
3314 = ToPointeeType->getAs<FunctionProtoType>();
3315
3316 if (!FromFunctionType || !ToFunctionType)
3317 return false;
3318
3319 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3320 return true;
3321
3322 // Perform the quick checks that will tell us whether these
3323 // function types are obviously different.
3324 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3325 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3326 return false;
3327
3328 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3329 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3330 if (FromEInfo != ToEInfo)
3331 return false;
3332
3333 bool IncompatibleObjC = false;
3334 if (Context.hasSameType(FromFunctionType->getReturnType(),
3335 ToFunctionType->getReturnType())) {
3336 // Okay, the types match exactly. Nothing to do.
3337 } else {
3338 QualType RHS = FromFunctionType->getReturnType();
3339 QualType LHS = ToFunctionType->getReturnType();
3340 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3341 !RHS.hasQualifiers() && LHS.hasQualifiers())
3342 LHS = LHS.getUnqualifiedType();
3343
3344 if (Context.hasSameType(RHS,LHS)) {
3345 // OK exact match.
3346 } else if (isObjCPointerConversion(RHS, LHS,
3347 ConvertedType, IncompatibleObjC)) {
3348 if (IncompatibleObjC)
3349 return false;
3350 // Okay, we have an Objective-C pointer conversion.
3351 }
3352 else
3353 return false;
3354 }
3355
3356 // Check argument types.
3357 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3358 ArgIdx != NumArgs; ++ArgIdx) {
3359 IncompatibleObjC = false;
3360 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3361 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3362 if (Context.hasSameType(FromArgType, ToArgType)) {
3363 // Okay, the types match exactly. Nothing to do.
3364 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3365 ConvertedType, IncompatibleObjC)) {
3366 if (IncompatibleObjC)
3367 return false;
3368 // Okay, we have an Objective-C pointer conversion.
3369 } else
3370 // Argument types are too different. Abort.
3371 return false;
3372 }
3373
3375 bool CanUseToFPT, CanUseFromFPT;
3376 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3377 CanUseToFPT, CanUseFromFPT,
3378 NewParamInfos))
3379 return false;
3380
3381 ConvertedType = ToType;
3382 return true;
3383}
3384
3385enum {
3393};
3394
3395/// Attempts to get the FunctionProtoType from a Type. Handles
3396/// MemberFunctionPointers properly.
3398 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3399 return FPT;
3400
3401 if (auto *MPT = FromType->getAs<MemberPointerType>())
3402 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3403
3404 return nullptr;
3405}
3406
3408 QualType FromType, QualType ToType) {
3409 // If either type is not valid, include no extra info.
3410 if (FromType.isNull() || ToType.isNull()) {
3411 PDiag << ft_default;
3412 return;
3413 }
3414
3415 // Get the function type from the pointers.
3416 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3417 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3418 *ToMember = ToType->castAs<MemberPointerType>();
3419 if (!declaresSameEntity(FromMember->getMostRecentCXXRecordDecl(),
3420 ToMember->getMostRecentCXXRecordDecl())) {
3422 if (ToMember->isSugared())
3423 PDiag << Context.getCanonicalTagType(
3424 ToMember->getMostRecentCXXRecordDecl());
3425 else
3426 PDiag << ToMember->getQualifier();
3427 if (FromMember->isSugared())
3428 PDiag << Context.getCanonicalTagType(
3429 FromMember->getMostRecentCXXRecordDecl());
3430 else
3431 PDiag << FromMember->getQualifier();
3432 return;
3433 }
3434 FromType = FromMember->getPointeeType();
3435 ToType = ToMember->getPointeeType();
3436 }
3437
3438 if (FromType->isPointerType())
3439 FromType = FromType->getPointeeType();
3440 if (ToType->isPointerType())
3441 ToType = ToType->getPointeeType();
3442
3443 // Remove references.
3444 FromType = FromType.getNonReferenceType();
3445 ToType = ToType.getNonReferenceType();
3446
3447 // Don't print extra info for non-specialized template functions.
3448 if (FromType->isInstantiationDependentType() &&
3449 !FromType->getAs<TemplateSpecializationType>()) {
3450 PDiag << ft_default;
3451 return;
3452 }
3453
3454 // No extra info for same types.
3455 if (Context.hasSameType(FromType, ToType)) {
3456 PDiag << ft_default;
3457 return;
3458 }
3459
3460 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3461 *ToFunction = tryGetFunctionProtoType(ToType);
3462
3463 // Both types need to be function types.
3464 if (!FromFunction || !ToFunction) {
3465 PDiag << ft_default;
3466 return;
3467 }
3468
3469 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3470 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3471 << FromFunction->getNumParams();
3472 return;
3473 }
3474
3475 // Handle different parameter types.
3476 unsigned ArgPos;
3477 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3478 PDiag << ft_parameter_mismatch << ArgPos + 1
3479 << ToFunction->getParamType(ArgPos)
3480 << FromFunction->getParamType(ArgPos);
3481 return;
3482 }
3483
3484 // Handle different return type.
3485 if (!Context.hasSameType(FromFunction->getReturnType(),
3486 ToFunction->getReturnType())) {
3487 PDiag << ft_return_type << ToFunction->getReturnType()
3488 << FromFunction->getReturnType();
3489 return;
3490 }
3491
3492 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3493 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3494 << FromFunction->getMethodQuals();
3495 return;
3496 }
3497
3498 // Handle exception specification differences on canonical type (in C++17
3499 // onwards).
3501 ->isNothrow() !=
3502 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3503 ->isNothrow()) {
3504 PDiag << ft_noexcept;
3505 return;
3506 }
3507
3508 // Unable to find a difference, so add no extra info.
3509 PDiag << ft_default;
3510}
3511
3513 ArrayRef<QualType> New, unsigned *ArgPos,
3514 bool Reversed) {
3515 assert(llvm::size(Old) == llvm::size(New) &&
3516 "Can't compare parameters of functions with different number of "
3517 "parameters!");
3518
3519 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3520 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3521 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3522
3523 // Ignore address spaces in pointee type. This is to disallow overloading
3524 // on __ptr32/__ptr64 address spaces.
3525 QualType OldType =
3526 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3527 QualType NewType =
3528 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3529
3530 if (!Context.hasSameType(OldType, NewType)) {
3531 if (ArgPos)
3532 *ArgPos = Idx;
3533 return false;
3534 }
3535 }
3536 return true;
3537}
3538
3540 const FunctionProtoType *NewType,
3541 unsigned *ArgPos, bool Reversed) {
3542 return FunctionParamTypesAreEqual(OldType->param_types(),
3543 NewType->param_types(), ArgPos, Reversed);
3544}
3545
3547 const FunctionDecl *NewFunction,
3548 unsigned *ArgPos,
3549 bool Reversed) {
3550
3551 if (OldFunction->getNumNonObjectParams() !=
3552 NewFunction->getNumNonObjectParams())
3553 return false;
3554
3555 unsigned OldIgnore =
3557 unsigned NewIgnore =
3559
3560 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3561 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3562
3563 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3564 NewPT->param_types().slice(NewIgnore),
3565 ArgPos, Reversed);
3566}
3567
3569 CastKind &Kind,
3570 CXXCastPath& BasePath,
3571 bool IgnoreBaseAccess,
3572 bool Diagnose) {
3573 QualType FromType = From->getType();
3574 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3575
3576 Kind = CK_BitCast;
3577
3578 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3581 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3582 DiagRuntimeBehavior(From->getExprLoc(), From,
3583 PDiag(diag::warn_impcast_bool_to_null_pointer)
3584 << ToType << From->getSourceRange());
3585 else if (!isUnevaluatedContext())
3586 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3587 << ToType << From->getSourceRange();
3588 }
3589 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3590 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3591 QualType FromPointeeType = FromPtrType->getPointeeType(),
3592 ToPointeeType = ToPtrType->getPointeeType();
3593
3594 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3595 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3596 // We must have a derived-to-base conversion. Check an
3597 // ambiguous or inaccessible conversion.
3598 unsigned InaccessibleID = 0;
3599 unsigned AmbiguousID = 0;
3600 if (Diagnose) {
3601 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3602 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3603 }
3605 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3606 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3607 &BasePath, IgnoreBaseAccess))
3608 return true;
3609
3610 // The conversion was successful.
3611 Kind = CK_DerivedToBase;
3612 }
3613
3614 if (Diagnose && !IsCStyleOrFunctionalCast &&
3615 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3616 assert(getLangOpts().MSVCCompat &&
3617 "this should only be possible with MSVCCompat!");
3618 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3619 << From->getSourceRange();
3620 }
3621 }
3622 } else if (const ObjCObjectPointerType *ToPtrType =
3623 ToType->getAs<ObjCObjectPointerType>()) {
3624 if (const ObjCObjectPointerType *FromPtrType =
3625 FromType->getAs<ObjCObjectPointerType>()) {
3626 // Objective-C++ conversions are always okay.
3627 // FIXME: We should have a different class of conversions for the
3628 // Objective-C++ implicit conversions.
3629 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3630 return false;
3631 } else if (FromType->isBlockPointerType()) {
3632 Kind = CK_BlockPointerToObjCPointerCast;
3633 } else {
3634 Kind = CK_CPointerToObjCPointerCast;
3635 }
3636 } else if (ToType->isBlockPointerType()) {
3637 if (!FromType->isBlockPointerType())
3638 Kind = CK_AnyPointerToBlockPointerCast;
3639 }
3640
3641 // We shouldn't fall into this case unless it's valid for other
3642 // reasons.
3644 Kind = CK_NullToPointer;
3645
3646 return false;
3647}
3648
3650 QualType ToType,
3651 bool InOverloadResolution,
3652 QualType &ConvertedType) {
3653 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3654 if (!ToTypePtr)
3655 return false;
3656
3657 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3659 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3661 ConvertedType = ToType;
3662 return true;
3663 }
3664
3665 // Otherwise, both types have to be member pointers.
3666 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3667 if (!FromTypePtr)
3668 return false;
3669
3670 // A pointer to member of B can be converted to a pointer to member of D,
3671 // where D is derived from B (C++ 4.11p2).
3672 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3673 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3674
3675 if (!declaresSameEntity(FromClass, ToClass) &&
3676 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3677 ConvertedType = Context.getMemberPointerType(
3678 FromTypePtr->getPointeeType(), FromTypePtr->getQualifier(), ToClass);
3679 return true;
3680 }
3681
3682 return false;
3683}
3684
3686 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3687 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3688 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3689 // Lock down the inheritance model right now in MS ABI, whether or not the
3690 // pointee types are the same.
3691 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3692 (void)isCompleteType(CheckLoc, FromType);
3693 (void)isCompleteType(CheckLoc, QualType(ToPtrType, 0));
3694 }
3695
3696 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3697 if (!FromPtrType) {
3698 // This must be a null pointer to member pointer conversion
3699 Kind = CK_NullToMemberPointer;
3701 }
3702
3703 // T == T, modulo cv
3705 !Context.hasSameUnqualifiedType(FromPtrType->getPointeeType(),
3706 ToPtrType->getPointeeType()))
3708
3709 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3710 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3711
3712 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3713 const CXXRecordDecl *Cls) {
3714 if (declaresSameEntity(Qual.getAsRecordDecl(), Cls))
3715 PD << Qual;
3716 else
3717 PD << Context.getCanonicalTagType(Cls);
3718 };
3719 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3720 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3721 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3722 return PD;
3723 };
3724
3725 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3727 std::swap(Base, Derived);
3728
3729 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3730 /*DetectVirtual=*/true);
3731 if (!IsDerivedFrom(OpRange.getBegin(), Derived, Base, Paths))
3733
3734 if (Paths.isAmbiguous(Context.getCanonicalTagType(Base))) {
3735 PartialDiagnostic PD = PDiag(diag::err_ambiguous_memptr_conv);
3736 PD << int(Direction);
3737 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3738 Diag(CheckLoc, PD);
3740 }
3741
3742 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3743 PartialDiagnostic PD = PDiag(diag::err_memptr_conv_via_virtual);
3744 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3745 Diag(CheckLoc, PD);
3747 }
3748
3749 // Must be a base to derived member conversion.
3750 BuildBasePathArray(Paths, BasePath);
3752 ? CK_DerivedToBaseMemberPointer
3753 : CK_BaseToDerivedMemberPointer;
3754
3755 if (!IgnoreBaseAccess)
3756 switch (CheckBaseClassAccess(
3757 CheckLoc, Base, Derived, Paths.front(),
3759 ? diag::err_upcast_to_inaccessible_base
3760 : diag::err_downcast_from_inaccessible_base,
3761 [&](PartialDiagnostic &PD) {
3762 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3763 DerivedQual = ToPtrType->getQualifier();
3764 if (Direction == MemberPointerConversionDirection::Upcast)
3765 std::swap(BaseQual, DerivedQual);
3766 DiagCls(PD, DerivedQual, Derived);
3767 DiagCls(PD, BaseQual, Base);
3768 })) {
3770 case Sema::AR_delayed:
3771 case Sema::AR_dependent:
3772 // Optimistically assume that the delayed and dependent cases
3773 // will work out.
3774 break;
3775
3778 }
3779
3781}
3782
3783/// Determine whether the lifetime conversion between the two given
3784/// qualifiers sets is nontrivial.
3786 Qualifiers ToQuals) {
3787 // Converting anything to const __unsafe_unretained is trivial.
3788 if (ToQuals.hasConst() &&
3790 return false;
3791
3792 return true;
3793}
3794
3795/// Perform a single iteration of the loop for checking if a qualification
3796/// conversion is valid.
3797///
3798/// Specifically, check whether any change between the qualifiers of \p
3799/// FromType and \p ToType is permissible, given knowledge about whether every
3800/// outer layer is const-qualified.
3802 bool CStyle, bool IsTopLevel,
3803 bool &PreviousToQualsIncludeConst,
3804 bool &ObjCLifetimeConversion,
3805 const ASTContext &Ctx) {
3806 Qualifiers FromQuals = FromType.getQualifiers();
3807 Qualifiers ToQuals = ToType.getQualifiers();
3808
3809 // Ignore __unaligned qualifier.
3810 FromQuals.removeUnaligned();
3811
3812 // Objective-C ARC:
3813 // Check Objective-C lifetime conversions.
3814 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3815 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3816 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3817 ObjCLifetimeConversion = true;
3818 FromQuals.removeObjCLifetime();
3819 ToQuals.removeObjCLifetime();
3820 } else {
3821 // Qualification conversions cannot cast between different
3822 // Objective-C lifetime qualifiers.
3823 return false;
3824 }
3825 }
3826
3827 // Allow addition/removal of GC attributes but not changing GC attributes.
3828 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3829 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3830 FromQuals.removeObjCGCAttr();
3831 ToQuals.removeObjCGCAttr();
3832 }
3833
3834 // __ptrauth qualifiers must match exactly.
3835 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3836 return false;
3837
3838 // -- for every j > 0, if const is in cv 1,j then const is in cv
3839 // 2,j, and similarly for volatile.
3840 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3841 return false;
3842
3843 // If address spaces mismatch:
3844 // - in top level it is only valid to convert to addr space that is a
3845 // superset in all cases apart from C-style casts where we allow
3846 // conversions between overlapping address spaces.
3847 // - in non-top levels it is not a valid conversion.
3848 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3849 (!IsTopLevel ||
3850 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
3851 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
3852 return false;
3853
3854 // -- if the cv 1,j and cv 2,j are different, then const is in
3855 // every cv for 0 < k < j.
3856 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3857 !PreviousToQualsIncludeConst)
3858 return false;
3859
3860 // The following wording is from C++20, where the result of the conversion
3861 // is T3, not T2.
3862 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3863 // "array of unknown bound of"
3864 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3865 return false;
3866
3867 // -- if the resulting P3,i is different from P1,i [...], then const is
3868 // added to every cv 3_k for 0 < k < i.
3869 if (!CStyle && FromType->isConstantArrayType() &&
3870 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3871 return false;
3872
3873 // Keep track of whether all prior cv-qualifiers in the "to" type
3874 // include const.
3875 PreviousToQualsIncludeConst =
3876 PreviousToQualsIncludeConst && ToQuals.hasConst();
3877 return true;
3878}
3879
3880bool
3882 bool CStyle, bool &ObjCLifetimeConversion) {
3883 FromType = Context.getCanonicalType(FromType);
3884 ToType = Context.getCanonicalType(ToType);
3885 ObjCLifetimeConversion = false;
3886
3887 // If FromType and ToType are the same type, this is not a
3888 // qualification conversion.
3889 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3890 return false;
3891
3892 // (C++ 4.4p4):
3893 // A conversion can add cv-qualifiers at levels other than the first
3894 // in multi-level pointers, subject to the following rules: [...]
3895 bool PreviousToQualsIncludeConst = true;
3896 bool UnwrappedAnyPointer = false;
3897 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3898 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3899 !UnwrappedAnyPointer,
3900 PreviousToQualsIncludeConst,
3901 ObjCLifetimeConversion, getASTContext()))
3902 return false;
3903 UnwrappedAnyPointer = true;
3904 }
3905
3906 // We are left with FromType and ToType being the pointee types
3907 // after unwrapping the original FromType and ToType the same number
3908 // of times. If we unwrapped any pointers, and if FromType and
3909 // ToType have the same unqualified type (since we checked
3910 // qualifiers above), then this is a qualification conversion.
3911 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3912}
3913
3914/// - Determine whether this is a conversion from a scalar type to an
3915/// atomic type.
3916///
3917/// If successful, updates \c SCS's second and third steps in the conversion
3918/// sequence to finish the conversion.
3919static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3920 bool InOverloadResolution,
3922 bool CStyle) {
3923 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3924 if (!ToAtomic)
3925 return false;
3926
3928 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3929 InOverloadResolution, InnerSCS,
3930 CStyle, /*AllowObjCWritebackConversion=*/false))
3931 return false;
3932
3933 SCS.Second = InnerSCS.Second;
3934 SCS.setToType(1, InnerSCS.getToType(1));
3935 SCS.Third = InnerSCS.Third;
3938 SCS.setToType(2, InnerSCS.getToType(2));
3939 return true;
3940}
3941
3944 QualType Type) {
3945 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3946 if (CtorType->getNumParams() > 0) {
3947 QualType FirstArg = CtorType->getParamType(0);
3948 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3949 return true;
3950 }
3951 return false;
3952}
3953
3954static OverloadingResult
3956 CXXRecordDecl *To,
3958 OverloadCandidateSet &CandidateSet,
3959 bool AllowExplicit) {
3961 for (auto *D : S.LookupConstructors(To)) {
3962 auto Info = getConstructorInfo(D);
3963 if (!Info)
3964 continue;
3965
3966 bool Usable = !Info.Constructor->isInvalidDecl() &&
3967 S.isInitListConstructor(Info.Constructor);
3968 if (Usable) {
3969 bool SuppressUserConversions = false;
3970 if (Info.ConstructorTmpl)
3971 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3972 /*ExplicitArgs*/ nullptr, From,
3973 CandidateSet, SuppressUserConversions,
3974 /*PartialOverloading*/ false,
3975 AllowExplicit);
3976 else
3977 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3978 CandidateSet, SuppressUserConversions,
3979 /*PartialOverloading*/ false, AllowExplicit);
3980 }
3981 }
3982
3983 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3984
3986 switch (auto Result =
3987 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3988 case OR_Deleted:
3989 case OR_Success: {
3990 // Record the standard conversion we used and the conversion function.
3992 QualType ThisType = Constructor->getFunctionObjectParameterType();
3993 // Initializer lists don't have conversions as such.
3995 User.HadMultipleCandidates = HadMultipleCandidates;
3997 User.FoundConversionFunction = Best->FoundDecl;
3999 User.After.setFromType(ThisType);
4000 User.After.setAllToTypes(ToType);
4001 return Result;
4002 }
4003
4005 return OR_No_Viable_Function;
4006 case OR_Ambiguous:
4007 return OR_Ambiguous;
4008 }
4009
4010 llvm_unreachable("Invalid OverloadResult!");
4011}
4012
4013/// Determines whether there is a user-defined conversion sequence
4014/// (C++ [over.ics.user]) that converts expression From to the type
4015/// ToType. If such a conversion exists, User will contain the
4016/// user-defined conversion sequence that performs such a conversion
4017/// and this routine will return true. Otherwise, this routine returns
4018/// false and User is unspecified.
4019///
4020/// \param AllowExplicit true if the conversion should consider C++0x
4021/// "explicit" conversion functions as well as non-explicit conversion
4022/// functions (C++0x [class.conv.fct]p2).
4023///
4024/// \param AllowObjCConversionOnExplicit true if the conversion should
4025/// allow an extra Objective-C pointer conversion on uses of explicit
4026/// constructors. Requires \c AllowExplicit to also be set.
4027static OverloadingResult
4030 OverloadCandidateSet &CandidateSet,
4031 AllowedExplicit AllowExplicit,
4032 bool AllowObjCConversionOnExplicit) {
4033 assert(AllowExplicit != AllowedExplicit::None ||
4034 !AllowObjCConversionOnExplicit);
4036
4037 // Whether we will only visit constructors.
4038 bool ConstructorsOnly = false;
4039
4040 // If the type we are conversion to is a class type, enumerate its
4041 // constructors.
4042 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
4043 // C++ [over.match.ctor]p1:
4044 // When objects of class type are direct-initialized (8.5), or
4045 // copy-initialized from an expression of the same or a
4046 // derived class type (8.5), overload resolution selects the
4047 // constructor. [...] For copy-initialization, the candidate
4048 // functions are all the converting constructors (12.3.1) of
4049 // that class. The argument list is the expression-list within
4050 // the parentheses of the initializer.
4051 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
4052 (From->getType()->isRecordType() &&
4053 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
4054 ConstructorsOnly = true;
4055
4056 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
4057 // We're not going to find any constructors.
4058 } else if (auto *ToRecordDecl =
4059 dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
4060 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
4061
4062 Expr **Args = &From;
4063 unsigned NumArgs = 1;
4064 bool ListInitializing = false;
4065 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
4066 // But first, see if there is an init-list-constructor that will work.
4068 S, From, ToType, ToRecordDecl, User, CandidateSet,
4069 AllowExplicit == AllowedExplicit::All);
4070 if (Result != OR_No_Viable_Function)
4071 return Result;
4072 // Never mind.
4073 CandidateSet.clear(
4075
4076 // If we're list-initializing, we pass the individual elements as
4077 // arguments, not the entire list.
4078 Args = InitList->getInits();
4079 NumArgs = InitList->getNumInits();
4080 ListInitializing = true;
4081 }
4082
4083 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
4084 auto Info = getConstructorInfo(D);
4085 if (!Info)
4086 continue;
4087
4088 bool Usable = !Info.Constructor->isInvalidDecl();
4089 if (!ListInitializing)
4090 Usable = Usable && Info.Constructor->isConvertingConstructor(
4091 /*AllowExplicit*/ true);
4092 if (Usable) {
4093 bool SuppressUserConversions = !ConstructorsOnly;
4094 // C++20 [over.best.ics.general]/4.5:
4095 // if the target is the first parameter of a constructor [of class
4096 // X] and the constructor [...] is a candidate by [...] the second
4097 // phase of [over.match.list] when the initializer list has exactly
4098 // one element that is itself an initializer list, [...] and the
4099 // conversion is to X or reference to cv X, user-defined conversion
4100 // sequences are not considered.
4101 if (SuppressUserConversions && ListInitializing) {
4102 SuppressUserConversions =
4103 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
4104 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
4105 ToType);
4106 }
4107 if (Info.ConstructorTmpl)
4109 Info.ConstructorTmpl, Info.FoundDecl,
4110 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
4111 CandidateSet, SuppressUserConversions,
4112 /*PartialOverloading*/ false,
4113 AllowExplicit == AllowedExplicit::All);
4114 else
4115 // Allow one user-defined conversion when user specifies a
4116 // From->ToType conversion via an static cast (c-style, etc).
4117 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4118 llvm::ArrayRef(Args, NumArgs), CandidateSet,
4119 SuppressUserConversions,
4120 /*PartialOverloading*/ false,
4121 AllowExplicit == AllowedExplicit::All);
4122 }
4123 }
4124 }
4125 }
4126
4127 // Enumerate conversion functions, if we're allowed to.
4128 if (ConstructorsOnly || isa<InitListExpr>(From)) {
4129 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
4130 // No conversion functions from incomplete types.
4131 } else if (const RecordType *FromRecordType =
4132 From->getType()->getAsCanonical<RecordType>()) {
4133 if (auto *FromRecordDecl =
4134 dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
4135 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4136 // Add all of the conversion functions as candidates.
4137 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4138 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4139 DeclAccessPair FoundDecl = I.getPair();
4140 NamedDecl *D = FoundDecl.getDecl();
4141 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
4142 if (isa<UsingShadowDecl>(D))
4143 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4144
4145 CXXConversionDecl *Conv;
4146 FunctionTemplateDecl *ConvTemplate;
4147 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
4148 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4149 else
4150 Conv = cast<CXXConversionDecl>(D);
4151
4152 if (ConvTemplate)
4154 ConvTemplate, FoundDecl, ActingContext, From, ToType,
4155 CandidateSet, AllowObjCConversionOnExplicit,
4156 AllowExplicit != AllowedExplicit::None);
4157 else
4158 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
4159 CandidateSet, AllowObjCConversionOnExplicit,
4160 AllowExplicit != AllowedExplicit::None);
4161 }
4162 }
4163 }
4164
4165 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4166
4168 switch (auto Result =
4169 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4170 case OR_Success:
4171 case OR_Deleted:
4172 // Record the standard conversion we used and the conversion function.
4174 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
4175 // C++ [over.ics.user]p1:
4176 // If the user-defined conversion is specified by a
4177 // constructor (12.3.1), the initial standard conversion
4178 // sequence converts the source type to the type required by
4179 // the argument of the constructor.
4180 //
4181 if (isa<InitListExpr>(From)) {
4182 // Initializer lists don't have conversions as such.
4184 User.Before.FromBracedInitList = true;
4185 } else {
4186 if (Best->Conversions[0].isEllipsis())
4187 User.EllipsisConversion = true;
4188 else {
4189 User.Before = Best->Conversions[0].Standard;
4190 User.EllipsisConversion = false;
4191 }
4192 }
4193 User.HadMultipleCandidates = HadMultipleCandidates;
4195 User.FoundConversionFunction = Best->FoundDecl;
4197 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4198 User.After.setAllToTypes(ToType);
4199 return Result;
4200 }
4201 if (CXXConversionDecl *Conversion
4202 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4203
4204 assert(Best->HasFinalConversion);
4205
4206 // C++ [over.ics.user]p1:
4207 //
4208 // [...] If the user-defined conversion is specified by a
4209 // conversion function (12.3.2), the initial standard
4210 // conversion sequence converts the source type to the
4211 // implicit object parameter of the conversion function.
4212 User.Before = Best->Conversions[0].Standard;
4213 User.HadMultipleCandidates = HadMultipleCandidates;
4214 User.ConversionFunction = Conversion;
4215 User.FoundConversionFunction = Best->FoundDecl;
4216 User.EllipsisConversion = false;
4217
4218 // C++ [over.ics.user]p2:
4219 // The second standard conversion sequence converts the
4220 // result of the user-defined conversion to the target type
4221 // for the sequence. Since an implicit conversion sequence
4222 // is an initialization, the special rules for
4223 // initialization by user-defined conversion apply when
4224 // selecting the best user-defined conversion for a
4225 // user-defined conversion sequence (see 13.3.3 and
4226 // 13.3.3.1).
4227 User.After = Best->FinalConversion;
4228 return Result;
4229 }
4230 llvm_unreachable("Not a constructor or conversion function?");
4231
4233 return OR_No_Viable_Function;
4234
4235 case OR_Ambiguous:
4236 return OR_Ambiguous;
4237 }
4238
4239 llvm_unreachable("Invalid OverloadResult!");
4240}
4241
4242bool
4245 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4247 OverloadingResult OvResult =
4248 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4249 CandidateSet, AllowedExplicit::None, false);
4250
4251 if (!(OvResult == OR_Ambiguous ||
4252 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4253 return false;
4254
4255 auto Cands = CandidateSet.CompleteCandidates(
4256 *this,
4258 From);
4259 if (OvResult == OR_Ambiguous)
4260 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4261 << From->getType() << ToType << From->getSourceRange();
4262 else { // OR_No_Viable_Function && !CandidateSet.empty()
4263 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4264 diag::err_typecheck_nonviable_condition_incomplete,
4265 From->getType(), From->getSourceRange()))
4266 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4267 << false << From->getType() << From->getSourceRange() << ToType;
4268 }
4269
4270 CandidateSet.NoteCandidates(
4271 *this, From, Cands);
4272 return true;
4273}
4274
4275// Helper for compareConversionFunctions that gets the FunctionType that the
4276// conversion-operator return value 'points' to, or nullptr.
4277static const FunctionType *
4279 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4280 const PointerType *RetPtrTy =
4281 ConvFuncTy->getReturnType()->getAs<PointerType>();
4282
4283 if (!RetPtrTy)
4284 return nullptr;
4285
4286 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4287}
4288
4289/// Compare the user-defined conversion functions or constructors
4290/// of two user-defined conversion sequences to determine whether any ordering
4291/// is possible.
4294 FunctionDecl *Function2) {
4295 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4296 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4297 if (!Conv1 || !Conv2)
4299
4300 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4302
4303 // Objective-C++:
4304 // If both conversion functions are implicitly-declared conversions from
4305 // a lambda closure type to a function pointer and a block pointer,
4306 // respectively, always prefer the conversion to a function pointer,
4307 // because the function pointer is more lightweight and is more likely
4308 // to keep code working.
4309 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4310 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4311 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4312 if (Block1 != Block2)
4313 return Block1 ? ImplicitConversionSequence::Worse
4315 }
4316
4317 // In order to support multiple calling conventions for the lambda conversion
4318 // operator (such as when the free and member function calling convention is
4319 // different), prefer the 'free' mechanism, followed by the calling-convention
4320 // of operator(). The latter is in place to support the MSVC-like solution of
4321 // defining ALL of the possible conversions in regards to calling-convention.
4322 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4323 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4324
4325 if (Conv1FuncRet && Conv2FuncRet &&
4326 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4327 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4328 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4329
4330 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4331 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4332
4333 CallingConv CallOpCC =
4334 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4336 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4338 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4339
4340 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4341 for (CallingConv CC : PrefOrder) {
4342 if (Conv1CC == CC)
4344 if (Conv2CC == CC)
4346 }
4347 }
4348
4350}
4351
4358
4359/// CompareImplicitConversionSequences - Compare two implicit
4360/// conversion sequences to determine whether one is better than the
4361/// other or if they are indistinguishable (C++ 13.3.3.2).
4364 const ImplicitConversionSequence& ICS1,
4365 const ImplicitConversionSequence& ICS2)
4366{
4367 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4368 // conversion sequences (as defined in 13.3.3.1)
4369 // -- a standard conversion sequence (13.3.3.1.1) is a better
4370 // conversion sequence than a user-defined conversion sequence or
4371 // an ellipsis conversion sequence, and
4372 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4373 // conversion sequence than an ellipsis conversion sequence
4374 // (13.3.3.1.3).
4375 //
4376 // C++0x [over.best.ics]p10:
4377 // For the purpose of ranking implicit conversion sequences as
4378 // described in 13.3.3.2, the ambiguous conversion sequence is
4379 // treated as a user-defined sequence that is indistinguishable
4380 // from any other user-defined conversion sequence.
4381
4382 // String literal to 'char *' conversion has been deprecated in C++03. It has
4383 // been removed from C++11. We still accept this conversion, if it happens at
4384 // the best viable function. Otherwise, this conversion is considered worse
4385 // than ellipsis conversion. Consider this as an extension; this is not in the
4386 // standard. For example:
4387 //
4388 // int &f(...); // #1
4389 // void f(char*); // #2
4390 // void g() { int &r = f("foo"); }
4391 //
4392 // In C++03, we pick #2 as the best viable function.
4393 // In C++11, we pick #1 as the best viable function, because ellipsis
4394 // conversion is better than string-literal to char* conversion (since there
4395 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4396 // convert arguments, #2 would be the best viable function in C++11.
4397 // If the best viable function has this conversion, a warning will be issued
4398 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4399
4400 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4403 // Ill-formedness must not differ
4404 ICS1.isBad() == ICS2.isBad())
4408
4409 if (ICS1.getKindRank() < ICS2.getKindRank())
4411 if (ICS2.getKindRank() < ICS1.getKindRank())
4413
4414 // The following checks require both conversion sequences to be of
4415 // the same kind.
4416 if (ICS1.getKind() != ICS2.getKind())
4418
4421
4422 // Two implicit conversion sequences of the same form are
4423 // indistinguishable conversion sequences unless one of the
4424 // following rules apply: (C++ 13.3.3.2p3):
4425
4426 // List-initialization sequence L1 is a better conversion sequence than
4427 // list-initialization sequence L2 if:
4428 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4429 // if not that,
4430 // — L1 and L2 convert to arrays of the same element type, and either the
4431 // number of elements n_1 initialized by L1 is less than the number of
4432 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4433 // an array of unknown bound and L1 does not,
4434 // even if one of the other rules in this paragraph would otherwise apply.
4435 if (!ICS1.isBad()) {
4436 bool StdInit1 = false, StdInit2 = false;
4439 nullptr);
4442 nullptr);
4443 if (StdInit1 != StdInit2)
4444 return StdInit1 ? ImplicitConversionSequence::Better
4446
4449 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4451 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4453 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4454 CAT2->getElementType())) {
4455 // Both to arrays of the same element type
4456 if (CAT1->getSize() != CAT2->getSize())
4457 // Different sized, the smaller wins
4458 return CAT1->getSize().ult(CAT2->getSize())
4463 // One is incomplete, it loses
4467 }
4468 }
4469 }
4470
4471 if (ICS1.isStandard())
4472 // Standard conversion sequence S1 is a better conversion sequence than
4473 // standard conversion sequence S2 if [...]
4474 Result = CompareStandardConversionSequences(S, Loc,
4475 ICS1.Standard, ICS2.Standard);
4476 else if (ICS1.isUserDefined()) {
4477 // With lazy template loading, it is possible to find non-canonical
4478 // FunctionDecls, depending on when redecl chains are completed. Make sure
4479 // to compare the canonical decls of conversion functions. This avoids
4480 // ambiguity problems for templated conversion operators.
4481 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4482 if (ConvFunc1)
4483 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4484 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4485 if (ConvFunc2)
4486 ConvFunc2 = ConvFunc2->getCanonicalDecl();
4487 // User-defined conversion sequence U1 is a better conversion
4488 // sequence than another user-defined conversion sequence U2 if
4489 // they contain the same user-defined conversion function or
4490 // constructor and if the second standard conversion sequence of
4491 // U1 is better than the second standard conversion sequence of
4492 // U2 (C++ 13.3.3.2p3).
4493 if (ConvFunc1 == ConvFunc2)
4494 Result = CompareStandardConversionSequences(S, Loc,
4495 ICS1.UserDefined.After,
4496 ICS2.UserDefined.After);
4497 else
4498 Result = compareConversionFunctions(S,
4501 }
4502
4503 return Result;
4504}
4505
4506// Per 13.3.3.2p3, compare the given standard conversion sequences to
4507// determine if one is a proper subset of the other.
4510 const StandardConversionSequence& SCS1,
4511 const StandardConversionSequence& SCS2) {
4514
4515 // the identity conversion sequence is considered to be a subsequence of
4516 // any non-identity conversion sequence
4517 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4519 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4521
4522 if (SCS1.Second != SCS2.Second) {
4523 if (SCS1.Second == ICK_Identity)
4525 else if (SCS2.Second == ICK_Identity)
4527 else
4529 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4531
4532 if (SCS1.Third == SCS2.Third) {
4533 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4535 }
4536
4537 if (SCS1.Third == ICK_Identity)
4538 return Result == ImplicitConversionSequence::Worse
4541
4542 if (SCS2.Third == ICK_Identity)
4543 return Result == ImplicitConversionSequence::Better
4546
4548}
4549
4550/// Determine whether one of the given reference bindings is better
4551/// than the other based on what kind of bindings they are.
4552static bool
4554 const StandardConversionSequence &SCS2) {
4555 // C++0x [over.ics.rank]p3b4:
4556 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4557 // implicit object parameter of a non-static member function declared
4558 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4559 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4560 // lvalue reference to a function lvalue and S2 binds an rvalue
4561 // reference*.
4562 //
4563 // FIXME: Rvalue references. We're going rogue with the above edits,
4564 // because the semantics in the current C++0x working paper (N3225 at the
4565 // time of this writing) break the standard definition of std::forward
4566 // and std::reference_wrapper when dealing with references to functions.
4567 // Proposed wording changes submitted to CWG for consideration.
4570 return false;
4571
4572 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4573 SCS2.IsLvalueReference) ||
4576}
4577
4583
4584/// Returns kind of fixed enum promotion the \a SCS uses.
4585static FixedEnumPromotion
4587
4588 if (SCS.Second != ICK_Integral_Promotion)
4590
4591 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4592 if (!Enum)
4594
4595 if (!Enum->isFixed())
4597
4598 QualType UnderlyingType = Enum->getIntegerType();
4599 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4601
4603}
4604
4605/// CompareStandardConversionSequences - Compare two standard
4606/// conversion sequences to determine whether one is better than the
4607/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4610 const StandardConversionSequence& SCS1,
4611 const StandardConversionSequence& SCS2)
4612{
4613 // Standard conversion sequence S1 is a better conversion sequence
4614 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4615
4616 // -- S1 is a proper subsequence of S2 (comparing the conversion
4617 // sequences in the canonical form defined by 13.3.3.1.1,
4618 // excluding any Lvalue Transformation; the identity conversion
4619 // sequence is considered to be a subsequence of any
4620 // non-identity conversion sequence) or, if not that,
4623 return CK;
4624
4625 // -- the rank of S1 is better than the rank of S2 (by the rules
4626 // defined below), or, if not that,
4627 ImplicitConversionRank Rank1 = SCS1.getRank();
4628 ImplicitConversionRank Rank2 = SCS2.getRank();
4629 if (Rank1 < Rank2)
4631 else if (Rank2 < Rank1)
4633
4634 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4635 // are indistinguishable unless one of the following rules
4636 // applies:
4637
4638 // A conversion that is not a conversion of a pointer, or
4639 // pointer to member, to bool is better than another conversion
4640 // that is such a conversion.
4642 return SCS2.isPointerConversionToBool()
4645
4646 // C++14 [over.ics.rank]p4b2:
4647 // This is retroactively applied to C++11 by CWG 1601.
4648 //
4649 // A conversion that promotes an enumeration whose underlying type is fixed
4650 // to its underlying type is better than one that promotes to the promoted
4651 // underlying type, if the two are different.
4654 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4655 FEP1 != FEP2)
4659
4660 // C++ [over.ics.rank]p4b2:
4661 //
4662 // If class B is derived directly or indirectly from class A,
4663 // conversion of B* to A* is better than conversion of B* to
4664 // void*, and conversion of A* to void* is better than conversion
4665 // of B* to void*.
4666 bool SCS1ConvertsToVoid
4668 bool SCS2ConvertsToVoid
4670 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4671 // Exactly one of the conversion sequences is a conversion to
4672 // a void pointer; it's the worse conversion.
4673 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4675 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4676 // Neither conversion sequence converts to a void pointer; compare
4677 // their derived-to-base conversions.
4679 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4680 return DerivedCK;
4681 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4682 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4683 // Both conversion sequences are conversions to void
4684 // pointers. Compare the source types to determine if there's an
4685 // inheritance relationship in their sources.
4686 QualType FromType1 = SCS1.getFromType();
4687 QualType FromType2 = SCS2.getFromType();
4688
4689 // Adjust the types we're converting from via the array-to-pointer
4690 // conversion, if we need to.
4691 if (SCS1.First == ICK_Array_To_Pointer)
4692 FromType1 = S.Context.getArrayDecayedType(FromType1);
4693 if (SCS2.First == ICK_Array_To_Pointer)
4694 FromType2 = S.Context.getArrayDecayedType(FromType2);
4695
4696 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4697 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4698
4699 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4701 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4703
4704 // Objective-C++: If one interface is more specific than the
4705 // other, it is the better one.
4706 const ObjCObjectPointerType* FromObjCPtr1
4707 = FromType1->getAs<ObjCObjectPointerType>();
4708 const ObjCObjectPointerType* FromObjCPtr2
4709 = FromType2->getAs<ObjCObjectPointerType>();
4710 if (FromObjCPtr1 && FromObjCPtr2) {
4711 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4712 FromObjCPtr2);
4713 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4714 FromObjCPtr1);
4715 if (AssignLeft != AssignRight) {
4716 return AssignLeft? ImplicitConversionSequence::Better
4718 }
4719 }
4720 }
4721
4722 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4723 // Check for a better reference binding based on the kind of bindings.
4724 if (isBetterReferenceBindingKind(SCS1, SCS2))
4726 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4728 }
4729
4730 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4731 // bullet 3).
4733 = CompareQualificationConversions(S, SCS1, SCS2))
4734 return QualCK;
4735
4736 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4737 // C++ [over.ics.rank]p3b4:
4738 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4739 // which the references refer are the same type except for
4740 // top-level cv-qualifiers, and the type to which the reference
4741 // initialized by S2 refers is more cv-qualified than the type
4742 // to which the reference initialized by S1 refers.
4743 QualType T1 = SCS1.getToType(2);
4744 QualType T2 = SCS2.getToType(2);
4745 T1 = S.Context.getCanonicalType(T1);
4746 T2 = S.Context.getCanonicalType(T2);
4747 Qualifiers T1Quals, T2Quals;
4748 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4749 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4750 if (UnqualT1 == UnqualT2) {
4751 // Objective-C++ ARC: If the references refer to objects with different
4752 // lifetimes, prefer bindings that don't change lifetime.
4758 }
4759
4760 // If the type is an array type, promote the element qualifiers to the
4761 // type for comparison.
4762 if (isa<ArrayType>(T1) && T1Quals)
4763 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4764 if (isa<ArrayType>(T2) && T2Quals)
4765 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4766 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4768 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4770 }
4771 }
4772
4773 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4774 // floating-to-integral conversion if the integral conversion
4775 // is between types of the same size.
4776 // For example:
4777 // void f(float);
4778 // void f(int);
4779 // int main {
4780 // long a;
4781 // f(a);
4782 // }
4783 // Here, MSVC will call f(int) instead of generating a compile error
4784 // as clang will do in standard mode.
4785 if (S.getLangOpts().MSVCCompat &&
4788 SCS2.Second == ICK_Floating_Integral &&
4789 S.Context.getTypeSize(SCS1.getFromType()) ==
4790 S.Context.getTypeSize(SCS1.getToType(2)))
4792
4793 // Prefer a compatible vector conversion over a lax vector conversion
4794 // For example:
4795 //
4796 // typedef float __v4sf __attribute__((__vector_size__(16)));
4797 // void f(vector float);
4798 // void f(vector signed int);
4799 // int main() {
4800 // __v4sf a;
4801 // f(a);
4802 // }
4803 // Here, we'd like to choose f(vector float) and not
4804 // report an ambiguous call error
4805 if (SCS1.Second == ICK_Vector_Conversion &&
4806 SCS2.Second == ICK_Vector_Conversion) {
4807 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4808 SCS1.getFromType(), SCS1.getToType(2));
4809 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4810 SCS2.getFromType(), SCS2.getToType(2));
4811
4812 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4813 return SCS1IsCompatibleVectorConversion
4816 }
4817
4818 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4820 bool SCS1IsCompatibleSVEVectorConversion =
4821 S.ARM().areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4822 bool SCS2IsCompatibleSVEVectorConversion =
4823 S.ARM().areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4824
4825 if (SCS1IsCompatibleSVEVectorConversion !=
4826 SCS2IsCompatibleSVEVectorConversion)
4827 return SCS1IsCompatibleSVEVectorConversion
4830 }
4831
4832 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4834 bool SCS1IsCompatibleRVVVectorConversion =
4836 bool SCS2IsCompatibleRVVVectorConversion =
4838
4839 if (SCS1IsCompatibleRVVVectorConversion !=
4840 SCS2IsCompatibleRVVVectorConversion)
4841 return SCS1IsCompatibleRVVVectorConversion
4844 }
4846}
4847
4848/// CompareQualificationConversions - Compares two standard conversion
4849/// sequences to determine whether they can be ranked based on their
4850/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4853 const StandardConversionSequence& SCS1,
4854 const StandardConversionSequence& SCS2) {
4855 // C++ [over.ics.rank]p3:
4856 // -- S1 and S2 differ only in their qualification conversion and
4857 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4858 // [C++98]
4859 // [...] and the cv-qualification signature of type T1 is a proper subset
4860 // of the cv-qualification signature of type T2, and S1 is not the
4861 // deprecated string literal array-to-pointer conversion (4.2).
4862 // [C++2a]
4863 // [...] where T1 can be converted to T2 by a qualification conversion.
4864 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4865 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4867
4868 // FIXME: the example in the standard doesn't use a qualification
4869 // conversion (!)
4870 QualType T1 = SCS1.getToType(2);
4871 QualType T2 = SCS2.getToType(2);
4872 T1 = S.Context.getCanonicalType(T1);
4873 T2 = S.Context.getCanonicalType(T2);
4874 assert(!T1->isReferenceType() && !T2->isReferenceType());
4875 Qualifiers T1Quals, T2Quals;
4876 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4877 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4878
4879 // If the types are the same, we won't learn anything by unwrapping
4880 // them.
4881 if (UnqualT1 == UnqualT2)
4883
4884 // Don't ever prefer a standard conversion sequence that uses the deprecated
4885 // string literal array to pointer conversion.
4886 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4887 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4888
4889 // Objective-C++ ARC:
4890 // Prefer qualification conversions not involving a change in lifetime
4891 // to qualification conversions that do change lifetime.
4894 CanPick1 = false;
4897 CanPick2 = false;
4898
4899 bool ObjCLifetimeConversion;
4900 if (CanPick1 &&
4901 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4902 CanPick1 = false;
4903 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4904 // directions, so we can't short-cut this second check in general.
4905 if (CanPick2 &&
4906 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4907 CanPick2 = false;
4908
4909 if (CanPick1 != CanPick2)
4910 return CanPick1 ? ImplicitConversionSequence::Better
4913}
4914
4915/// CompareDerivedToBaseConversions - Compares two standard conversion
4916/// sequences to determine whether they can be ranked based on their
4917/// various kinds of derived-to-base conversions (C++
4918/// [over.ics.rank]p4b3). As part of these checks, we also look at
4919/// conversions between Objective-C interface types.
4922 const StandardConversionSequence& SCS1,
4923 const StandardConversionSequence& SCS2) {
4924 QualType FromType1 = SCS1.getFromType();
4925 QualType ToType1 = SCS1.getToType(1);
4926 QualType FromType2 = SCS2.getFromType();
4927 QualType ToType2 = SCS2.getToType(1);
4928
4929 // Adjust the types we're converting from via the array-to-pointer
4930 // conversion, if we need to.
4931 if (SCS1.First == ICK_Array_To_Pointer)
4932 FromType1 = S.Context.getArrayDecayedType(FromType1);
4933 if (SCS2.First == ICK_Array_To_Pointer)
4934 FromType2 = S.Context.getArrayDecayedType(FromType2);
4935
4936 // Canonicalize all of the types.
4937 FromType1 = S.Context.getCanonicalType(FromType1);
4938 ToType1 = S.Context.getCanonicalType(ToType1);
4939 FromType2 = S.Context.getCanonicalType(FromType2);
4940 ToType2 = S.Context.getCanonicalType(ToType2);
4941
4942 // C++ [over.ics.rank]p4b3:
4943 //
4944 // If class B is derived directly or indirectly from class A and
4945 // class C is derived directly or indirectly from B,
4946 //
4947 // Compare based on pointer conversions.
4948 if (SCS1.Second == ICK_Pointer_Conversion &&
4950 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4951 FromType1->isPointerType() && FromType2->isPointerType() &&
4952 ToType1->isPointerType() && ToType2->isPointerType()) {
4953 QualType FromPointee1 =
4955 QualType ToPointee1 =
4957 QualType FromPointee2 =
4959 QualType ToPointee2 =
4961
4962 // -- conversion of C* to B* is better than conversion of C* to A*,
4963 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4964 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4966 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4968 }
4969
4970 // -- conversion of B* to A* is better than conversion of C* to A*,
4971 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4972 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4974 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4976 }
4977 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4979 const ObjCObjectPointerType *FromPtr1
4980 = FromType1->getAs<ObjCObjectPointerType>();
4981 const ObjCObjectPointerType *FromPtr2
4982 = FromType2->getAs<ObjCObjectPointerType>();
4983 const ObjCObjectPointerType *ToPtr1
4984 = ToType1->getAs<ObjCObjectPointerType>();
4985 const ObjCObjectPointerType *ToPtr2
4986 = ToType2->getAs<ObjCObjectPointerType>();
4987
4988 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4989 // Apply the same conversion ranking rules for Objective-C pointer types
4990 // that we do for C++ pointers to class types. However, we employ the
4991 // Objective-C pseudo-subtyping relationship used for assignment of
4992 // Objective-C pointer types.
4993 bool FromAssignLeft
4994 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4995 bool FromAssignRight
4996 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4997 bool ToAssignLeft
4998 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4999 bool ToAssignRight
5000 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
5001
5002 // A conversion to an a non-id object pointer type or qualified 'id'
5003 // type is better than a conversion to 'id'.
5004 if (ToPtr1->isObjCIdType() &&
5005 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
5007 if (ToPtr2->isObjCIdType() &&
5008 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
5010
5011 // A conversion to a non-id object pointer type is better than a
5012 // conversion to a qualified 'id' type
5013 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
5015 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
5017
5018 // A conversion to an a non-Class object pointer type or qualified 'Class'
5019 // type is better than a conversion to 'Class'.
5020 if (ToPtr1->isObjCClassType() &&
5021 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
5023 if (ToPtr2->isObjCClassType() &&
5024 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
5026
5027 // A conversion to a non-Class object pointer type is better than a
5028 // conversion to a qualified 'Class' type.
5029 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
5031 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
5033
5034 // -- "conversion of C* to B* is better than conversion of C* to A*,"
5035 if (S.Context.hasSameType(FromType1, FromType2) &&
5036 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
5037 (ToAssignLeft != ToAssignRight)) {
5038 if (FromPtr1->isSpecialized()) {
5039 // "conversion of B<A> * to B * is better than conversion of B * to
5040 // C *.
5041 bool IsFirstSame =
5042 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
5043 bool IsSecondSame =
5044 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
5045 if (IsFirstSame) {
5046 if (!IsSecondSame)
5048 } else if (IsSecondSame)
5050 }
5051 return ToAssignLeft? ImplicitConversionSequence::Worse
5053 }
5054
5055 // -- "conversion of B* to A* is better than conversion of C* to A*,"
5056 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
5057 (FromAssignLeft != FromAssignRight))
5058 return FromAssignLeft? ImplicitConversionSequence::Better
5060 }
5061 }
5062
5063 // Ranking of member-pointer types.
5064 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
5065 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
5066 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
5067 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
5068 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
5069 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
5070 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
5071 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5072 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5073 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5074 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5075 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5076 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5077 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5079 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5081 }
5082 // conversion of B::* to C::* is better than conversion of A::* to C::*
5083 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5084 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5086 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5088 }
5089 }
5090
5091 if (SCS1.Second == ICK_Derived_To_Base) {
5092 // -- conversion of C to B is better than conversion of C to A,
5093 // -- binding of an expression of type C to a reference of type
5094 // B& is better than binding an expression of type C to a
5095 // reference of type A&,
5096 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5097 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5098 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
5100 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
5102 }
5103
5104 // -- conversion of B to A is better than conversion of C to A.
5105 // -- binding of an expression of type B to a reference of type
5106 // A& is better than binding an expression of type C to a
5107 // reference of type A&,
5108 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5109 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5110 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
5112 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
5114 }
5115 }
5116
5118}
5119
5121 if (!T.getQualifiers().hasUnaligned())
5122 return T;
5123
5124 Qualifiers Q;
5125 T = Ctx.getUnqualifiedArrayType(T, Q);
5126 Q.removeUnaligned();
5127 return Ctx.getQualifiedType(T, Q);
5128}
5129
5132 QualType OrigT1, QualType OrigT2,
5133 ReferenceConversions *ConvOut) {
5134 assert(!OrigT1->isReferenceType() &&
5135 "T1 must be the pointee type of the reference type");
5136 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5137
5138 QualType T1 = Context.getCanonicalType(OrigT1);
5139 QualType T2 = Context.getCanonicalType(OrigT2);
5140 Qualifiers T1Quals, T2Quals;
5141 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
5142 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
5143
5144 ReferenceConversions ConvTmp;
5145 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5146 Conv = ReferenceConversions();
5147
5148 // C++2a [dcl.init.ref]p4:
5149 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5150 // reference-related to "cv2 T2" if T1 is similar to T2, or
5151 // T1 is a base class of T2.
5152 // "cv1 T1" is reference-compatible with "cv2 T2" if
5153 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5154 // "pointer to cv1 T1" via a standard conversion sequence.
5155
5156 // Check for standard conversions we can apply to pointers: derived-to-base
5157 // conversions, ObjC pointer conversions, and function pointer conversions.
5158 // (Qualification conversions are checked last.)
5159 if (UnqualT1 == UnqualT2) {
5160 // Nothing to do.
5161 } else if (isCompleteType(Loc, OrigT2) &&
5162 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
5163 Conv |= ReferenceConversions::DerivedToBase;
5164 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5165 UnqualT2->isObjCObjectOrInterfaceType() &&
5166 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
5167 Conv |= ReferenceConversions::ObjC;
5168 else if (UnqualT2->isFunctionType() &&
5169 IsFunctionConversion(UnqualT2, UnqualT1)) {
5170 Conv |= ReferenceConversions::Function;
5171 // No need to check qualifiers; function types don't have them.
5172 return Ref_Compatible;
5173 }
5174 bool ConvertedReferent = Conv != 0;
5175
5176 // We can have a qualification conversion. Compute whether the types are
5177 // similar at the same time.
5178 bool PreviousToQualsIncludeConst = true;
5179 bool TopLevel = true;
5180 do {
5181 if (T1 == T2)
5182 break;
5183
5184 // We will need a qualification conversion.
5185 Conv |= ReferenceConversions::Qualification;
5186
5187 // Track whether we performed a qualification conversion anywhere other
5188 // than the top level. This matters for ranking reference bindings in
5189 // overload resolution.
5190 if (!TopLevel)
5191 Conv |= ReferenceConversions::NestedQualification;
5192
5193 // MS compiler ignores __unaligned qualifier for references; do the same.
5194 T1 = withoutUnaligned(Context, T1);
5195 T2 = withoutUnaligned(Context, T2);
5196
5197 // If we find a qualifier mismatch, the types are not reference-compatible,
5198 // but are still be reference-related if they're similar.
5199 bool ObjCLifetimeConversion = false;
5200 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5201 PreviousToQualsIncludeConst,
5202 ObjCLifetimeConversion, getASTContext()))
5203 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5204 ? Ref_Related
5206
5207 // FIXME: Should we track this for any level other than the first?
5208 if (ObjCLifetimeConversion)
5209 Conv |= ReferenceConversions::ObjCLifetime;
5210
5211 TopLevel = false;
5212 } while (Context.UnwrapSimilarTypes(T1, T2));
5213
5214 // At this point, if the types are reference-related, we must either have the
5215 // same inner type (ignoring qualifiers), or must have already worked out how
5216 // to convert the referent.
5217 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5220}
5221
5222/// Look for a user-defined conversion to a value reference-compatible
5223/// with DeclType. Return true if something definite is found.
5224static bool
5226 QualType DeclType, SourceLocation DeclLoc,
5227 Expr *Init, QualType T2, bool AllowRvalues,
5228 bool AllowExplicit) {
5229 assert(T2->isRecordType() && "Can only find conversions of record types.");
5230 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5231 OverloadCandidateSet CandidateSet(
5233 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5234 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5235 NamedDecl *D = *I;
5237 if (isa<UsingShadowDecl>(D))
5238 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5239
5240 FunctionTemplateDecl *ConvTemplate
5241 = dyn_cast<FunctionTemplateDecl>(D);
5242 CXXConversionDecl *Conv;
5243 if (ConvTemplate)
5244 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5245 else
5246 Conv = cast<CXXConversionDecl>(D);
5247
5248 if (AllowRvalues) {
5249 // If we are initializing an rvalue reference, don't permit conversion
5250 // functions that return lvalues.
5251 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5252 const ReferenceType *RefType
5254 if (RefType && !RefType->getPointeeType()->isFunctionType())
5255 continue;
5256 }
5257
5258 if (!ConvTemplate &&
5260 DeclLoc,
5261 Conv->getConversionType()
5266 continue;
5267 } else {
5268 // If the conversion function doesn't return a reference type,
5269 // it can't be considered for this conversion. An rvalue reference
5270 // is only acceptable if its referencee is a function type.
5271
5272 const ReferenceType *RefType =
5274 if (!RefType ||
5275 (!RefType->isLValueReferenceType() &&
5276 !RefType->getPointeeType()->isFunctionType()))
5277 continue;
5278 }
5279
5280 if (ConvTemplate)
5282 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5283 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5284 else
5286 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5287 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5288 }
5289
5290 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5291
5293 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5294 case OR_Success:
5295
5296 assert(Best->HasFinalConversion);
5297
5298 // C++ [over.ics.ref]p1:
5299 //
5300 // [...] If the parameter binds directly to the result of
5301 // applying a conversion function to the argument
5302 // expression, the implicit conversion sequence is a
5303 // user-defined conversion sequence (13.3.3.1.2), with the
5304 // second standard conversion sequence either an identity
5305 // conversion or, if the conversion function returns an
5306 // entity of a type that is a derived class of the parameter
5307 // type, a derived-to-base Conversion.
5308 if (!Best->FinalConversion.DirectBinding)
5309 return false;
5310
5311 ICS.setUserDefined();
5312 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5313 ICS.UserDefined.After = Best->FinalConversion;
5314 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5315 ICS.UserDefined.ConversionFunction = Best->Function;
5316 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5317 ICS.UserDefined.EllipsisConversion = false;
5318 assert(ICS.UserDefined.After.ReferenceBinding &&
5320 "Expected a direct reference binding!");
5321 return true;
5322
5323 case OR_Ambiguous:
5324 ICS.setAmbiguous();
5325 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5326 Cand != CandidateSet.end(); ++Cand)
5327 if (Cand->Best)
5328 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5329 return true;
5330
5332 case OR_Deleted:
5333 // There was no suitable conversion, or we found a deleted
5334 // conversion; continue with other checks.
5335 return false;
5336 }
5337
5338 llvm_unreachable("Invalid OverloadResult!");
5339}
5340
5341/// Compute an implicit conversion sequence for reference
5342/// initialization.
5343static ImplicitConversionSequence
5345 SourceLocation DeclLoc,
5346 bool SuppressUserConversions,
5347 bool AllowExplicit) {
5348 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5349
5350 // Most paths end in a failed conversion.
5353
5354 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5355 QualType T2 = Init->getType();
5356
5357 // If the initializer is the address of an overloaded function, try
5358 // to resolve the overloaded function. If all goes well, T2 is the
5359 // type of the resulting function.
5360 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5363 false, Found))
5364 T2 = Fn->getType();
5365 }
5366
5367 // Compute some basic properties of the types and the initializer.
5368 bool isRValRef = DeclType->isRValueReferenceType();
5369 Expr::Classification InitCategory = Init->Classify(S.Context);
5370
5372 Sema::ReferenceCompareResult RefRelationship =
5373 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5374
5375 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5376 ICS.setStandard();
5378 // FIXME: A reference binding can be a function conversion too. We should
5379 // consider that when ordering reference-to-function bindings.
5380 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5382 : (RefConv & Sema::ReferenceConversions::ObjC)
5384 : ICK_Identity;
5386 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5387 // a reference binding that performs a non-top-level qualification
5388 // conversion as a qualification conversion, not as an identity conversion.
5389 ICS.Standard.Third = (RefConv &
5390 Sema::ReferenceConversions::NestedQualification)
5392 : ICK_Identity;
5393 ICS.Standard.setFromType(T2);
5394 ICS.Standard.setToType(0, T2);
5395 ICS.Standard.setToType(1, T1);
5396 ICS.Standard.setToType(2, T1);
5397 ICS.Standard.ReferenceBinding = true;
5398 ICS.Standard.DirectBinding = BindsDirectly;
5399 ICS.Standard.IsLvalueReference = !isRValRef;
5401 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5404 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5405 ICS.Standard.FromBracedInitList = false;
5406 ICS.Standard.CopyConstructor = nullptr;
5408 };
5409
5410 // C++0x [dcl.init.ref]p5:
5411 // A reference to type "cv1 T1" is initialized by an expression
5412 // of type "cv2 T2" as follows:
5413
5414 // -- If reference is an lvalue reference and the initializer expression
5415 if (!isRValRef) {
5416 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5417 // reference-compatible with "cv2 T2," or
5418 //
5419 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5420 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5421 // C++ [over.ics.ref]p1:
5422 // When a parameter of reference type binds directly (8.5.3)
5423 // to an argument expression, the implicit conversion sequence
5424 // is the identity conversion, unless the argument expression
5425 // has a type that is a derived class of the parameter type,
5426 // in which case the implicit conversion sequence is a
5427 // derived-to-base Conversion (13.3.3.1).
5428 SetAsReferenceBinding(/*BindsDirectly=*/true);
5429
5430 // Nothing more to do: the inaccessibility/ambiguity check for
5431 // derived-to-base conversions is suppressed when we're
5432 // computing the implicit conversion sequence (C++
5433 // [over.best.ics]p2).
5434 return ICS;
5435 }
5436
5437 // -- has a class type (i.e., T2 is a class type), where T1 is
5438 // not reference-related to T2, and can be implicitly
5439 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5440 // is reference-compatible with "cv3 T3" 92) (this
5441 // conversion is selected by enumerating the applicable
5442 // conversion functions (13.3.1.6) and choosing the best
5443 // one through overload resolution (13.3)),
5444 if (!SuppressUserConversions && T2->isRecordType() &&
5445 S.isCompleteType(DeclLoc, T2) &&
5446 RefRelationship == Sema::Ref_Incompatible) {
5447 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5448 Init, T2, /*AllowRvalues=*/false,
5449 AllowExplicit))
5450 return ICS;
5451 }
5452 }
5453
5454 // -- Otherwise, the reference shall be an lvalue reference to a
5455 // non-volatile const type (i.e., cv1 shall be const), or the reference
5456 // shall be an rvalue reference.
5457 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5458 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5460 return ICS;
5461 }
5462
5463 // -- If the initializer expression
5464 //
5465 // -- is an xvalue, class prvalue, array prvalue or function
5466 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5467 if (RefRelationship == Sema::Ref_Compatible &&
5468 (InitCategory.isXValue() ||
5469 (InitCategory.isPRValue() &&
5470 (T2->isRecordType() || T2->isArrayType())) ||
5471 (InitCategory.isLValue() && T2->isFunctionType()))) {
5472 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5473 // binding unless we're binding to a class prvalue.
5474 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5475 // allow the use of rvalue references in C++98/03 for the benefit of
5476 // standard library implementors; therefore, we need the xvalue check here.
5477 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5478 !(InitCategory.isPRValue() || T2->isRecordType()));
5479 return ICS;
5480 }
5481
5482 // -- has a class type (i.e., T2 is a class type), where T1 is not
5483 // reference-related to T2, and can be implicitly converted to
5484 // an xvalue, class prvalue, or function lvalue of type
5485 // "cv3 T3", where "cv1 T1" is reference-compatible with
5486 // "cv3 T3",
5487 //
5488 // then the reference is bound to the value of the initializer
5489 // expression in the first case and to the result of the conversion
5490 // in the second case (or, in either case, to an appropriate base
5491 // class subobject).
5492 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5493 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5494 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5495 Init, T2, /*AllowRvalues=*/true,
5496 AllowExplicit)) {
5497 // In the second case, if the reference is an rvalue reference
5498 // and the second standard conversion sequence of the
5499 // user-defined conversion sequence includes an lvalue-to-rvalue
5500 // conversion, the program is ill-formed.
5501 if (ICS.isUserDefined() && isRValRef &&
5504
5505 return ICS;
5506 }
5507
5508 // A temporary of function type cannot be created; don't even try.
5509 if (T1->isFunctionType())
5510 return ICS;
5511
5512 // -- Otherwise, a temporary of type "cv1 T1" is created and
5513 // initialized from the initializer expression using the
5514 // rules for a non-reference copy initialization (8.5). The
5515 // reference is then bound to the temporary. If T1 is
5516 // reference-related to T2, cv1 must be the same
5517 // cv-qualification as, or greater cv-qualification than,
5518 // cv2; otherwise, the program is ill-formed.
5519 if (RefRelationship == Sema::Ref_Related) {
5520 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5521 // we would be reference-compatible or reference-compatible with
5522 // added qualification. But that wasn't the case, so the reference
5523 // initialization fails.
5524 //
5525 // Note that we only want to check address spaces and cvr-qualifiers here.
5526 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5527 Qualifiers T1Quals = T1.getQualifiers();
5528 Qualifiers T2Quals = T2.getQualifiers();
5529 T1Quals.removeObjCGCAttr();
5530 T1Quals.removeObjCLifetime();
5531 T2Quals.removeObjCGCAttr();
5532 T2Quals.removeObjCLifetime();
5533 // MS compiler ignores __unaligned qualifier for references; do the same.
5534 T1Quals.removeUnaligned();
5535 T2Quals.removeUnaligned();
5536 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5537 return ICS;
5538 }
5539
5540 // If at least one of the types is a class type, the types are not
5541 // related, and we aren't allowed any user conversions, the
5542 // reference binding fails. This case is important for breaking
5543 // recursion, since TryImplicitConversion below will attempt to
5544 // create a temporary through the use of a copy constructor.
5545 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5546 (T1->isRecordType() || T2->isRecordType()))
5547 return ICS;
5548
5549 // If T1 is reference-related to T2 and the reference is an rvalue
5550 // reference, the initializer expression shall not be an lvalue.
5551 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5552 Init->Classify(S.Context).isLValue()) {
5554 return ICS;
5555 }
5556
5557 // C++ [over.ics.ref]p2:
5558 // When a parameter of reference type is not bound directly to
5559 // an argument expression, the conversion sequence is the one
5560 // required to convert the argument expression to the
5561 // underlying type of the reference according to
5562 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5563 // to copy-initializing a temporary of the underlying type with
5564 // the argument expression. Any difference in top-level
5565 // cv-qualification is subsumed by the initialization itself
5566 // and does not constitute a conversion.
5567 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5568 AllowedExplicit::None,
5569 /*InOverloadResolution=*/false,
5570 /*CStyle=*/false,
5571 /*AllowObjCWritebackConversion=*/false,
5572 /*AllowObjCConversionOnExplicit=*/false);
5573
5574 // Of course, that's still a reference binding.
5575 if (ICS.isStandard()) {
5576 ICS.Standard.ReferenceBinding = true;
5577 ICS.Standard.IsLvalueReference = !isRValRef;
5578 ICS.Standard.BindsToFunctionLvalue = false;
5579 ICS.Standard.BindsToRvalue = true;
5582 } else if (ICS.isUserDefined()) {
5583 const ReferenceType *LValRefType =
5586
5587 // C++ [over.ics.ref]p3:
5588 // Except for an implicit object parameter, for which see 13.3.1, a
5589 // standard conversion sequence cannot be formed if it requires [...]
5590 // binding an rvalue reference to an lvalue other than a function
5591 // lvalue.
5592 // Note that the function case is not possible here.
5593 if (isRValRef && LValRefType) {
5595 return ICS;
5596 }
5597
5599 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5601 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5605 }
5606
5607 return ICS;
5608}
5609
5610static ImplicitConversionSequence
5611TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5612 bool SuppressUserConversions,
5613 bool InOverloadResolution,
5614 bool AllowObjCWritebackConversion,
5615 bool AllowExplicit = false);
5616
5617/// TryListConversion - Try to copy-initialize a value of type ToType from the
5618/// initializer list From.
5619static ImplicitConversionSequence
5621 bool SuppressUserConversions,
5622 bool InOverloadResolution,
5623 bool AllowObjCWritebackConversion) {
5624 // C++11 [over.ics.list]p1:
5625 // When an argument is an initializer list, it is not an expression and
5626 // special rules apply for converting it to a parameter type.
5627
5629 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5630
5631 // We need a complete type for what follows. With one C++20 exception,
5632 // incomplete types can never be initialized from init lists.
5633 QualType InitTy = ToType;
5634 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5635 if (AT && S.getLangOpts().CPlusPlus20)
5636 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5637 // C++20 allows list initialization of an incomplete array type.
5638 InitTy = IAT->getElementType();
5639 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5640 return Result;
5641
5642 // C++20 [over.ics.list]/2:
5643 // If the initializer list is a designated-initializer-list, a conversion
5644 // is only possible if the parameter has an aggregate type
5645 //
5646 // FIXME: The exception for reference initialization here is not part of the
5647 // language rules, but follow other compilers in adding it as a tentative DR
5648 // resolution.
5649 bool IsDesignatedInit = From->hasDesignatedInit();
5650 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5651 IsDesignatedInit)
5652 return Result;
5653
5654 // Per DR1467 and DR2137:
5655 // If the parameter type is an aggregate class X and the initializer list
5656 // has a single element of type cv U, where U is X or a class derived from
5657 // X, the implicit conversion sequence is the one required to convert the
5658 // element to the parameter type.
5659 //
5660 // Otherwise, if the parameter type is a character array [... ]
5661 // and the initializer list has a single element that is an
5662 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5663 // implicit conversion sequence is the identity conversion.
5664 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5665 if (ToType->isRecordType() && ToType->isAggregateType()) {
5666 QualType InitType = From->getInit(0)->getType();
5667 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5668 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5669 return TryCopyInitialization(S, From->getInit(0), ToType,
5670 SuppressUserConversions,
5671 InOverloadResolution,
5672 AllowObjCWritebackConversion);
5673 }
5674
5675 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5676 InitializedEntity Entity =
5678 /*Consumed=*/false);
5679 if (S.CanPerformCopyInitialization(Entity, From)) {
5680 Result.setStandard();
5681 Result.Standard.setAsIdentityConversion();
5682 Result.Standard.setFromType(ToType);
5683 Result.Standard.setAllToTypes(ToType);
5684 return Result;
5685 }
5686 }
5687 }
5688
5689 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5690 // C++11 [over.ics.list]p2:
5691 // If the parameter type is std::initializer_list<X> or "array of X" and
5692 // all the elements can be implicitly converted to X, the implicit
5693 // conversion sequence is the worst conversion necessary to convert an
5694 // element of the list to X.
5695 //
5696 // C++14 [over.ics.list]p3:
5697 // Otherwise, if the parameter type is "array of N X", if the initializer
5698 // list has exactly N elements or if it has fewer than N elements and X is
5699 // default-constructible, and if all the elements of the initializer list
5700 // can be implicitly converted to X, the implicit conversion sequence is
5701 // the worst conversion necessary to convert an element of the list to X.
5702 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5703 unsigned e = From->getNumInits();
5706 QualType());
5707 QualType ContTy = ToType;
5708 bool IsUnbounded = false;
5709 if (AT) {
5710 InitTy = AT->getElementType();
5711 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5712 if (CT->getSize().ult(e)) {
5713 // Too many inits, fatally bad
5715 ToType);
5716 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5717 return Result;
5718 }
5719 if (CT->getSize().ugt(e)) {
5720 // Need an init from empty {}, is there one?
5721 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5722 From->getEndLoc());
5723 EmptyList.setType(S.Context.VoidTy);
5724 DfltElt = TryListConversion(
5725 S, &EmptyList, InitTy, SuppressUserConversions,
5726 InOverloadResolution, AllowObjCWritebackConversion);
5727 if (DfltElt.isBad()) {
5728 // No {} init, fatally bad
5730 ToType);
5731 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5732 return Result;
5733 }
5734 }
5735 } else {
5736 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5737 IsUnbounded = true;
5738 if (!e) {
5739 // Cannot convert to zero-sized.
5741 ToType);
5742 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5743 return Result;
5744 }
5745 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5746 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5748 }
5749 }
5750
5751 Result.setStandard();
5752 Result.Standard.setAsIdentityConversion();
5753 Result.Standard.setFromType(InitTy);
5754 Result.Standard.setAllToTypes(InitTy);
5755 for (unsigned i = 0; i < e; ++i) {
5756 Expr *Init = From->getInit(i);
5758 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5759 AllowObjCWritebackConversion);
5760
5761 // Keep the worse conversion seen so far.
5762 // FIXME: Sequences are not totally ordered, so 'worse' can be
5763 // ambiguous. CWG has been informed.
5765 Result) ==
5767 Result = ICS;
5768 // Bail as soon as we find something unconvertible.
5769 if (Result.isBad()) {
5770 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5771 return Result;
5772 }
5773 }
5774 }
5775
5776 // If we needed any implicit {} initialization, compare that now.
5777 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5778 // has been informed that this might not be the best thing.
5779 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5780 S, From->getEndLoc(), DfltElt, Result) ==
5782 Result = DfltElt;
5783 // Record the type being initialized so that we may compare sequences
5784 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5785 return Result;
5786 }
5787
5788 // C++14 [over.ics.list]p4:
5789 // C++11 [over.ics.list]p3:
5790 // Otherwise, if the parameter is a non-aggregate class X and overload
5791 // resolution chooses a single best constructor [...] the implicit
5792 // conversion sequence is a user-defined conversion sequence. If multiple
5793 // constructors are viable but none is better than the others, the
5794 // implicit conversion sequence is a user-defined conversion sequence.
5795 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5796 // This function can deal with initializer lists.
5797 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5798 AllowedExplicit::None,
5799 InOverloadResolution, /*CStyle=*/false,
5800 AllowObjCWritebackConversion,
5801 /*AllowObjCConversionOnExplicit=*/false);
5802 }
5803
5804 // C++14 [over.ics.list]p5:
5805 // C++11 [over.ics.list]p4:
5806 // Otherwise, if the parameter has an aggregate type which can be
5807 // initialized from the initializer list [...] the implicit conversion
5808 // sequence is a user-defined conversion sequence.
5809 if (ToType->isAggregateType()) {
5810 // Type is an aggregate, argument is an init list. At this point it comes
5811 // down to checking whether the initialization works.
5812 // FIXME: Find out whether this parameter is consumed or not.
5813 InitializedEntity Entity =
5815 /*Consumed=*/false);
5817 From)) {
5818 Result.setUserDefined();
5819 Result.UserDefined.Before.setAsIdentityConversion();
5820 // Initializer lists don't have a type.
5821 Result.UserDefined.Before.setFromType(QualType());
5822 Result.UserDefined.Before.setAllToTypes(QualType());
5823
5824 Result.UserDefined.After.setAsIdentityConversion();
5825 Result.UserDefined.After.setFromType(ToType);
5826 Result.UserDefined.After.setAllToTypes(ToType);
5827 Result.UserDefined.ConversionFunction = nullptr;
5828 }
5829 return Result;
5830 }
5831
5832 // C++14 [over.ics.list]p6:
5833 // C++11 [over.ics.list]p5:
5834 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5835 if (ToType->isReferenceType()) {
5836 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5837 // mention initializer lists in any way. So we go by what list-
5838 // initialization would do and try to extrapolate from that.
5839
5840 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5841
5842 // If the initializer list has a single element that is reference-related
5843 // to the parameter type, we initialize the reference from that.
5844 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5845 Expr *Init = From->getInit(0);
5846
5847 QualType T2 = Init->getType();
5848
5849 // If the initializer is the address of an overloaded function, try
5850 // to resolve the overloaded function. If all goes well, T2 is the
5851 // type of the resulting function.
5852 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5855 Init, ToType, false, Found))
5856 T2 = Fn->getType();
5857 }
5858
5859 // Compute some basic properties of the types and the initializer.
5860 Sema::ReferenceCompareResult RefRelationship =
5861 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5862
5863 if (RefRelationship >= Sema::Ref_Related) {
5864 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5865 SuppressUserConversions,
5866 /*AllowExplicit=*/false);
5867 }
5868 }
5869
5870 // Otherwise, we bind the reference to a temporary created from the
5871 // initializer list.
5872 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5873 InOverloadResolution,
5874 AllowObjCWritebackConversion);
5875 if (Result.isFailure())
5876 return Result;
5877 assert(!Result.isEllipsis() &&
5878 "Sub-initialization cannot result in ellipsis conversion.");
5879
5880 // Can we even bind to a temporary?
5881 if (ToType->isRValueReferenceType() ||
5882 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5883 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5884 Result.UserDefined.After;
5885 SCS.ReferenceBinding = true;
5887 SCS.BindsToRvalue = true;
5888 SCS.BindsToFunctionLvalue = false;
5891 SCS.FromBracedInitList = false;
5892
5893 } else
5895 From, ToType);
5896 return Result;
5897 }
5898
5899 // C++14 [over.ics.list]p7:
5900 // C++11 [over.ics.list]p6:
5901 // Otherwise, if the parameter type is not a class:
5902 if (!ToType->isRecordType()) {
5903 // - if the initializer list has one element that is not itself an
5904 // initializer list, the implicit conversion sequence is the one
5905 // required to convert the element to the parameter type.
5906 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
5907 // single integer.
5908 unsigned NumInits = From->getNumInits();
5909 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)) &&
5910 !isa<EmbedExpr>(From->getInit(0))) {
5911 Result = TryCopyInitialization(
5912 S, From->getInit(0), ToType, SuppressUserConversions,
5913 InOverloadResolution, AllowObjCWritebackConversion);
5914 if (Result.isStandard())
5915 Result.Standard.FromBracedInitList = true;
5916 }
5917 // - if the initializer list has no elements, the implicit conversion
5918 // sequence is the identity conversion.
5919 else if (NumInits == 0) {
5920 Result.setStandard();
5921 Result.Standard.setAsIdentityConversion();
5922 Result.Standard.setFromType(ToType);
5923 Result.Standard.setAllToTypes(ToType);
5924 }
5925 return Result;
5926 }
5927
5928 // C++14 [over.ics.list]p8:
5929 // C++11 [over.ics.list]p7:
5930 // In all cases other than those enumerated above, no conversion is possible
5931 return Result;
5932}
5933
5934/// TryCopyInitialization - Try to copy-initialize a value of type
5935/// ToType from the expression From. Return the implicit conversion
5936/// sequence required to pass this argument, which may be a bad
5937/// conversion sequence (meaning that the argument cannot be passed to
5938/// a parameter of this type). If @p SuppressUserConversions, then we
5939/// do not permit any user-defined conversion sequences.
5940static ImplicitConversionSequence
5942 bool SuppressUserConversions,
5943 bool InOverloadResolution,
5944 bool AllowObjCWritebackConversion,
5945 bool AllowExplicit) {
5946 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5947 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5948 InOverloadResolution,AllowObjCWritebackConversion);
5949
5950 if (ToType->isReferenceType())
5951 return TryReferenceInit(S, From, ToType,
5952 /*FIXME:*/ From->getBeginLoc(),
5953 SuppressUserConversions, AllowExplicit);
5954
5955 return TryImplicitConversion(S, From, ToType,
5956 SuppressUserConversions,
5957 AllowedExplicit::None,
5958 InOverloadResolution,
5959 /*CStyle=*/false,
5960 AllowObjCWritebackConversion,
5961 /*AllowObjCConversionOnExplicit=*/false);
5962}
5963
5964static bool TryCopyInitialization(const CanQualType FromQTy,
5965 const CanQualType ToQTy,
5966 Sema &S,
5967 SourceLocation Loc,
5968 ExprValueKind FromVK) {
5969 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5971 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5972
5973 return !ICS.isBad();
5974}
5975
5976/// TryObjectArgumentInitialization - Try to initialize the object
5977/// parameter of the given member function (@c Method) from the
5978/// expression @p From.
5980 Sema &S, SourceLocation Loc, QualType FromType,
5981 Expr::Classification FromClassification, CXXMethodDecl *Method,
5982 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5983 QualType ExplicitParameterType = QualType(),
5984 bool SuppressUserConversion = false) {
5985
5986 // We need to have an object of class type.
5987 if (const auto *PT = FromType->getAs<PointerType>()) {
5988 FromType = PT->getPointeeType();
5989
5990 // When we had a pointer, it's implicitly dereferenced, so we
5991 // better have an lvalue.
5992 assert(FromClassification.isLValue());
5993 }
5994
5995 auto ValueKindFromClassification = [](Expr::Classification C) {
5996 if (C.isPRValue())
5997 return clang::VK_PRValue;
5998 if (C.isXValue())
5999 return VK_XValue;
6000 return clang::VK_LValue;
6001 };
6002
6003 if (Method->isExplicitObjectMemberFunction()) {
6004 if (ExplicitParameterType.isNull())
6005 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
6006 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
6007 ValueKindFromClassification(FromClassification));
6009 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
6010 /*InOverloadResolution=*/true, false);
6011 if (ICS.isBad())
6012 ICS.Bad.FromExpr = nullptr;
6013 return ICS;
6014 }
6015
6016 assert(FromType->isRecordType());
6017
6018 CanQualType ClassType = S.Context.getCanonicalTagType(ActingContext);
6019 // C++98 [class.dtor]p2:
6020 // A destructor can be invoked for a const, volatile or const volatile
6021 // object.
6022 // C++98 [over.match.funcs]p4:
6023 // For static member functions, the implicit object parameter is considered
6024 // to match any object (since if the function is selected, the object is
6025 // discarded).
6026 Qualifiers Quals = Method->getMethodQualifiers();
6027 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
6028 Quals.addConst();
6029 Quals.addVolatile();
6030 }
6031
6032 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
6033
6034 // Set up the conversion sequence as a "bad" conversion, to allow us
6035 // to exit early.
6037
6038 // C++0x [over.match.funcs]p4:
6039 // For non-static member functions, the type of the implicit object
6040 // parameter is
6041 //
6042 // - "lvalue reference to cv X" for functions declared without a
6043 // ref-qualifier or with the & ref-qualifier
6044 // - "rvalue reference to cv X" for functions declared with the &&
6045 // ref-qualifier
6046 //
6047 // where X is the class of which the function is a member and cv is the
6048 // cv-qualification on the member function declaration.
6049 //
6050 // However, when finding an implicit conversion sequence for the argument, we
6051 // are not allowed to perform user-defined conversions
6052 // (C++ [over.match.funcs]p5). We perform a simplified version of
6053 // reference binding here, that allows class rvalues to bind to
6054 // non-constant references.
6055
6056 // First check the qualifiers.
6057 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
6058 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
6059 if (ImplicitParamType.getCVRQualifiers() !=
6060 FromTypeCanon.getLocalCVRQualifiers() &&
6061 !ImplicitParamType.isAtLeastAsQualifiedAs(
6062 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
6064 FromType, ImplicitParamType);
6065 return ICS;
6066 }
6067
6068 if (FromTypeCanon.hasAddressSpace()) {
6069 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
6070 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6071 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
6072 S.getASTContext())) {
6074 FromType, ImplicitParamType);
6075 return ICS;
6076 }
6077 }
6078
6079 // Check that we have either the same type or a derived type. It
6080 // affects the conversion rank.
6081 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
6082 ImplicitConversionKind SecondKind;
6083 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6084 SecondKind = ICK_Identity;
6085 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
6086 SecondKind = ICK_Derived_To_Base;
6087 } else if (!Method->isExplicitObjectMemberFunction()) {
6089 FromType, ImplicitParamType);
6090 return ICS;
6091 }
6092
6093 // Check the ref-qualifier.
6094 switch (Method->getRefQualifier()) {
6095 case RQ_None:
6096 // Do nothing; we don't care about lvalueness or rvalueness.
6097 break;
6098
6099 case RQ_LValue:
6100 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6101 // non-const lvalue reference cannot bind to an rvalue
6103 ImplicitParamType);
6104 return ICS;
6105 }
6106 break;
6107
6108 case RQ_RValue:
6109 if (!FromClassification.isRValue()) {
6110 // rvalue reference cannot bind to an lvalue
6112 ImplicitParamType);
6113 return ICS;
6114 }
6115 break;
6116 }
6117
6118 // Success. Mark this as a reference binding.
6119 ICS.setStandard();
6121 ICS.Standard.Second = SecondKind;
6122 ICS.Standard.setFromType(FromType);
6123 ICS.Standard.setAllToTypes(ImplicitParamType);
6124 ICS.Standard.ReferenceBinding = true;
6125 ICS.Standard.DirectBinding = true;
6126 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6127 ICS.Standard.BindsToFunctionLvalue = false;
6128 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6129 ICS.Standard.FromBracedInitList = false;
6131 = (Method->getRefQualifier() == RQ_None);
6132 return ICS;
6133}
6134
6135/// PerformObjectArgumentInitialization - Perform initialization of
6136/// the implicit object parameter for the given Method with the given
6137/// expression.
6139 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6141 QualType FromRecordType, DestType;
6142 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6143
6144 Expr::Classification FromClassification;
6145 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6146 FromRecordType = PT->getPointeeType();
6147 DestType = Method->getThisType();
6148 FromClassification = Expr::Classification::makeSimpleLValue();
6149 } else {
6150 FromRecordType = From->getType();
6151 DestType = ImplicitParamRecordType;
6152 FromClassification = From->Classify(Context);
6153
6154 // CWG2813 [expr.call]p6:
6155 // If the function is an implicit object member function, the object
6156 // expression of the class member access shall be a glvalue [...]
6157 if (From->isPRValue()) {
6158 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
6159 Method->getRefQualifier() !=
6161 }
6162 }
6163
6164 // Note that we always use the true parent context when performing
6165 // the actual argument initialization.
6167 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
6168 Method->getParent());
6169 if (ICS.isBad()) {
6170 switch (ICS.Bad.Kind) {
6172 Qualifiers FromQs = FromRecordType.getQualifiers();
6173 Qualifiers ToQs = DestType.getQualifiers();
6174 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6175 if (CVR) {
6176 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
6177 << Method->getDeclName() << FromRecordType << (CVR - 1)
6178 << From->getSourceRange();
6179 Diag(Method->getLocation(), diag::note_previous_decl)
6180 << Method->getDeclName();
6181 return ExprError();
6182 }
6183 break;
6184 }
6185
6188 bool IsRValueQualified =
6189 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6190 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
6191 << Method->getDeclName() << FromClassification.isRValue()
6192 << IsRValueQualified;
6193 Diag(Method->getLocation(), diag::note_previous_decl)
6194 << Method->getDeclName();
6195 return ExprError();
6196 }
6197
6200 break;
6201
6204 llvm_unreachable("Lists are not objects");
6205 }
6206
6207 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
6208 << ImplicitParamRecordType << FromRecordType
6209 << From->getSourceRange();
6210 }
6211
6212 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6213 ExprResult FromRes =
6214 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6215 if (FromRes.isInvalid())
6216 return ExprError();
6217 From = FromRes.get();
6218 }
6219
6220 if (!Context.hasSameType(From->getType(), DestType)) {
6221 CastKind CK;
6222 QualType PteeTy = DestType->getPointeeType();
6223 LangAS DestAS =
6224 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6225 if (FromRecordType.getAddressSpace() != DestAS)
6226 CK = CK_AddressSpaceConversion;
6227 else
6228 CK = CK_NoOp;
6229 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6230 }
6231 return From;
6232}
6233
6234/// TryContextuallyConvertToBool - Attempt to contextually convert the
6235/// expression From to bool (C++0x [conv]p3).
6238 // C++ [dcl.init]/17.8:
6239 // - Otherwise, if the initialization is direct-initialization, the source
6240 // type is std::nullptr_t, and the destination type is bool, the initial
6241 // value of the object being initialized is false.
6242 if (From->getType()->isNullPtrType())
6244 S.Context.BoolTy,
6245 From->isGLValue());
6246
6247 // All other direct-initialization of bool is equivalent to an implicit
6248 // conversion to bool in which explicit conversions are permitted.
6249 return TryImplicitConversion(S, From, S.Context.BoolTy,
6250 /*SuppressUserConversions=*/false,
6251 AllowedExplicit::Conversions,
6252 /*InOverloadResolution=*/false,
6253 /*CStyle=*/false,
6254 /*AllowObjCWritebackConversion=*/false,
6255 /*AllowObjCConversionOnExplicit=*/false);
6256}
6257
6259 if (checkPlaceholderForOverload(*this, From))
6260 return ExprError();
6261
6263 if (!ICS.isBad())
6264 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6266
6268 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6269 << From->getType() << From->getSourceRange();
6270 return ExprError();
6271}
6272
6273/// Check that the specified conversion is permitted in a converted constant
6274/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6275/// is acceptable.
6278 // Since we know that the target type is an integral or unscoped enumeration
6279 // type, most conversion kinds are impossible. All possible First and Third
6280 // conversions are fine.
6281 switch (SCS.Second) {
6282 case ICK_Identity:
6284 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6286 return true;
6287
6289 // Conversion from an integral or unscoped enumeration type to bool is
6290 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6291 // conversion, so we allow it in a converted constant expression.
6292 //
6293 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6294 // a lot of popular code. We should at least add a warning for this
6295 // (non-conforming) extension.
6297 SCS.getToType(2)->isBooleanType();
6298
6300 case ICK_Pointer_Member:
6301 // C++1z: null pointer conversions and null member pointer conversions are
6302 // only permitted if the source type is std::nullptr_t.
6303 return SCS.getFromType()->isNullPtrType();
6304
6317 case ICK_Vector_Splat:
6318 case ICK_Complex_Real:
6328 return false;
6329
6334 llvm_unreachable("found a first conversion kind in Second");
6335
6337 case ICK_Qualification:
6338 llvm_unreachable("found a third conversion kind in Second");
6339
6341 break;
6342 }
6343
6344 llvm_unreachable("unknown conversion kind");
6345}
6346
6347/// BuildConvertedConstantExpression - Check that the expression From is a
6348/// converted constant expression of type T, perform the conversion but
6349/// does not evaluate the expression
6351 QualType T, CCEKind CCE,
6352 NamedDecl *Dest,
6353 APValue &PreNarrowingValue) {
6354 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6356 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6357 "converted constant expression outside C++11 or TTP matching");
6358
6359 if (checkPlaceholderForOverload(S, From))
6360 return ExprError();
6361
6362 // C++1z [expr.const]p3:
6363 // A converted constant expression of type T is an expression,
6364 // implicitly converted to type T, where the converted
6365 // expression is a constant expression and the implicit conversion
6366 // sequence contains only [... list of conversions ...].
6368 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6370 : TryCopyInitialization(S, From, T,
6371 /*SuppressUserConversions=*/false,
6372 /*InOverloadResolution=*/false,
6373 /*AllowObjCWritebackConversion=*/false,
6374 /*AllowExplicit=*/false);
6375 StandardConversionSequence *SCS = nullptr;
6376 switch (ICS.getKind()) {
6378 SCS = &ICS.Standard;
6379 break;
6381 if (T->isRecordType())
6382 SCS = &ICS.UserDefined.Before;
6383 else
6384 SCS = &ICS.UserDefined.After;
6385 break;
6389 return S.Diag(From->getBeginLoc(),
6390 diag::err_typecheck_converted_constant_expression)
6391 << From->getType() << From->getSourceRange() << T;
6392 return ExprError();
6393
6396 llvm_unreachable("bad conversion in converted constant expression");
6397 }
6398
6399 // Check that we would only use permitted conversions.
6400 if (!CheckConvertedConstantConversions(S, *SCS)) {
6401 return S.Diag(From->getBeginLoc(),
6402 diag::err_typecheck_converted_constant_expression_disallowed)
6403 << From->getType() << From->getSourceRange() << T;
6404 }
6405 // [...] and where the reference binding (if any) binds directly.
6406 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6407 return S.Diag(From->getBeginLoc(),
6408 diag::err_typecheck_converted_constant_expression_indirect)
6409 << From->getType() << From->getSourceRange() << T;
6410 }
6411 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6412 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6413 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6414 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6415 // case explicitly.
6416 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6417 return S.Diag(From->getBeginLoc(),
6418 diag::err_reference_bind_to_bitfield_in_cce)
6419 << From->getSourceRange();
6420 }
6421
6422 // Usually we can simply apply the ImplicitConversionSequence we formed
6423 // earlier, but that's not guaranteed to work when initializing an object of
6424 // class type.
6425 ExprResult Result;
6426 bool IsTemplateArgument =
6428 if (T->isRecordType()) {
6429 assert(IsTemplateArgument &&
6430 "unexpected class type converted constant expr");
6431 Result = S.PerformCopyInitialization(
6434 SourceLocation(), From);
6435 } else {
6436 Result =
6438 }
6439 if (Result.isInvalid())
6440 return Result;
6441
6442 // C++2a [intro.execution]p5:
6443 // A full-expression is [...] a constant-expression [...]
6444 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6445 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6446 IsTemplateArgument);
6447 if (Result.isInvalid())
6448 return Result;
6449
6450 // Check for a narrowing implicit conversion.
6451 bool ReturnPreNarrowingValue = false;
6452 QualType PreNarrowingType;
6453 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6454 PreNarrowingType)) {
6456 // Implicit conversion to a narrower type, and the value is not a constant
6457 // expression. We'll diagnose this in a moment.
6458 case NK_Not_Narrowing:
6459 break;
6460
6462 if (CCE == CCEKind::ArrayBound &&
6463 PreNarrowingType->isIntegralOrEnumerationType() &&
6464 PreNarrowingValue.isInt()) {
6465 // Don't diagnose array bound narrowing here; we produce more precise
6466 // errors by allowing the un-narrowed value through.
6467 ReturnPreNarrowingValue = true;
6468 break;
6469 }
6470 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6471 << CCE << /*Constant*/ 1
6472 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6473 break;
6474
6476 // Implicit conversion to a narrower type, but the expression is
6477 // value-dependent so we can't tell whether it's actually narrowing.
6478 // For matching the parameters of a TTP, the conversion is ill-formed
6479 // if it may narrow.
6480 if (CCE != CCEKind::TempArgStrict)
6481 break;
6482 [[fallthrough]];
6483 case NK_Type_Narrowing:
6484 // FIXME: It would be better to diagnose that the expression is not a
6485 // constant expression.
6486 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6487 << CCE << /*Constant*/ 0 << From->getType() << T;
6488 break;
6489 }
6490 if (!ReturnPreNarrowingValue)
6491 PreNarrowingValue = {};
6492
6493 return Result;
6494}
6495
6496/// CheckConvertedConstantExpression - Check that the expression From is a
6497/// converted constant expression of type T, perform the conversion and produce
6498/// the converted expression, per C++11 [expr.const]p3.
6501 CCEKind CCE, bool RequireInt,
6502 NamedDecl *Dest) {
6503
6504 APValue PreNarrowingValue;
6505 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6506 PreNarrowingValue);
6507 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6508 Value = APValue();
6509 return Result;
6510 }
6511 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6512 RequireInt, PreNarrowingValue);
6513}
6514
6516 CCEKind CCE,
6517 NamedDecl *Dest) {
6518 APValue PreNarrowingValue;
6519 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6520 PreNarrowingValue);
6521}
6522
6524 APValue &Value, CCEKind CCE,
6525 NamedDecl *Dest) {
6526 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6527 Dest);
6528}
6529
6531 llvm::APSInt &Value,
6532 CCEKind CCE) {
6533 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6534
6535 APValue V;
6536 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6537 /*Dest=*/nullptr);
6538 if (!R.isInvalid() && !R.get()->isValueDependent())
6539 Value = V.getInt();
6540 return R;
6541}
6542
6545 CCEKind CCE, bool RequireInt,
6546 const APValue &PreNarrowingValue) {
6547
6548 ExprResult Result = E;
6549 // Check the expression is a constant expression.
6551 Expr::EvalResult Eval;
6552 Eval.Diag = &Notes;
6553
6554 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6555
6556 ConstantExprKind Kind;
6557 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6558 Kind = ConstantExprKind::ClassTemplateArgument;
6559 else if (CCE == CCEKind::TemplateArg)
6560 Kind = ConstantExprKind::NonClassTemplateArgument;
6561 else
6562 Kind = ConstantExprKind::Normal;
6563
6564 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6565 (RequireInt && !Eval.Val.isInt())) {
6566 // The expression can't be folded, so we can't keep it at this position in
6567 // the AST.
6568 Result = ExprError();
6569 } else {
6570 Value = Eval.Val;
6571
6572 if (Notes.empty()) {
6573 // It's a constant expression.
6574 Expr *E = Result.get();
6575 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6576 // We expect a ConstantExpr to have a value associated with it
6577 // by this point.
6578 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6579 "ConstantExpr has no value associated with it");
6580 (void)CE;
6581 } else {
6583 }
6584 if (!PreNarrowingValue.isAbsent())
6585 Value = std::move(PreNarrowingValue);
6586 return E;
6587 }
6588 }
6589
6590 // It's not a constant expression. Produce an appropriate diagnostic.
6591 if (Notes.size() == 1 &&
6592 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6593 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6594 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6595 diag::note_constexpr_invalid_template_arg) {
6596 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6597 for (unsigned I = 0; I < Notes.size(); ++I)
6598 Diag(Notes[I].first, Notes[I].second);
6599 } else {
6600 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6601 << CCE << E->getSourceRange();
6602 for (unsigned I = 0; I < Notes.size(); ++I)
6603 Diag(Notes[I].first, Notes[I].second);
6604 }
6605 return ExprError();
6606}
6607
6608/// dropPointerConversions - If the given standard conversion sequence
6609/// involves any pointer conversions, remove them. This may change
6610/// the result type of the conversion sequence.
6612 if (SCS.Second == ICK_Pointer_Conversion) {
6613 SCS.Second = ICK_Identity;
6614 SCS.Dimension = ICK_Identity;
6615 SCS.Third = ICK_Identity;
6616 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6617 }
6618}
6619
6620/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6621/// convert the expression From to an Objective-C pointer type.
6622static ImplicitConversionSequence
6624 // Do an implicit conversion to 'id'.
6627 = TryImplicitConversion(S, From, Ty,
6628 // FIXME: Are these flags correct?
6629 /*SuppressUserConversions=*/false,
6630 AllowedExplicit::Conversions,
6631 /*InOverloadResolution=*/false,
6632 /*CStyle=*/false,
6633 /*AllowObjCWritebackConversion=*/false,
6634 /*AllowObjCConversionOnExplicit=*/true);
6635
6636 // Strip off any final conversions to 'id'.
6637 switch (ICS.getKind()) {
6642 break;
6643
6646 break;
6647
6650 break;
6651 }
6652
6653 return ICS;
6654}
6655
6657 if (checkPlaceholderForOverload(*this, From))
6658 return ExprError();
6659
6660 QualType Ty = Context.getObjCIdType();
6663 if (!ICS.isBad())
6664 return PerformImplicitConversion(From, Ty, ICS,
6666 return ExprResult();
6667}
6668
6669static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6670 const Expr *Base = nullptr;
6671 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6672 "expected a member expression");
6673
6674 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6675 M && !M->isImplicitAccess())
6676 Base = M->getBase();
6677 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6678 M && !M->isImplicitAccess())
6679 Base = M->getBase();
6680
6681 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6682
6683 if (T->isPointerType())
6684 T = T->getPointeeType();
6685
6686 return T;
6687}
6688
6690 const FunctionDecl *Fun) {
6691 QualType ObjType = Obj->getType();
6692 if (ObjType->isPointerType()) {
6693 ObjType = ObjType->getPointeeType();
6694 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6696 /*CanOverflow=*/false, FPOptionsOverride());
6697 }
6698 return Obj;
6699}
6700
6708
6710 Expr *Object, MultiExprArg &Args,
6711 SmallVectorImpl<Expr *> &NewArgs) {
6712 assert(Method->isExplicitObjectMemberFunction() &&
6713 "Method is not an explicit member function");
6714 assert(NewArgs.empty() && "NewArgs should be empty");
6715
6716 NewArgs.reserve(Args.size() + 1);
6717 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6718 NewArgs.push_back(This);
6719 NewArgs.append(Args.begin(), Args.end());
6720 Args = NewArgs;
6722 Method, Object->getBeginLoc());
6723}
6724
6725/// Determine whether the provided type is an integral type, or an enumeration
6726/// type of a permitted flavor.
6728 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6729 : T->isIntegralOrUnscopedEnumerationType();
6730}
6731
6732static ExprResult
6735 QualType T, UnresolvedSetImpl &ViableConversions) {
6736
6737 if (Converter.Suppress)
6738 return ExprError();
6739
6740 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6741 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6742 CXXConversionDecl *Conv =
6743 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6745 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6746 }
6747 return From;
6748}
6749
6750static bool
6753 QualType T, bool HadMultipleCandidates,
6754 UnresolvedSetImpl &ExplicitConversions) {
6755 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6756 DeclAccessPair Found = ExplicitConversions[0];
6757 CXXConversionDecl *Conversion =
6758 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6759
6760 // The user probably meant to invoke the given explicit
6761 // conversion; use it.
6762 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6763 std::string TypeStr;
6764 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6765
6766 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6768 "static_cast<" + TypeStr + ">(")
6770 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6771 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6772
6773 // If we aren't in a SFINAE context, build a call to the
6774 // explicit conversion function.
6775 if (SemaRef.isSFINAEContext())
6776 return true;
6777
6778 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6779 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6780 HadMultipleCandidates);
6781 if (Result.isInvalid())
6782 return true;
6783
6784 // Replace the conversion with a RecoveryExpr, so we don't try to
6785 // instantiate it later, but can further diagnose here.
6786 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6787 From, Result.get()->getType());
6788 if (Result.isInvalid())
6789 return true;
6790 From = Result.get();
6791 }
6792 return false;
6793}
6794
6795static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6797 QualType T, bool HadMultipleCandidates,
6799 CXXConversionDecl *Conversion =
6800 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6801 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6802
6803 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6804 if (!Converter.SuppressConversion) {
6805 if (SemaRef.isSFINAEContext())
6806 return true;
6807
6808 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6809 << From->getSourceRange();
6810 }
6811
6812 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6813 HadMultipleCandidates);
6814 if (Result.isInvalid())
6815 return true;
6816 // Record usage of conversion in an implicit cast.
6817 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6818 CK_UserDefinedConversion, Result.get(),
6819 nullptr, Result.get()->getValueKind(),
6820 SemaRef.CurFPFeatureOverrides());
6821 return false;
6822}
6823
6825 Sema &SemaRef, SourceLocation Loc, Expr *From,
6827 if (!Converter.match(From->getType()) && !Converter.Suppress)
6828 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6829 << From->getSourceRange();
6830
6831 return SemaRef.DefaultLvalueConversion(From);
6832}
6833
6834static void
6836 UnresolvedSetImpl &ViableConversions,
6837 OverloadCandidateSet &CandidateSet) {
6838 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6839 NamedDecl *D = FoundDecl.getDecl();
6840 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6841 if (isa<UsingShadowDecl>(D))
6842 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6843
6844 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
6846 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6847 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6848 continue;
6849 }
6851 SemaRef.AddConversionCandidate(
6852 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
6853 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6854 }
6855}
6856
6857/// Attempt to convert the given expression to a type which is accepted
6858/// by the given converter.
6859///
6860/// This routine will attempt to convert an expression of class type to a
6861/// type accepted by the specified converter. In C++11 and before, the class
6862/// must have a single non-explicit conversion function converting to a matching
6863/// type. In C++1y, there can be multiple such conversion functions, but only
6864/// one target type.
6865///
6866/// \param Loc The source location of the construct that requires the
6867/// conversion.
6868///
6869/// \param From The expression we're converting from.
6870///
6871/// \param Converter Used to control and diagnose the conversion process.
6872///
6873/// \returns The expression, converted to an integral or enumeration type if
6874/// successful.
6876 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6877 // We can't perform any more checking for type-dependent expressions.
6878 if (From->isTypeDependent())
6879 return From;
6880
6881 // Process placeholders immediately.
6882 if (From->hasPlaceholderType()) {
6883 ExprResult result = CheckPlaceholderExpr(From);
6884 if (result.isInvalid())
6885 return result;
6886 From = result.get();
6887 }
6888
6889 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6890 ExprResult Converted = DefaultLvalueConversion(From);
6891 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6892 // If the expression already has a matching type, we're golden.
6893 if (Converter.match(T))
6894 return Converted;
6895
6896 // FIXME: Check for missing '()' if T is a function type?
6897
6898 // We can only perform contextual implicit conversions on objects of class
6899 // type.
6900 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
6901 if (!RecordTy || !getLangOpts().CPlusPlus) {
6902 if (!Converter.Suppress)
6903 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6904 return From;
6905 }
6906
6907 // We must have a complete class type.
6908 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6909 ContextualImplicitConverter &Converter;
6910 Expr *From;
6911
6912 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6913 : Converter(Converter), From(From) {}
6914
6915 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6916 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6917 }
6918 } IncompleteDiagnoser(Converter, From);
6919
6920 if (Converter.Suppress ? !isCompleteType(Loc, T)
6921 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6922 return From;
6923
6924 // Look for a conversion to an integral or enumeration type.
6926 ViableConversions; // These are *potentially* viable in C++1y.
6927 UnresolvedSet<4> ExplicitConversions;
6928 const auto &Conversions = cast<CXXRecordDecl>(RecordTy->getDecl())
6929 ->getDefinitionOrSelf()
6930 ->getVisibleConversionFunctions();
6931
6932 bool HadMultipleCandidates =
6933 (std::distance(Conversions.begin(), Conversions.end()) > 1);
6934
6935 // To check that there is only one target type, in C++1y:
6936 QualType ToType;
6937 bool HasUniqueTargetType = true;
6938
6939 // Collect explicit or viable (potentially in C++1y) conversions.
6940 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6941 NamedDecl *D = (*I)->getUnderlyingDecl();
6942 CXXConversionDecl *Conversion;
6943 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6944 if (ConvTemplate) {
6946 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6947 else
6948 continue; // C++11 does not consider conversion operator templates(?).
6949 } else
6950 Conversion = cast<CXXConversionDecl>(D);
6951
6952 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6953 "Conversion operator templates are considered potentially "
6954 "viable in C++1y");
6955
6956 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6957 if (Converter.match(CurToType) || ConvTemplate) {
6958
6959 if (Conversion->isExplicit()) {
6960 // FIXME: For C++1y, do we need this restriction?
6961 // cf. diagnoseNoViableConversion()
6962 if (!ConvTemplate)
6963 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6964 } else {
6965 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6966 if (ToType.isNull())
6967 ToType = CurToType.getUnqualifiedType();
6968 else if (HasUniqueTargetType &&
6969 (CurToType.getUnqualifiedType() != ToType))
6970 HasUniqueTargetType = false;
6971 }
6972 ViableConversions.addDecl(I.getDecl(), I.getAccess());
6973 }
6974 }
6975 }
6976
6977 if (getLangOpts().CPlusPlus14) {
6978 // C++1y [conv]p6:
6979 // ... An expression e of class type E appearing in such a context
6980 // is said to be contextually implicitly converted to a specified
6981 // type T and is well-formed if and only if e can be implicitly
6982 // converted to a type T that is determined as follows: E is searched
6983 // for conversion functions whose return type is cv T or reference to
6984 // cv T such that T is allowed by the context. There shall be
6985 // exactly one such T.
6986
6987 // If no unique T is found:
6988 if (ToType.isNull()) {
6989 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6990 HadMultipleCandidates,
6991 ExplicitConversions))
6992 return ExprError();
6993 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6994 }
6995
6996 // If more than one unique Ts are found:
6997 if (!HasUniqueTargetType)
6998 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6999 ViableConversions);
7000
7001 // If one unique T is found:
7002 // First, build a candidate set from the previously recorded
7003 // potentially viable conversions.
7005 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
7006 CandidateSet);
7007
7008 // Then, perform overload resolution over the candidate set.
7010 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
7011 case OR_Success: {
7012 // Apply this conversion.
7014 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
7015 if (recordConversion(*this, Loc, From, Converter, T,
7016 HadMultipleCandidates, Found))
7017 return ExprError();
7018 break;
7019 }
7020 case OR_Ambiguous:
7021 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7022 ViableConversions);
7024 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7025 HadMultipleCandidates,
7026 ExplicitConversions))
7027 return ExprError();
7028 [[fallthrough]];
7029 case OR_Deleted:
7030 // We'll complain below about a non-integral condition type.
7031 break;
7032 }
7033 } else {
7034 switch (ViableConversions.size()) {
7035 case 0: {
7036 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7037 HadMultipleCandidates,
7038 ExplicitConversions))
7039 return ExprError();
7040
7041 // We'll complain below about a non-integral condition type.
7042 break;
7043 }
7044 case 1: {
7045 // Apply this conversion.
7046 DeclAccessPair Found = ViableConversions[0];
7047 if (recordConversion(*this, Loc, From, Converter, T,
7048 HadMultipleCandidates, Found))
7049 return ExprError();
7050 break;
7051 }
7052 default:
7053 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7054 ViableConversions);
7055 }
7056 }
7057
7058 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7059}
7060
7061/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
7062/// an acceptable non-member overloaded operator for a call whose
7063/// arguments have types T1 (and, if non-empty, T2). This routine
7064/// implements the check in C++ [over.match.oper]p3b2 concerning
7065/// enumeration types.
7067 FunctionDecl *Fn,
7068 ArrayRef<Expr *> Args) {
7069 QualType T1 = Args[0]->getType();
7070 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
7071
7072 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7073 return true;
7074
7075 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7076 return true;
7077
7078 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7079 if (Proto->getNumParams() < 1)
7080 return false;
7081
7082 if (T1->isEnumeralType()) {
7083 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
7084 if (Context.hasSameUnqualifiedType(T1, ArgType))
7085 return true;
7086 }
7087
7088 if (Proto->getNumParams() < 2)
7089 return false;
7090
7091 if (!T2.isNull() && T2->isEnumeralType()) {
7092 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
7093 if (Context.hasSameUnqualifiedType(T2, ArgType))
7094 return true;
7095 }
7096
7097 return false;
7098}
7099
7102 return false;
7103
7104 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7105 return FD->isTargetMultiVersion();
7106
7107 if (!FD->isMultiVersion())
7108 return false;
7109
7110 // Among multiple target versions consider either the default,
7111 // or the first non-default in the absence of default version.
7112 unsigned SeenAt = 0;
7113 unsigned I = 0;
7114 bool HasDefault = false;
7116 FD, [&](const FunctionDecl *CurFD) {
7117 if (FD == CurFD)
7118 SeenAt = I;
7119 else if (CurFD->isTargetMultiVersionDefault())
7120 HasDefault = true;
7121 ++I;
7122 });
7123 return HasDefault || SeenAt != 0;
7124}
7125
7128 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7129 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7130 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7131 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7132 bool StrictPackMatch) {
7133 const FunctionProtoType *Proto
7134 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
7135 assert(Proto && "Functions without a prototype cannot be overloaded");
7136 assert(!Function->getDescribedFunctionTemplate() &&
7137 "Use AddTemplateOverloadCandidate for function templates");
7138
7139 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
7141 // If we get here, it's because we're calling a member function
7142 // that is named without a member access expression (e.g.,
7143 // "this->f") that was either written explicitly or created
7144 // implicitly. This can happen with a qualified call to a member
7145 // function, e.g., X::f(). We use an empty type for the implied
7146 // object argument (C++ [over.call.func]p3), and the acting context
7147 // is irrelevant.
7148 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
7150 CandidateSet, SuppressUserConversions,
7151 PartialOverloading, EarlyConversions, PO,
7152 StrictPackMatch);
7153 return;
7154 }
7155 // We treat a constructor like a non-member function, since its object
7156 // argument doesn't participate in overload resolution.
7157 }
7158
7159 if (!CandidateSet.isNewCandidate(Function, PO))
7160 return;
7161
7162 // C++11 [class.copy]p11: [DR1402]
7163 // A defaulted move constructor that is defined as deleted is ignored by
7164 // overload resolution.
7165 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
7166 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7167 Constructor->isMoveConstructor())
7168 return;
7169
7170 // Overload resolution is always an unevaluated context.
7173
7174 // C++ [over.match.oper]p3:
7175 // if no operand has a class type, only those non-member functions in the
7176 // lookup set that have a first parameter of type T1 or "reference to
7177 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7178 // is a right operand) a second parameter of type T2 or "reference to
7179 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7180 // candidate functions.
7181 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7183 return;
7184
7185 // Add this candidate
7186 OverloadCandidate &Candidate =
7187 CandidateSet.addCandidate(Args.size(), EarlyConversions);
7188 Candidate.FoundDecl = FoundDecl;
7189 Candidate.Function = Function;
7190 Candidate.Viable = true;
7191 Candidate.RewriteKind =
7192 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
7193 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
7194 Candidate.ExplicitCallArguments = Args.size();
7195 Candidate.StrictPackMatch = StrictPackMatch;
7196
7197 // Explicit functions are not actually candidates at all if we're not
7198 // allowing them in this context, but keep them around so we can point
7199 // to them in diagnostics.
7200 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7201 Candidate.Viable = false;
7202 Candidate.FailureKind = ovl_fail_explicit;
7203 return;
7204 }
7205
7206 // Functions with internal linkage are only viable in the same module unit.
7207 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7208 /// FIXME: Currently, the semantics of linkage in clang is slightly
7209 /// different from the semantics in C++ spec. In C++ spec, only names
7210 /// have linkage. So that all entities of the same should share one
7211 /// linkage. But in clang, different entities of the same could have
7212 /// different linkage.
7213 const NamedDecl *ND = Function;
7214 bool IsImplicitlyInstantiated = false;
7215 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7216 ND = SpecInfo->getTemplate();
7217 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7219 }
7220
7221 /// Don't remove inline functions with internal linkage from the overload
7222 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7223 /// However:
7224 /// - Inline functions with internal linkage are a common pattern in
7225 /// headers to avoid ODR issues.
7226 /// - The global module is meant to be a transition mechanism for C and C++
7227 /// headers, and the current rules as written work against that goal.
7228 const bool IsInlineFunctionInGMF =
7229 Function->isFromGlobalModule() &&
7230 (IsImplicitlyInstantiated || Function->isInlined());
7231
7232 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7233 Candidate.Viable = false;
7235 return;
7236 }
7237 }
7238
7240 Candidate.Viable = false;
7242 return;
7243 }
7244
7245 if (Constructor) {
7246 // C++ [class.copy]p3:
7247 // A member function template is never instantiated to perform the copy
7248 // of a class object to an object of its class type.
7249 CanQualType ClassType =
7250 Context.getCanonicalTagType(Constructor->getParent());
7251 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7252 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7253 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7254 ClassType))) {
7255 Candidate.Viable = false;
7257 return;
7258 }
7259
7260 // C++ [over.match.funcs]p8: (proposed DR resolution)
7261 // A constructor inherited from class type C that has a first parameter
7262 // of type "reference to P" (including such a constructor instantiated
7263 // from a template) is excluded from the set of candidate functions when
7264 // constructing an object of type cv D if the argument list has exactly
7265 // one argument and D is reference-related to P and P is reference-related
7266 // to C.
7267 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7268 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7269 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7270 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7271 CanQualType C = Context.getCanonicalTagType(Constructor->getParent());
7272 CanQualType D = Context.getCanonicalTagType(Shadow->getParent());
7273 SourceLocation Loc = Args.front()->getExprLoc();
7274 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7275 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7276 Candidate.Viable = false;
7278 return;
7279 }
7280 }
7281
7282 // Check that the constructor is capable of constructing an object in the
7283 // destination address space.
7285 Constructor->getMethodQualifiers().getAddressSpace(),
7286 CandidateSet.getDestAS(), getASTContext())) {
7287 Candidate.Viable = false;
7289 }
7290 }
7291
7292 unsigned NumParams = Proto->getNumParams();
7293
7294 // (C++ 13.3.2p2): A candidate function having fewer than m
7295 // parameters is viable only if it has an ellipsis in its parameter
7296 // list (8.3.5).
7297 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7298 !Proto->isVariadic() &&
7299 shouldEnforceArgLimit(PartialOverloading, Function)) {
7300 Candidate.Viable = false;
7302 return;
7303 }
7304
7305 // (C++ 13.3.2p2): A candidate function having more than m parameters
7306 // is viable only if the (m+1)st parameter has a default argument
7307 // (8.3.6). For the purposes of overload resolution, the
7308 // parameter list is truncated on the right, so that there are
7309 // exactly m parameters.
7310 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7311 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7312 !PartialOverloading) {
7313 // Not enough arguments.
7314 Candidate.Viable = false;
7316 return;
7317 }
7318
7319 // (CUDA B.1): Check for invalid calls between targets.
7320 if (getLangOpts().CUDA) {
7321 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7322 // Skip the check for callers that are implicit members, because in this
7323 // case we may not yet know what the member's target is; the target is
7324 // inferred for the member automatically, based on the bases and fields of
7325 // the class.
7326 if (!(Caller && Caller->isImplicit()) &&
7327 !CUDA().IsAllowedCall(Caller, Function)) {
7328 Candidate.Viable = false;
7329 Candidate.FailureKind = ovl_fail_bad_target;
7330 return;
7331 }
7332 }
7333
7334 if (Function->getTrailingRequiresClause()) {
7335 ConstraintSatisfaction Satisfaction;
7336 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7337 /*ForOverloadResolution*/ true) ||
7338 !Satisfaction.IsSatisfied) {
7339 Candidate.Viable = false;
7341 return;
7342 }
7343 }
7344
7345 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7346 // Determine the implicit conversion sequences for each of the
7347 // arguments.
7348 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7349 unsigned ConvIdx =
7350 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7351 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7352 // We already formed a conversion sequence for this parameter during
7353 // template argument deduction.
7354 } else if (ArgIdx < NumParams) {
7355 // (C++ 13.3.2p3): for F to be a viable function, there shall
7356 // exist for each argument an implicit conversion sequence
7357 // (13.3.3.1) that converts that argument to the corresponding
7358 // parameter of F.
7359 QualType ParamType = Proto->getParamType(ArgIdx);
7360 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7361 if (ParamABI == ParameterABI::HLSLOut ||
7362 ParamABI == ParameterABI::HLSLInOut)
7363 ParamType = ParamType.getNonReferenceType();
7364 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7365 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7366 /*InOverloadResolution=*/true,
7367 /*AllowObjCWritebackConversion=*/
7368 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7369 if (Candidate.Conversions[ConvIdx].isBad()) {
7370 Candidate.Viable = false;
7372 return;
7373 }
7374 } else {
7375 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7376 // argument for which there is no corresponding parameter is
7377 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7378 Candidate.Conversions[ConvIdx].setEllipsis();
7379 }
7380 }
7381
7382 if (EnableIfAttr *FailedAttr =
7383 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7384 Candidate.Viable = false;
7385 Candidate.FailureKind = ovl_fail_enable_if;
7386 Candidate.DeductionFailure.Data = FailedAttr;
7387 return;
7388 }
7389}
7390
7394 if (Methods.size() <= 1)
7395 return nullptr;
7396
7397 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7398 bool Match = true;
7399 ObjCMethodDecl *Method = Methods[b];
7400 unsigned NumNamedArgs = Sel.getNumArgs();
7401 // Method might have more arguments than selector indicates. This is due
7402 // to addition of c-style arguments in method.
7403 if (Method->param_size() > NumNamedArgs)
7404 NumNamedArgs = Method->param_size();
7405 if (Args.size() < NumNamedArgs)
7406 continue;
7407
7408 for (unsigned i = 0; i < NumNamedArgs; i++) {
7409 // We can't do any type-checking on a type-dependent argument.
7410 if (Args[i]->isTypeDependent()) {
7411 Match = false;
7412 break;
7413 }
7414
7415 ParmVarDecl *param = Method->parameters()[i];
7416 Expr *argExpr = Args[i];
7417 assert(argExpr && "SelectBestMethod(): missing expression");
7418
7419 // Strip the unbridged-cast placeholder expression off unless it's
7420 // a consumed argument.
7421 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7422 !param->hasAttr<CFConsumedAttr>())
7423 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7424
7425 // If the parameter is __unknown_anytype, move on to the next method.
7426 if (param->getType() == Context.UnknownAnyTy) {
7427 Match = false;
7428 break;
7429 }
7430
7431 ImplicitConversionSequence ConversionState
7432 = TryCopyInitialization(*this, argExpr, param->getType(),
7433 /*SuppressUserConversions*/false,
7434 /*InOverloadResolution=*/true,
7435 /*AllowObjCWritebackConversion=*/
7436 getLangOpts().ObjCAutoRefCount,
7437 /*AllowExplicit*/false);
7438 // This function looks for a reasonably-exact match, so we consider
7439 // incompatible pointer conversions to be a failure here.
7440 if (ConversionState.isBad() ||
7441 (ConversionState.isStandard() &&
7442 ConversionState.Standard.Second ==
7444 Match = false;
7445 break;
7446 }
7447 }
7448 // Promote additional arguments to variadic methods.
7449 if (Match && Method->isVariadic()) {
7450 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7451 if (Args[i]->isTypeDependent()) {
7452 Match = false;
7453 break;
7454 }
7456 Args[i], VariadicCallType::Method, nullptr);
7457 if (Arg.isInvalid()) {
7458 Match = false;
7459 break;
7460 }
7461 }
7462 } else {
7463 // Check for extra arguments to non-variadic methods.
7464 if (Args.size() != NumNamedArgs)
7465 Match = false;
7466 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7467 // Special case when selectors have no argument. In this case, select
7468 // one with the most general result type of 'id'.
7469 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7470 QualType ReturnT = Methods[b]->getReturnType();
7471 if (ReturnT->isObjCIdType())
7472 return Methods[b];
7473 }
7474 }
7475 }
7476
7477 if (Match)
7478 return Method;
7479 }
7480 return nullptr;
7481}
7482
7484 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7485 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7486 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7487 if (ThisArg) {
7488 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7489 assert(!isa<CXXConstructorDecl>(Method) &&
7490 "Shouldn't have `this` for ctors!");
7491 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7493 ThisArg, /*Qualifier=*/std::nullopt, Method, Method);
7494 if (R.isInvalid())
7495 return false;
7496 ConvertedThis = R.get();
7497 } else {
7498 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7499 (void)MD;
7500 assert((MissingImplicitThis || MD->isStatic() ||
7502 "Expected `this` for non-ctor instance methods");
7503 }
7504 ConvertedThis = nullptr;
7505 }
7506
7507 // Ignore any variadic arguments. Converting them is pointless, since the
7508 // user can't refer to them in the function condition.
7509 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7510
7511 // Convert the arguments.
7512 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7513 ExprResult R;
7515 S.Context, Function->getParamDecl(I)),
7516 SourceLocation(), Args[I]);
7517
7518 if (R.isInvalid())
7519 return false;
7520
7521 ConvertedArgs.push_back(R.get());
7522 }
7523
7524 if (Trap.hasErrorOccurred())
7525 return false;
7526
7527 // Push default arguments if needed.
7528 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7529 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7530 ParmVarDecl *P = Function->getParamDecl(i);
7531 if (!P->hasDefaultArg())
7532 return false;
7533 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
7534 if (R.isInvalid())
7535 return false;
7536 ConvertedArgs.push_back(R.get());
7537 }
7538
7539 if (Trap.hasErrorOccurred())
7540 return false;
7541 }
7542 return true;
7543}
7544
7546 SourceLocation CallLoc,
7547 ArrayRef<Expr *> Args,
7548 bool MissingImplicitThis) {
7549 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7550 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7551 return nullptr;
7552
7553 SFINAETrap Trap(*this);
7554 SmallVector<Expr *, 16> ConvertedArgs;
7555 // FIXME: We should look into making enable_if late-parsed.
7556 Expr *DiscardedThis;
7558 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7559 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7560 return *EnableIfAttrs.begin();
7561
7562 for (auto *EIA : EnableIfAttrs) {
7564 // FIXME: This doesn't consider value-dependent cases, because doing so is
7565 // very difficult. Ideally, we should handle them more gracefully.
7566 if (EIA->getCond()->isValueDependent() ||
7567 !EIA->getCond()->EvaluateWithSubstitution(
7568 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7569 return EIA;
7570
7571 if (!Result.isInt() || !Result.getInt().getBoolValue())
7572 return EIA;
7573 }
7574 return nullptr;
7575}
7576
7577template <typename CheckFn>
7579 bool ArgDependent, SourceLocation Loc,
7580 CheckFn &&IsSuccessful) {
7582 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7583 if (ArgDependent == DIA->getArgDependent())
7584 Attrs.push_back(DIA);
7585 }
7586
7587 // Common case: No diagnose_if attributes, so we can quit early.
7588 if (Attrs.empty())
7589 return false;
7590
7591 auto WarningBegin = std::stable_partition(
7592 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7593 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7594 DIA->getWarningGroup().empty();
7595 });
7596
7597 // Note that diagnose_if attributes are late-parsed, so they appear in the
7598 // correct order (unlike enable_if attributes).
7599 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7600 IsSuccessful);
7601 if (ErrAttr != WarningBegin) {
7602 const DiagnoseIfAttr *DIA = *ErrAttr;
7603 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7604 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7605 << DIA->getParent() << DIA->getCond()->getSourceRange();
7606 return true;
7607 }
7608
7609 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7610 switch (Sev) {
7611 case DiagnoseIfAttr::DS_warning:
7613 case DiagnoseIfAttr::DS_error:
7614 return diag::Severity::Error;
7615 }
7616 llvm_unreachable("Fully covered switch above!");
7617 };
7618
7619 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7620 if (IsSuccessful(DIA)) {
7621 if (DIA->getWarningGroup().empty() &&
7622 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7623 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7624 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7625 << DIA->getParent() << DIA->getCond()->getSourceRange();
7626 } else {
7627 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7628 DIA->getWarningGroup());
7629 assert(DiagGroup);
7630 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7631 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7632 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7633 S.Diag(Loc, DiagID) << DIA->getMessage();
7634 }
7635 }
7636
7637 return false;
7638}
7639
7641 const Expr *ThisArg,
7643 SourceLocation Loc) {
7645 *this, Function, /*ArgDependent=*/true, Loc,
7646 [&](const DiagnoseIfAttr *DIA) {
7648 // It's sane to use the same Args for any redecl of this function, since
7649 // EvaluateWithSubstitution only cares about the position of each
7650 // argument in the arg list, not the ParmVarDecl* it maps to.
7651 if (!DIA->getCond()->EvaluateWithSubstitution(
7652 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7653 return false;
7654 return Result.isInt() && Result.getInt().getBoolValue();
7655 });
7656}
7657
7659 SourceLocation Loc) {
7661 *this, ND, /*ArgDependent=*/false, Loc,
7662 [&](const DiagnoseIfAttr *DIA) {
7663 bool Result;
7664 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7665 Result;
7666 });
7667}
7668
7670 ArrayRef<Expr *> Args,
7671 OverloadCandidateSet &CandidateSet,
7672 TemplateArgumentListInfo *ExplicitTemplateArgs,
7673 bool SuppressUserConversions,
7674 bool PartialOverloading,
7675 bool FirstArgumentIsBase) {
7676 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7677 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7678 ArrayRef<Expr *> FunctionArgs = Args;
7679
7680 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7681 FunctionDecl *FD =
7682 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7683
7684 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7685 QualType ObjectType;
7686 Expr::Classification ObjectClassification;
7687 if (Args.size() > 0) {
7688 if (Expr *E = Args[0]) {
7689 // Use the explicit base to restrict the lookup:
7690 ObjectType = E->getType();
7691 // Pointers in the object arguments are implicitly dereferenced, so we
7692 // always classify them as l-values.
7693 if (!ObjectType.isNull() && ObjectType->isPointerType())
7694 ObjectClassification = Expr::Classification::makeSimpleLValue();
7695 else
7696 ObjectClassification = E->Classify(Context);
7697 } // .. else there is an implicit base.
7698 FunctionArgs = Args.slice(1);
7699 }
7700 if (FunTmpl) {
7702 FunTmpl, F.getPair(),
7704 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7705 FunctionArgs, CandidateSet, SuppressUserConversions,
7706 PartialOverloading);
7707 } else {
7708 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7709 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7710 ObjectClassification, FunctionArgs, CandidateSet,
7711 SuppressUserConversions, PartialOverloading);
7712 }
7713 } else {
7714 // This branch handles both standalone functions and static methods.
7715
7716 // Slice the first argument (which is the base) when we access
7717 // static method as non-static.
7718 if (Args.size() > 0 &&
7719 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7720 !isa<CXXConstructorDecl>(FD)))) {
7721 assert(cast<CXXMethodDecl>(FD)->isStatic());
7722 FunctionArgs = Args.slice(1);
7723 }
7724 if (FunTmpl) {
7725 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7726 ExplicitTemplateArgs, FunctionArgs,
7727 CandidateSet, SuppressUserConversions,
7728 PartialOverloading);
7729 } else {
7730 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7731 SuppressUserConversions, PartialOverloading);
7732 }
7733 }
7734 }
7735}
7736
7738 Expr::Classification ObjectClassification,
7739 ArrayRef<Expr *> Args,
7740 OverloadCandidateSet &CandidateSet,
7741 bool SuppressUserConversions,
7743 NamedDecl *Decl = FoundDecl.getDecl();
7745
7747 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7748
7749 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7750 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7751 "Expected a member function template");
7752 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7753 /*ExplicitArgs*/ nullptr, ObjectType,
7754 ObjectClassification, Args, CandidateSet,
7755 SuppressUserConversions, false, PO);
7756 } else {
7757 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7758 ObjectType, ObjectClassification, Args, CandidateSet,
7759 SuppressUserConversions, false, {}, PO);
7760 }
7761}
7762
7765 CXXRecordDecl *ActingContext, QualType ObjectType,
7766 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7767 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7768 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7769 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7770 const FunctionProtoType *Proto
7771 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7772 assert(Proto && "Methods without a prototype cannot be overloaded");
7774 "Use AddOverloadCandidate for constructors");
7775
7776 if (!CandidateSet.isNewCandidate(Method, PO))
7777 return;
7778
7779 // C++11 [class.copy]p23: [DR1402]
7780 // A defaulted move assignment operator that is defined as deleted is
7781 // ignored by overload resolution.
7782 if (Method->isDefaulted() && Method->isDeleted() &&
7783 Method->isMoveAssignmentOperator())
7784 return;
7785
7786 // Overload resolution is always an unevaluated context.
7789
7790 bool IgnoreExplicitObject =
7791 (Method->isExplicitObjectMemberFunction() &&
7792 CandidateSet.getKind() ==
7794 bool ImplicitObjectMethodTreatedAsStatic =
7795 CandidateSet.getKind() ==
7797 Method->isImplicitObjectMemberFunction();
7798
7799 unsigned ExplicitOffset =
7800 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7801
7802 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7803 int(ImplicitObjectMethodTreatedAsStatic);
7804
7805 unsigned ExtraArgs =
7807 ? 0
7808 : 1;
7809
7810 // Add this candidate
7811 OverloadCandidate &Candidate =
7812 CandidateSet.addCandidate(Args.size() + ExtraArgs, EarlyConversions);
7813 Candidate.FoundDecl = FoundDecl;
7814 Candidate.Function = Method;
7815 Candidate.RewriteKind =
7816 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7817 Candidate.TookAddressOfOverload =
7819 Candidate.ExplicitCallArguments = Args.size();
7820 Candidate.StrictPackMatch = StrictPackMatch;
7821
7822 // (C++ 13.3.2p2): A candidate function having fewer than m
7823 // parameters is viable only if it has an ellipsis in its parameter
7824 // list (8.3.5).
7825 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7826 !Proto->isVariadic() &&
7827 shouldEnforceArgLimit(PartialOverloading, Method)) {
7828 Candidate.Viable = false;
7830 return;
7831 }
7832
7833 // (C++ 13.3.2p2): A candidate function having more than m parameters
7834 // is viable only if the (m+1)st parameter has a default argument
7835 // (8.3.6). For the purposes of overload resolution, the
7836 // parameter list is truncated on the right, so that there are
7837 // exactly m parameters.
7838 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7839 ExplicitOffset +
7840 int(ImplicitObjectMethodTreatedAsStatic);
7841
7842 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7843 // Not enough arguments.
7844 Candidate.Viable = false;
7846 return;
7847 }
7848
7849 Candidate.Viable = true;
7850
7851 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7852 if (!IgnoreExplicitObject) {
7853 if (ObjectType.isNull())
7854 Candidate.IgnoreObjectArgument = true;
7855 else if (Method->isStatic()) {
7856 // [over.best.ics.general]p8
7857 // When the parameter is the implicit object parameter of a static member
7858 // function, the implicit conversion sequence is a standard conversion
7859 // sequence that is neither better nor worse than any other standard
7860 // conversion sequence.
7861 //
7862 // This is a rule that was introduced in C++23 to support static lambdas.
7863 // We apply it retroactively because we want to support static lambdas as
7864 // an extension and it doesn't hurt previous code.
7865 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7866 } else {
7867 // Determine the implicit conversion sequence for the object
7868 // parameter.
7869 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7870 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7871 Method, ActingContext, /*InOverloadResolution=*/true);
7872 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7873 Candidate.Viable = false;
7875 return;
7876 }
7877 }
7878 }
7879
7880 // (CUDA B.1): Check for invalid calls between targets.
7881 if (getLangOpts().CUDA)
7882 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
7883 Method)) {
7884 Candidate.Viable = false;
7885 Candidate.FailureKind = ovl_fail_bad_target;
7886 return;
7887 }
7888
7889 if (Method->getTrailingRequiresClause()) {
7890 ConstraintSatisfaction Satisfaction;
7891 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7892 /*ForOverloadResolution*/ true) ||
7893 !Satisfaction.IsSatisfied) {
7894 Candidate.Viable = false;
7896 return;
7897 }
7898 }
7899
7900 // Determine the implicit conversion sequences for each of the
7901 // arguments.
7902 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7903 unsigned ConvIdx =
7904 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
7905 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7906 // We already formed a conversion sequence for this parameter during
7907 // template argument deduction.
7908 } else if (ArgIdx < NumParams) {
7909 // (C++ 13.3.2p3): for F to be a viable function, there shall
7910 // exist for each argument an implicit conversion sequence
7911 // (13.3.3.1) that converts that argument to the corresponding
7912 // parameter of F.
7913 QualType ParamType;
7914 if (ImplicitObjectMethodTreatedAsStatic) {
7915 ParamType = ArgIdx == 0
7916 ? Method->getFunctionObjectParameterReferenceType()
7917 : Proto->getParamType(ArgIdx - 1);
7918 } else {
7919 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
7920 }
7921 Candidate.Conversions[ConvIdx]
7922 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7923 SuppressUserConversions,
7924 /*InOverloadResolution=*/true,
7925 /*AllowObjCWritebackConversion=*/
7926 getLangOpts().ObjCAutoRefCount);
7927 if (Candidate.Conversions[ConvIdx].isBad()) {
7928 Candidate.Viable = false;
7930 return;
7931 }
7932 } else {
7933 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7934 // argument for which there is no corresponding parameter is
7935 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7936 Candidate.Conversions[ConvIdx].setEllipsis();
7937 }
7938 }
7939
7940 if (EnableIfAttr *FailedAttr =
7941 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7942 Candidate.Viable = false;
7943 Candidate.FailureKind = ovl_fail_enable_if;
7944 Candidate.DeductionFailure.Data = FailedAttr;
7945 return;
7946 }
7947
7949 Candidate.Viable = false;
7951 }
7952}
7953
7955 Sema &S, OverloadCandidateSet &CandidateSet,
7956 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7957 CXXRecordDecl *ActingContext,
7958 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7959 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7960 bool SuppressUserConversions, bool PartialOverloading,
7962
7963 // C++ [over.match.funcs]p7:
7964 // In each case where a candidate is a function template, candidate
7965 // function template specializations are generated using template argument
7966 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7967 // candidate functions in the usual way.113) A given name can refer to one
7968 // or more function templates and also to a set of overloaded non-template
7969 // functions. In such a case, the candidate functions generated from each
7970 // function template are combined with the set of non-template candidate
7971 // functions.
7972 TemplateDeductionInfo Info(CandidateSet.getLocation());
7973 auto *Method = cast<CXXMethodDecl>(MethodTmpl->getTemplatedDecl());
7974 FunctionDecl *Specialization = nullptr;
7975 ConversionSequenceList Conversions;
7977 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7978 PartialOverloading, /*AggregateDeductionCandidate=*/false,
7979 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
7980 CandidateSet.getKind() ==
7982 [&](ArrayRef<QualType> ParamTypes,
7983 bool OnlyInitializeNonUserDefinedConversions) {
7984 return S.CheckNonDependentConversions(
7985 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7986 Sema::CheckNonDependentConversionsFlag(
7987 SuppressUserConversions,
7988 OnlyInitializeNonUserDefinedConversions),
7989 ActingContext, ObjectType, ObjectClassification, PO);
7990 });
7992 OverloadCandidate &Candidate =
7993 CandidateSet.addCandidate(Conversions.size(), Conversions);
7994 Candidate.FoundDecl = FoundDecl;
7995 Candidate.Function = Method;
7996 Candidate.Viable = false;
7997 Candidate.RewriteKind =
7998 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7999 Candidate.IsSurrogate = false;
8000 Candidate.TookAddressOfOverload =
8001 CandidateSet.getKind() ==
8003
8004 Candidate.IgnoreObjectArgument =
8005 Method->isStatic() ||
8006 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
8007 Candidate.ExplicitCallArguments = Args.size();
8010 else {
8012 Candidate.DeductionFailure =
8013 MakeDeductionFailureInfo(S.Context, Result, Info);
8014 }
8015 return;
8016 }
8017
8018 // Add the function template specialization produced by template argument
8019 // deduction as a candidate.
8020 assert(Specialization && "Missing member function template specialization?");
8022 "Specialization is not a member function?");
8024 cast<CXXMethodDecl>(Specialization), FoundDecl, ActingContext, ObjectType,
8025 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
8026 PartialOverloading, Conversions, PO, Info.hasStrictPackMatch());
8027}
8028
8030 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8031 CXXRecordDecl *ActingContext,
8032 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8033 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8034 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8035 bool PartialOverloading, OverloadCandidateParamOrder PO) {
8036 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
8037 return;
8038
8039 if (ExplicitTemplateArgs ||
8042 *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
8043 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
8044 SuppressUserConversions, PartialOverloading, PO);
8045 return;
8046 }
8047
8049 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
8050 Args, SuppressUserConversions, PartialOverloading, PO);
8051}
8052
8053/// Determine whether a given function template has a simple explicit specifier
8054/// or a non-value-dependent explicit-specification that evaluates to true.
8058
8063
8065 Sema &S, OverloadCandidateSet &CandidateSet,
8067 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8068 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
8070 bool AggregateCandidateDeduction) {
8071
8072 // If the function template has a non-dependent explicit specification,
8073 // exclude it now if appropriate; we are not permitted to perform deduction
8074 // and substitution in this case.
8075 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8076 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8077 Candidate.FoundDecl = FoundDecl;
8078 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8079 Candidate.Viable = false;
8080 Candidate.FailureKind = ovl_fail_explicit;
8081 return;
8082 }
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 FunctionTemplate->getTemplateDepth());
8095 FunctionDecl *Specialization = nullptr;
8096 ConversionSequenceList Conversions;
8098 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8099 PartialOverloading, AggregateCandidateDeduction,
8100 /*PartialOrdering=*/false,
8101 /*ObjectType=*/QualType(),
8102 /*ObjectClassification=*/Expr::Classification(),
8103 CandidateSet.getKind() ==
8105 [&](ArrayRef<QualType> ParamTypes,
8106 bool OnlyInitializeNonUserDefinedConversions) {
8107 return S.CheckNonDependentConversions(
8108 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8109 Sema::CheckNonDependentConversionsFlag(
8110 SuppressUserConversions,
8111 OnlyInitializeNonUserDefinedConversions),
8112 nullptr, QualType(), {}, PO);
8113 });
8115 OverloadCandidate &Candidate =
8116 CandidateSet.addCandidate(Conversions.size(), Conversions);
8117 Candidate.FoundDecl = FoundDecl;
8118 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8119 Candidate.Viable = false;
8120 Candidate.RewriteKind =
8121 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8122 Candidate.IsSurrogate = false;
8123 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
8124 // Ignore the object argument if there is one, since we don't have an object
8125 // type.
8126 Candidate.TookAddressOfOverload =
8127 CandidateSet.getKind() ==
8129
8130 Candidate.IgnoreObjectArgument =
8131 isa<CXXMethodDecl>(Candidate.Function) &&
8132 !cast<CXXMethodDecl>(Candidate.Function)
8133 ->isExplicitObjectMemberFunction() &&
8135
8136 Candidate.ExplicitCallArguments = Args.size();
8139 else {
8141 Candidate.DeductionFailure =
8143 }
8144 return;
8145 }
8146
8147 // Add the function template specialization produced by template argument
8148 // deduction as a candidate.
8149 assert(Specialization && "Missing function template specialization?");
8151 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8152 PartialOverloading, AllowExplicit,
8153 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
8154 Info.AggregateDeductionCandidateHasMismatchedArity,
8155 Info.hasStrictPackMatch());
8156}
8157
8160 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8161 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8162 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8163 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8164 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
8165 return;
8166
8167 bool DependentExplicitSpecifier = hasDependentExplicit(FunctionTemplate);
8168
8169 if (ExplicitTemplateArgs ||
8171 (isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl()) &&
8172 DependentExplicitSpecifier)) {
8173
8175 *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8176 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8177 IsADLCandidate, PO, AggregateCandidateDeduction);
8178
8179 if (DependentExplicitSpecifier)
8181 return;
8182 }
8183
8184 CandidateSet.AddDeferredTemplateCandidate(
8185 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8186 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8187 AggregateCandidateDeduction);
8188}
8189
8192 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8194 CheckNonDependentConversionsFlag UserConversionFlag,
8195 CXXRecordDecl *ActingContext, QualType ObjectType,
8196 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8197 // FIXME: The cases in which we allow explicit conversions for constructor
8198 // arguments never consider calling a constructor template. It's not clear
8199 // that is correct.
8200 const bool AllowExplicit = false;
8201
8202 bool ForOverloadSetAddressResolution =
8204 auto *FD = FunctionTemplate->getTemplatedDecl();
8205 auto *Method = dyn_cast<CXXMethodDecl>(FD);
8206 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8208 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8209
8210 if (Conversions.empty())
8211 Conversions =
8212 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
8213
8214 // Overload resolution is always an unevaluated context.
8217
8218 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8219 // require that, but this check should never result in a hard error, and
8220 // overload resolution is permitted to sidestep instantiations.
8221 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
8222 !ObjectType.isNull()) {
8223 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8224 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8225 !ParamTypes[0]->isDependentType()) {
8227 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8228 Method, ActingContext, /*InOverloadResolution=*/true,
8229 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8230 : QualType());
8231 if (Conversions[ConvIdx].isBad())
8232 return true;
8233 }
8234 }
8235
8236 // A speculative workaround for self-dependent constraint bugs that manifest
8237 // after CWG2369.
8238 // FIXME: Add references to the standard once P3606 is adopted.
8239 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8240 QualType ArgType) {
8241 ParamType = ParamType.getNonReferenceType();
8242 ArgType = ArgType.getNonReferenceType();
8243 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8244 if (PointerConv) {
8245 ParamType = ParamType->getPointeeType();
8246 ArgType = ArgType->getPointeeType();
8247 }
8248
8249 if (auto *RD = ParamType->getAsCXXRecordDecl();
8250 RD && RD->hasDefinition() &&
8251 llvm::any_of(LookupConstructors(RD), [](NamedDecl *ND) {
8252 auto Info = getConstructorInfo(ND);
8253 if (!Info)
8254 return false;
8255 CXXConstructorDecl *Ctor = Info.Constructor;
8256 /// isConvertingConstructor takes copy/move constructors into
8257 /// account!
8258 return !Ctor->isCopyOrMoveConstructor() &&
8260 /*AllowExplicit=*/true);
8261 }))
8262 return true;
8263 if (auto *RD = ArgType->getAsCXXRecordDecl();
8264 RD && RD->hasDefinition() &&
8265 !RD->getVisibleConversionFunctions().empty())
8266 return true;
8267
8268 return false;
8269 };
8270
8271 unsigned Offset =
8272 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8273 : 0;
8274
8275 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
8276 I != N; ++I) {
8277 QualType ParamType = ParamTypes[I + Offset];
8278 if (!ParamType->isDependentType()) {
8279 unsigned ConvIdx;
8281 ConvIdx = Args.size() - 1 - I;
8282 assert(Args.size() + ThisConversions == 2 &&
8283 "number of args (including 'this') must be exactly 2 for "
8284 "reversed order");
8285 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8286 // would also be 0. 'this' got ConvIdx = 1 previously.
8287 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8288 } else {
8289 // For members, 'this' got ConvIdx = 0 previously.
8290 ConvIdx = ThisConversions + I;
8291 }
8292 if (Conversions[ConvIdx].isInitialized())
8293 continue;
8294 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8295 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8296 continue;
8298 *this, Args[I], ParamType, UserConversionFlag.SuppressUserConversions,
8299 /*InOverloadResolution=*/true,
8300 /*AllowObjCWritebackConversion=*/
8301 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8302 if (Conversions[ConvIdx].isBad())
8303 return true;
8304 }
8305 }
8306
8307 return false;
8308}
8309
8310/// Determine whether this is an allowable conversion from the result
8311/// of an explicit conversion operator to the expected type, per C++
8312/// [over.match.conv]p1 and [over.match.ref]p1.
8313///
8314/// \param ConvType The return type of the conversion function.
8315///
8316/// \param ToType The type we are converting to.
8317///
8318/// \param AllowObjCPointerConversion Allow a conversion from one
8319/// Objective-C pointer to another.
8320///
8321/// \returns true if the conversion is allowable, false otherwise.
8323 QualType ConvType, QualType ToType,
8324 bool AllowObjCPointerConversion) {
8325 QualType ToNonRefType = ToType.getNonReferenceType();
8326
8327 // Easy case: the types are the same.
8328 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
8329 return true;
8330
8331 // Allow qualification conversions.
8332 bool ObjCLifetimeConversion;
8333 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
8334 ObjCLifetimeConversion))
8335 return true;
8336
8337 // If we're not allowed to consider Objective-C pointer conversions,
8338 // we're done.
8339 if (!AllowObjCPointerConversion)
8340 return false;
8341
8342 // Is this an Objective-C pointer conversion?
8343 bool IncompatibleObjC = false;
8344 QualType ConvertedType;
8345 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
8346 IncompatibleObjC);
8347}
8348
8350 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8351 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8352 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8353 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8354 assert(!Conversion->getDescribedFunctionTemplate() &&
8355 "Conversion function templates use AddTemplateConversionCandidate");
8356 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8357 if (!CandidateSet.isNewCandidate(Conversion))
8358 return;
8359
8360 // If the conversion function has an undeduced return type, trigger its
8361 // deduction now.
8362 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8363 if (DeduceReturnType(Conversion, From->getExprLoc()))
8364 return;
8365 ConvType = Conversion->getConversionType().getNonReferenceType();
8366 }
8367
8368 // If we don't allow any conversion of the result type, ignore conversion
8369 // functions that don't convert to exactly (possibly cv-qualified) T.
8370 if (!AllowResultConversion &&
8371 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
8372 return;
8373
8374 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8375 // operator is only a candidate if its return type is the target type or
8376 // can be converted to the target type with a qualification conversion.
8377 //
8378 // FIXME: Include such functions in the candidate list and explain why we
8379 // can't select them.
8380 if (Conversion->isExplicit() &&
8381 !isAllowableExplicitConversion(*this, ConvType, ToType,
8382 AllowObjCConversionOnExplicit))
8383 return;
8384
8385 // Overload resolution is always an unevaluated context.
8388
8389 // Add this candidate
8390 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8391 Candidate.FoundDecl = FoundDecl;
8392 Candidate.Function = Conversion;
8394 Candidate.FinalConversion.setFromType(ConvType);
8395 Candidate.FinalConversion.setAllToTypes(ToType);
8396 Candidate.HasFinalConversion = true;
8397 Candidate.Viable = true;
8398 Candidate.ExplicitCallArguments = 1;
8399 Candidate.StrictPackMatch = StrictPackMatch;
8400
8401 // Explicit functions are not actually candidates at all if we're not
8402 // allowing them in this context, but keep them around so we can point
8403 // to them in diagnostics.
8404 if (!AllowExplicit && Conversion->isExplicit()) {
8405 Candidate.Viable = false;
8406 Candidate.FailureKind = ovl_fail_explicit;
8407 return;
8408 }
8409
8410 // C++ [over.match.funcs]p4:
8411 // For conversion functions, the function is considered to be a member of
8412 // the class of the implicit implied object argument for the purpose of
8413 // defining the type of the implicit object parameter.
8414 //
8415 // Determine the implicit conversion sequence for the implicit
8416 // object parameter.
8417 QualType ObjectType = From->getType();
8418 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8419 ObjectType = FromPtrType->getPointeeType();
8420 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8421 // C++23 [over.best.ics.general]
8422 // However, if the target is [...]
8423 // - the object parameter of a user-defined conversion function
8424 // [...] user-defined conversion sequences are not considered.
8426 *this, CandidateSet.getLocation(), From->getType(),
8427 From->Classify(Context), Conversion, ConversionContext,
8428 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8429 /*SuppressUserConversion*/ true);
8430
8431 if (Candidate.Conversions[0].isBad()) {
8432 Candidate.Viable = false;
8434 return;
8435 }
8436
8437 if (Conversion->getTrailingRequiresClause()) {
8438 ConstraintSatisfaction Satisfaction;
8439 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8440 !Satisfaction.IsSatisfied) {
8441 Candidate.Viable = false;
8443 return;
8444 }
8445 }
8446
8447 // We won't go through a user-defined type conversion function to convert a
8448 // derived to base as such conversions are given Conversion Rank. They only
8449 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8450 QualType FromCanon
8451 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8452 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8453 if (FromCanon == ToCanon ||
8454 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8455 Candidate.Viable = false;
8457 return;
8458 }
8459
8460 // To determine what the conversion from the result of calling the
8461 // conversion function to the type we're eventually trying to
8462 // convert to (ToType), we need to synthesize a call to the
8463 // conversion function and attempt copy initialization from it. This
8464 // makes sure that we get the right semantics with respect to
8465 // lvalues/rvalues and the type. Fortunately, we can allocate this
8466 // call on the stack and we don't need its arguments to be
8467 // well-formed.
8468 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8469 VK_LValue, From->getBeginLoc());
8471 Context.getPointerType(Conversion->getType()),
8472 CK_FunctionToPointerDecay, &ConversionRef,
8474
8475 QualType ConversionType = Conversion->getConversionType();
8476 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8477 Candidate.Viable = false;
8479 return;
8480 }
8481
8482 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8483
8484 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8485
8486 // Introduce a temporary expression with the right type and value category
8487 // that we can use for deduction purposes.
8488 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8489
8491 TryCopyInitialization(*this, &FakeCall, ToType,
8492 /*SuppressUserConversions=*/true,
8493 /*InOverloadResolution=*/false,
8494 /*AllowObjCWritebackConversion=*/false);
8495
8496 switch (ICS.getKind()) {
8498 Candidate.FinalConversion = ICS.Standard;
8499 Candidate.HasFinalConversion = true;
8500
8501 // C++ [over.ics.user]p3:
8502 // If the user-defined conversion is specified by a specialization of a
8503 // conversion function template, the second standard conversion sequence
8504 // shall have exact match rank.
8505 if (Conversion->getPrimaryTemplate() &&
8507 Candidate.Viable = false;
8509 return;
8510 }
8511
8512 // C++0x [dcl.init.ref]p5:
8513 // In the second case, if the reference is an rvalue reference and
8514 // the second standard conversion sequence of the user-defined
8515 // conversion sequence includes an lvalue-to-rvalue conversion, the
8516 // program is ill-formed.
8517 if (ToType->isRValueReferenceType() &&
8519 Candidate.Viable = false;
8521 return;
8522 }
8523 break;
8524
8526 Candidate.Viable = false;
8528 return;
8529
8530 default:
8531 llvm_unreachable(
8532 "Can only end up with a standard conversion sequence or failure");
8533 }
8534
8535 if (EnableIfAttr *FailedAttr =
8536 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8537 Candidate.Viable = false;
8538 Candidate.FailureKind = ovl_fail_enable_if;
8539 Candidate.DeductionFailure.Data = FailedAttr;
8540 return;
8541 }
8542
8543 if (isNonViableMultiVersionOverload(Conversion)) {
8544 Candidate.Viable = false;
8546 }
8547}
8548
8550 Sema &S, OverloadCandidateSet &CandidateSet,
8552 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8553 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8554 bool AllowResultConversion) {
8555
8556 // If the function template has a non-dependent explicit specification,
8557 // exclude it now if appropriate; we are not permitted to perform deduction
8558 // and substitution in this case.
8559 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8560 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8561 Candidate.FoundDecl = FoundDecl;
8562 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8563 Candidate.Viable = false;
8564 Candidate.FailureKind = ovl_fail_explicit;
8565 return;
8566 }
8567
8568 QualType ObjectType = From->getType();
8569 Expr::Classification ObjectClassification = From->Classify(S.Context);
8570
8571 TemplateDeductionInfo Info(CandidateSet.getLocation());
8574 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8575 Specialization, Info);
8577 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8578 Candidate.FoundDecl = FoundDecl;
8579 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8580 Candidate.Viable = false;
8582 Candidate.ExplicitCallArguments = 1;
8583 Candidate.DeductionFailure =
8584 MakeDeductionFailureInfo(S.Context, Result, Info);
8585 return;
8586 }
8587
8588 // Add the conversion function template specialization produced by
8589 // template argument deduction as a candidate.
8590 assert(Specialization && "Missing function template specialization?");
8591 S.AddConversionCandidate(Specialization, FoundDecl, ActingContext, From,
8592 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8593 AllowExplicit, AllowResultConversion,
8594 Info.hasStrictPackMatch());
8595}
8596
8599 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8600 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8601 bool AllowExplicit, bool AllowResultConversion) {
8602 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8603 "Only conversion function templates permitted here");
8604
8605 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8606 return;
8607
8609 CandidateSet.getKind() ==
8613 *this, CandidateSet, FunctionTemplate, FoundDecl, ActingDC, From,
8614 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8615 AllowResultConversion);
8616
8618 return;
8619 }
8620
8622 FunctionTemplate, FoundDecl, ActingDC, From, ToType,
8623 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8624}
8625
8627 DeclAccessPair FoundDecl,
8628 CXXRecordDecl *ActingContext,
8629 const FunctionProtoType *Proto,
8630 Expr *Object,
8631 ArrayRef<Expr *> Args,
8632 OverloadCandidateSet& CandidateSet) {
8633 if (!CandidateSet.isNewCandidate(Conversion))
8634 return;
8635
8636 // Overload resolution is always an unevaluated context.
8639
8640 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8641 Candidate.FoundDecl = FoundDecl;
8642 Candidate.Function = nullptr;
8643 Candidate.Surrogate = Conversion;
8644 Candidate.IsSurrogate = true;
8645 Candidate.Viable = true;
8646 Candidate.ExplicitCallArguments = Args.size();
8647
8648 // Determine the implicit conversion sequence for the implicit
8649 // object parameter.
8650 ImplicitConversionSequence ObjectInit;
8651 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8652 ObjectInit = TryCopyInitialization(*this, Object,
8653 Conversion->getParamDecl(0)->getType(),
8654 /*SuppressUserConversions=*/false,
8655 /*InOverloadResolution=*/true, false);
8656 } else {
8658 *this, CandidateSet.getLocation(), Object->getType(),
8659 Object->Classify(Context), Conversion, ActingContext);
8660 }
8661
8662 if (ObjectInit.isBad()) {
8663 Candidate.Viable = false;
8665 Candidate.Conversions[0] = ObjectInit;
8666 return;
8667 }
8668
8669 // The first conversion is actually a user-defined conversion whose
8670 // first conversion is ObjectInit's standard conversion (which is
8671 // effectively a reference binding). Record it as such.
8672 Candidate.Conversions[0].setUserDefined();
8673 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8674 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8675 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8676 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8677 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8678 Candidate.Conversions[0].UserDefined.After
8679 = Candidate.Conversions[0].UserDefined.Before;
8680 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8681
8682 // Find the
8683 unsigned NumParams = Proto->getNumParams();
8684
8685 // (C++ 13.3.2p2): A candidate function having fewer than m
8686 // parameters is viable only if it has an ellipsis in its parameter
8687 // list (8.3.5).
8688 if (Args.size() > NumParams && !Proto->isVariadic()) {
8689 Candidate.Viable = false;
8691 return;
8692 }
8693
8694 // Function types don't have any default arguments, so just check if
8695 // we have enough arguments.
8696 if (Args.size() < NumParams) {
8697 // Not enough arguments.
8698 Candidate.Viable = false;
8700 return;
8701 }
8702
8703 // Determine the implicit conversion sequences for each of the
8704 // arguments.
8705 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8706 if (ArgIdx < NumParams) {
8707 // (C++ 13.3.2p3): for F to be a viable function, there shall
8708 // exist for each argument an implicit conversion sequence
8709 // (13.3.3.1) that converts that argument to the corresponding
8710 // parameter of F.
8711 QualType ParamType = Proto->getParamType(ArgIdx);
8712 Candidate.Conversions[ArgIdx + 1]
8713 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8714 /*SuppressUserConversions=*/false,
8715 /*InOverloadResolution=*/false,
8716 /*AllowObjCWritebackConversion=*/
8717 getLangOpts().ObjCAutoRefCount);
8718 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8719 Candidate.Viable = false;
8721 return;
8722 }
8723 } else {
8724 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8725 // argument for which there is no corresponding parameter is
8726 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8727 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8728 }
8729 }
8730
8731 if (Conversion->getTrailingRequiresClause()) {
8732 ConstraintSatisfaction Satisfaction;
8733 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8734 /*ForOverloadResolution*/ true) ||
8735 !Satisfaction.IsSatisfied) {
8736 Candidate.Viable = false;
8738 return;
8739 }
8740 }
8741
8742 if (EnableIfAttr *FailedAttr =
8743 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8744 Candidate.Viable = false;
8745 Candidate.FailureKind = ovl_fail_enable_if;
8746 Candidate.DeductionFailure.Data = FailedAttr;
8747 return;
8748 }
8749}
8750
8752 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8753 OverloadCandidateSet &CandidateSet,
8754 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8755 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8756 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8757 ArrayRef<Expr *> FunctionArgs = Args;
8758
8759 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8760 FunctionDecl *FD =
8761 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8762
8763 // Don't consider rewritten functions if we're not rewriting.
8764 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8765 continue;
8766
8767 assert(!isa<CXXMethodDecl>(FD) &&
8768 "unqualified operator lookup found a member function");
8769
8770 if (FunTmpl) {
8771 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8772 FunctionArgs, CandidateSet);
8773 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
8774
8775 // As template candidates are not deduced immediately,
8776 // persist the array in the overload set.
8778 FunctionArgs[1], FunctionArgs[0]);
8779 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8780 Reversed, CandidateSet, false, false, true,
8781 ADLCallKind::NotADL,
8783 }
8784 } else {
8785 if (ExplicitTemplateArgs)
8786 continue;
8787 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8788 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8789 AddOverloadCandidate(FD, F.getPair(),
8790 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8791 false, false, true, false, ADLCallKind::NotADL, {},
8793 }
8794 }
8795}
8796
8798 SourceLocation OpLoc,
8799 ArrayRef<Expr *> Args,
8800 OverloadCandidateSet &CandidateSet,
8802 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8803
8804 // C++ [over.match.oper]p3:
8805 // For a unary operator @ with an operand of a type whose
8806 // cv-unqualified version is T1, and for a binary operator @ with
8807 // a left operand of a type whose cv-unqualified version is T1 and
8808 // a right operand of a type whose cv-unqualified version is T2,
8809 // three sets of candidate functions, designated member
8810 // candidates, non-member candidates and built-in candidates, are
8811 // constructed as follows:
8812 QualType T1 = Args[0]->getType();
8813
8814 // -- If T1 is a complete class type or a class currently being
8815 // defined, the set of member candidates is the result of the
8816 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8817 // the set of member candidates is empty.
8818 if (T1->isRecordType()) {
8819 bool IsComplete = isCompleteType(OpLoc, T1);
8820 auto *T1RD = T1->getAsCXXRecordDecl();
8821 // Complete the type if it can be completed.
8822 // If the type is neither complete nor being defined, bail out now.
8823 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
8824 return;
8825
8826 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8827 LookupQualifiedName(Operators, T1RD);
8828 Operators.suppressAccessDiagnostics();
8829
8830 for (LookupResult::iterator Oper = Operators.begin(),
8831 OperEnd = Operators.end();
8832 Oper != OperEnd; ++Oper) {
8833 if (Oper->getAsFunction() &&
8835 !CandidateSet.getRewriteInfo().shouldAddReversed(
8836 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8837 continue;
8838 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8839 Args[0]->Classify(Context), Args.slice(1),
8840 CandidateSet, /*SuppressUserConversion=*/false, PO);
8841 }
8842 }
8843}
8844
8846 OverloadCandidateSet& CandidateSet,
8847 bool IsAssignmentOperator,
8848 unsigned NumContextualBoolArguments) {
8849 // Overload resolution is always an unevaluated context.
8852
8853 // Add this candidate
8854 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8855 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8856 Candidate.Function = nullptr;
8857 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8858
8859 // Determine the implicit conversion sequences for each of the
8860 // arguments.
8861 Candidate.Viable = true;
8862 Candidate.ExplicitCallArguments = Args.size();
8863 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8864 // C++ [over.match.oper]p4:
8865 // For the built-in assignment operators, conversions of the
8866 // left operand are restricted as follows:
8867 // -- no temporaries are introduced to hold the left operand, and
8868 // -- no user-defined conversions are applied to the left
8869 // operand to achieve a type match with the left-most
8870 // parameter of a built-in candidate.
8871 //
8872 // We block these conversions by turning off user-defined
8873 // conversions, since that is the only way that initialization of
8874 // a reference to a non-class type can occur from something that
8875 // is not of the same type.
8876 if (ArgIdx < NumContextualBoolArguments) {
8877 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8878 "Contextual conversion to bool requires bool type");
8879 Candidate.Conversions[ArgIdx]
8880 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
8881 } else {
8882 Candidate.Conversions[ArgIdx]
8883 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
8884 ArgIdx == 0 && IsAssignmentOperator,
8885 /*InOverloadResolution=*/false,
8886 /*AllowObjCWritebackConversion=*/
8887 getLangOpts().ObjCAutoRefCount);
8888 }
8889 if (Candidate.Conversions[ArgIdx].isBad()) {
8890 Candidate.Viable = false;
8892 break;
8893 }
8894 }
8895}
8896
8897namespace {
8898
8899/// BuiltinCandidateTypeSet - A set of types that will be used for the
8900/// candidate operator functions for built-in operators (C++
8901/// [over.built]). The types are separated into pointer types and
8902/// enumeration types.
8903class BuiltinCandidateTypeSet {
8904 /// TypeSet - A set of types.
8905 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8906
8907 /// PointerTypes - The set of pointer types that will be used in the
8908 /// built-in candidates.
8909 TypeSet PointerTypes;
8910
8911 /// MemberPointerTypes - The set of member pointer types that will be
8912 /// used in the built-in candidates.
8913 TypeSet MemberPointerTypes;
8914
8915 /// EnumerationTypes - The set of enumeration types that will be
8916 /// used in the built-in candidates.
8917 TypeSet EnumerationTypes;
8918
8919 /// The set of vector types that will be used in the built-in
8920 /// candidates.
8921 TypeSet VectorTypes;
8922
8923 /// The set of matrix types that will be used in the built-in
8924 /// candidates.
8925 TypeSet MatrixTypes;
8926
8927 /// The set of _BitInt types that will be used in the built-in candidates.
8928 TypeSet BitIntTypes;
8929
8930 /// A flag indicating non-record types are viable candidates
8931 bool HasNonRecordTypes;
8932
8933 /// A flag indicating whether either arithmetic or enumeration types
8934 /// were present in the candidate set.
8935 bool HasArithmeticOrEnumeralTypes;
8936
8937 /// A flag indicating whether the nullptr type was present in the
8938 /// candidate set.
8939 bool HasNullPtrType;
8940
8941 /// Sema - The semantic analysis instance where we are building the
8942 /// candidate type set.
8943 Sema &SemaRef;
8944
8945 /// Context - The AST context in which we will build the type sets.
8946 ASTContext &Context;
8947
8948 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8949 const Qualifiers &VisibleQuals);
8950 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8951
8952public:
8953 /// iterator - Iterates through the types that are part of the set.
8954 typedef TypeSet::iterator iterator;
8955
8956 BuiltinCandidateTypeSet(Sema &SemaRef)
8957 : HasNonRecordTypes(false),
8958 HasArithmeticOrEnumeralTypes(false),
8959 HasNullPtrType(false),
8960 SemaRef(SemaRef),
8961 Context(SemaRef.Context) { }
8962
8963 void AddTypesConvertedFrom(QualType Ty,
8964 SourceLocation Loc,
8965 bool AllowUserConversions,
8966 bool AllowExplicitConversions,
8967 const Qualifiers &VisibleTypeConversionsQuals);
8968
8969 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8970 llvm::iterator_range<iterator> member_pointer_types() {
8971 return MemberPointerTypes;
8972 }
8973 llvm::iterator_range<iterator> enumeration_types() {
8974 return EnumerationTypes;
8975 }
8976 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8977 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8978 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8979
8980 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
8981 bool hasNonRecordTypes() { return HasNonRecordTypes; }
8982 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8983 bool hasNullPtrType() const { return HasNullPtrType; }
8984};
8985
8986} // end anonymous namespace
8987
8988/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8989/// the set of pointer types along with any more-qualified variants of
8990/// that type. For example, if @p Ty is "int const *", this routine
8991/// will add "int const *", "int const volatile *", "int const
8992/// restrict *", and "int const volatile restrict *" to the set of
8993/// pointer types. Returns true if the add of @p Ty itself succeeded,
8994/// false otherwise.
8995///
8996/// FIXME: what to do about extended qualifiers?
8997bool
8998BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8999 const Qualifiers &VisibleQuals) {
9000
9001 // Insert this type.
9002 if (!PointerTypes.insert(Ty))
9003 return false;
9004
9005 QualType PointeeTy;
9006 const PointerType *PointerTy = Ty->getAs<PointerType>();
9007 bool buildObjCPtr = false;
9008 if (!PointerTy) {
9009 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
9010 PointeeTy = PTy->getPointeeType();
9011 buildObjCPtr = true;
9012 } else {
9013 PointeeTy = PointerTy->getPointeeType();
9014 }
9015
9016 // Don't add qualified variants of arrays. For one, they're not allowed
9017 // (the qualifier would sink to the element type), and for another, the
9018 // only overload situation where it matters is subscript or pointer +- int,
9019 // and those shouldn't have qualifier variants anyway.
9020 if (PointeeTy->isArrayType())
9021 return true;
9022
9023 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9024 bool hasVolatile = VisibleQuals.hasVolatile();
9025 bool hasRestrict = VisibleQuals.hasRestrict();
9026
9027 // Iterate through all strict supersets of BaseCVR.
9028 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9029 if ((CVR | BaseCVR) != CVR) continue;
9030 // Skip over volatile if no volatile found anywhere in the types.
9031 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
9032
9033 // Skip over restrict if no restrict found anywhere in the types, or if
9034 // the type cannot be restrict-qualified.
9035 if ((CVR & Qualifiers::Restrict) &&
9036 (!hasRestrict ||
9037 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
9038 continue;
9039
9040 // Build qualified pointee type.
9041 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9042
9043 // Build qualified pointer type.
9044 QualType QPointerTy;
9045 if (!buildObjCPtr)
9046 QPointerTy = Context.getPointerType(QPointeeTy);
9047 else
9048 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
9049
9050 // Insert qualified pointer type.
9051 PointerTypes.insert(QPointerTy);
9052 }
9053
9054 return true;
9055}
9056
9057/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
9058/// to the set of pointer types along with any more-qualified variants of
9059/// that type. For example, if @p Ty is "int const *", this routine
9060/// will add "int const *", "int const volatile *", "int const
9061/// restrict *", and "int const volatile restrict *" to the set of
9062/// pointer types. Returns true if the add of @p Ty itself succeeded,
9063/// false otherwise.
9064///
9065/// FIXME: what to do about extended qualifiers?
9066bool
9067BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
9068 QualType Ty) {
9069 // Insert this type.
9070 if (!MemberPointerTypes.insert(Ty))
9071 return false;
9072
9073 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9074 assert(PointerTy && "type was not a member pointer type!");
9075
9076 QualType PointeeTy = PointerTy->getPointeeType();
9077 // Don't add qualified variants of arrays. For one, they're not allowed
9078 // (the qualifier would sink to the element type), and for another, the
9079 // only overload situation where it matters is subscript or pointer +- int,
9080 // and those shouldn't have qualifier variants anyway.
9081 if (PointeeTy->isArrayType())
9082 return true;
9083 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9084
9085 // Iterate through all strict supersets of the pointee type's CVR
9086 // qualifiers.
9087 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9088 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9089 if ((CVR | BaseCVR) != CVR) continue;
9090
9091 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9092 MemberPointerTypes.insert(Context.getMemberPointerType(
9093 QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9094 }
9095
9096 return true;
9097}
9098
9099/// AddTypesConvertedFrom - Add each of the types to which the type @p
9100/// Ty can be implicit converted to the given set of @p Types. We're
9101/// primarily interested in pointer types and enumeration types. We also
9102/// take member pointer types, for the conditional operator.
9103/// AllowUserConversions is true if we should look at the conversion
9104/// functions of a class type, and AllowExplicitConversions if we
9105/// should also include the explicit conversion functions of a class
9106/// type.
9107void
9108BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9109 SourceLocation Loc,
9110 bool AllowUserConversions,
9111 bool AllowExplicitConversions,
9112 const Qualifiers &VisibleQuals) {
9113 // Only deal with canonical types.
9114 Ty = Context.getCanonicalType(Ty);
9115
9116 // Look through reference types; they aren't part of the type of an
9117 // expression for the purposes of conversions.
9118 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9119 Ty = RefTy->getPointeeType();
9120
9121 // If we're dealing with an array type, decay to the pointer.
9122 if (Ty->isArrayType())
9123 Ty = SemaRef.Context.getArrayDecayedType(Ty);
9124
9125 // Otherwise, we don't care about qualifiers on the type.
9126 Ty = Ty.getLocalUnqualifiedType();
9127
9128 // Flag if we ever add a non-record type.
9129 bool TyIsRec = Ty->isRecordType();
9130 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9131
9132 // Flag if we encounter an arithmetic type.
9133 HasArithmeticOrEnumeralTypes =
9134 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9135
9136 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9137 PointerTypes.insert(Ty);
9138 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9139 // Insert our type, and its more-qualified variants, into the set
9140 // of types.
9141 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9142 return;
9143 } else if (Ty->isMemberPointerType()) {
9144 // Member pointers are far easier, since the pointee can't be converted.
9145 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9146 return;
9147 } else if (Ty->isEnumeralType()) {
9148 HasArithmeticOrEnumeralTypes = true;
9149 EnumerationTypes.insert(Ty);
9150 } else if (Ty->isBitIntType()) {
9151 HasArithmeticOrEnumeralTypes = true;
9152 BitIntTypes.insert(Ty);
9153 } else if (Ty->isVectorType()) {
9154 // We treat vector types as arithmetic types in many contexts as an
9155 // extension.
9156 HasArithmeticOrEnumeralTypes = true;
9157 VectorTypes.insert(Ty);
9158 } else if (Ty->isMatrixType()) {
9159 // Similar to vector types, we treat vector types as arithmetic types in
9160 // many contexts as an extension.
9161 HasArithmeticOrEnumeralTypes = true;
9162 MatrixTypes.insert(Ty);
9163 } else if (Ty->isNullPtrType()) {
9164 HasNullPtrType = true;
9165 } else if (AllowUserConversions && TyIsRec) {
9166 // No conversion functions in incomplete types.
9167 if (!SemaRef.isCompleteType(Loc, Ty))
9168 return;
9169
9170 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9171 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9172 if (isa<UsingShadowDecl>(D))
9173 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9174
9175 // Skip conversion function templates; they don't tell us anything
9176 // about which builtin types we can convert to.
9178 continue;
9179
9180 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
9181 if (AllowExplicitConversions || !Conv->isExplicit()) {
9182 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
9183 VisibleQuals);
9184 }
9185 }
9186 }
9187}
9188/// Helper function for adjusting address spaces for the pointer or reference
9189/// operands of builtin operators depending on the argument.
9194
9195/// Helper function for AddBuiltinOperatorCandidates() that adds
9196/// the volatile- and non-volatile-qualified assignment operators for the
9197/// given type to the candidate set.
9199 QualType T,
9200 ArrayRef<Expr *> Args,
9201 OverloadCandidateSet &CandidateSet) {
9202 QualType ParamTypes[2];
9203
9204 // T& operator=(T&, T)
9205 ParamTypes[0] = S.Context.getLValueReferenceType(
9207 ParamTypes[1] = T;
9208 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9209 /*IsAssignmentOperator=*/true);
9210
9212 // volatile T& operator=(volatile T&, T)
9213 ParamTypes[0] = S.Context.getLValueReferenceType(
9215 Args[0]));
9216 ParamTypes[1] = T;
9217 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9218 /*IsAssignmentOperator=*/true);
9219 }
9220}
9221
9222/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9223/// if any, found in visible type conversion functions found in ArgExpr's type.
9224static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9225 Qualifiers VRQuals;
9226 CXXRecordDecl *ClassDecl;
9227 if (const MemberPointerType *RHSMPType =
9228 ArgExpr->getType()->getAs<MemberPointerType>())
9229 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9230 else
9231 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9232 if (!ClassDecl) {
9233 // Just to be safe, assume the worst case.
9234 VRQuals.addVolatile();
9235 VRQuals.addRestrict();
9236 return VRQuals;
9237 }
9238 if (!ClassDecl->hasDefinition())
9239 return VRQuals;
9240
9241 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9242 if (isa<UsingShadowDecl>(D))
9243 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9244 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
9245 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
9246 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9247 CanTy = ResTypeRef->getPointeeType();
9248 // Need to go down the pointer/mempointer chain and add qualifiers
9249 // as see them.
9250 bool done = false;
9251 while (!done) {
9252 if (CanTy.isRestrictQualified())
9253 VRQuals.addRestrict();
9254 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9255 CanTy = ResTypePtr->getPointeeType();
9256 else if (const MemberPointerType *ResTypeMPtr =
9257 CanTy->getAs<MemberPointerType>())
9258 CanTy = ResTypeMPtr->getPointeeType();
9259 else
9260 done = true;
9261 if (CanTy.isVolatileQualified())
9262 VRQuals.addVolatile();
9263 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9264 return VRQuals;
9265 }
9266 }
9267 }
9268 return VRQuals;
9269}
9270
9271// Note: We're currently only handling qualifiers that are meaningful for the
9272// LHS of compound assignment overloading.
9274 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9275 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9276 // _Atomic
9277 if (Available.hasAtomic()) {
9278 Available.removeAtomic();
9279 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
9280 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9281 return;
9282 }
9283
9284 // volatile
9285 if (Available.hasVolatile()) {
9286 Available.removeVolatile();
9287 assert(!Applied.hasVolatile());
9288 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
9289 Callback);
9290 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9291 return;
9292 }
9293
9294 Callback(Applied);
9295}
9296
9298 QualifiersAndAtomic Quals,
9299 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9301 Callback);
9302}
9303
9305 QualifiersAndAtomic Quals,
9306 Sema &S) {
9307 if (Quals.hasAtomic())
9309 if (Quals.hasVolatile())
9312}
9313
9314namespace {
9315
9316/// Helper class to manage the addition of builtin operator overload
9317/// candidates. It provides shared state and utility methods used throughout
9318/// the process, as well as a helper method to add each group of builtin
9319/// operator overloads from the standard to a candidate set.
9320class BuiltinOperatorOverloadBuilder {
9321 // Common instance state available to all overload candidate addition methods.
9322 Sema &S;
9323 ArrayRef<Expr *> Args;
9324 QualifiersAndAtomic VisibleTypeConversionsQuals;
9325 bool HasArithmeticOrEnumeralCandidateType;
9326 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9327 OverloadCandidateSet &CandidateSet;
9328
9329 static constexpr int ArithmeticTypesCap = 26;
9330 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9331
9332 // Define some indices used to iterate over the arithmetic types in
9333 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9334 // types are that preserved by promotion (C++ [over.built]p2).
9335 unsigned FirstIntegralType,
9336 LastIntegralType;
9337 unsigned FirstPromotedIntegralType,
9338 LastPromotedIntegralType;
9339 unsigned FirstPromotedArithmeticType,
9340 LastPromotedArithmeticType;
9341 unsigned NumArithmeticTypes;
9342
9343 void InitArithmeticTypes() {
9344 // Start of promoted types.
9345 FirstPromotedArithmeticType = 0;
9346 ArithmeticTypes.push_back(S.Context.FloatTy);
9347 ArithmeticTypes.push_back(S.Context.DoubleTy);
9348 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
9350 ArithmeticTypes.push_back(S.Context.Float128Ty);
9352 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
9353
9354 // Start of integral types.
9355 FirstIntegralType = ArithmeticTypes.size();
9356 FirstPromotedIntegralType = ArithmeticTypes.size();
9357 ArithmeticTypes.push_back(S.Context.IntTy);
9358 ArithmeticTypes.push_back(S.Context.LongTy);
9359 ArithmeticTypes.push_back(S.Context.LongLongTy);
9363 ArithmeticTypes.push_back(S.Context.Int128Ty);
9364 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
9365 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
9366 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
9370 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
9371
9372 /// We add candidates for the unique, unqualified _BitInt types present in
9373 /// the candidate type set. The candidate set already handled ensuring the
9374 /// type is unqualified and canonical, but because we're adding from N
9375 /// different sets, we need to do some extra work to unique things. Insert
9376 /// the candidates into a unique set, then move from that set into the list
9377 /// of arithmetic types.
9378 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9379 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9380 for (QualType BitTy : Candidate.bitint_types())
9381 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
9382 }
9383 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
9384 LastPromotedIntegralType = ArithmeticTypes.size();
9385 LastPromotedArithmeticType = ArithmeticTypes.size();
9386 // End of promoted types.
9387
9388 ArithmeticTypes.push_back(S.Context.BoolTy);
9389 ArithmeticTypes.push_back(S.Context.CharTy);
9390 ArithmeticTypes.push_back(S.Context.WCharTy);
9391 if (S.Context.getLangOpts().Char8)
9392 ArithmeticTypes.push_back(S.Context.Char8Ty);
9393 ArithmeticTypes.push_back(S.Context.Char16Ty);
9394 ArithmeticTypes.push_back(S.Context.Char32Ty);
9395 ArithmeticTypes.push_back(S.Context.SignedCharTy);
9396 ArithmeticTypes.push_back(S.Context.ShortTy);
9397 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9398 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9399 LastIntegralType = ArithmeticTypes.size();
9400 NumArithmeticTypes = ArithmeticTypes.size();
9401 // End of integral types.
9402 // FIXME: What about complex? What about half?
9403
9404 // We don't know for sure how many bit-precise candidates were involved, so
9405 // we subtract those from the total when testing whether we're under the
9406 // cap or not.
9407 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9408 ArithmeticTypesCap &&
9409 "Enough inline storage for all arithmetic types.");
9410 }
9411
9412 /// Helper method to factor out the common pattern of adding overloads
9413 /// for '++' and '--' builtin operators.
9414 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9415 bool HasVolatile,
9416 bool HasRestrict) {
9417 QualType ParamTypes[2] = {
9418 S.Context.getLValueReferenceType(CandidateTy),
9419 S.Context.IntTy
9420 };
9421
9422 // Non-volatile version.
9423 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9424
9425 // Use a heuristic to reduce number of builtin candidates in the set:
9426 // add volatile version only if there are conversions to a volatile type.
9427 if (HasVolatile) {
9428 ParamTypes[0] =
9430 S.Context.getVolatileType(CandidateTy));
9431 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9432 }
9433
9434 // Add restrict version only if there are conversions to a restrict type
9435 // and our candidate type is a non-restrict-qualified pointer.
9436 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9437 !CandidateTy.isRestrictQualified()) {
9438 ParamTypes[0]
9441 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9442
9443 if (HasVolatile) {
9444 ParamTypes[0]
9446 S.Context.getCVRQualifiedType(CandidateTy,
9449 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9450 }
9451 }
9452
9453 }
9454
9455 /// Helper to add an overload candidate for a binary builtin with types \p L
9456 /// and \p R.
9457 void AddCandidate(QualType L, QualType R) {
9458 QualType LandR[2] = {L, R};
9459 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9460 }
9461
9462public:
9463 BuiltinOperatorOverloadBuilder(
9464 Sema &S, ArrayRef<Expr *> Args,
9465 QualifiersAndAtomic VisibleTypeConversionsQuals,
9466 bool HasArithmeticOrEnumeralCandidateType,
9467 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9468 OverloadCandidateSet &CandidateSet)
9469 : S(S), Args(Args),
9470 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9471 HasArithmeticOrEnumeralCandidateType(
9472 HasArithmeticOrEnumeralCandidateType),
9473 CandidateTypes(CandidateTypes),
9474 CandidateSet(CandidateSet) {
9475
9476 InitArithmeticTypes();
9477 }
9478
9479 // Increment is deprecated for bool since C++17.
9480 //
9481 // C++ [over.built]p3:
9482 //
9483 // For every pair (T, VQ), where T is an arithmetic type other
9484 // than bool, and VQ is either volatile or empty, there exist
9485 // candidate operator functions of the form
9486 //
9487 // VQ T& operator++(VQ T&);
9488 // T operator++(VQ T&, int);
9489 //
9490 // C++ [over.built]p4:
9491 //
9492 // For every pair (T, VQ), where T is an arithmetic type other
9493 // than bool, and VQ is either volatile or empty, there exist
9494 // candidate operator functions of the form
9495 //
9496 // VQ T& operator--(VQ T&);
9497 // T operator--(VQ T&, int);
9498 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9499 if (!HasArithmeticOrEnumeralCandidateType)
9500 return;
9501
9502 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9503 const auto TypeOfT = ArithmeticTypes[Arith];
9504 if (TypeOfT == S.Context.BoolTy) {
9505 if (Op == OO_MinusMinus)
9506 continue;
9507 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9508 continue;
9509 }
9510 addPlusPlusMinusMinusStyleOverloads(
9511 TypeOfT,
9512 VisibleTypeConversionsQuals.hasVolatile(),
9513 VisibleTypeConversionsQuals.hasRestrict());
9514 }
9515 }
9516
9517 // C++ [over.built]p5:
9518 //
9519 // For every pair (T, VQ), where T is a cv-qualified or
9520 // cv-unqualified object type, and VQ is either volatile or
9521 // empty, there exist candidate operator functions of the form
9522 //
9523 // T*VQ& operator++(T*VQ&);
9524 // T*VQ& operator--(T*VQ&);
9525 // T* operator++(T*VQ&, int);
9526 // T* operator--(T*VQ&, int);
9527 void addPlusPlusMinusMinusPointerOverloads() {
9528 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9529 // Skip pointer types that aren't pointers to object types.
9530 if (!PtrTy->getPointeeType()->isObjectType())
9531 continue;
9532
9533 addPlusPlusMinusMinusStyleOverloads(
9534 PtrTy,
9535 (!PtrTy.isVolatileQualified() &&
9536 VisibleTypeConversionsQuals.hasVolatile()),
9537 (!PtrTy.isRestrictQualified() &&
9538 VisibleTypeConversionsQuals.hasRestrict()));
9539 }
9540 }
9541
9542 // C++ [over.built]p6:
9543 // For every cv-qualified or cv-unqualified object type T, there
9544 // exist candidate operator functions of the form
9545 //
9546 // T& operator*(T*);
9547 //
9548 // C++ [over.built]p7:
9549 // For every function type T that does not have cv-qualifiers or a
9550 // ref-qualifier, there exist candidate operator functions of the form
9551 // T& operator*(T*);
9552 void addUnaryStarPointerOverloads() {
9553 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9554 QualType PointeeTy = ParamTy->getPointeeType();
9555 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9556 continue;
9557
9558 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9559 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9560 continue;
9561
9562 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9563 }
9564 }
9565
9566 // C++ [over.built]p9:
9567 // For every promoted arithmetic type T, there exist candidate
9568 // operator functions of the form
9569 //
9570 // T operator+(T);
9571 // T operator-(T);
9572 void addUnaryPlusOrMinusArithmeticOverloads() {
9573 if (!HasArithmeticOrEnumeralCandidateType)
9574 return;
9575
9576 for (unsigned Arith = FirstPromotedArithmeticType;
9577 Arith < LastPromotedArithmeticType; ++Arith) {
9578 QualType ArithTy = ArithmeticTypes[Arith];
9579 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9580 }
9581
9582 // Extension: We also add these operators for vector types.
9583 for (QualType VecTy : CandidateTypes[0].vector_types())
9584 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9585 }
9586
9587 // C++ [over.built]p8:
9588 // For every type T, there exist candidate operator functions of
9589 // the form
9590 //
9591 // T* operator+(T*);
9592 void addUnaryPlusPointerOverloads() {
9593 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9594 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9595 }
9596
9597 // C++ [over.built]p10:
9598 // For every promoted integral type T, there exist candidate
9599 // operator functions of the form
9600 //
9601 // T operator~(T);
9602 void addUnaryTildePromotedIntegralOverloads() {
9603 if (!HasArithmeticOrEnumeralCandidateType)
9604 return;
9605
9606 for (unsigned Int = FirstPromotedIntegralType;
9607 Int < LastPromotedIntegralType; ++Int) {
9608 QualType IntTy = ArithmeticTypes[Int];
9609 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9610 }
9611
9612 // Extension: We also add this operator for vector types.
9613 for (QualType VecTy : CandidateTypes[0].vector_types())
9614 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9615 }
9616
9617 // C++ [over.match.oper]p16:
9618 // For every pointer to member type T or type std::nullptr_t, there
9619 // exist candidate operator functions of the form
9620 //
9621 // bool operator==(T,T);
9622 // bool operator!=(T,T);
9623 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9624 /// Set of (canonical) types that we've already handled.
9625 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9626
9627 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9628 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9629 // Don't add the same builtin candidate twice.
9630 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9631 continue;
9632
9633 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9634 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9635 }
9636
9637 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9639 if (AddedTypes.insert(NullPtrTy).second) {
9640 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9641 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9642 }
9643 }
9644 }
9645 }
9646
9647 // C++ [over.built]p15:
9648 //
9649 // For every T, where T is an enumeration type or a pointer type,
9650 // there exist candidate operator functions of the form
9651 //
9652 // bool operator<(T, T);
9653 // bool operator>(T, T);
9654 // bool operator<=(T, T);
9655 // bool operator>=(T, T);
9656 // bool operator==(T, T);
9657 // bool operator!=(T, T);
9658 // R operator<=>(T, T)
9659 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9660 // C++ [over.match.oper]p3:
9661 // [...]the built-in candidates include all of the candidate operator
9662 // functions defined in 13.6 that, compared to the given operator, [...]
9663 // do not have the same parameter-type-list as any non-template non-member
9664 // candidate.
9665 //
9666 // Note that in practice, this only affects enumeration types because there
9667 // aren't any built-in candidates of record type, and a user-defined operator
9668 // must have an operand of record or enumeration type. Also, the only other
9669 // overloaded operator with enumeration arguments, operator=,
9670 // cannot be overloaded for enumeration types, so this is the only place
9671 // where we must suppress candidates like this.
9672 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9673 UserDefinedBinaryOperators;
9674
9675 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9676 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9677 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9678 CEnd = CandidateSet.end();
9679 C != CEnd; ++C) {
9680 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9681 continue;
9682
9683 if (C->Function->isFunctionTemplateSpecialization())
9684 continue;
9685
9686 // We interpret "same parameter-type-list" as applying to the
9687 // "synthesized candidate, with the order of the two parameters
9688 // reversed", not to the original function.
9689 bool Reversed = C->isReversed();
9690 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9691 ->getType()
9692 .getUnqualifiedType();
9693 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9694 ->getType()
9695 .getUnqualifiedType();
9696
9697 // Skip if either parameter isn't of enumeral type.
9698 if (!FirstParamType->isEnumeralType() ||
9699 !SecondParamType->isEnumeralType())
9700 continue;
9701
9702 // Add this operator to the set of known user-defined operators.
9703 UserDefinedBinaryOperators.insert(
9704 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9705 S.Context.getCanonicalType(SecondParamType)));
9706 }
9707 }
9708 }
9709
9710 /// Set of (canonical) types that we've already handled.
9711 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9712
9713 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9714 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9715 // Don't add the same builtin candidate twice.
9716 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9717 continue;
9718 if (IsSpaceship && PtrTy->isFunctionPointerType())
9719 continue;
9720
9721 QualType ParamTypes[2] = {PtrTy, PtrTy};
9722 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9723 }
9724 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9725 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9726
9727 // Don't add the same builtin candidate twice, or if a user defined
9728 // candidate exists.
9729 if (!AddedTypes.insert(CanonType).second ||
9730 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9731 CanonType)))
9732 continue;
9733 QualType ParamTypes[2] = {EnumTy, EnumTy};
9734 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9735 }
9736 }
9737 }
9738
9739 // C++ [over.built]p13:
9740 //
9741 // For every cv-qualified or cv-unqualified object type T
9742 // there exist candidate operator functions of the form
9743 //
9744 // T* operator+(T*, ptrdiff_t);
9745 // T& operator[](T*, ptrdiff_t); [BELOW]
9746 // T* operator-(T*, ptrdiff_t);
9747 // T* operator+(ptrdiff_t, T*);
9748 // T& operator[](ptrdiff_t, T*); [BELOW]
9749 //
9750 // C++ [over.built]p14:
9751 //
9752 // For every T, where T is a pointer to object type, there
9753 // exist candidate operator functions of the form
9754 //
9755 // ptrdiff_t operator-(T, T);
9756 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9757 /// Set of (canonical) types that we've already handled.
9758 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9759
9760 for (int Arg = 0; Arg < 2; ++Arg) {
9761 QualType AsymmetricParamTypes[2] = {
9764 };
9765 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9766 QualType PointeeTy = PtrTy->getPointeeType();
9767 if (!PointeeTy->isObjectType())
9768 continue;
9769
9770 AsymmetricParamTypes[Arg] = PtrTy;
9771 if (Arg == 0 || Op == OO_Plus) {
9772 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9773 // T* operator+(ptrdiff_t, T*);
9774 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9775 }
9776 if (Op == OO_Minus) {
9777 // ptrdiff_t operator-(T, T);
9778 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9779 continue;
9780
9781 QualType ParamTypes[2] = {PtrTy, PtrTy};
9782 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9783 }
9784 }
9785 }
9786 }
9787
9788 // C++ [over.built]p12:
9789 //
9790 // For every pair of promoted arithmetic types L and R, there
9791 // exist candidate operator functions of the form
9792 //
9793 // LR operator*(L, R);
9794 // LR operator/(L, R);
9795 // LR operator+(L, R);
9796 // LR operator-(L, R);
9797 // bool operator<(L, R);
9798 // bool operator>(L, R);
9799 // bool operator<=(L, R);
9800 // bool operator>=(L, R);
9801 // bool operator==(L, R);
9802 // bool operator!=(L, R);
9803 //
9804 // where LR is the result of the usual arithmetic conversions
9805 // between types L and R.
9806 //
9807 // C++ [over.built]p24:
9808 //
9809 // For every pair of promoted arithmetic types L and R, there exist
9810 // candidate operator functions of the form
9811 //
9812 // LR operator?(bool, L, R);
9813 //
9814 // where LR is the result of the usual arithmetic conversions
9815 // between types L and R.
9816 // Our candidates ignore the first parameter.
9817 void addGenericBinaryArithmeticOverloads() {
9818 if (!HasArithmeticOrEnumeralCandidateType)
9819 return;
9820
9821 for (unsigned Left = FirstPromotedArithmeticType;
9822 Left < LastPromotedArithmeticType; ++Left) {
9823 for (unsigned Right = FirstPromotedArithmeticType;
9824 Right < LastPromotedArithmeticType; ++Right) {
9825 QualType LandR[2] = { ArithmeticTypes[Left],
9826 ArithmeticTypes[Right] };
9827 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9828 }
9829 }
9830
9831 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9832 // conditional operator for vector types.
9833 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9834 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9835 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9836 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9837 }
9838 }
9839
9840 /// Add binary operator overloads for each candidate matrix type M1, M2:
9841 /// * (M1, M1) -> M1
9842 /// * (M1, M1.getElementType()) -> M1
9843 /// * (M2.getElementType(), M2) -> M2
9844 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9845 void addMatrixBinaryArithmeticOverloads() {
9846 if (!HasArithmeticOrEnumeralCandidateType)
9847 return;
9848
9849 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9850 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9851 AddCandidate(M1, M1);
9852 }
9853
9854 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9855 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9856 if (!CandidateTypes[0].containsMatrixType(M2))
9857 AddCandidate(M2, M2);
9858 }
9859 }
9860
9861 // C++2a [over.built]p14:
9862 //
9863 // For every integral type T there exists a candidate operator function
9864 // of the form
9865 //
9866 // std::strong_ordering operator<=>(T, T)
9867 //
9868 // C++2a [over.built]p15:
9869 //
9870 // For every pair of floating-point types L and R, there exists a candidate
9871 // operator function of the form
9872 //
9873 // std::partial_ordering operator<=>(L, R);
9874 //
9875 // FIXME: The current specification for integral types doesn't play nice with
9876 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9877 // comparisons. Under the current spec this can lead to ambiguity during
9878 // overload resolution. For example:
9879 //
9880 // enum A : int {a};
9881 // auto x = (a <=> (long)42);
9882 //
9883 // error: call is ambiguous for arguments 'A' and 'long'.
9884 // note: candidate operator<=>(int, int)
9885 // note: candidate operator<=>(long, long)
9886 //
9887 // To avoid this error, this function deviates from the specification and adds
9888 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9889 // arithmetic types (the same as the generic relational overloads).
9890 //
9891 // For now this function acts as a placeholder.
9892 void addThreeWayArithmeticOverloads() {
9893 addGenericBinaryArithmeticOverloads();
9894 }
9895
9896 // C++ [over.built]p17:
9897 //
9898 // For every pair of promoted integral types L and R, there
9899 // exist candidate operator functions of the form
9900 //
9901 // LR operator%(L, R);
9902 // LR operator&(L, R);
9903 // LR operator^(L, R);
9904 // LR operator|(L, R);
9905 // L operator<<(L, R);
9906 // L operator>>(L, R);
9907 //
9908 // where LR is the result of the usual arithmetic conversions
9909 // between types L and R.
9910 void addBinaryBitwiseArithmeticOverloads() {
9911 if (!HasArithmeticOrEnumeralCandidateType)
9912 return;
9913
9914 for (unsigned Left = FirstPromotedIntegralType;
9915 Left < LastPromotedIntegralType; ++Left) {
9916 for (unsigned Right = FirstPromotedIntegralType;
9917 Right < LastPromotedIntegralType; ++Right) {
9918 QualType LandR[2] = { ArithmeticTypes[Left],
9919 ArithmeticTypes[Right] };
9920 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9921 }
9922 }
9923 }
9924
9925 // C++ [over.built]p20:
9926 //
9927 // For every pair (T, VQ), where T is an enumeration or
9928 // pointer to member type and VQ is either volatile or
9929 // empty, there exist candidate operator functions of the form
9930 //
9931 // VQ T& operator=(VQ T&, T);
9932 void addAssignmentMemberPointerOrEnumeralOverloads() {
9933 /// Set of (canonical) types that we've already handled.
9934 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9935
9936 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9937 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9938 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9939 continue;
9940
9941 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9942 }
9943
9944 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9945 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9946 continue;
9947
9948 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9949 }
9950 }
9951 }
9952
9953 // C++ [over.built]p19:
9954 //
9955 // For every pair (T, VQ), where T is any type and VQ is either
9956 // volatile or empty, there exist candidate operator functions
9957 // of the form
9958 //
9959 // T*VQ& operator=(T*VQ&, T*);
9960 //
9961 // C++ [over.built]p21:
9962 //
9963 // For every pair (T, VQ), where T is a cv-qualified or
9964 // cv-unqualified object type and VQ is either volatile or
9965 // empty, there exist candidate operator functions of the form
9966 //
9967 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9968 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9969 void addAssignmentPointerOverloads(bool isEqualOp) {
9970 /// Set of (canonical) types that we've already handled.
9971 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9972
9973 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9974 // If this is operator=, keep track of the builtin candidates we added.
9975 if (isEqualOp)
9976 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9977 else if (!PtrTy->getPointeeType()->isObjectType())
9978 continue;
9979
9980 // non-volatile version
9981 QualType ParamTypes[2] = {
9983 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9984 };
9985 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9986 /*IsAssignmentOperator=*/ isEqualOp);
9987
9988 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9989 VisibleTypeConversionsQuals.hasVolatile();
9990 if (NeedVolatile) {
9991 // volatile version
9992 ParamTypes[0] =
9994 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9995 /*IsAssignmentOperator=*/isEqualOp);
9996 }
9997
9998 if (!PtrTy.isRestrictQualified() &&
9999 VisibleTypeConversionsQuals.hasRestrict()) {
10000 // restrict version
10001 ParamTypes[0] =
10003 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10004 /*IsAssignmentOperator=*/isEqualOp);
10005
10006 if (NeedVolatile) {
10007 // volatile restrict version
10008 ParamTypes[0] =
10011 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10012 /*IsAssignmentOperator=*/isEqualOp);
10013 }
10014 }
10015 }
10016
10017 if (isEqualOp) {
10018 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10019 // Make sure we don't add the same candidate twice.
10020 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10021 continue;
10022
10023 QualType ParamTypes[2] = {
10025 PtrTy,
10026 };
10027
10028 // non-volatile version
10029 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10030 /*IsAssignmentOperator=*/true);
10031
10032 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10033 VisibleTypeConversionsQuals.hasVolatile();
10034 if (NeedVolatile) {
10035 // volatile version
10036 ParamTypes[0] = S.Context.getLValueReferenceType(
10037 S.Context.getVolatileType(PtrTy));
10038 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10039 /*IsAssignmentOperator=*/true);
10040 }
10041
10042 if (!PtrTy.isRestrictQualified() &&
10043 VisibleTypeConversionsQuals.hasRestrict()) {
10044 // restrict version
10045 ParamTypes[0] = S.Context.getLValueReferenceType(
10046 S.Context.getRestrictType(PtrTy));
10047 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10048 /*IsAssignmentOperator=*/true);
10049
10050 if (NeedVolatile) {
10051 // volatile restrict version
10052 ParamTypes[0] =
10055 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10056 /*IsAssignmentOperator=*/true);
10057 }
10058 }
10059 }
10060 }
10061 }
10062
10063 // C++ [over.built]p18:
10064 //
10065 // For every triple (L, VQ, R), where L is an arithmetic type,
10066 // VQ is either volatile or empty, and R is a promoted
10067 // arithmetic type, there exist candidate operator functions of
10068 // the form
10069 //
10070 // VQ L& operator=(VQ L&, R);
10071 // VQ L& operator*=(VQ L&, R);
10072 // VQ L& operator/=(VQ L&, R);
10073 // VQ L& operator+=(VQ L&, R);
10074 // VQ L& operator-=(VQ L&, R);
10075 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10076 if (!HasArithmeticOrEnumeralCandidateType)
10077 return;
10078
10079 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10080 for (unsigned Right = FirstPromotedArithmeticType;
10081 Right < LastPromotedArithmeticType; ++Right) {
10082 QualType ParamTypes[2];
10083 ParamTypes[1] = ArithmeticTypes[Right];
10085 S, ArithmeticTypes[Left], Args[0]);
10086
10088 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10089 ParamTypes[0] =
10090 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10091 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10092 /*IsAssignmentOperator=*/isEqualOp);
10093 });
10094 }
10095 }
10096
10097 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10098 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10099 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10100 QualType ParamTypes[2];
10101 ParamTypes[1] = Vec2Ty;
10102 // Add this built-in operator as a candidate (VQ is empty).
10103 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
10104 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10105 /*IsAssignmentOperator=*/isEqualOp);
10106
10107 // Add this built-in operator as a candidate (VQ is 'volatile').
10108 if (VisibleTypeConversionsQuals.hasVolatile()) {
10109 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
10110 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
10111 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10112 /*IsAssignmentOperator=*/isEqualOp);
10113 }
10114 }
10115 }
10116
10117 // C++ [over.built]p22:
10118 //
10119 // For every triple (L, VQ, R), where L is an integral type, VQ
10120 // is either volatile or empty, and R is a promoted integral
10121 // type, there exist candidate operator functions of the form
10122 //
10123 // VQ L& operator%=(VQ L&, R);
10124 // VQ L& operator<<=(VQ L&, R);
10125 // VQ L& operator>>=(VQ L&, R);
10126 // VQ L& operator&=(VQ L&, R);
10127 // VQ L& operator^=(VQ L&, R);
10128 // VQ L& operator|=(VQ L&, R);
10129 void addAssignmentIntegralOverloads() {
10130 if (!HasArithmeticOrEnumeralCandidateType)
10131 return;
10132
10133 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10134 for (unsigned Right = FirstPromotedIntegralType;
10135 Right < LastPromotedIntegralType; ++Right) {
10136 QualType ParamTypes[2];
10137 ParamTypes[1] = ArithmeticTypes[Right];
10139 S, ArithmeticTypes[Left], Args[0]);
10140
10142 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10143 ParamTypes[0] =
10144 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10145 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10146 });
10147 }
10148 }
10149 }
10150
10151 // C++ [over.operator]p23:
10152 //
10153 // There also exist candidate operator functions of the form
10154 //
10155 // bool operator!(bool);
10156 // bool operator&&(bool, bool);
10157 // bool operator||(bool, bool);
10158 void addExclaimOverload() {
10159 QualType ParamTy = S.Context.BoolTy;
10160 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
10161 /*IsAssignmentOperator=*/false,
10162 /*NumContextualBoolArguments=*/1);
10163 }
10164 void addAmpAmpOrPipePipeOverload() {
10165 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10166 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10167 /*IsAssignmentOperator=*/false,
10168 /*NumContextualBoolArguments=*/2);
10169 }
10170
10171 // C++ [over.built]p13:
10172 //
10173 // For every cv-qualified or cv-unqualified object type T there
10174 // exist candidate operator functions of the form
10175 //
10176 // T* operator+(T*, ptrdiff_t); [ABOVE]
10177 // T& operator[](T*, ptrdiff_t);
10178 // T* operator-(T*, ptrdiff_t); [ABOVE]
10179 // T* operator+(ptrdiff_t, T*); [ABOVE]
10180 // T& operator[](ptrdiff_t, T*);
10181 void addSubscriptOverloads() {
10182 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10183 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10184 QualType PointeeType = PtrTy->getPointeeType();
10185 if (!PointeeType->isObjectType())
10186 continue;
10187
10188 // T& operator[](T*, ptrdiff_t)
10189 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10190 }
10191
10192 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10193 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10194 QualType PointeeType = PtrTy->getPointeeType();
10195 if (!PointeeType->isObjectType())
10196 continue;
10197
10198 // T& operator[](ptrdiff_t, T*)
10199 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10200 }
10201 }
10202
10203 // C++ [over.built]p11:
10204 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10205 // C1 is the same type as C2 or is a derived class of C2, T is an object
10206 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10207 // there exist candidate operator functions of the form
10208 //
10209 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10210 //
10211 // where CV12 is the union of CV1 and CV2.
10212 void addArrowStarOverloads() {
10213 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10214 QualType C1Ty = PtrTy;
10215 QualType C1;
10216 QualifierCollector Q1;
10217 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
10218 if (!isa<RecordType>(C1))
10219 continue;
10220 // heuristic to reduce number of builtin candidates in the set.
10221 // Add volatile/restrict version only if there are conversions to a
10222 // volatile/restrict type.
10223 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10224 continue;
10225 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10226 continue;
10227 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10228 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
10229 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10230 *D2 = mptr->getMostRecentCXXRecordDecl();
10231 if (!declaresSameEntity(D1, D2) &&
10232 !S.IsDerivedFrom(CandidateSet.getLocation(), D1, D2))
10233 break;
10234 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10235 // build CV12 T&
10236 QualType T = mptr->getPointeeType();
10237 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10238 T.isVolatileQualified())
10239 continue;
10240 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10241 T.isRestrictQualified())
10242 continue;
10243 T = Q1.apply(S.Context, T);
10244 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10245 }
10246 }
10247 }
10248
10249 // Note that we don't consider the first argument, since it has been
10250 // contextually converted to bool long ago. The candidates below are
10251 // therefore added as binary.
10252 //
10253 // C++ [over.built]p25:
10254 // For every type T, where T is a pointer, pointer-to-member, or scoped
10255 // enumeration type, there exist candidate operator functions of the form
10256 //
10257 // T operator?(bool, T, T);
10258 //
10259 void addConditionalOperatorOverloads() {
10260 /// Set of (canonical) types that we've already handled.
10261 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10262
10263 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10264 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10265 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10266 continue;
10267
10268 QualType ParamTypes[2] = {PtrTy, PtrTy};
10269 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10270 }
10271
10272 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10273 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10274 continue;
10275
10276 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10277 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10278 }
10279
10280 if (S.getLangOpts().CPlusPlus11) {
10281 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10282 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10283 continue;
10284
10285 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10286 continue;
10287
10288 QualType ParamTypes[2] = {EnumTy, EnumTy};
10289 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10290 }
10291 }
10292 }
10293 }
10294};
10295
10296} // end anonymous namespace
10297
10299 SourceLocation OpLoc,
10300 ArrayRef<Expr *> Args,
10301 OverloadCandidateSet &CandidateSet) {
10302 // Find all of the types that the arguments can convert to, but only
10303 // if the operator we're looking at has built-in operator candidates
10304 // that make use of these types. Also record whether we encounter non-record
10305 // candidate types or either arithmetic or enumeral candidate types.
10306 QualifiersAndAtomic VisibleTypeConversionsQuals;
10307 VisibleTypeConversionsQuals.addConst();
10308 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10309 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
10310 if (Args[ArgIdx]->getType()->isAtomicType())
10311 VisibleTypeConversionsQuals.addAtomic();
10312 }
10313
10314 bool HasNonRecordCandidateType = false;
10315 bool HasArithmeticOrEnumeralCandidateType = false;
10317 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10318 CandidateTypes.emplace_back(*this);
10319 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
10320 OpLoc,
10321 true,
10322 (Op == OO_Exclaim ||
10323 Op == OO_AmpAmp ||
10324 Op == OO_PipePipe),
10325 VisibleTypeConversionsQuals);
10326 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10327 CandidateTypes[ArgIdx].hasNonRecordTypes();
10328 HasArithmeticOrEnumeralCandidateType =
10329 HasArithmeticOrEnumeralCandidateType ||
10330 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10331 }
10332
10333 // Exit early when no non-record types have been added to the candidate set
10334 // for any of the arguments to the operator.
10335 //
10336 // We can't exit early for !, ||, or &&, since there we have always have
10337 // 'bool' overloads.
10338 if (!HasNonRecordCandidateType &&
10339 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10340 return;
10341
10342 // Setup an object to manage the common state for building overloads.
10343 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10344 VisibleTypeConversionsQuals,
10345 HasArithmeticOrEnumeralCandidateType,
10346 CandidateTypes, CandidateSet);
10347
10348 // Dispatch over the operation to add in only those overloads which apply.
10349 switch (Op) {
10350 case OO_None:
10352 llvm_unreachable("Expected an overloaded operator");
10353
10354 case OO_New:
10355 case OO_Delete:
10356 case OO_Array_New:
10357 case OO_Array_Delete:
10358 case OO_Call:
10359 llvm_unreachable(
10360 "Special operators don't use AddBuiltinOperatorCandidates");
10361
10362 case OO_Comma:
10363 case OO_Arrow:
10364 case OO_Coawait:
10365 // C++ [over.match.oper]p3:
10366 // -- For the operator ',', the unary operator '&', the
10367 // operator '->', or the operator 'co_await', the
10368 // built-in candidates set is empty.
10369 break;
10370
10371 case OO_Plus: // '+' is either unary or binary
10372 if (Args.size() == 1)
10373 OpBuilder.addUnaryPlusPointerOverloads();
10374 [[fallthrough]];
10375
10376 case OO_Minus: // '-' is either unary or binary
10377 if (Args.size() == 1) {
10378 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10379 } else {
10380 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10381 OpBuilder.addGenericBinaryArithmeticOverloads();
10382 OpBuilder.addMatrixBinaryArithmeticOverloads();
10383 }
10384 break;
10385
10386 case OO_Star: // '*' is either unary or binary
10387 if (Args.size() == 1)
10388 OpBuilder.addUnaryStarPointerOverloads();
10389 else {
10390 OpBuilder.addGenericBinaryArithmeticOverloads();
10391 OpBuilder.addMatrixBinaryArithmeticOverloads();
10392 }
10393 break;
10394
10395 case OO_Slash:
10396 OpBuilder.addGenericBinaryArithmeticOverloads();
10397 break;
10398
10399 case OO_PlusPlus:
10400 case OO_MinusMinus:
10401 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10402 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10403 break;
10404
10405 case OO_EqualEqual:
10406 case OO_ExclaimEqual:
10407 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10408 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10409 OpBuilder.addGenericBinaryArithmeticOverloads();
10410 break;
10411
10412 case OO_Less:
10413 case OO_Greater:
10414 case OO_LessEqual:
10415 case OO_GreaterEqual:
10416 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10417 OpBuilder.addGenericBinaryArithmeticOverloads();
10418 break;
10419
10420 case OO_Spaceship:
10421 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10422 OpBuilder.addThreeWayArithmeticOverloads();
10423 break;
10424
10425 case OO_Percent:
10426 case OO_Caret:
10427 case OO_Pipe:
10428 case OO_LessLess:
10429 case OO_GreaterGreater:
10430 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10431 break;
10432
10433 case OO_Amp: // '&' is either unary or binary
10434 if (Args.size() == 1)
10435 // C++ [over.match.oper]p3:
10436 // -- For the operator ',', the unary operator '&', or the
10437 // operator '->', the built-in candidates set is empty.
10438 break;
10439
10440 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10441 break;
10442
10443 case OO_Tilde:
10444 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10445 break;
10446
10447 case OO_Equal:
10448 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10449 [[fallthrough]];
10450
10451 case OO_PlusEqual:
10452 case OO_MinusEqual:
10453 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10454 [[fallthrough]];
10455
10456 case OO_StarEqual:
10457 case OO_SlashEqual:
10458 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10459 break;
10460
10461 case OO_PercentEqual:
10462 case OO_LessLessEqual:
10463 case OO_GreaterGreaterEqual:
10464 case OO_AmpEqual:
10465 case OO_CaretEqual:
10466 case OO_PipeEqual:
10467 OpBuilder.addAssignmentIntegralOverloads();
10468 break;
10469
10470 case OO_Exclaim:
10471 OpBuilder.addExclaimOverload();
10472 break;
10473
10474 case OO_AmpAmp:
10475 case OO_PipePipe:
10476 OpBuilder.addAmpAmpOrPipePipeOverload();
10477 break;
10478
10479 case OO_Subscript:
10480 if (Args.size() == 2)
10481 OpBuilder.addSubscriptOverloads();
10482 break;
10483
10484 case OO_ArrowStar:
10485 OpBuilder.addArrowStarOverloads();
10486 break;
10487
10488 case OO_Conditional:
10489 OpBuilder.addConditionalOperatorOverloads();
10490 OpBuilder.addGenericBinaryArithmeticOverloads();
10491 break;
10492 }
10493}
10494
10495void
10497 SourceLocation Loc,
10498 ArrayRef<Expr *> Args,
10499 TemplateArgumentListInfo *ExplicitTemplateArgs,
10500 OverloadCandidateSet& CandidateSet,
10501 bool PartialOverloading) {
10502 ADLResult Fns;
10503
10504 // FIXME: This approach for uniquing ADL results (and removing
10505 // redundant candidates from the set) relies on pointer-equality,
10506 // which means we need to key off the canonical decl. However,
10507 // always going back to the canonical decl might not get us the
10508 // right set of default arguments. What default arguments are
10509 // we supposed to consider on ADL candidates, anyway?
10510
10511 // FIXME: Pass in the explicit template arguments?
10512 ArgumentDependentLookup(Name, Loc, Args, Fns);
10513
10514 ArrayRef<Expr *> ReversedArgs;
10515
10516 // Erase all of the candidates we already knew about.
10517 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10518 CandEnd = CandidateSet.end();
10519 Cand != CandEnd; ++Cand)
10520 if (Cand->Function) {
10521 FunctionDecl *Fn = Cand->Function;
10522 Fns.erase(Fn);
10523 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10524 Fns.erase(FunTmpl);
10525 }
10526
10527 // For each of the ADL candidates we found, add it to the overload
10528 // set.
10529 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10531
10532 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10533 if (ExplicitTemplateArgs)
10534 continue;
10535
10537 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10538 PartialOverloading, /*AllowExplicit=*/true,
10539 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10540 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10542 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10543 /*SuppressUserConversions=*/false, PartialOverloading,
10544 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10545 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10546 }
10547 } else {
10548 auto *FTD = cast<FunctionTemplateDecl>(*I);
10550 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10551 /*SuppressUserConversions=*/false, PartialOverloading,
10552 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10553 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10554 *this, Args, FTD->getTemplatedDecl())) {
10555
10556 // As template candidates are not deduced immediately,
10557 // persist the array in the overload set.
10558 if (ReversedArgs.empty())
10559 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
10560
10562 FTD, FoundDecl, ExplicitTemplateArgs, ReversedArgs, CandidateSet,
10563 /*SuppressUserConversions=*/false, PartialOverloading,
10564 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10566 }
10567 }
10568 }
10569}
10570
10571namespace {
10572enum class Comparison { Equal, Better, Worse };
10573}
10574
10575/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10576/// overload resolution.
10577///
10578/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10579/// Cand1's first N enable_if attributes have precisely the same conditions as
10580/// Cand2's first N enable_if attributes (where N = the number of enable_if
10581/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10582///
10583/// Note that you can have a pair of candidates such that Cand1's enable_if
10584/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10585/// worse than Cand1's.
10586static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10587 const FunctionDecl *Cand2) {
10588 // Common case: One (or both) decls don't have enable_if attrs.
10589 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10590 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10591 if (!Cand1Attr || !Cand2Attr) {
10592 if (Cand1Attr == Cand2Attr)
10593 return Comparison::Equal;
10594 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10595 }
10596
10597 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10598 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10599
10600 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10601 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10602 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10603 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10604
10605 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10606 // has fewer enable_if attributes than Cand2, and vice versa.
10607 if (!Cand1A)
10608 return Comparison::Worse;
10609 if (!Cand2A)
10610 return Comparison::Better;
10611
10612 Cand1ID.clear();
10613 Cand2ID.clear();
10614
10615 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10616 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10617 if (Cand1ID != Cand2ID)
10618 return Comparison::Worse;
10619 }
10620
10621 return Comparison::Equal;
10622}
10623
10624static Comparison
10626 const OverloadCandidate &Cand2) {
10627 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10628 !Cand2.Function->isMultiVersion())
10629 return Comparison::Equal;
10630
10631 // If both are invalid, they are equal. If one of them is invalid, the other
10632 // is better.
10633 if (Cand1.Function->isInvalidDecl()) {
10634 if (Cand2.Function->isInvalidDecl())
10635 return Comparison::Equal;
10636 return Comparison::Worse;
10637 }
10638 if (Cand2.Function->isInvalidDecl())
10639 return Comparison::Better;
10640
10641 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10642 // cpu_dispatch, else arbitrarily based on the identifiers.
10643 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10644 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10645 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10646 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10647
10648 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10649 return Comparison::Equal;
10650
10651 if (Cand1CPUDisp && !Cand2CPUDisp)
10652 return Comparison::Better;
10653 if (Cand2CPUDisp && !Cand1CPUDisp)
10654 return Comparison::Worse;
10655
10656 if (Cand1CPUSpec && Cand2CPUSpec) {
10657 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10658 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10659 ? Comparison::Better
10660 : Comparison::Worse;
10661
10662 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10663 FirstDiff = std::mismatch(
10664 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10665 Cand2CPUSpec->cpus_begin(),
10666 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10667 return LHS->getName() == RHS->getName();
10668 });
10669
10670 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10671 "Two different cpu-specific versions should not have the same "
10672 "identifier list, otherwise they'd be the same decl!");
10673 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10674 ? Comparison::Better
10675 : Comparison::Worse;
10676 }
10677 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10678}
10679
10680/// Compute the type of the implicit object parameter for the given function,
10681/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10682/// null QualType if there is a 'matches anything' implicit object parameter.
10683static std::optional<QualType>
10686 return std::nullopt;
10687
10688 auto *M = cast<CXXMethodDecl>(F);
10689 // Static member functions' object parameters match all types.
10690 if (M->isStatic())
10691 return QualType();
10692 return M->getFunctionObjectParameterReferenceType();
10693}
10694
10695// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10696// represent the same entity.
10697static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10698 const FunctionDecl *F2) {
10699 if (declaresSameEntity(F1, F2))
10700 return true;
10701 auto PT1 = F1->getPrimaryTemplate();
10702 auto PT2 = F2->getPrimaryTemplate();
10703 if (PT1 && PT2) {
10704 if (declaresSameEntity(PT1, PT2) ||
10705 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10706 PT2->getInstantiatedFromMemberTemplate()))
10707 return true;
10708 }
10709 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10710 // different functions with same params). Consider removing this (as no test
10711 // fail w/o it).
10712 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10713 if (First) {
10714 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10715 return *T;
10716 }
10717 assert(I < F->getNumParams());
10718 return F->getParamDecl(I++)->getType();
10719 };
10720
10721 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10722 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10723
10724 if (F1NumParams != F2NumParams)
10725 return false;
10726
10727 unsigned I1 = 0, I2 = 0;
10728 for (unsigned I = 0; I != F1NumParams; ++I) {
10729 QualType T1 = NextParam(F1, I1, I == 0);
10730 QualType T2 = NextParam(F2, I2, I == 0);
10731 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10732 if (!Context.hasSameUnqualifiedType(T1, T2))
10733 return false;
10734 }
10735 return true;
10736}
10737
10738/// We're allowed to use constraints partial ordering only if the candidates
10739/// have the same parameter types:
10740/// [over.match.best.general]p2.6
10741/// F1 and F2 are non-template functions with the same
10742/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10744 FunctionDecl *Fn2,
10745 bool IsFn1Reversed,
10746 bool IsFn2Reversed) {
10747 assert(Fn1 && Fn2);
10748 if (Fn1->isVariadic() != Fn2->isVariadic())
10749 return false;
10750
10751 if (!S.FunctionNonObjectParamTypesAreEqual(Fn1, Fn2, nullptr,
10752 IsFn1Reversed ^ IsFn2Reversed))
10753 return false;
10754
10755 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10756 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10757 if (Mem1 && Mem2) {
10758 // if they are member functions, both are direct members of the same class,
10759 // and
10760 if (Mem1->getParent() != Mem2->getParent())
10761 return false;
10762 // if both are non-static member functions, they have the same types for
10763 // their object parameters
10764 if (Mem1->isInstance() && Mem2->isInstance() &&
10766 Mem1->getFunctionObjectParameterReferenceType(),
10767 Mem1->getFunctionObjectParameterReferenceType()))
10768 return false;
10769 }
10770 return true;
10771}
10772
10773static FunctionDecl *
10775 bool IsFn1Reversed, bool IsFn2Reversed) {
10776 if (!Fn1 || !Fn2)
10777 return nullptr;
10778
10779 // C++ [temp.constr.order]:
10780 // A non-template function F1 is more partial-ordering-constrained than a
10781 // non-template function F2 if:
10782 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10783 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10784
10785 if (Cand1IsSpecialization || Cand2IsSpecialization)
10786 return nullptr;
10787
10788 // - they have the same non-object-parameter-type-lists, and [...]
10789 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10790 IsFn2Reversed))
10791 return nullptr;
10792
10793 // - the declaration of F1 is more constrained than the declaration of F2.
10794 return S.getMoreConstrainedFunction(Fn1, Fn2);
10795}
10796
10797/// isBetterOverloadCandidate - Determines whether the first overload
10798/// candidate is a better candidate than the second (C++ 13.3.3p1).
10800 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10802 bool PartialOverloading) {
10803 // Define viable functions to be better candidates than non-viable
10804 // functions.
10805 if (!Cand2.Viable)
10806 return Cand1.Viable;
10807 else if (!Cand1.Viable)
10808 return false;
10809
10810 // [CUDA] A function with 'never' preference is marked not viable, therefore
10811 // is never shown up here. The worst preference shown up here is 'wrong side',
10812 // e.g. an H function called by a HD function in device compilation. This is
10813 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10814 // function which is called only by an H function. A deferred diagnostic will
10815 // be triggered if it is emitted. However a wrong-sided function is still
10816 // a viable candidate here.
10817 //
10818 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10819 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10820 // can be emitted, Cand1 is not better than Cand2. This rule should have
10821 // precedence over other rules.
10822 //
10823 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10824 // other rules should be used to determine which is better. This is because
10825 // host/device based overloading resolution is mostly for determining
10826 // viability of a function. If two functions are both viable, other factors
10827 // should take precedence in preference, e.g. the standard-defined preferences
10828 // like argument conversion ranks or enable_if partial-ordering. The
10829 // preference for pass-object-size parameters is probably most similar to a
10830 // type-based-overloading decision and so should take priority.
10831 //
10832 // If other rules cannot determine which is better, CUDA preference will be
10833 // used again to determine which is better.
10834 //
10835 // TODO: Currently IdentifyPreference does not return correct values
10836 // for functions called in global variable initializers due to missing
10837 // correct context about device/host. Therefore we can only enforce this
10838 // rule when there is a caller. We should enforce this rule for functions
10839 // in global variable initializers once proper context is added.
10840 //
10841 // TODO: We can only enable the hostness based overloading resolution when
10842 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10843 // overloading resolution diagnostics.
10844 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10845 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10846 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10847 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
10848 bool IsCand1ImplicitHD =
10850 bool IsCand2ImplicitHD =
10852 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
10853 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10854 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10855 // The implicit HD function may be a function in a system header which
10856 // is forced by pragma. In device compilation, if we prefer HD candidates
10857 // over wrong-sided candidates, overloading resolution may change, which
10858 // may result in non-deferrable diagnostics. As a workaround, we let
10859 // implicit HD candidates take equal preference as wrong-sided candidates.
10860 // This will preserve the overloading resolution.
10861 // TODO: We still need special handling of implicit HD functions since
10862 // they may incur other diagnostics to be deferred. We should make all
10863 // host/device related diagnostics deferrable and remove special handling
10864 // of implicit HD functions.
10865 auto EmitThreshold =
10866 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10867 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10870 auto Cand1Emittable = P1 > EmitThreshold;
10871 auto Cand2Emittable = P2 > EmitThreshold;
10872 if (Cand1Emittable && !Cand2Emittable)
10873 return true;
10874 if (!Cand1Emittable && Cand2Emittable)
10875 return false;
10876 }
10877 }
10878
10879 // C++ [over.match.best]p1: (Changed in C++23)
10880 //
10881 // -- if F is a static member function, ICS1(F) is defined such
10882 // that ICS1(F) is neither better nor worse than ICS1(G) for
10883 // any function G, and, symmetrically, ICS1(G) is neither
10884 // better nor worse than ICS1(F).
10885 unsigned StartArg = 0;
10886 if (!Cand1.TookAddressOfOverload &&
10888 StartArg = 1;
10889
10890 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10891 // We don't allow incompatible pointer conversions in C++.
10892 if (!S.getLangOpts().CPlusPlus)
10893 return ICS.isStandard() &&
10894 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10895
10896 // The only ill-formed conversion we allow in C++ is the string literal to
10897 // char* conversion, which is only considered ill-formed after C++11.
10898 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10900 };
10901
10902 // Define functions that don't require ill-formed conversions for a given
10903 // argument to be better candidates than functions that do.
10904 unsigned NumArgs = Cand1.Conversions.size();
10905 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10906 bool HasBetterConversion = false;
10907 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10908 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10909 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10910 if (Cand1Bad != Cand2Bad) {
10911 if (Cand1Bad)
10912 return false;
10913 HasBetterConversion = true;
10914 }
10915 }
10916
10917 if (HasBetterConversion)
10918 return true;
10919
10920 // C++ [over.match.best]p1:
10921 // A viable function F1 is defined to be a better function than another
10922 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10923 // conversion sequence than ICSi(F2), and then...
10924 bool HasWorseConversion = false;
10925 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10927 Cand1.Conversions[ArgIdx],
10928 Cand2.Conversions[ArgIdx])) {
10930 // Cand1 has a better conversion sequence.
10931 HasBetterConversion = true;
10932 break;
10933
10935 if (Cand1.Function && Cand2.Function &&
10936 Cand1.isReversed() != Cand2.isReversed() &&
10937 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
10938 // Work around large-scale breakage caused by considering reversed
10939 // forms of operator== in C++20:
10940 //
10941 // When comparing a function against a reversed function, if we have a
10942 // better conversion for one argument and a worse conversion for the
10943 // other, the implicit conversion sequences are treated as being equally
10944 // good.
10945 //
10946 // This prevents a comparison function from being considered ambiguous
10947 // with a reversed form that is written in the same way.
10948 //
10949 // We diagnose this as an extension from CreateOverloadedBinOp.
10950 HasWorseConversion = true;
10951 break;
10952 }
10953
10954 // Cand1 can't be better than Cand2.
10955 return false;
10956
10958 // Do nothing.
10959 break;
10960 }
10961 }
10962
10963 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10964 // ICSj(F2), or, if not that,
10965 if (HasBetterConversion && !HasWorseConversion)
10966 return true;
10967
10968 // -- the context is an initialization by user-defined conversion
10969 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10970 // from the return type of F1 to the destination type (i.e.,
10971 // the type of the entity being initialized) is a better
10972 // conversion sequence than the standard conversion sequence
10973 // from the return type of F2 to the destination type.
10975 Cand1.Function && Cand2.Function &&
10978
10979 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
10980 // First check whether we prefer one of the conversion functions over the
10981 // other. This only distinguishes the results in non-standard, extension
10982 // cases such as the conversion from a lambda closure type to a function
10983 // pointer or block.
10988 Cand1.FinalConversion,
10989 Cand2.FinalConversion);
10990
10993
10994 // FIXME: Compare kind of reference binding if conversion functions
10995 // convert to a reference type used in direct reference binding, per
10996 // C++14 [over.match.best]p1 section 2 bullet 3.
10997 }
10998
10999 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
11000 // as combined with the resolution to CWG issue 243.
11001 //
11002 // When the context is initialization by constructor ([over.match.ctor] or
11003 // either phase of [over.match.list]), a constructor is preferred over
11004 // a conversion function.
11005 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
11006 Cand1.Function && Cand2.Function &&
11009 return isa<CXXConstructorDecl>(Cand1.Function);
11010
11011 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
11012 return Cand2.StrictPackMatch;
11013
11014 // -- F1 is a non-template function and F2 is a function template
11015 // specialization, or, if not that,
11016 bool Cand1IsSpecialization = Cand1.Function &&
11018 bool Cand2IsSpecialization = Cand2.Function &&
11020 if (Cand1IsSpecialization != Cand2IsSpecialization)
11021 return Cand2IsSpecialization;
11022
11023 // -- F1 and F2 are function template specializations, and the function
11024 // template for F1 is more specialized than the template for F2
11025 // according to the partial ordering rules described in 14.5.5.2, or,
11026 // if not that,
11027 if (Cand1IsSpecialization && Cand2IsSpecialization) {
11028 const auto *Obj1Context =
11029 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
11030 const auto *Obj2Context =
11031 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
11032 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
11034 Cand2.Function->getPrimaryTemplate(), Loc,
11036 : TPOC_Call,
11038 Obj1Context ? S.Context.getCanonicalTagType(Obj1Context)
11039 : QualType{},
11040 Obj2Context ? S.Context.getCanonicalTagType(Obj2Context)
11041 : QualType{},
11042 Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
11043 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
11044 }
11045 }
11046
11047 // -— F1 and F2 are non-template functions and F1 is more
11048 // partial-ordering-constrained than F2 [...],
11050 S, Cand1.Function, Cand2.Function, Cand1.isReversed(),
11051 Cand2.isReversed());
11052 F && F == Cand1.Function)
11053 return true;
11054
11055 // -- F1 is a constructor for a class D, F2 is a constructor for a base
11056 // class B of D, and for all arguments the corresponding parameters of
11057 // F1 and F2 have the same type.
11058 // FIXME: Implement the "all parameters have the same type" check.
11059 bool Cand1IsInherited =
11060 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
11061 bool Cand2IsInherited =
11062 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
11063 if (Cand1IsInherited != Cand2IsInherited)
11064 return Cand2IsInherited;
11065 else if (Cand1IsInherited) {
11066 assert(Cand2IsInherited);
11067 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
11068 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
11069 if (Cand1Class->isDerivedFrom(Cand2Class))
11070 return true;
11071 if (Cand2Class->isDerivedFrom(Cand1Class))
11072 return false;
11073 // Inherited from sibling base classes: still ambiguous.
11074 }
11075
11076 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11077 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11078 // with reversed order of parameters and F1 is not
11079 //
11080 // We rank reversed + different operator as worse than just reversed, but
11081 // that comparison can never happen, because we only consider reversing for
11082 // the maximally-rewritten operator (== or <=>).
11083 if (Cand1.RewriteKind != Cand2.RewriteKind)
11084 return Cand1.RewriteKind < Cand2.RewriteKind;
11085
11086 // Check C++17 tie-breakers for deduction guides.
11087 {
11088 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
11089 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
11090 if (Guide1 && Guide2) {
11091 // -- F1 is generated from a deduction-guide and F2 is not
11092 if (Guide1->isImplicit() != Guide2->isImplicit())
11093 return Guide2->isImplicit();
11094
11095 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11096 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11097 return true;
11098 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11099 return false;
11100
11101 // --F1 is generated from a non-template constructor and F2 is generated
11102 // from a constructor template
11103 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11104 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11105 if (Constructor1 && Constructor2) {
11106 bool isC1Templated = Constructor1->getTemplatedKind() !=
11108 bool isC2Templated = Constructor2->getTemplatedKind() !=
11110 if (isC1Templated != isC2Templated)
11111 return isC2Templated;
11112 }
11113 }
11114 }
11115
11116 // Check for enable_if value-based overload resolution.
11117 if (Cand1.Function && Cand2.Function) {
11118 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
11119 if (Cmp != Comparison::Equal)
11120 return Cmp == Comparison::Better;
11121 }
11122
11123 bool HasPS1 = Cand1.Function != nullptr &&
11125 bool HasPS2 = Cand2.Function != nullptr &&
11127 if (HasPS1 != HasPS2 && HasPS1)
11128 return true;
11129
11130 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11131 if (MV == Comparison::Better)
11132 return true;
11133 if (MV == Comparison::Worse)
11134 return false;
11135
11136 // If other rules cannot determine which is better, CUDA preference is used
11137 // to determine which is better.
11138 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11139 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11140 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
11141 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11142 }
11143
11144 // General member function overloading is handled above, so this only handles
11145 // constructors with address spaces.
11146 // This only handles address spaces since C++ has no other
11147 // qualifier that can be used with constructors.
11148 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
11149 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
11150 if (CD1 && CD2) {
11151 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11152 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11153 if (AS1 != AS2) {
11155 return true;
11157 return false;
11158 }
11159 }
11160
11161 return false;
11162}
11163
11164/// Determine whether two declarations are "equivalent" for the purposes of
11165/// name lookup and overload resolution. This applies when the same internal/no
11166/// linkage entity is defined by two modules (probably by textually including
11167/// the same header). In such a case, we don't consider the declarations to
11168/// declare the same entity, but we also don't want lookups with both
11169/// declarations visible to be ambiguous in some cases (this happens when using
11170/// a modularized libstdc++).
11172 const NamedDecl *B) {
11173 auto *VA = dyn_cast_or_null<ValueDecl>(A);
11174 auto *VB = dyn_cast_or_null<ValueDecl>(B);
11175 if (!VA || !VB)
11176 return false;
11177
11178 // The declarations must be declaring the same name as an internal linkage
11179 // entity in different modules.
11180 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11181 VB->getDeclContext()->getRedeclContext()) ||
11182 getOwningModule(VA) == getOwningModule(VB) ||
11183 VA->isExternallyVisible() || VB->isExternallyVisible())
11184 return false;
11185
11186 // Check that the declarations appear to be equivalent.
11187 //
11188 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11189 // For constants and functions, we should check the initializer or body is
11190 // the same. For non-constant variables, we shouldn't allow it at all.
11191 if (Context.hasSameType(VA->getType(), VB->getType()))
11192 return true;
11193
11194 // Enum constants within unnamed enumerations will have different types, but
11195 // may still be similar enough to be interchangeable for our purposes.
11196 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
11197 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
11198 // Only handle anonymous enums. If the enumerations were named and
11199 // equivalent, they would have been merged to the same type.
11200 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
11201 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
11202 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11203 !Context.hasSameType(EnumA->getIntegerType(),
11204 EnumB->getIntegerType()))
11205 return false;
11206 // Allow this only if the value is the same for both enumerators.
11207 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
11208 }
11209 }
11210
11211 // Nothing else is sufficiently similar.
11212 return false;
11213}
11214
11217 assert(D && "Unknown declaration");
11218 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11219
11220 Module *M = getOwningModule(D);
11221 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
11222 << !M << (M ? M->getFullModuleName() : "");
11223
11224 for (auto *E : Equiv) {
11225 Module *M = getOwningModule(E);
11226 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
11227 << !M << (M ? M->getFullModuleName() : "");
11228 }
11229}
11230
11233 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11235 static_cast<CNSInfo *>(DeductionFailure.Data)
11236 ->Satisfaction.ContainsErrors;
11237}
11238
11241 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11242 bool PartialOverloading, bool AllowExplicit,
11244 bool AggregateCandidateDeduction) {
11245
11246 auto *C =
11247 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11248
11251 /*AllowObjCConversionOnExplicit=*/false,
11252 /*AllowResultConversion=*/false, AllowExplicit, SuppressUserConversions,
11253 PartialOverloading, AggregateCandidateDeduction},
11255 FoundDecl,
11256 Args,
11257 IsADLCandidate,
11258 PO};
11259
11260 HasDeferredTemplateConstructors |=
11261 isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl());
11262}
11263
11265 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11266 CXXRecordDecl *ActingContext, QualType ObjectType,
11267 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11268 bool SuppressUserConversions, bool PartialOverloading,
11270
11271 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11272
11273 auto *C =
11274 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11275
11278 /*AllowObjCConversionOnExplicit=*/false,
11279 /*AllowResultConversion=*/false,
11280 /*AllowExplicit=*/false, SuppressUserConversions, PartialOverloading,
11281 /*AggregateCandidateDeduction=*/false},
11282 MethodTmpl,
11283 FoundDecl,
11284 Args,
11285 ActingContext,
11286 ObjectClassification,
11287 ObjectType,
11288 PO};
11289}
11290
11293 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11294 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11295 bool AllowResultConversion) {
11296
11297 auto *C =
11298 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11299
11302 AllowObjCConversionOnExplicit, AllowResultConversion,
11303 /*AllowExplicit=*/false,
11304 /*SuppressUserConversions=*/false,
11305 /*PartialOverloading*/ false,
11306 /*AggregateCandidateDeduction=*/false},
11308 FoundDecl,
11309 ActingContext,
11310 From,
11311 ToType};
11312}
11313
11314static void
11317
11319 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext,
11320 /*ExplicitTemplateArgs=*/nullptr, C.ObjectType, C.ObjectClassification,
11321 C.Args, C.SuppressUserConversions, C.PartialOverloading, C.PO);
11322}
11323
11324static void
11328 S, CandidateSet, C.FunctionTemplate, C.FoundDecl,
11329 /*ExplicitTemplateArgs=*/nullptr, C.Args, C.SuppressUserConversions,
11330 C.PartialOverloading, C.AllowExplicit, C.IsADLCandidate, C.PO,
11331 C.AggregateCandidateDeduction);
11332}
11333
11334static void
11338 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From,
11339 C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit,
11340 C.AllowResultConversion);
11341}
11342
11344 Candidates.reserve(Candidates.size() + DeferredCandidatesCount);
11345 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11346 while (Cand) {
11347 switch (Cand->Kind) {
11350 S, *this,
11351 *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11352 break;
11355 S, *this,
11356 *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11357 break;
11360 S, *this,
11361 *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11362 break;
11363 }
11364 Cand = Cand->Next;
11365 }
11366 FirstDeferredCandidate = nullptr;
11367 DeferredCandidatesCount = 0;
11368}
11369
11371OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11372 Best->Best = true;
11373 if (Best->Function && Best->Function->isDeleted())
11374 return OR_Deleted;
11375 return OR_Success;
11376}
11377
11378void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11380 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11381 // are accepted by both clang and NVCC. However, during a particular
11382 // compilation mode only one call variant is viable. We need to
11383 // exclude non-viable overload candidates from consideration based
11384 // only on their host/device attributes. Specifically, if one
11385 // candidate call is WrongSide and the other is SameSide, we ignore
11386 // the WrongSide candidate.
11387 // We only need to remove wrong-sided candidates here if
11388 // -fgpu-exclude-wrong-side-overloads is off. When
11389 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11390 // uniformly in isBetterOverloadCandidate.
11391 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11392 return;
11393 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11394
11395 bool ContainsSameSideCandidate =
11396 llvm::any_of(Candidates, [&](const OverloadCandidate *Cand) {
11397 // Check viable function only.
11398 return Cand->Viable && Cand->Function &&
11399 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11401 });
11402
11403 if (!ContainsSameSideCandidate)
11404 return;
11405
11406 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11407 // Check viable function only to avoid unnecessary data copying/moving.
11408 return Cand->Viable && Cand->Function &&
11409 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11411 };
11412 llvm::erase_if(Candidates, IsWrongSideCandidate);
11413}
11414
11415/// Computes the best viable function (C++ 13.3.3)
11416/// within an overload candidate set.
11417///
11418/// \param Loc The location of the function name (or operator symbol) for
11419/// which overload resolution occurs.
11420///
11421/// \param Best If overload resolution was successful or found a deleted
11422/// function, \p Best points to the candidate function found.
11423///
11424/// \returns The result of overload resolution.
11426 SourceLocation Loc,
11427 iterator &Best) {
11428
11430 DeferredCandidatesCount == 0) &&
11431 "Unexpected deferred template candidates");
11432
11433 bool TwoPhaseResolution =
11434 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11435
11436 if (TwoPhaseResolution) {
11437 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11438 if (Best != end() && Best->isPerfectMatch(S.Context)) {
11439 if (!(HasDeferredTemplateConstructors &&
11440 isa_and_nonnull<CXXConversionDecl>(Best->Function)))
11441 return Res;
11442 }
11443 }
11444
11446 return BestViableFunctionImpl(S, Loc, Best);
11447}
11448
11449OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11451
11453 Candidates.reserve(this->Candidates.size());
11454 std::transform(this->Candidates.begin(), this->Candidates.end(),
11455 std::back_inserter(Candidates),
11456 [](OverloadCandidate &Cand) { return &Cand; });
11457
11458 if (S.getLangOpts().CUDA)
11459 CudaExcludeWrongSideCandidates(S, Candidates);
11460
11461 Best = end();
11462 for (auto *Cand : Candidates) {
11463 Cand->Best = false;
11464 if (Cand->Viable) {
11465 if (Best == end() ||
11466 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
11467 Best = Cand;
11468 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11469 // This candidate has constraint that we were unable to evaluate because
11470 // it referenced an expression that contained an error. Rather than fall
11471 // back onto a potentially unintended candidate (made worse by
11472 // subsuming constraints), treat this as 'no viable candidate'.
11473 Best = end();
11474 return OR_No_Viable_Function;
11475 }
11476 }
11477
11478 // If we didn't find any viable functions, abort.
11479 if (Best == end())
11480 return OR_No_Viable_Function;
11481
11482 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11483 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11484 PendingBest.push_back(&*Best);
11485 Best->Best = true;
11486
11487 // Make sure that this function is better than every other viable
11488 // function. If not, we have an ambiguity.
11489 while (!PendingBest.empty()) {
11490 auto *Curr = PendingBest.pop_back_val();
11491 for (auto *Cand : Candidates) {
11492 if (Cand->Viable && !Cand->Best &&
11493 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
11494 PendingBest.push_back(Cand);
11495 Cand->Best = true;
11496
11498 Curr->Function))
11499 EquivalentCands.push_back(Cand->Function);
11500 else
11501 Best = end();
11502 }
11503 }
11504 }
11505
11506 if (Best == end())
11507 return OR_Ambiguous;
11508
11509 OverloadingResult R = ResultForBestCandidate(Best);
11510
11511 if (!EquivalentCands.empty())
11513 EquivalentCands);
11514 return R;
11515}
11516
11517namespace {
11518
11519enum OverloadCandidateKind {
11520 oc_function,
11521 oc_method,
11522 oc_reversed_binary_operator,
11523 oc_constructor,
11524 oc_implicit_default_constructor,
11525 oc_implicit_copy_constructor,
11526 oc_implicit_move_constructor,
11527 oc_implicit_copy_assignment,
11528 oc_implicit_move_assignment,
11529 oc_implicit_equality_comparison,
11530 oc_inherited_constructor
11531};
11532
11533enum OverloadCandidateSelect {
11534 ocs_non_template,
11535 ocs_template,
11536 ocs_described_template,
11537};
11538
11539static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11540ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11541 const FunctionDecl *Fn,
11543 std::string &Description) {
11544
11545 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11546 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11547 isTemplate = true;
11548 Description = S.getTemplateArgumentBindingsText(
11549 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11550 }
11551
11552 OverloadCandidateSelect Select = [&]() {
11553 if (!Description.empty())
11554 return ocs_described_template;
11555 return isTemplate ? ocs_template : ocs_non_template;
11556 }();
11557
11558 OverloadCandidateKind Kind = [&]() {
11559 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11560 return oc_implicit_equality_comparison;
11561
11562 if (CRK & CRK_Reversed)
11563 return oc_reversed_binary_operator;
11564
11565 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
11566 if (!Ctor->isImplicit()) {
11568 return oc_inherited_constructor;
11569 else
11570 return oc_constructor;
11571 }
11572
11573 if (Ctor->isDefaultConstructor())
11574 return oc_implicit_default_constructor;
11575
11576 if (Ctor->isMoveConstructor())
11577 return oc_implicit_move_constructor;
11578
11579 assert(Ctor->isCopyConstructor() &&
11580 "unexpected sort of implicit constructor");
11581 return oc_implicit_copy_constructor;
11582 }
11583
11584 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11585 // This actually gets spelled 'candidate function' for now, but
11586 // it doesn't hurt to split it out.
11587 if (!Meth->isImplicit())
11588 return oc_method;
11589
11590 if (Meth->isMoveAssignmentOperator())
11591 return oc_implicit_move_assignment;
11592
11593 if (Meth->isCopyAssignmentOperator())
11594 return oc_implicit_copy_assignment;
11595
11596 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11597 return oc_method;
11598 }
11599
11600 return oc_function;
11601 }();
11602
11603 return std::make_pair(Kind, Select);
11604}
11605
11606void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11607 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11608 // set.
11609 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11610 S.Diag(FoundDecl->getLocation(),
11611 diag::note_ovl_candidate_inherited_constructor)
11612 << Shadow->getNominatedBaseClass();
11613}
11614
11615} // end anonymous namespace
11616
11618 const FunctionDecl *FD) {
11619 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11620 bool AlwaysTrue;
11621 if (EnableIf->getCond()->isValueDependent() ||
11622 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11623 return false;
11624 if (!AlwaysTrue)
11625 return false;
11626 }
11627 return true;
11628}
11629
11630/// Returns true if we can take the address of the function.
11631///
11632/// \param Complain - If true, we'll emit a diagnostic
11633/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11634/// we in overload resolution?
11635/// \param Loc - The location of the statement we're complaining about. Ignored
11636/// if we're not complaining, or if we're in overload resolution.
11638 bool Complain,
11639 bool InOverloadResolution,
11640 SourceLocation Loc) {
11641 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11642 if (Complain) {
11643 if (InOverloadResolution)
11644 S.Diag(FD->getBeginLoc(),
11645 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11646 else
11647 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11648 }
11649 return false;
11650 }
11651
11652 if (FD->getTrailingRequiresClause()) {
11653 ConstraintSatisfaction Satisfaction;
11654 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11655 return false;
11656 if (!Satisfaction.IsSatisfied) {
11657 if (Complain) {
11658 if (InOverloadResolution) {
11659 SmallString<128> TemplateArgString;
11660 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11661 TemplateArgString += " ";
11662 TemplateArgString += S.getTemplateArgumentBindingsText(
11663 FunTmpl->getTemplateParameters(),
11665 }
11666
11667 S.Diag(FD->getBeginLoc(),
11668 diag::note_ovl_candidate_unsatisfied_constraints)
11669 << TemplateArgString;
11670 } else
11671 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11672 << FD;
11673 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11674 }
11675 return false;
11676 }
11677 }
11678
11679 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11680 return P->hasAttr<PassObjectSizeAttr>();
11681 });
11682 if (I == FD->param_end())
11683 return true;
11684
11685 if (Complain) {
11686 // Add one to ParamNo because it's user-facing
11687 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11688 if (InOverloadResolution)
11689 S.Diag(FD->getLocation(),
11690 diag::note_ovl_candidate_has_pass_object_size_params)
11691 << ParamNo;
11692 else
11693 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11694 << FD << ParamNo;
11695 }
11696 return false;
11697}
11698
11700 const FunctionDecl *FD) {
11701 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11702 /*InOverloadResolution=*/true,
11703 /*Loc=*/SourceLocation());
11704}
11705
11707 bool Complain,
11708 SourceLocation Loc) {
11709 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11710 /*InOverloadResolution=*/false,
11711 Loc);
11712}
11713
11714// Don't print candidates other than the one that matches the calling
11715// convention of the call operator, since that is guaranteed to exist.
11717 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11718
11719 if (!ConvD)
11720 return false;
11721 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11722 if (!RD->isLambda())
11723 return false;
11724
11725 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11726 CallingConv CallOpCC =
11727 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11728 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11729 CallingConv ConvToCC =
11730 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11731
11732 return ConvToCC != CallOpCC;
11733}
11734
11735// Notes the location of an overload candidate.
11737 OverloadCandidateRewriteKind RewriteKind,
11738 QualType DestType, bool TakingAddress) {
11739 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11740 return;
11741 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11742 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11743 return;
11744 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11745 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11746 return;
11748 return;
11749
11750 std::string FnDesc;
11751 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11752 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11753 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11754 << (unsigned)KSPair.first << (unsigned)KSPair.second
11755 << Fn << FnDesc;
11756
11757 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11758 Diag(Fn->getLocation(), PD);
11759 MaybeEmitInheritedConstructorNote(*this, Found);
11760}
11761
11762static void
11764 // Perhaps the ambiguity was caused by two atomic constraints that are
11765 // 'identical' but not equivalent:
11766 //
11767 // void foo() requires (sizeof(T) > 4) { } // #1
11768 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11769 //
11770 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11771 // #2 to subsume #1, but these constraint are not considered equivalent
11772 // according to the subsumption rules because they are not the same
11773 // source-level construct. This behavior is quite confusing and we should try
11774 // to help the user figure out what happened.
11775
11776 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11777 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11778 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11779 if (!I->Function)
11780 continue;
11782 if (auto *Template = I->Function->getPrimaryTemplate())
11783 Template->getAssociatedConstraints(AC);
11784 else
11785 I->Function->getAssociatedConstraints(AC);
11786 if (AC.empty())
11787 continue;
11788 if (FirstCand == nullptr) {
11789 FirstCand = I->Function;
11790 FirstAC = AC;
11791 } else if (SecondCand == nullptr) {
11792 SecondCand = I->Function;
11793 SecondAC = AC;
11794 } else {
11795 // We have more than one pair of constrained functions - this check is
11796 // expensive and we'd rather not try to diagnose it.
11797 return;
11798 }
11799 }
11800 if (!SecondCand)
11801 return;
11802 // The diagnostic can only happen if there are associated constraints on
11803 // both sides (there needs to be some identical atomic constraint).
11804 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11805 SecondCand, SecondAC))
11806 // Just show the user one diagnostic, they'll probably figure it out
11807 // from here.
11808 return;
11809}
11810
11811// Notes the location of all overload candidates designated through
11812// OverloadedExpr
11813void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11814 bool TakingAddress) {
11815 assert(OverloadedExpr->getType() == Context.OverloadTy);
11816
11817 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11818 OverloadExpr *OvlExpr = Ovl.Expression;
11819
11820 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11821 IEnd = OvlExpr->decls_end();
11822 I != IEnd; ++I) {
11823 if (FunctionTemplateDecl *FunTmpl =
11824 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11825 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11826 TakingAddress);
11827 } else if (FunctionDecl *Fun
11828 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11829 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11830 }
11831 }
11832}
11833
11834/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11835/// "lead" diagnostic; it will be given two arguments, the source and
11836/// target types of the conversion.
11838 Sema &S,
11839 SourceLocation CaretLoc,
11840 const PartialDiagnostic &PDiag) const {
11841 S.Diag(CaretLoc, PDiag)
11842 << Ambiguous.getFromType() << Ambiguous.getToType();
11843 unsigned CandsShown = 0;
11845 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11846 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11847 break;
11848 ++CandsShown;
11849 S.NoteOverloadCandidate(I->first, I->second);
11850 }
11851 S.Diags.overloadCandidatesShown(CandsShown);
11852 if (I != E)
11853 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11854}
11855
11857 unsigned I, bool TakingCandidateAddress) {
11858 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11859 assert(Conv.isBad());
11860 assert(Cand->Function && "for now, candidate must be a function");
11861 FunctionDecl *Fn = Cand->Function;
11862
11863 // There's a conversion slot for the object argument if this is a
11864 // non-constructor method. Note that 'I' corresponds the
11865 // conversion-slot index.
11866 bool isObjectArgument = false;
11867 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Fn) &&
11869 if (I == 0)
11870 isObjectArgument = true;
11871 else if (!Fn->hasCXXExplicitFunctionObjectParameter())
11872 I--;
11873 }
11874
11875 std::string FnDesc;
11876 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11877 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
11878 FnDesc);
11879
11880 Expr *FromExpr = Conv.Bad.FromExpr;
11881 QualType FromTy = Conv.Bad.getFromType();
11882 QualType ToTy = Conv.Bad.getToType();
11883 SourceRange ToParamRange;
11884
11885 // FIXME: In presence of parameter packs we can't determine parameter range
11886 // reliably, as we don't have access to instantiation.
11887 bool HasParamPack =
11888 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
11889 return Parm->isParameterPack();
11890 });
11891 if (!isObjectArgument && !HasParamPack)
11892 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
11893
11894 if (FromTy == S.Context.OverloadTy) {
11895 assert(FromExpr && "overload set argument came from implicit argument?");
11896 Expr *E = FromExpr->IgnoreParens();
11897 if (isa<UnaryOperator>(E))
11898 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11899 DeclarationName Name = cast<OverloadExpr>(E)->getName();
11900
11901 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
11902 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11903 << ToParamRange << ToTy << Name << I + 1;
11904 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11905 return;
11906 }
11907
11908 // Do some hand-waving analysis to see if the non-viability is due
11909 // to a qualifier mismatch.
11910 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
11911 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
11912 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11913 CToTy = RT->getPointeeType();
11914 else {
11915 // TODO: detect and diagnose the full richness of const mismatches.
11916 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11917 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11918 CFromTy = FromPT->getPointeeType();
11919 CToTy = ToPT->getPointeeType();
11920 }
11921 }
11922
11923 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11924 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
11925 Qualifiers FromQs = CFromTy.getQualifiers();
11926 Qualifiers ToQs = CToTy.getQualifiers();
11927
11928 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11929 if (isObjectArgument)
11930 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
11931 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11932 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11933 else
11934 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
11935 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11936 << FnDesc << ToParamRange << FromQs.getAddressSpace()
11937 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11938 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11939 return;
11940 }
11941
11942 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11943 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
11944 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11945 << ToParamRange << FromTy << FromQs.getObjCLifetime()
11946 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11947 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11948 return;
11949 }
11950
11951 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11952 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
11953 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11954 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11955 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11956 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11957 return;
11958 }
11959
11960 if (!FromQs.getPointerAuth().isEquivalent(ToQs.getPointerAuth())) {
11961 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ptrauth)
11962 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11963 << FromTy << !!FromQs.getPointerAuth()
11964 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
11965 << ToQs.getPointerAuth().getAsString() << I + 1
11966 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
11967 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11968 return;
11969 }
11970
11971 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11972 assert(CVR && "expected qualifiers mismatch");
11973
11974 if (isObjectArgument) {
11975 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
11976 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11977 << FromTy << (CVR - 1);
11978 } else {
11979 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
11980 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11981 << ToParamRange << FromTy << (CVR - 1) << I + 1;
11982 }
11983 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11984 return;
11985 }
11986
11989 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
11990 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11991 << (unsigned)isObjectArgument << I + 1
11993 << ToParamRange;
11994 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11995 return;
11996 }
11997
11998 // Special diagnostic for failure to convert an initializer list, since
11999 // telling the user that it has type void is not useful.
12000 if (FromExpr && isa<InitListExpr>(FromExpr)) {
12001 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
12002 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12003 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12006 ? 2
12007 : 0);
12008 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12009 return;
12010 }
12011
12012 // Diagnose references or pointers to incomplete types differently,
12013 // since it's far from impossible that the incompleteness triggered
12014 // the failure.
12015 QualType TempFromTy = FromTy.getNonReferenceType();
12016 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
12017 TempFromTy = PTy->getPointeeType();
12018 if (TempFromTy->isIncompleteType()) {
12019 // Emit the generic diagnostic and, optionally, add the hints to it.
12020 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
12021 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12022 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12023 << (unsigned)(Cand->Fix.Kind);
12024
12025 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12026 return;
12027 }
12028
12029 // Diagnose base -> derived pointer conversions.
12030 unsigned BaseToDerivedConversion = 0;
12031 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
12032 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
12033 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12034 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12035 !FromPtrTy->getPointeeType()->isIncompleteType() &&
12036 !ToPtrTy->getPointeeType()->isIncompleteType() &&
12037 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
12038 FromPtrTy->getPointeeType()))
12039 BaseToDerivedConversion = 1;
12040 }
12041 } else if (const ObjCObjectPointerType *FromPtrTy
12042 = FromTy->getAs<ObjCObjectPointerType>()) {
12043 if (const ObjCObjectPointerType *ToPtrTy
12044 = ToTy->getAs<ObjCObjectPointerType>())
12045 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
12046 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
12047 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12048 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12049 FromIface->isSuperClassOf(ToIface))
12050 BaseToDerivedConversion = 2;
12051 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
12052 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
12053 S.getASTContext()) &&
12054 !FromTy->isIncompleteType() &&
12055 !ToRefTy->getPointeeType()->isIncompleteType() &&
12056 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
12057 BaseToDerivedConversion = 3;
12058 }
12059 }
12060
12061 if (BaseToDerivedConversion) {
12062 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
12063 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12064 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
12065 << I + 1;
12066 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12067 return;
12068 }
12069
12070 if (isa<ObjCObjectPointerType>(CFromTy) &&
12071 isa<PointerType>(CToTy)) {
12072 Qualifiers FromQs = CFromTy.getQualifiers();
12073 Qualifiers ToQs = CToTy.getQualifiers();
12074 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12075 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
12076 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12077 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12078 << I + 1;
12079 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12080 return;
12081 }
12082 }
12083
12084 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
12085 return;
12086
12087 // Emit the generic diagnostic and, optionally, add the hints to it.
12088 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
12089 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12090 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12091 << (unsigned)(Cand->Fix.Kind);
12092
12093 // Check that location of Fn is not in system header.
12094 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
12095 // If we can fix the conversion, suggest the FixIts.
12096 for (const FixItHint &HI : Cand->Fix.Hints)
12097 FDiag << HI;
12098 }
12099
12100 S.Diag(Fn->getLocation(), FDiag);
12101
12102 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12103}
12104
12105/// Additional arity mismatch diagnosis specific to a function overload
12106/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12107/// over a candidate in any candidate set.
12109 unsigned NumArgs, bool IsAddressOf = false) {
12110 assert(Cand->Function && "Candidate is required to be a function.");
12111 FunctionDecl *Fn = Cand->Function;
12112 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12113 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12114
12115 // With invalid overloaded operators, it's possible that we think we
12116 // have an arity mismatch when in fact it looks like we have the
12117 // right number of arguments, because only overloaded operators have
12118 // the weird behavior of overloading member and non-member functions.
12119 // Just don't report anything.
12120 if (Fn->isInvalidDecl() &&
12121 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12122 return true;
12123
12124 if (NumArgs < MinParams) {
12125 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12127 Cand->DeductionFailure.getResult() ==
12129 } else {
12130 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12132 Cand->DeductionFailure.getResult() ==
12134 }
12135
12136 return false;
12137}
12138
12139/// General arity mismatch diagnosis over a candidate in a candidate set.
12141 unsigned NumFormalArgs,
12142 bool IsAddressOf = false) {
12143 assert(isa<FunctionDecl>(D) &&
12144 "The templated declaration should at least be a function"
12145 " when diagnosing bad template argument deduction due to too many"
12146 " or too few arguments");
12147
12149
12150 // TODO: treat calls to a missing default constructor as a special case
12151 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12152 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12153 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12154
12155 // at least / at most / exactly
12156 bool HasExplicitObjectParam =
12157 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12158
12159 unsigned ParamCount =
12160 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12161 unsigned mode, modeCount;
12162
12163 if (NumFormalArgs < MinParams) {
12164 if (MinParams != ParamCount || FnTy->isVariadic() ||
12165 FnTy->isTemplateVariadic())
12166 mode = 0; // "at least"
12167 else
12168 mode = 2; // "exactly"
12169 modeCount = MinParams;
12170 } else {
12171 if (MinParams != ParamCount)
12172 mode = 1; // "at most"
12173 else
12174 mode = 2; // "exactly"
12175 modeCount = ParamCount;
12176 }
12177
12178 std::string Description;
12179 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12180 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
12181
12182 if (modeCount == 1 && !IsAddressOf &&
12183 Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())
12184 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
12185 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12186 << Description << mode
12187 << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
12188 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12189 else
12190 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
12191 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12192 << Description << mode << modeCount << NumFormalArgs
12193 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12194
12195 MaybeEmitInheritedConstructorNote(S, Found);
12196}
12197
12198/// Arity mismatch diagnosis specific to a function overload candidate.
12200 unsigned NumFormalArgs) {
12201 assert(Cand->Function && "Candidate must be a function");
12202 FunctionDecl *Fn = Cand->Function;
12203 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
12204 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
12205 Cand->TookAddressOfOverload);
12206}
12207
12209 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12210 return TD;
12211 llvm_unreachable("Unsupported: Getting the described template declaration"
12212 " for bad deduction diagnosis");
12213}
12214
12215/// Diagnose a failed template-argument deduction.
12216static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12217 DeductionFailureInfo &DeductionFailure,
12218 unsigned NumArgs,
12219 bool TakingCandidateAddress) {
12220 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12221 NamedDecl *ParamD;
12222 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12223 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12224 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12225 switch (DeductionFailure.getResult()) {
12227 llvm_unreachable(
12228 "TemplateDeductionResult::Success while diagnosing bad deduction");
12230 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12231 "while diagnosing bad deduction");
12234 return;
12235
12237 assert(ParamD && "no parameter found for incomplete deduction result");
12238 S.Diag(Templated->getLocation(),
12239 diag::note_ovl_candidate_incomplete_deduction)
12240 << ParamD->getDeclName();
12241 MaybeEmitInheritedConstructorNote(S, Found);
12242 return;
12243 }
12244
12246 assert(ParamD && "no parameter found for incomplete deduction result");
12247 S.Diag(Templated->getLocation(),
12248 diag::note_ovl_candidate_incomplete_deduction_pack)
12249 << ParamD->getDeclName()
12250 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12251 << *DeductionFailure.getFirstArg();
12252 MaybeEmitInheritedConstructorNote(S, Found);
12253 return;
12254 }
12255
12257 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12259
12260 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12261
12262 // Param will have been canonicalized, but it should just be a
12263 // qualified version of ParamD, so move the qualifiers to that.
12265 Qs.strip(Param);
12266 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
12267 assert(S.Context.hasSameType(Param, NonCanonParam));
12268
12269 // Arg has also been canonicalized, but there's nothing we can do
12270 // about that. It also doesn't matter as much, because it won't
12271 // have any template parameters in it (because deduction isn't
12272 // done on dependent types).
12273 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12274
12275 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
12276 << ParamD->getDeclName() << Arg << NonCanonParam;
12277 MaybeEmitInheritedConstructorNote(S, Found);
12278 return;
12279 }
12280
12282 assert(ParamD && "no parameter found for inconsistent deduction result");
12283 int which = 0;
12284 if (isa<TemplateTypeParmDecl>(ParamD))
12285 which = 0;
12286 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
12287 // Deduction might have failed because we deduced arguments of two
12288 // different types for a non-type template parameter.
12289 // FIXME: Use a different TDK value for this.
12290 QualType T1 =
12291 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12292 QualType T2 =
12293 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12294 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12295 S.Diag(Templated->getLocation(),
12296 diag::note_ovl_candidate_inconsistent_deduction_types)
12297 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12298 << *DeductionFailure.getSecondArg() << T2;
12299 MaybeEmitInheritedConstructorNote(S, Found);
12300 return;
12301 }
12302
12303 which = 1;
12304 } else {
12305 which = 2;
12306 }
12307
12308 // Tweak the diagnostic if the problem is that we deduced packs of
12309 // different arities. We'll print the actual packs anyway in case that
12310 // includes additional useful information.
12311 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12312 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12313 DeductionFailure.getFirstArg()->pack_size() !=
12314 DeductionFailure.getSecondArg()->pack_size()) {
12315 which = 3;
12316 }
12317
12318 S.Diag(Templated->getLocation(),
12319 diag::note_ovl_candidate_inconsistent_deduction)
12320 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12321 << *DeductionFailure.getSecondArg();
12322 MaybeEmitInheritedConstructorNote(S, Found);
12323 return;
12324 }
12325
12327 assert(ParamD && "no parameter found for invalid explicit arguments");
12328 if (ParamD->getDeclName())
12329 S.Diag(Templated->getLocation(),
12330 diag::note_ovl_candidate_explicit_arg_mismatch_named)
12331 << ParamD->getDeclName();
12332 else {
12333 int index = 0;
12334 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
12335 index = TTP->getIndex();
12336 else if (NonTypeTemplateParmDecl *NTTP
12337 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
12338 index = NTTP->getIndex();
12339 else
12340 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
12341 S.Diag(Templated->getLocation(),
12342 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
12343 << (index + 1);
12344 }
12345 MaybeEmitInheritedConstructorNote(S, Found);
12346 return;
12347
12349 // Format the template argument list into the argument string.
12350 SmallString<128> TemplateArgString;
12351 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12352 TemplateArgString = " ";
12353 TemplateArgString += S.getTemplateArgumentBindingsText(
12354 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12355 if (TemplateArgString.size() == 1)
12356 TemplateArgString.clear();
12357 S.Diag(Templated->getLocation(),
12358 diag::note_ovl_candidate_unsatisfied_constraints)
12359 << TemplateArgString;
12360
12362 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12363 return;
12364 }
12367 DiagnoseArityMismatch(S, Found, Templated, NumArgs, TakingCandidateAddress);
12368 return;
12369
12371 S.Diag(Templated->getLocation(),
12372 diag::note_ovl_candidate_instantiation_depth);
12373 MaybeEmitInheritedConstructorNote(S, Found);
12374 return;
12375
12377 // Format the template argument list into the argument string.
12378 SmallString<128> TemplateArgString;
12379 if (TemplateArgumentList *Args =
12380 DeductionFailure.getTemplateArgumentList()) {
12381 TemplateArgString = " ";
12382 TemplateArgString += S.getTemplateArgumentBindingsText(
12383 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12384 if (TemplateArgString.size() == 1)
12385 TemplateArgString.clear();
12386 }
12387
12388 // If this candidate was disabled by enable_if, say so.
12389 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12390 if (PDiag && PDiag->second.getDiagID() ==
12391 diag::err_typename_nested_not_found_enable_if) {
12392 // FIXME: Use the source range of the condition, and the fully-qualified
12393 // name of the enable_if template. These are both present in PDiag.
12394 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
12395 << "'enable_if'" << TemplateArgString;
12396 return;
12397 }
12398
12399 // We found a specific requirement that disabled the enable_if.
12400 if (PDiag && PDiag->second.getDiagID() ==
12401 diag::err_typename_nested_not_found_requirement) {
12402 S.Diag(Templated->getLocation(),
12403 diag::note_ovl_candidate_disabled_by_requirement)
12404 << PDiag->second.getStringArg(0) << TemplateArgString;
12405 return;
12406 }
12407
12408 // Format the SFINAE diagnostic into the argument string.
12409 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12410 // formatted message in another diagnostic.
12411 SmallString<128> SFINAEArgString;
12412 SourceRange R;
12413 if (PDiag) {
12414 SFINAEArgString = ": ";
12415 R = SourceRange(PDiag->first, PDiag->first);
12416 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
12417 }
12418
12419 S.Diag(Templated->getLocation(),
12420 diag::note_ovl_candidate_substitution_failure)
12421 << TemplateArgString << SFINAEArgString << R;
12422 MaybeEmitInheritedConstructorNote(S, Found);
12423 return;
12424 }
12425
12428 // Format the template argument list into the argument string.
12429 SmallString<128> TemplateArgString;
12430 if (TemplateArgumentList *Args =
12431 DeductionFailure.getTemplateArgumentList()) {
12432 TemplateArgString = " ";
12433 TemplateArgString += S.getTemplateArgumentBindingsText(
12434 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12435 if (TemplateArgString.size() == 1)
12436 TemplateArgString.clear();
12437 }
12438
12439 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
12440 << (*DeductionFailure.getCallArgIndex() + 1)
12441 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12442 << TemplateArgString
12443 << (DeductionFailure.getResult() ==
12445 break;
12446 }
12447
12449 // FIXME: Provide a source location to indicate what we couldn't match.
12450 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12451 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12452 if (FirstTA.getKind() == TemplateArgument::Template &&
12453 SecondTA.getKind() == TemplateArgument::Template) {
12454 TemplateName FirstTN = FirstTA.getAsTemplate();
12455 TemplateName SecondTN = SecondTA.getAsTemplate();
12456 if (FirstTN.getKind() == TemplateName::Template &&
12457 SecondTN.getKind() == TemplateName::Template) {
12458 if (FirstTN.getAsTemplateDecl()->getName() ==
12459 SecondTN.getAsTemplateDecl()->getName()) {
12460 // FIXME: This fixes a bad diagnostic where both templates are named
12461 // the same. This particular case is a bit difficult since:
12462 // 1) It is passed as a string to the diagnostic printer.
12463 // 2) The diagnostic printer only attempts to find a better
12464 // name for types, not decls.
12465 // Ideally, this should folded into the diagnostic printer.
12466 S.Diag(Templated->getLocation(),
12467 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12468 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12469 return;
12470 }
12471 }
12472 }
12473
12474 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
12476 return;
12477
12478 // FIXME: For generic lambda parameters, check if the function is a lambda
12479 // call operator, and if so, emit a prettier and more informative
12480 // diagnostic that mentions 'auto' and lambda in addition to
12481 // (or instead of?) the canonical template type parameters.
12482 S.Diag(Templated->getLocation(),
12483 diag::note_ovl_candidate_non_deduced_mismatch)
12484 << FirstTA << SecondTA;
12485 return;
12486 }
12487 // TODO: diagnose these individually, then kill off
12488 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12490 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
12491 MaybeEmitInheritedConstructorNote(S, Found);
12492 return;
12494 S.Diag(Templated->getLocation(),
12495 diag::note_cuda_ovl_candidate_target_mismatch);
12496 return;
12497 }
12498}
12499
12500/// Diagnose a failed template-argument deduction, for function calls.
12502 unsigned NumArgs,
12503 bool TakingCandidateAddress) {
12504 assert(Cand->Function && "Candidate must be a function");
12505 FunctionDecl *Fn = Cand->Function;
12509 if (CheckArityMismatch(S, Cand, NumArgs))
12510 return;
12511 }
12512 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
12513 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12514}
12515
12516/// CUDA: diagnose an invalid call across targets.
12518 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12519 assert(Cand->Function && "Candidate must be a Function.");
12520 FunctionDecl *Callee = Cand->Function;
12521
12522 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
12523 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
12524
12525 std::string FnDesc;
12526 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12527 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
12528 Cand->getRewriteKind(), FnDesc);
12529
12530 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
12531 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12532 << FnDesc /* Ignored */
12533 << CalleeTarget << CallerTarget;
12534
12535 // This could be an implicit constructor for which we could not infer the
12536 // target due to a collsion. Diagnose that case.
12537 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
12538 if (Meth != nullptr && Meth->isImplicit()) {
12539 CXXRecordDecl *ParentClass = Meth->getParent();
12541
12542 switch (FnKindPair.first) {
12543 default:
12544 return;
12545 case oc_implicit_default_constructor:
12547 break;
12548 case oc_implicit_copy_constructor:
12550 break;
12551 case oc_implicit_move_constructor:
12553 break;
12554 case oc_implicit_copy_assignment:
12556 break;
12557 case oc_implicit_move_assignment:
12559 break;
12560 };
12561
12562 bool ConstRHS = false;
12563 if (Meth->getNumParams()) {
12564 if (const ReferenceType *RT =
12565 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
12566 ConstRHS = RT->getPointeeType().isConstQualified();
12567 }
12568 }
12569
12570 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
12571 /* ConstRHS */ ConstRHS,
12572 /* Diagnose */ true);
12573 }
12574}
12575
12577 assert(Cand->Function && "Candidate must be a function");
12578 FunctionDecl *Callee = Cand->Function;
12579 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12580
12581 S.Diag(Callee->getLocation(),
12582 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12583 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12584}
12585
12587 assert(Cand->Function && "Candidate must be a function");
12588 FunctionDecl *Fn = Cand->Function;
12590 assert(ES.isExplicit() && "not an explicit candidate");
12591
12592 unsigned Kind;
12593 switch (Fn->getDeclKind()) {
12594 case Decl::Kind::CXXConstructor:
12595 Kind = 0;
12596 break;
12597 case Decl::Kind::CXXConversion:
12598 Kind = 1;
12599 break;
12600 case Decl::Kind::CXXDeductionGuide:
12601 Kind = Fn->isImplicit() ? 0 : 2;
12602 break;
12603 default:
12604 llvm_unreachable("invalid Decl");
12605 }
12606
12607 // Note the location of the first (in-class) declaration; a redeclaration
12608 // (particularly an out-of-class definition) will typically lack the
12609 // 'explicit' specifier.
12610 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12611 FunctionDecl *First = Fn->getFirstDecl();
12612 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12613 First = Pattern->getFirstDecl();
12614
12615 S.Diag(First->getLocation(),
12616 diag::note_ovl_candidate_explicit)
12617 << Kind << (ES.getExpr() ? 1 : 0)
12618 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12619}
12620
12622 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
12623 if (!DG)
12624 return;
12625 TemplateDecl *OriginTemplate =
12627 // We want to always print synthesized deduction guides for type aliases.
12628 // They would retain the explicit bit of the corresponding constructor.
12629 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12630 return;
12631 std::string FunctionProto;
12632 llvm::raw_string_ostream OS(FunctionProto);
12633 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12634 if (!Template) {
12635 // This also could be an instantiation. Find out the primary template.
12636 FunctionDecl *Pattern =
12637 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12638 if (!Pattern) {
12639 // The implicit deduction guide is built on an explicit non-template
12640 // deduction guide. Currently, this might be the case only for type
12641 // aliases.
12642 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12643 // gets merged.
12644 assert(OriginTemplate->isTypeAlias() &&
12645 "Non-template implicit deduction guides are only possible for "
12646 "type aliases");
12647 DG->print(OS);
12648 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12649 << FunctionProto;
12650 return;
12651 }
12653 assert(Template && "Cannot find the associated function template of "
12654 "CXXDeductionGuideDecl?");
12655 }
12656 Template->print(OS);
12657 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12658 << FunctionProto;
12659}
12660
12661/// Generates a 'note' diagnostic for an overload candidate. We've
12662/// already generated a primary error at the call site.
12663///
12664/// It really does need to be a single diagnostic with its caret
12665/// pointed at the candidate declaration. Yes, this creates some
12666/// major challenges of technical writing. Yes, this makes pointing
12667/// out problems with specific arguments quite awkward. It's still
12668/// better than generating twenty screens of text for every failed
12669/// overload.
12670///
12671/// It would be great to be able to express per-candidate problems
12672/// more richly for those diagnostic clients that cared, but we'd
12673/// still have to be just as careful with the default diagnostics.
12674/// \param CtorDestAS Addr space of object being constructed (for ctor
12675/// candidates only).
12677 unsigned NumArgs,
12678 bool TakingCandidateAddress,
12679 LangAS CtorDestAS = LangAS::Default) {
12680 assert(Cand->Function && "Candidate must be a function");
12681 FunctionDecl *Fn = Cand->Function;
12683 return;
12684
12685 // There is no physical candidate declaration to point to for OpenCL builtins.
12686 // Except for failed conversions, the notes are identical for each candidate,
12687 // so do not generate such notes.
12688 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12690 return;
12691
12692 // Skip implicit member functions when trying to resolve
12693 // the address of a an overload set for a function pointer.
12694 if (Cand->TookAddressOfOverload &&
12695 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12696 return;
12697
12698 // Note deleted candidates, but only if they're viable.
12699 if (Cand->Viable) {
12700 if (Fn->isDeleted()) {
12701 std::string FnDesc;
12702 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12703 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12704 Cand->getRewriteKind(), FnDesc);
12705
12706 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12707 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12708 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12709 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12710 return;
12711 }
12712
12713 // We don't really have anything else to say about viable candidates.
12714 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12715 return;
12716 }
12717
12718 // If this is a synthesized deduction guide we're deducing against, add a note
12719 // for it. These deduction guides are not explicitly spelled in the source
12720 // code, so simply printing a deduction failure note mentioning synthesized
12721 // template parameters or pointing to the header of the surrounding RecordDecl
12722 // would be confusing.
12723 //
12724 // We prefer adding such notes at the end of the deduction failure because
12725 // duplicate code snippets appearing in the diagnostic would likely become
12726 // noisy.
12727 llvm::scope_exit _([&] { NoteImplicitDeductionGuide(S, Fn); });
12728
12729 switch (Cand->FailureKind) {
12732 return DiagnoseArityMismatch(S, Cand, NumArgs);
12733
12735 return DiagnoseBadDeduction(S, Cand, NumArgs,
12736 TakingCandidateAddress);
12737
12739 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12740 << (Fn->getPrimaryTemplate() ? 1 : 0);
12741 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12742 return;
12743 }
12744
12746 Qualifiers QualsForPrinting;
12747 QualsForPrinting.setAddressSpace(CtorDestAS);
12748 S.Diag(Fn->getLocation(),
12749 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12750 << QualsForPrinting;
12751 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12752 return;
12753 }
12754
12758 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12759
12761 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12762 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12763 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12764 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12765
12766 // FIXME: this currently happens when we're called from SemaInit
12767 // when user-conversion overload fails. Figure out how to handle
12768 // those conditions and diagnose them well.
12769 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12770 }
12771
12773 return DiagnoseBadTarget(S, Cand);
12774
12775 case ovl_fail_enable_if:
12776 return DiagnoseFailedEnableIfAttr(S, Cand);
12777
12778 case ovl_fail_explicit:
12779 return DiagnoseFailedExplicitSpec(S, Cand);
12780
12782 // It's generally not interesting to note copy/move constructors here.
12783 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12784 return;
12785 S.Diag(Fn->getLocation(),
12786 diag::note_ovl_candidate_inherited_constructor_slice)
12787 << (Fn->getPrimaryTemplate() ? 1 : 0)
12788 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12789 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12790 return;
12791
12793 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
12794 (void)Available;
12795 assert(!Available);
12796 break;
12797 }
12799 // Do nothing, these should simply be ignored.
12800 break;
12801
12803 std::string FnDesc;
12804 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12805 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12806 Cand->getRewriteKind(), FnDesc);
12807
12808 S.Diag(Fn->getLocation(),
12809 diag::note_ovl_candidate_constraints_not_satisfied)
12810 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12811 << FnDesc /* Ignored */;
12812 ConstraintSatisfaction Satisfaction;
12813 if (S.CheckFunctionConstraints(Fn, Satisfaction, SourceLocation(),
12814 /*ForOverloadResolution=*/true))
12815 break;
12816 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12817 }
12818 }
12819}
12820
12823 return;
12824
12825 // Desugar the type of the surrogate down to a function type,
12826 // retaining as many typedefs as possible while still showing
12827 // the function type (and, therefore, its parameter types).
12828 QualType FnType = Cand->Surrogate->getConversionType();
12829 bool isLValueReference = false;
12830 bool isRValueReference = false;
12831 bool isPointer = false;
12832 if (const LValueReferenceType *FnTypeRef =
12833 FnType->getAs<LValueReferenceType>()) {
12834 FnType = FnTypeRef->getPointeeType();
12835 isLValueReference = true;
12836 } else if (const RValueReferenceType *FnTypeRef =
12837 FnType->getAs<RValueReferenceType>()) {
12838 FnType = FnTypeRef->getPointeeType();
12839 isRValueReference = true;
12840 }
12841 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12842 FnType = FnTypePtr->getPointeeType();
12843 isPointer = true;
12844 }
12845 // Desugar down to a function type.
12846 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12847 // Reconstruct the pointer/reference as appropriate.
12848 if (isPointer) FnType = S.Context.getPointerType(FnType);
12849 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
12850 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
12851
12852 if (!Cand->Viable &&
12854 S.Diag(Cand->Surrogate->getLocation(),
12855 diag::note_ovl_surrogate_constraints_not_satisfied)
12856 << Cand->Surrogate;
12857 ConstraintSatisfaction Satisfaction;
12858 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12859 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12860 } else {
12861 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
12862 << FnType;
12863 }
12864}
12865
12866static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12867 SourceLocation OpLoc,
12868 OverloadCandidate *Cand) {
12869 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12870 std::string TypeStr("operator");
12871 TypeStr += Opc;
12872 TypeStr += "(";
12873 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12874 if (Cand->Conversions.size() == 1) {
12875 TypeStr += ")";
12876 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12877 } else {
12878 TypeStr += ", ";
12879 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12880 TypeStr += ")";
12881 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12882 }
12883}
12884
12886 OverloadCandidate *Cand) {
12887 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12888 if (ICS.isBad()) break; // all meaningless after first invalid
12889 if (!ICS.isAmbiguous()) continue;
12890
12892 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
12893 }
12894}
12895
12897 if (Cand->Function)
12898 return Cand->Function->getLocation();
12899 if (Cand->IsSurrogate)
12900 return Cand->Surrogate->getLocation();
12901 return SourceLocation();
12902}
12903
12904static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12905 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12909 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12910
12914 return 1;
12915
12918 return 2;
12919
12927 return 3;
12928
12930 return 4;
12931
12933 return 5;
12934
12937 return 6;
12938 }
12939 llvm_unreachable("Unhandled deduction result");
12940}
12941
12942namespace {
12943
12944struct CompareOverloadCandidatesForDisplay {
12945 Sema &S;
12946 SourceLocation Loc;
12947 size_t NumArgs;
12949
12950 CompareOverloadCandidatesForDisplay(
12951 Sema &S, SourceLocation Loc, size_t NArgs,
12953 : S(S), NumArgs(NArgs), CSK(CSK) {}
12954
12955 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12956 // If there are too many or too few arguments, that's the high-order bit we
12957 // want to sort by, even if the immediate failure kind was something else.
12958 if (C->FailureKind == ovl_fail_too_many_arguments ||
12959 C->FailureKind == ovl_fail_too_few_arguments)
12960 return static_cast<OverloadFailureKind>(C->FailureKind);
12961
12962 if (C->Function) {
12963 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12965 if (NumArgs < C->Function->getMinRequiredArguments())
12967 }
12968
12969 return static_cast<OverloadFailureKind>(C->FailureKind);
12970 }
12971
12972 bool operator()(const OverloadCandidate *L,
12973 const OverloadCandidate *R) {
12974 // Fast-path this check.
12975 if (L == R) return false;
12976
12977 // Order first by viability.
12978 if (L->Viable) {
12979 if (!R->Viable) return true;
12980
12981 if (int Ord = CompareConversions(*L, *R))
12982 return Ord < 0;
12983 // Use other tie breakers.
12984 } else if (R->Viable)
12985 return false;
12986
12987 assert(L->Viable == R->Viable);
12988
12989 // Criteria by which we can sort non-viable candidates:
12990 if (!L->Viable) {
12991 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
12992 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
12993
12994 // 1. Arity mismatches come after other candidates.
12995 if (LFailureKind == ovl_fail_too_many_arguments ||
12996 LFailureKind == ovl_fail_too_few_arguments) {
12997 if (RFailureKind == ovl_fail_too_many_arguments ||
12998 RFailureKind == ovl_fail_too_few_arguments) {
12999 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
13000 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
13001 if (LDist == RDist) {
13002 if (LFailureKind == RFailureKind)
13003 // Sort non-surrogates before surrogates.
13004 return !L->IsSurrogate && R->IsSurrogate;
13005 // Sort candidates requiring fewer parameters than there were
13006 // arguments given after candidates requiring more parameters
13007 // than there were arguments given.
13008 return LFailureKind == ovl_fail_too_many_arguments;
13009 }
13010 return LDist < RDist;
13011 }
13012 return false;
13013 }
13014 if (RFailureKind == ovl_fail_too_many_arguments ||
13015 RFailureKind == ovl_fail_too_few_arguments)
13016 return true;
13017
13018 // 2. Bad conversions come first and are ordered by the number
13019 // of bad conversions and quality of good conversions.
13020 if (LFailureKind == ovl_fail_bad_conversion) {
13021 if (RFailureKind != ovl_fail_bad_conversion)
13022 return true;
13023
13024 // The conversion that can be fixed with a smaller number of changes,
13025 // comes first.
13026 unsigned numLFixes = L->Fix.NumConversionsFixed;
13027 unsigned numRFixes = R->Fix.NumConversionsFixed;
13028 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
13029 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
13030 if (numLFixes != numRFixes) {
13031 return numLFixes < numRFixes;
13032 }
13033
13034 // If there's any ordering between the defined conversions...
13035 if (int Ord = CompareConversions(*L, *R))
13036 return Ord < 0;
13037 } else if (RFailureKind == ovl_fail_bad_conversion)
13038 return false;
13039
13040 if (LFailureKind == ovl_fail_bad_deduction) {
13041 if (RFailureKind != ovl_fail_bad_deduction)
13042 return true;
13043
13045 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
13046 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
13047 if (LRank != RRank)
13048 return LRank < RRank;
13049 }
13050 } else if (RFailureKind == ovl_fail_bad_deduction)
13051 return false;
13052
13053 // TODO: others?
13054 }
13055
13056 // Sort everything else by location.
13057 SourceLocation LLoc = GetLocationForCandidate(L);
13058 SourceLocation RLoc = GetLocationForCandidate(R);
13059
13060 // Put candidates without locations (e.g. builtins) at the end.
13061 if (LLoc.isValid() && RLoc.isValid())
13062 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13063 if (LLoc.isValid() && !RLoc.isValid())
13064 return true;
13065 if (RLoc.isValid() && !LLoc.isValid())
13066 return false;
13067 assert(!LLoc.isValid() && !RLoc.isValid());
13068 // For builtins and other functions without locations, fallback to the order
13069 // in which they were added into the candidate set.
13070 return L < R;
13071 }
13072
13073private:
13074 struct ConversionSignals {
13075 unsigned KindRank = 0;
13077
13078 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13079 ConversionSignals Sig;
13080 Sig.KindRank = Seq.getKindRank();
13081 if (Seq.isStandard())
13082 Sig.Rank = Seq.Standard.getRank();
13083 else if (Seq.isUserDefined())
13084 Sig.Rank = Seq.UserDefined.After.getRank();
13085 // We intend StaticObjectArgumentConversion to compare the same as
13086 // StandardConversion with ICR_ExactMatch rank.
13087 return Sig;
13088 }
13089
13090 static ConversionSignals ForObjectArgument() {
13091 // We intend StaticObjectArgumentConversion to compare the same as
13092 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13093 return {};
13094 }
13095 };
13096
13097 // Returns -1 if conversions in L are considered better.
13098 // 0 if they are considered indistinguishable.
13099 // 1 if conversions in R are better.
13100 int CompareConversions(const OverloadCandidate &L,
13101 const OverloadCandidate &R) {
13102 // We cannot use `isBetterOverloadCandidate` because it is defined
13103 // according to the C++ standard and provides a partial order, but we need
13104 // a total order as this function is used in sort.
13105 assert(L.Conversions.size() == R.Conversions.size());
13106 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13107 auto LS = L.IgnoreObjectArgument && I == 0
13108 ? ConversionSignals::ForObjectArgument()
13109 : ConversionSignals::ForSequence(L.Conversions[I]);
13110 auto RS = R.IgnoreObjectArgument
13111 ? ConversionSignals::ForObjectArgument()
13112 : ConversionSignals::ForSequence(R.Conversions[I]);
13113 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
13114 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
13115 ? -1
13116 : 1;
13117 }
13118 // FIXME: find a way to compare templates for being more or less
13119 // specialized that provides a strict weak ordering.
13120 return 0;
13121 }
13122};
13123}
13124
13125/// CompleteNonViableCandidate - Normally, overload resolution only
13126/// computes up to the first bad conversion. Produces the FixIt set if
13127/// possible.
13128static void
13130 ArrayRef<Expr *> Args,
13132 assert(!Cand->Viable);
13133
13134 // Don't do anything on failures other than bad conversion.
13136 return;
13137
13138 // We only want the FixIts if all the arguments can be corrected.
13139 bool Unfixable = false;
13140 // Use a implicit copy initialization to check conversion fixes.
13142
13143 // Attempt to fix the bad conversion.
13144 unsigned ConvCount = Cand->Conversions.size();
13145 for (unsigned ConvIdx =
13146 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13147 : 0);
13148 /**/; ++ConvIdx) {
13149 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13150 if (Cand->Conversions[ConvIdx].isInitialized() &&
13151 Cand->Conversions[ConvIdx].isBad()) {
13152 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13153 break;
13154 }
13155 }
13156
13157 // FIXME: this should probably be preserved from the overload
13158 // operation somehow.
13159 bool SuppressUserConversions = false;
13160
13161 unsigned ConvIdx = 0;
13162 unsigned ArgIdx = 0;
13163 ArrayRef<QualType> ParamTypes;
13164 bool Reversed = Cand->isReversed();
13165
13166 if (Cand->IsSurrogate) {
13167 QualType ConvType
13169 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13170 ConvType = ConvPtrType->getPointeeType();
13171 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13172 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13173 ConvIdx = 1;
13174 } else if (Cand->Function) {
13175 ParamTypes =
13176 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13177 if (isa<CXXMethodDecl>(Cand->Function) &&
13180 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13181 ConvIdx = 1;
13183 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13185 OO_Subscript)
13186 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13187 ArgIdx = 1;
13188 }
13189 } else {
13190 // Builtin operator.
13191 assert(ConvCount <= 3);
13192 ParamTypes = Cand->BuiltinParamTypes;
13193 }
13194
13195 // Fill in the rest of the conversions.
13196 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13197 ConvIdx != ConvCount && ArgIdx < Args.size();
13198 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13199 if (Cand->Conversions[ConvIdx].isInitialized()) {
13200 // We've already checked this conversion.
13201 } else if (ParamIdx < ParamTypes.size()) {
13202 if (ParamTypes[ParamIdx]->isDependentType())
13203 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13204 Args[ArgIdx]->getType());
13205 else {
13206 Cand->Conversions[ConvIdx] =
13207 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
13208 SuppressUserConversions,
13209 /*InOverloadResolution=*/true,
13210 /*AllowObjCWritebackConversion=*/
13211 S.getLangOpts().ObjCAutoRefCount);
13212 // Store the FixIt in the candidate if it exists.
13213 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13214 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13215 }
13216 } else
13217 Cand->Conversions[ConvIdx].setEllipsis();
13218 }
13219}
13220
13223 SourceLocation OpLoc,
13224 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13225
13227
13228 // Sort the candidates by viability and position. Sorting directly would
13229 // be prohibitive, so we make a set of pointers and sort those.
13231 if (OCD == OCD_AllCandidates) Cands.reserve(size());
13232 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13233 Cand != LastCand; ++Cand) {
13234 if (!Filter(*Cand))
13235 continue;
13236 switch (OCD) {
13237 case OCD_AllCandidates:
13238 if (!Cand->Viable) {
13239 if (!Cand->Function && !Cand->IsSurrogate) {
13240 // This a non-viable builtin candidate. We do not, in general,
13241 // want to list every possible builtin candidate.
13242 continue;
13243 }
13244 CompleteNonViableCandidate(S, Cand, Args, Kind);
13245 }
13246 break;
13247
13249 if (!Cand->Viable)
13250 continue;
13251 break;
13252
13254 if (!Cand->Best)
13255 continue;
13256 break;
13257 }
13258
13259 Cands.push_back(Cand);
13260 }
13261
13262 llvm::stable_sort(
13263 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13264
13265 return Cands;
13266}
13267
13269 SourceLocation OpLoc) {
13270 bool DeferHint = false;
13271 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13272 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13273 // host device candidates.
13274 auto WrongSidedCands =
13275 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
13276 return (Cand.Viable == false &&
13278 (Cand.Function &&
13279 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13280 Cand.Function->template hasAttr<CUDADeviceAttr>());
13281 });
13282 DeferHint = !WrongSidedCands.empty();
13283 }
13284 return DeferHint;
13285}
13286
13287/// When overload resolution fails, prints diagnostic messages containing the
13288/// candidates in the candidate set.
13291 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13292 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13293
13294 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13295
13296 {
13297 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13298 S.Diag(PD.first, PD.second);
13299 }
13300
13301 // In WebAssembly we don't want to emit further diagnostics if a table is
13302 // passed as an argument to a function.
13303 bool NoteCands = true;
13304 for (const Expr *Arg : Args) {
13305 if (Arg->getType()->isWebAssemblyTableType())
13306 NoteCands = false;
13307 }
13308
13309 if (NoteCands)
13310 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13311
13312 if (OCD == OCD_AmbiguousCandidates)
13314 {Candidates.begin(), Candidates.end()});
13315}
13316
13319 StringRef Opc, SourceLocation OpLoc) {
13320 bool ReportedAmbiguousConversions = false;
13321
13322 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13323 unsigned CandsShown = 0;
13324 auto I = Cands.begin(), E = Cands.end();
13325 for (; I != E; ++I) {
13326 OverloadCandidate *Cand = *I;
13327
13328 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13329 ShowOverloads == Ovl_Best) {
13330 break;
13331 }
13332 ++CandsShown;
13333
13334 if (Cand->Function)
13335 NoteFunctionCandidate(S, Cand, Args.size(),
13336 Kind == CSK_AddressOfOverloadSet, DestAS);
13337 else if (Cand->IsSurrogate)
13338 NoteSurrogateCandidate(S, Cand);
13339 else {
13340 assert(Cand->Viable &&
13341 "Non-viable built-in candidates are not added to Cands.");
13342 // Generally we only see ambiguities including viable builtin
13343 // operators if overload resolution got screwed up by an
13344 // ambiguous user-defined conversion.
13345 //
13346 // FIXME: It's quite possible for different conversions to see
13347 // different ambiguities, though.
13348 if (!ReportedAmbiguousConversions) {
13349 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13350 ReportedAmbiguousConversions = true;
13351 }
13352
13353 // If this is a viable builtin, print it.
13354 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13355 }
13356 }
13357
13358 // Inform S.Diags that we've shown an overload set with N elements. This may
13359 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13360 S.Diags.overloadCandidatesShown(CandsShown);
13361
13362 if (I != E) {
13363 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13364 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
13365 }
13366}
13367
13368static SourceLocation
13370 return Cand->Specialization ? Cand->Specialization->getLocation()
13371 : SourceLocation();
13372}
13373
13374namespace {
13375struct CompareTemplateSpecCandidatesForDisplay {
13376 Sema &S;
13377 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13378
13379 bool operator()(const TemplateSpecCandidate *L,
13380 const TemplateSpecCandidate *R) {
13381 // Fast-path this check.
13382 if (L == R)
13383 return false;
13384
13385 // Assuming that both candidates are not matches...
13386
13387 // Sort by the ranking of deduction failures.
13391
13392 // Sort everything else by location.
13393 SourceLocation LLoc = GetLocationForCandidate(L);
13394 SourceLocation RLoc = GetLocationForCandidate(R);
13395
13396 // Put candidates without locations (e.g. builtins) at the end.
13397 if (LLoc.isInvalid())
13398 return false;
13399 if (RLoc.isInvalid())
13400 return true;
13401
13402 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13403 }
13404};
13405}
13406
13407/// Diagnose a template argument deduction failure.
13408/// We are treating these failures as overload failures due to bad
13409/// deductions.
13411 bool ForTakingAddress) {
13413 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
13414}
13415
13416void TemplateSpecCandidateSet::destroyCandidates() {
13417 for (iterator i = begin(), e = end(); i != e; ++i) {
13418 i->DeductionFailure.Destroy();
13419 }
13420}
13421
13423 destroyCandidates();
13424 Candidates.clear();
13425}
13426
13427/// NoteCandidates - When no template specialization match is found, prints
13428/// diagnostic messages containing the non-matching specializations that form
13429/// the candidate set.
13430/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13431/// OCD == OCD_AllCandidates and Cand->Viable == false.
13433 // Sort the candidates by position (assuming no candidate is a match).
13434 // Sorting directly would be prohibitive, so we make a set of pointers
13435 // and sort those.
13437 Cands.reserve(size());
13438 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13439 if (Cand->Specialization)
13440 Cands.push_back(Cand);
13441 // Otherwise, this is a non-matching builtin candidate. We do not,
13442 // in general, want to list every possible builtin candidate.
13443 }
13444
13445 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
13446
13447 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13448 // for generalization purposes (?).
13449 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13450
13452 unsigned CandsShown = 0;
13453 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13454 TemplateSpecCandidate *Cand = *I;
13455
13456 // Set an arbitrary limit on the number of candidates we'll spam
13457 // the user with. FIXME: This limit should depend on details of the
13458 // candidate list.
13459 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13460 break;
13461 ++CandsShown;
13462
13463 assert(Cand->Specialization &&
13464 "Non-matching built-in candidates are not added to Cands.");
13465 Cand->NoteDeductionFailure(S, ForTakingAddress);
13466 }
13467
13468 if (I != E)
13469 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
13470}
13471
13472// [PossiblyAFunctionType] --> [Return]
13473// NonFunctionType --> NonFunctionType
13474// R (A) --> R(A)
13475// R (*)(A) --> R (A)
13476// R (&)(A) --> R (A)
13477// R (S::*)(A) --> R (A)
13479 QualType Ret = PossiblyAFunctionType;
13480 if (const PointerType *ToTypePtr =
13481 PossiblyAFunctionType->getAs<PointerType>())
13482 Ret = ToTypePtr->getPointeeType();
13483 else if (const ReferenceType *ToTypeRef =
13484 PossiblyAFunctionType->getAs<ReferenceType>())
13485 Ret = ToTypeRef->getPointeeType();
13486 else if (const MemberPointerType *MemTypePtr =
13487 PossiblyAFunctionType->getAs<MemberPointerType>())
13488 Ret = MemTypePtr->getPointeeType();
13489 Ret =
13490 Context.getCanonicalType(Ret).getUnqualifiedType();
13491 return Ret;
13492}
13493
13495 bool Complain = true) {
13496 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13497 S.DeduceReturnType(FD, Loc, Complain))
13498 return true;
13499
13500 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13501 if (S.getLangOpts().CPlusPlus17 &&
13502 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
13503 !S.ResolveExceptionSpec(Loc, FPT))
13504 return true;
13505
13506 return false;
13507}
13508
13509namespace {
13510// A helper class to help with address of function resolution
13511// - allows us to avoid passing around all those ugly parameters
13512class AddressOfFunctionResolver {
13513 Sema& S;
13514 Expr* SourceExpr;
13515 const QualType& TargetType;
13516 QualType TargetFunctionType; // Extracted function type from target type
13517
13518 bool Complain;
13519 //DeclAccessPair& ResultFunctionAccessPair;
13520 ASTContext& Context;
13521
13522 bool TargetTypeIsNonStaticMemberFunction;
13523 bool FoundNonTemplateFunction;
13524 bool StaticMemberFunctionFromBoundPointer;
13525 bool HasComplained;
13526
13527 OverloadExpr::FindResult OvlExprInfo;
13528 OverloadExpr *OvlExpr;
13529 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13530 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13531 TemplateSpecCandidateSet FailedCandidates;
13532
13533public:
13534 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13535 const QualType &TargetType, bool Complain)
13536 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13537 Complain(Complain), Context(S.getASTContext()),
13538 TargetTypeIsNonStaticMemberFunction(
13539 !!TargetType->getAs<MemberPointerType>()),
13540 FoundNonTemplateFunction(false),
13541 StaticMemberFunctionFromBoundPointer(false),
13542 HasComplained(false),
13543 OvlExprInfo(OverloadExpr::find(SourceExpr)),
13544 OvlExpr(OvlExprInfo.Expression),
13545 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13546 ExtractUnqualifiedFunctionTypeFromTargetType();
13547
13548 if (TargetFunctionType->isFunctionType()) {
13549 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
13550 if (!UME->isImplicitAccess() &&
13552 StaticMemberFunctionFromBoundPointer = true;
13553 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13554 DeclAccessPair dap;
13555 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13556 OvlExpr, false, &dap)) {
13557 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
13558 if (!Method->isStatic()) {
13559 // If the target type is a non-function type and the function found
13560 // is a non-static member function, pretend as if that was the
13561 // target, it's the only possible type to end up with.
13562 TargetTypeIsNonStaticMemberFunction = true;
13563
13564 // And skip adding the function if its not in the proper form.
13565 // We'll diagnose this due to an empty set of functions.
13566 if (!OvlExprInfo.HasFormOfMemberPointer)
13567 return;
13568 }
13569
13570 Matches.push_back(std::make_pair(dap, Fn));
13571 }
13572 return;
13573 }
13574
13575 if (OvlExpr->hasExplicitTemplateArgs())
13576 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
13577
13578 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13579 // C++ [over.over]p4:
13580 // If more than one function is selected, [...]
13581 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13582 if (FoundNonTemplateFunction) {
13583 EliminateAllTemplateMatches();
13584 EliminateLessPartialOrderingConstrainedMatches();
13585 } else
13586 EliminateAllExceptMostSpecializedTemplate();
13587 }
13588 }
13589
13590 if (S.getLangOpts().CUDA && Matches.size() > 1)
13591 EliminateSuboptimalCudaMatches();
13592 }
13593
13594 bool hasComplained() const { return HasComplained; }
13595
13596private:
13597 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13598 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
13599 S.IsFunctionConversion(FD->getType(), TargetFunctionType);
13600 }
13601
13602 /// \return true if A is considered a better overload candidate for the
13603 /// desired type than B.
13604 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13605 // If A doesn't have exactly the correct type, we don't want to classify it
13606 // as "better" than anything else. This way, the user is required to
13607 // disambiguate for us if there are multiple candidates and no exact match.
13608 return candidateHasExactlyCorrectType(A) &&
13609 (!candidateHasExactlyCorrectType(B) ||
13610 compareEnableIfAttrs(S, A, B) == Comparison::Better);
13611 }
13612
13613 /// \return true if we were able to eliminate all but one overload candidate,
13614 /// false otherwise.
13615 bool eliminiateSuboptimalOverloadCandidates() {
13616 // Same algorithm as overload resolution -- one pass to pick the "best",
13617 // another pass to be sure that nothing is better than the best.
13618 auto Best = Matches.begin();
13619 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13620 if (isBetterCandidate(I->second, Best->second))
13621 Best = I;
13622
13623 const FunctionDecl *BestFn = Best->second;
13624 auto IsBestOrInferiorToBest = [this, BestFn](
13625 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13626 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
13627 };
13628
13629 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13630 // option, so we can potentially give the user a better error
13631 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
13632 return false;
13633 Matches[0] = *Best;
13634 Matches.resize(1);
13635 return true;
13636 }
13637
13638 bool isTargetTypeAFunction() const {
13639 return TargetFunctionType->isFunctionType();
13640 }
13641
13642 // [ToType] [Return]
13643
13644 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13645 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13646 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13647 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13648 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13649 }
13650
13651 // return true if any matching specializations were found
13652 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13653 const DeclAccessPair& CurAccessFunPair) {
13654 if (CXXMethodDecl *Method
13655 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13656 // Skip non-static function templates when converting to pointer, and
13657 // static when converting to member pointer.
13658 bool CanConvertToFunctionPointer =
13659 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13660 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13661 return false;
13662 }
13663 else if (TargetTypeIsNonStaticMemberFunction)
13664 return false;
13665
13666 // C++ [over.over]p2:
13667 // If the name is a function template, template argument deduction is
13668 // done (14.8.2.2), and if the argument deduction succeeds, the
13669 // resulting template argument list is used to generate a single
13670 // function template specialization, which is added to the set of
13671 // overloaded functions considered.
13672 FunctionDecl *Specialization = nullptr;
13673 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13675 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13676 Specialization, Info, /*IsAddressOfFunction*/ true);
13677 Result != TemplateDeductionResult::Success) {
13678 // Make a note of the failed deduction for diagnostics.
13679 FailedCandidates.addCandidate()
13680 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13681 MakeDeductionFailureInfo(Context, Result, Info));
13682 return false;
13683 }
13684
13685 // Template argument deduction ensures that we have an exact match or
13686 // compatible pointer-to-function arguments that would be adjusted by ICS.
13687 // This function template specicalization works.
13689 Context.getCanonicalType(Specialization->getType()),
13690 Context.getCanonicalType(TargetFunctionType)));
13691
13693 return false;
13694
13695 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13696 return true;
13697 }
13698
13699 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13700 const DeclAccessPair& CurAccessFunPair) {
13701 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13702 // Skip non-static functions when converting to pointer, and static
13703 // when converting to member pointer.
13704 bool CanConvertToFunctionPointer =
13705 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13706 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13707 return false;
13708 }
13709 else if (TargetTypeIsNonStaticMemberFunction)
13710 return false;
13711
13712 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13713 if (S.getLangOpts().CUDA) {
13714 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13715 if (!(Caller && Caller->isImplicit()) &&
13716 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13717 return false;
13718 }
13719 if (FunDecl->isMultiVersion()) {
13720 const auto *TA = FunDecl->getAttr<TargetAttr>();
13721 if (TA && !TA->isDefaultVersion())
13722 return false;
13723 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13724 if (TVA && !TVA->isDefaultVersion())
13725 return false;
13726 }
13727
13728 // If any candidate has a placeholder return type, trigger its deduction
13729 // now.
13730 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13731 Complain)) {
13732 HasComplained |= Complain;
13733 return false;
13734 }
13735
13736 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13737 return false;
13738
13739 // If we're in C, we need to support types that aren't exactly identical.
13740 if (!S.getLangOpts().CPlusPlus ||
13741 candidateHasExactlyCorrectType(FunDecl)) {
13742 Matches.push_back(std::make_pair(
13743 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13744 FoundNonTemplateFunction = true;
13745 return true;
13746 }
13747 }
13748
13749 return false;
13750 }
13751
13752 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13753 bool Ret = false;
13754
13755 // If the overload expression doesn't have the form of a pointer to
13756 // member, don't try to convert it to a pointer-to-member type.
13757 if (IsInvalidFormOfPointerToMemberFunction())
13758 return false;
13759
13760 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13761 E = OvlExpr->decls_end();
13762 I != E; ++I) {
13763 // Look through any using declarations to find the underlying function.
13764 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13765
13766 // C++ [over.over]p3:
13767 // Non-member functions and static member functions match
13768 // targets of type "pointer-to-function" or "reference-to-function."
13769 // Nonstatic member functions match targets of
13770 // type "pointer-to-member-function."
13771 // Note that according to DR 247, the containing class does not matter.
13772 if (FunctionTemplateDecl *FunctionTemplate
13773 = dyn_cast<FunctionTemplateDecl>(Fn)) {
13774 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13775 Ret = true;
13776 }
13777 // If we have explicit template arguments supplied, skip non-templates.
13778 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13779 AddMatchingNonTemplateFunction(Fn, I.getPair()))
13780 Ret = true;
13781 }
13782 assert(Ret || Matches.empty());
13783 return Ret;
13784 }
13785
13786 void EliminateAllExceptMostSpecializedTemplate() {
13787 // [...] and any given function template specialization F1 is
13788 // eliminated if the set contains a second function template
13789 // specialization whose function template is more specialized
13790 // than the function template of F1 according to the partial
13791 // ordering rules of 14.5.5.2.
13792
13793 // The algorithm specified above is quadratic. We instead use a
13794 // two-pass algorithm (similar to the one used to identify the
13795 // best viable function in an overload set) that identifies the
13796 // best function template (if it exists).
13797
13798 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13799 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13800 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13801
13802 // TODO: It looks like FailedCandidates does not serve much purpose
13803 // here, since the no_viable diagnostic has index 0.
13804 UnresolvedSetIterator Result = S.getMostSpecialized(
13805 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13806 SourceExpr->getBeginLoc(), S.PDiag(),
13807 S.PDiag(diag::err_addr_ovl_ambiguous)
13808 << Matches[0].second->getDeclName(),
13809 S.PDiag(diag::note_ovl_candidate)
13810 << (unsigned)oc_function << (unsigned)ocs_described_template,
13811 Complain, TargetFunctionType);
13812
13813 if (Result != MatchesCopy.end()) {
13814 // Make it the first and only element
13815 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13816 Matches[0].second = cast<FunctionDecl>(*Result);
13817 Matches.resize(1);
13818 } else
13819 HasComplained |= Complain;
13820 }
13821
13822 void EliminateAllTemplateMatches() {
13823 // [...] any function template specializations in the set are
13824 // eliminated if the set also contains a non-template function, [...]
13825 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13826 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13827 ++I;
13828 else {
13829 Matches[I] = Matches[--N];
13830 Matches.resize(N);
13831 }
13832 }
13833 }
13834
13835 void EliminateLessPartialOrderingConstrainedMatches() {
13836 // C++ [over.over]p5:
13837 // [...] Any given non-template function F0 is eliminated if the set
13838 // contains a second non-template function that is more
13839 // partial-ordering-constrained than F0. [...]
13840 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
13841 "Call EliminateAllTemplateMatches() first");
13842 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
13843 Results.push_back(Matches[0]);
13844 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
13845 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
13846 FunctionDecl *F = getMorePartialOrderingConstrained(
13847 S, Matches[I].second, Results[0].second,
13848 /*IsFn1Reversed=*/false,
13849 /*IsFn2Reversed=*/false);
13850 if (!F) {
13851 Results.push_back(Matches[I]);
13852 continue;
13853 }
13854 if (F == Matches[I].second) {
13855 Results.clear();
13856 Results.push_back(Matches[I]);
13857 }
13858 }
13859 std::swap(Matches, Results);
13860 }
13861
13862 void EliminateSuboptimalCudaMatches() {
13863 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
13864 Matches);
13865 }
13866
13867public:
13868 void ComplainNoMatchesFound() const {
13869 assert(Matches.empty());
13870 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
13871 << OvlExpr->getName() << TargetFunctionType
13872 << OvlExpr->getSourceRange();
13873 if (FailedCandidates.empty())
13874 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13875 /*TakingAddress=*/true);
13876 else {
13877 // We have some deduction failure messages. Use them to diagnose
13878 // the function templates, and diagnose the non-template candidates
13879 // normally.
13880 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13881 IEnd = OvlExpr->decls_end();
13882 I != IEnd; ++I)
13883 if (FunctionDecl *Fun =
13884 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
13886 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
13887 /*TakingAddress=*/true);
13888 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
13889 }
13890 }
13891
13892 bool IsInvalidFormOfPointerToMemberFunction() const {
13893 return TargetTypeIsNonStaticMemberFunction &&
13894 !OvlExprInfo.HasFormOfMemberPointer;
13895 }
13896
13897 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13898 // TODO: Should we condition this on whether any functions might
13899 // have matched, or is it more appropriate to do that in callers?
13900 // TODO: a fixit wouldn't hurt.
13901 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
13902 << TargetType << OvlExpr->getSourceRange();
13903 }
13904
13905 bool IsStaticMemberFunctionFromBoundPointer() const {
13906 return StaticMemberFunctionFromBoundPointer;
13907 }
13908
13909 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13910 S.Diag(OvlExpr->getBeginLoc(),
13911 diag::err_invalid_form_pointer_member_function)
13912 << OvlExpr->getSourceRange();
13913 }
13914
13915 void ComplainOfInvalidConversion() const {
13916 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
13917 << OvlExpr->getName() << TargetType;
13918 }
13919
13920 void ComplainMultipleMatchesFound() const {
13921 assert(Matches.size() > 1);
13922 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
13923 << OvlExpr->getName() << OvlExpr->getSourceRange();
13924 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13925 /*TakingAddress=*/true);
13926 }
13927
13928 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13929
13930 int getNumMatches() const { return Matches.size(); }
13931
13932 FunctionDecl* getMatchingFunctionDecl() const {
13933 if (Matches.size() != 1) return nullptr;
13934 return Matches[0].second;
13935 }
13936
13937 const DeclAccessPair* getMatchingFunctionAccessPair() const {
13938 if (Matches.size() != 1) return nullptr;
13939 return &Matches[0].first;
13940 }
13941};
13942}
13943
13944FunctionDecl *
13946 QualType TargetType,
13947 bool Complain,
13948 DeclAccessPair &FoundResult,
13949 bool *pHadMultipleCandidates) {
13950 assert(AddressOfExpr->getType() == Context.OverloadTy);
13951
13952 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13953 Complain);
13954 int NumMatches = Resolver.getNumMatches();
13955 FunctionDecl *Fn = nullptr;
13956 bool ShouldComplain = Complain && !Resolver.hasComplained();
13957 if (NumMatches == 0 && ShouldComplain) {
13958 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13959 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13960 else
13961 Resolver.ComplainNoMatchesFound();
13962 }
13963 else if (NumMatches > 1 && ShouldComplain)
13964 Resolver.ComplainMultipleMatchesFound();
13965 else if (NumMatches == 1) {
13966 Fn = Resolver.getMatchingFunctionDecl();
13967 assert(Fn);
13968 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13969 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
13970 FoundResult = *Resolver.getMatchingFunctionAccessPair();
13971 if (Complain) {
13972 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13973 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13974 else
13975 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
13976 }
13977 }
13978
13979 if (pHadMultipleCandidates)
13980 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13981 return Fn;
13982}
13983
13987 OverloadExpr *Ovl = R.Expression;
13988 bool IsResultAmbiguous = false;
13989 FunctionDecl *Result = nullptr;
13990 DeclAccessPair DAP;
13991 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
13992
13993 // Return positive for better, negative for worse, 0 for equal preference.
13994 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
13995 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
13996 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
13997 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
13998 };
13999
14000 // Don't use the AddressOfResolver because we're specifically looking for
14001 // cases where we have one overload candidate that lacks
14002 // enable_if/pass_object_size/...
14003 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
14004 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
14005 if (!FD)
14006 return nullptr;
14007
14009 continue;
14010
14011 // If we found a better result, update Result.
14012 auto FoundBetter = [&]() {
14013 IsResultAmbiguous = false;
14014 DAP = I.getPair();
14015 Result = FD;
14016 };
14017
14018 // We have more than one result - see if it is more
14019 // partial-ordering-constrained than the previous one.
14020 if (Result) {
14021 // Check CUDA preference first. If the candidates have differennt CUDA
14022 // preference, choose the one with higher CUDA preference. Otherwise,
14023 // choose the one with more constraints.
14024 if (getLangOpts().CUDA) {
14025 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
14026 // FD has different preference than Result.
14027 if (PreferenceByCUDA != 0) {
14028 // FD is more preferable than Result.
14029 if (PreferenceByCUDA > 0)
14030 FoundBetter();
14031 continue;
14032 }
14033 }
14034 // FD has the same CUDA preference than Result. Continue to check
14035 // constraints.
14036
14037 // C++ [over.over]p5:
14038 // [...] Any given non-template function F0 is eliminated if the set
14039 // contains a second non-template function that is more
14040 // partial-ordering-constrained than F0 [...]
14041 FunctionDecl *MoreConstrained =
14043 /*IsFn1Reversed=*/false,
14044 /*IsFn2Reversed=*/false);
14045 if (MoreConstrained != FD) {
14046 if (!MoreConstrained) {
14047 IsResultAmbiguous = true;
14048 AmbiguousDecls.push_back(FD);
14049 }
14050 continue;
14051 }
14052 // FD is more constrained - replace Result with it.
14053 }
14054 FoundBetter();
14055 }
14056
14057 if (IsResultAmbiguous)
14058 return nullptr;
14059
14060 if (Result) {
14061 // We skipped over some ambiguous declarations which might be ambiguous with
14062 // the selected result.
14063 for (FunctionDecl *Skipped : AmbiguousDecls) {
14064 // If skipped candidate has different CUDA preference than the result,
14065 // there is no ambiguity. Otherwise check whether they have different
14066 // constraints.
14067 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
14068 continue;
14069 if (!getMoreConstrainedFunction(Skipped, Result))
14070 return nullptr;
14071 }
14072 Pair = DAP;
14073 }
14074 return Result;
14075}
14076
14078 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14079 Expr *E = SrcExpr.get();
14080 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14081
14082 DeclAccessPair DAP;
14084 if (!Found || Found->isCPUDispatchMultiVersion() ||
14085 Found->isCPUSpecificMultiVersion())
14086 return false;
14087
14088 // Emitting multiple diagnostics for a function that is both inaccessible and
14089 // unavailable is consistent with our behavior elsewhere. So, always check
14090 // for both.
14094 if (Res.isInvalid())
14095 return false;
14096 Expr *Fixed = Res.get();
14097 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14098 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
14099 else
14100 SrcExpr = Fixed;
14101 return true;
14102}
14103
14105 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14106 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14107 // C++ [over.over]p1:
14108 // [...] [Note: any redundant set of parentheses surrounding the
14109 // overloaded function name is ignored (5.1). ]
14110 // C++ [over.over]p1:
14111 // [...] The overloaded function name can be preceded by the &
14112 // operator.
14113
14114 // If we didn't actually find any template-ids, we're done.
14115 if (!ovl->hasExplicitTemplateArgs())
14116 return nullptr;
14117
14118 TemplateArgumentListInfo ExplicitTemplateArgs;
14119 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
14120
14121 // Look through all of the overloaded functions, searching for one
14122 // whose type matches exactly.
14123 FunctionDecl *Matched = nullptr;
14124 for (UnresolvedSetIterator I = ovl->decls_begin(),
14125 E = ovl->decls_end(); I != E; ++I) {
14126 // C++0x [temp.arg.explicit]p3:
14127 // [...] In contexts where deduction is done and fails, or in contexts
14128 // where deduction is not done, if a template argument list is
14129 // specified and it, along with any default template arguments,
14130 // identifies a single function template specialization, then the
14131 // template-id is an lvalue for the function template specialization.
14133 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
14134 if (!FunctionTemplate)
14135 continue;
14136
14137 // C++ [over.over]p2:
14138 // If the name is a function template, template argument deduction is
14139 // done (14.8.2.2), and if the argument deduction succeeds, the
14140 // resulting template argument list is used to generate a single
14141 // function template specialization, which is added to the set of
14142 // overloaded functions considered.
14143 FunctionDecl *Specialization = nullptr;
14144 TemplateDeductionInfo Info(ovl->getNameLoc());
14146 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
14147 /*IsAddressOfFunction*/ true);
14149 // Make a note of the failed deduction for diagnostics.
14150 if (FailedTSC)
14151 FailedTSC->addCandidate().set(
14152 I.getPair(), FunctionTemplate->getTemplatedDecl(),
14154 continue;
14155 }
14156
14157 assert(Specialization && "no specialization and no error?");
14158
14159 // C++ [temp.deduct.call]p6:
14160 // [...] If all successful deductions yield the same deduced A, that
14161 // deduced A is the result of deduction; otherwise, the parameter is
14162 // treated as a non-deduced context.
14163 if (Matched) {
14164 if (ForTypeDeduction &&
14166 Specialization->getType()))
14167 continue;
14168 // Multiple matches; we can't resolve to a single declaration.
14169 if (Complain) {
14170 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
14171 << ovl->getName();
14173 }
14174 return nullptr;
14175 }
14176
14177 Matched = Specialization;
14178 if (FoundResult) *FoundResult = I.getPair();
14179 }
14180
14181 if (Matched &&
14182 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
14183 return nullptr;
14184
14185 return Matched;
14186}
14187
14189 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14190 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14191 unsigned DiagIDForComplaining) {
14192 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14193
14195
14196 DeclAccessPair found;
14197 ExprResult SingleFunctionExpression;
14199 ovl.Expression, /*complain*/ false, &found)) {
14200 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
14201 SrcExpr = ExprError();
14202 return true;
14203 }
14204
14205 // It is only correct to resolve to an instance method if we're
14206 // resolving a form that's permitted to be a pointer to member.
14207 // Otherwise we'll end up making a bound member expression, which
14208 // is illegal in all the contexts we resolve like this.
14209 if (!ovl.HasFormOfMemberPointer &&
14210 isa<CXXMethodDecl>(fn) &&
14211 cast<CXXMethodDecl>(fn)->isInstance()) {
14212 if (!complain) return false;
14213
14214 Diag(ovl.Expression->getExprLoc(),
14215 diag::err_bound_member_function)
14216 << 0 << ovl.Expression->getSourceRange();
14217
14218 // TODO: I believe we only end up here if there's a mix of
14219 // static and non-static candidates (otherwise the expression
14220 // would have 'bound member' type, not 'overload' type).
14221 // Ideally we would note which candidate was chosen and why
14222 // the static candidates were rejected.
14223 SrcExpr = ExprError();
14224 return true;
14225 }
14226
14227 // Fix the expression to refer to 'fn'.
14228 SingleFunctionExpression =
14229 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
14230
14231 // If desired, do function-to-pointer decay.
14232 if (doFunctionPointerConversion) {
14233 SingleFunctionExpression =
14234 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
14235 if (SingleFunctionExpression.isInvalid()) {
14236 SrcExpr = ExprError();
14237 return true;
14238 }
14239 }
14240 }
14241
14242 if (!SingleFunctionExpression.isUsable()) {
14243 if (complain) {
14244 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
14245 << ovl.Expression->getName()
14246 << DestTypeForComplaining
14247 << OpRangeForComplaining
14249 NoteAllOverloadCandidates(SrcExpr.get());
14250
14251 SrcExpr = ExprError();
14252 return true;
14253 }
14254
14255 return false;
14256 }
14257
14258 SrcExpr = SingleFunctionExpression;
14259 return true;
14260}
14261
14262/// Add a single candidate to the overload set.
14264 DeclAccessPair FoundDecl,
14265 TemplateArgumentListInfo *ExplicitTemplateArgs,
14266 ArrayRef<Expr *> Args,
14267 OverloadCandidateSet &CandidateSet,
14268 bool PartialOverloading,
14269 bool KnownValid) {
14270 NamedDecl *Callee = FoundDecl.getDecl();
14271 if (isa<UsingShadowDecl>(Callee))
14272 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
14273
14274 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
14275 if (ExplicitTemplateArgs) {
14276 assert(!KnownValid && "Explicit template arguments?");
14277 return;
14278 }
14279 // Prevent ill-formed function decls to be added as overload candidates.
14280 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
14281 return;
14282
14283 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
14284 /*SuppressUserConversions=*/false,
14285 PartialOverloading);
14286 return;
14287 }
14288
14289 if (FunctionTemplateDecl *FuncTemplate
14290 = dyn_cast<FunctionTemplateDecl>(Callee)) {
14291 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
14292 ExplicitTemplateArgs, Args, CandidateSet,
14293 /*SuppressUserConversions=*/false,
14294 PartialOverloading);
14295 return;
14296 }
14297
14298 assert(!KnownValid && "unhandled case in overloaded call candidate");
14299}
14300
14302 ArrayRef<Expr *> Args,
14303 OverloadCandidateSet &CandidateSet,
14304 bool PartialOverloading) {
14305
14306#ifndef NDEBUG
14307 // Verify that ArgumentDependentLookup is consistent with the rules
14308 // in C++0x [basic.lookup.argdep]p3:
14309 //
14310 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14311 // and let Y be the lookup set produced by argument dependent
14312 // lookup (defined as follows). If X contains
14313 //
14314 // -- a declaration of a class member, or
14315 //
14316 // -- a block-scope function declaration that is not a
14317 // using-declaration, or
14318 //
14319 // -- a declaration that is neither a function or a function
14320 // template
14321 //
14322 // then Y is empty.
14323
14324 if (ULE->requiresADL()) {
14326 E = ULE->decls_end(); I != E; ++I) {
14327 assert(!(*I)->getDeclContext()->isRecord());
14328 assert(isa<UsingShadowDecl>(*I) ||
14329 !(*I)->getDeclContext()->isFunctionOrMethod());
14330 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14331 }
14332 }
14333#endif
14334
14335 // It would be nice to avoid this copy.
14336 TemplateArgumentListInfo TABuffer;
14337 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14338 if (ULE->hasExplicitTemplateArgs()) {
14339 ULE->copyTemplateArgumentsInto(TABuffer);
14340 ExplicitTemplateArgs = &TABuffer;
14341 }
14342
14344 E = ULE->decls_end(); I != E; ++I)
14345 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14346 CandidateSet, PartialOverloading,
14347 /*KnownValid*/ true);
14348
14349 if (ULE->requiresADL())
14351 Args, ExplicitTemplateArgs,
14352 CandidateSet, PartialOverloading);
14353}
14354
14356 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14357 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14358 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14359 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14360 CandidateSet, false, /*KnownValid*/ false);
14361}
14362
14363/// Determine whether a declaration with the specified name could be moved into
14364/// a different namespace.
14366 switch (Name.getCXXOverloadedOperator()) {
14367 case OO_New: case OO_Array_New:
14368 case OO_Delete: case OO_Array_Delete:
14369 return false;
14370
14371 default:
14372 return true;
14373 }
14374}
14375
14376/// Attempt to recover from an ill-formed use of a non-dependent name in a
14377/// template, where the non-dependent name was declared after the template
14378/// was defined. This is common in code written for a compilers which do not
14379/// correctly implement two-stage name lookup.
14380///
14381/// Returns true if a viable candidate was found and a diagnostic was issued.
14383 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14385 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14386 CXXRecordDecl **FoundInClass = nullptr) {
14387 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14388 return false;
14389
14390 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14391 if (DC->isTransparentContext())
14392 continue;
14393
14394 SemaRef.LookupQualifiedName(R, DC);
14395
14396 if (!R.empty()) {
14398
14399 OverloadCandidateSet Candidates(FnLoc, CSK);
14400 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14401 Candidates);
14402
14405 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
14406
14407 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
14408 // We either found non-function declarations or a best viable function
14409 // at class scope. A class-scope lookup result disables ADL. Don't
14410 // look past this, but let the caller know that we found something that
14411 // either is, or might be, usable in this class.
14412 if (FoundInClass) {
14413 *FoundInClass = RD;
14414 if (OR == OR_Success) {
14415 R.clear();
14416 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
14417 R.resolveKind();
14418 }
14419 }
14420 return false;
14421 }
14422
14423 if (OR != OR_Success) {
14424 // There wasn't a unique best function or function template.
14425 return false;
14426 }
14427
14428 // Find the namespaces where ADL would have looked, and suggest
14429 // declaring the function there instead.
14430 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14431 Sema::AssociatedClassSet AssociatedClasses;
14432 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
14433 AssociatedNamespaces,
14434 AssociatedClasses);
14435 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14437 DeclContext *Std = SemaRef.getStdNamespace();
14438 for (Sema::AssociatedNamespaceSet::iterator
14439 it = AssociatedNamespaces.begin(),
14440 end = AssociatedNamespaces.end(); it != end; ++it) {
14441 // Never suggest declaring a function within namespace 'std'.
14442 if (Std && Std->Encloses(*it))
14443 continue;
14444
14445 // Never suggest declaring a function within a namespace with a
14446 // reserved name, like __gnu_cxx.
14447 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
14448 if (NS &&
14449 NS->getQualifiedNameAsString().find("__") != std::string::npos)
14450 continue;
14451
14452 SuggestedNamespaces.insert(*it);
14453 }
14454 }
14455
14456 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
14457 << R.getLookupName();
14458 if (SuggestedNamespaces.empty()) {
14459 SemaRef.Diag(Best->Function->getLocation(),
14460 diag::note_not_found_by_two_phase_lookup)
14461 << R.getLookupName() << 0;
14462 } else if (SuggestedNamespaces.size() == 1) {
14463 SemaRef.Diag(Best->Function->getLocation(),
14464 diag::note_not_found_by_two_phase_lookup)
14465 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14466 } else {
14467 // FIXME: It would be useful to list the associated namespaces here,
14468 // but the diagnostics infrastructure doesn't provide a way to produce
14469 // a localized representation of a list of items.
14470 SemaRef.Diag(Best->Function->getLocation(),
14471 diag::note_not_found_by_two_phase_lookup)
14472 << R.getLookupName() << 2;
14473 }
14474
14475 // Try to recover by calling this function.
14476 return true;
14477 }
14478
14479 R.clear();
14480 }
14481
14482 return false;
14483}
14484
14485/// Attempt to recover from ill-formed use of a non-dependent operator in a
14486/// template, where the non-dependent operator was declared after the template
14487/// was defined.
14488///
14489/// Returns true if a viable candidate was found and a diagnostic was issued.
14490static bool
14492 SourceLocation OpLoc,
14493 ArrayRef<Expr *> Args) {
14494 DeclarationName OpName =
14496 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14497 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
14499 /*ExplicitTemplateArgs=*/nullptr, Args);
14500}
14501
14502namespace {
14503class BuildRecoveryCallExprRAII {
14504 Sema &SemaRef;
14505 Sema::SatisfactionStackResetRAII SatStack;
14506
14507public:
14508 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14509 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14510 SemaRef.IsBuildingRecoveryCallExpr = true;
14511 }
14512
14513 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14514};
14515}
14516
14517/// Attempts to recover from a call where no functions were found.
14518///
14519/// This function will do one of three things:
14520/// * Diagnose, recover, and return a recovery expression.
14521/// * Diagnose, fail to recover, and return ExprError().
14522/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14523/// expected to diagnose as appropriate.
14524static ExprResult
14527 SourceLocation LParenLoc,
14529 SourceLocation RParenLoc,
14530 bool EmptyLookup, bool AllowTypoCorrection) {
14531 // Do not try to recover if it is already building a recovery call.
14532 // This stops infinite loops for template instantiations like
14533 //
14534 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14535 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14536 if (SemaRef.IsBuildingRecoveryCallExpr)
14537 return ExprResult();
14538 BuildRecoveryCallExprRAII RCE(SemaRef);
14539
14540 CXXScopeSpec SS;
14541 SS.Adopt(ULE->getQualifierLoc());
14542 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14543
14544 TemplateArgumentListInfo TABuffer;
14545 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14546 if (ULE->hasExplicitTemplateArgs()) {
14547 ULE->copyTemplateArgumentsInto(TABuffer);
14548 ExplicitTemplateArgs = &TABuffer;
14549 }
14550
14551 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14553 CXXRecordDecl *FoundInClass = nullptr;
14554 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
14556 ExplicitTemplateArgs, Args, &FoundInClass)) {
14557 // OK, diagnosed a two-phase lookup issue.
14558 } else if (EmptyLookup) {
14559 // Try to recover from an empty lookup with typo correction.
14560 R.clear();
14561 NoTypoCorrectionCCC NoTypoValidator{};
14562 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14563 ExplicitTemplateArgs != nullptr,
14564 dyn_cast<MemberExpr>(Fn));
14565 CorrectionCandidateCallback &Validator =
14566 AllowTypoCorrection
14567 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14568 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14569 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
14570 Args))
14571 return ExprError();
14572 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14573 // We found a usable declaration of the name in a dependent base of some
14574 // enclosing class.
14575 // FIXME: We should also explain why the candidates found by name lookup
14576 // were not viable.
14577 if (SemaRef.DiagnoseDependentMemberLookup(R))
14578 return ExprError();
14579 } else {
14580 // We had viable candidates and couldn't recover; let the caller diagnose
14581 // this.
14582 return ExprResult();
14583 }
14584
14585 // If we get here, we should have issued a diagnostic and formed a recovery
14586 // lookup result.
14587 assert(!R.empty() && "lookup results empty despite recovery");
14588
14589 // If recovery created an ambiguity, just bail out.
14590 if (R.isAmbiguous()) {
14592 return ExprError();
14593 }
14594
14595 // Build an implicit member call if appropriate. Just drop the
14596 // casts and such from the call, we don't really care.
14597 ExprResult NewFn = ExprError();
14598 if ((*R.begin())->isCXXClassMember())
14599 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14600 ExplicitTemplateArgs, S);
14601 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14602 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
14603 ExplicitTemplateArgs);
14604 else
14605 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
14606
14607 if (NewFn.isInvalid())
14608 return ExprError();
14609
14610 // This shouldn't cause an infinite loop because we're giving it
14611 // an expression with viable lookup results, which should never
14612 // end up here.
14613 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
14614 MultiExprArg(Args.data(), Args.size()),
14615 RParenLoc);
14616}
14617
14620 MultiExprArg Args,
14621 SourceLocation RParenLoc,
14622 OverloadCandidateSet *CandidateSet,
14623 ExprResult *Result) {
14624#ifndef NDEBUG
14625 if (ULE->requiresADL()) {
14626 // To do ADL, we must have found an unqualified name.
14627 assert(!ULE->getQualifier() && "qualified name with ADL");
14628
14629 // We don't perform ADL for implicit declarations of builtins.
14630 // Verify that this was correctly set up.
14631 FunctionDecl *F;
14632 if (ULE->decls_begin() != ULE->decls_end() &&
14633 ULE->decls_begin() + 1 == ULE->decls_end() &&
14634 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14635 F->getBuiltinID() && F->isImplicit())
14636 llvm_unreachable("performing ADL for builtin");
14637
14638 // We don't perform ADL in C.
14639 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14640 }
14641#endif
14642
14643 UnbridgedCastsSet UnbridgedCasts;
14644 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14645 *Result = ExprError();
14646 return true;
14647 }
14648
14649 // Add the functions denoted by the callee to the set of candidate
14650 // functions, including those from argument-dependent lookup.
14651 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
14652
14653 if (getLangOpts().MSVCCompat &&
14654 CurContext->isDependentContext() && !isSFINAEContext() &&
14656
14658 if (CandidateSet->empty() ||
14659 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
14661 // In Microsoft mode, if we are inside a template class member function
14662 // then create a type dependent CallExpr. The goal is to postpone name
14663 // lookup to instantiation time to be able to search into type dependent
14664 // base classes.
14665 CallExpr *CE =
14666 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
14667 RParenLoc, CurFPFeatureOverrides());
14669 *Result = CE;
14670 return true;
14671 }
14672 }
14673
14674 if (CandidateSet->empty())
14675 return false;
14676
14677 UnbridgedCasts.restore();
14678 return false;
14679}
14680
14681// Guess at what the return type for an unresolvable overload should be.
14684 std::optional<QualType> Result;
14685 // Adjust Type after seeing a candidate.
14686 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14687 if (!Candidate.Function)
14688 return;
14689 if (Candidate.Function->isInvalidDecl())
14690 return;
14691 QualType T = Candidate.Function->getReturnType();
14692 if (T.isNull())
14693 return;
14694 if (!Result)
14695 Result = T;
14696 else if (Result != T)
14697 Result = QualType();
14698 };
14699
14700 // Look for an unambiguous type from a progressively larger subset.
14701 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14702 //
14703 // First, consider only the best candidate.
14704 if (Best && *Best != CS.end())
14705 ConsiderCandidate(**Best);
14706 // Next, consider only viable candidates.
14707 if (!Result)
14708 for (const auto &C : CS)
14709 if (C.Viable)
14710 ConsiderCandidate(C);
14711 // Finally, consider all candidates.
14712 if (!Result)
14713 for (const auto &C : CS)
14714 ConsiderCandidate(C);
14715
14716 if (!Result)
14717 return QualType();
14718 auto Value = *Result;
14719 if (Value.isNull() || Value->isUndeducedType())
14720 return QualType();
14721 return Value;
14722}
14723
14724/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14725/// the completed call expression. If overload resolution fails, emits
14726/// diagnostics and returns ExprError()
14729 SourceLocation LParenLoc,
14730 MultiExprArg Args,
14731 SourceLocation RParenLoc,
14732 Expr *ExecConfig,
14733 OverloadCandidateSet *CandidateSet,
14735 OverloadingResult OverloadResult,
14736 bool AllowTypoCorrection) {
14737 switch (OverloadResult) {
14738 case OR_Success: {
14739 FunctionDecl *FDecl = (*Best)->Function;
14740 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14741 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14742 return ExprError();
14743 ExprResult Res =
14744 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14745 if (Res.isInvalid())
14746 return ExprError();
14747 return SemaRef.BuildResolvedCallExpr(
14748 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14749 /*IsExecConfig=*/false,
14750 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14751 }
14752
14753 case OR_No_Viable_Function: {
14754 if (*Best != CandidateSet->end() &&
14755 CandidateSet->getKind() ==
14757 if (CXXMethodDecl *M =
14758 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
14760 CandidateSet->NoteCandidates(
14762 Fn->getBeginLoc(),
14763 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
14764 SemaRef, OCD_AmbiguousCandidates, Args);
14765 return ExprError();
14766 }
14767 }
14768
14769 // Try to recover by looking for viable functions which the user might
14770 // have meant to call.
14771 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14772 Args, RParenLoc,
14773 CandidateSet->empty(),
14774 AllowTypoCorrection);
14775 if (Recovery.isInvalid() || Recovery.isUsable())
14776 return Recovery;
14777
14778 // If the user passes in a function that we can't take the address of, we
14779 // generally end up emitting really bad error messages. Here, we attempt to
14780 // emit better ones.
14781 for (const Expr *Arg : Args) {
14782 if (!Arg->getType()->isFunctionType())
14783 continue;
14784 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14785 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14786 if (FD &&
14787 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14788 Arg->getExprLoc()))
14789 return ExprError();
14790 }
14791 }
14792
14793 CandidateSet->NoteCandidates(
14795 Fn->getBeginLoc(),
14796 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14797 << ULE->getName() << Fn->getSourceRange()),
14798 SemaRef, OCD_AllCandidates, Args);
14799 break;
14800 }
14801
14802 case OR_Ambiguous:
14803 CandidateSet->NoteCandidates(
14804 PartialDiagnosticAt(Fn->getBeginLoc(),
14805 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14806 << ULE->getName() << Fn->getSourceRange()),
14807 SemaRef, OCD_AmbiguousCandidates, Args);
14808 break;
14809
14810 case OR_Deleted: {
14811 FunctionDecl *FDecl = (*Best)->Function;
14812 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
14813 Fn->getSourceRange(), ULE->getName(),
14814 *CandidateSet, FDecl, Args);
14815
14816 // We emitted an error for the unavailable/deleted function call but keep
14817 // the call in the AST.
14818 ExprResult Res =
14819 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14820 if (Res.isInvalid())
14821 return ExprError();
14822 return SemaRef.BuildResolvedCallExpr(
14823 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14824 /*IsExecConfig=*/false,
14825 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14826 }
14827 }
14828
14829 // Overload resolution failed, try to recover.
14830 SmallVector<Expr *, 8> SubExprs = {Fn};
14831 SubExprs.append(Args.begin(), Args.end());
14832 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
14833 chooseRecoveryType(*CandidateSet, Best));
14834}
14835
14838 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14839 if (I->Viable &&
14840 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
14841 I->Viable = false;
14842 I->FailureKind = ovl_fail_addr_not_available;
14843 }
14844 }
14845}
14846
14849 SourceLocation LParenLoc,
14850 MultiExprArg Args,
14851 SourceLocation RParenLoc,
14852 Expr *ExecConfig,
14853 bool AllowTypoCorrection,
14854 bool CalleesAddressIsTaken) {
14855
14859
14860 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
14861 ExprResult result;
14862
14863 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
14864 &result))
14865 return result;
14866
14867 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14868 // functions that aren't addressible are considered unviable.
14869 if (CalleesAddressIsTaken)
14870 markUnaddressableCandidatesUnviable(*this, CandidateSet);
14871
14873 OverloadingResult OverloadResult =
14874 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
14875
14876 // [C++23][over.call.func]
14877 // if overload resolution selects a non-static member function,
14878 // the call is ill-formed;
14880 Best != CandidateSet.end()) {
14881 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
14882 M && M->isImplicitObjectMemberFunction()) {
14883 OverloadResult = OR_No_Viable_Function;
14884 }
14885 }
14886
14887 // Model the case with a call to a templated function whose definition
14888 // encloses the call and whose return type contains a placeholder type as if
14889 // the UnresolvedLookupExpr was type-dependent.
14890 if (OverloadResult == OR_Success) {
14891 const FunctionDecl *FDecl = Best->Function;
14892 if (LangOpts.CUDA)
14893 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
14894 if (FDecl && FDecl->isTemplateInstantiation() &&
14895 FDecl->getReturnType()->isUndeducedType()) {
14896
14897 // Creating dependent CallExpr is not okay if the enclosing context itself
14898 // is not dependent. This situation notably arises if a non-dependent
14899 // member function calls the later-defined overloaded static function.
14900 //
14901 // For example, in
14902 // class A {
14903 // void c() { callee(1); }
14904 // static auto callee(auto x) { }
14905 // };
14906 //
14907 // Here callee(1) is unresolved at the call site, but is not inside a
14908 // dependent context. There will be no further attempt to resolve this
14909 // call if it is made dependent.
14910
14911 if (const auto *TP =
14912 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14913 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
14914 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
14915 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
14916 }
14917 }
14918 }
14919
14920 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14921 ExecConfig, &CandidateSet, &Best,
14922 OverloadResult, AllowTypoCorrection);
14923}
14924
14928 const UnresolvedSetImpl &Fns,
14929 bool PerformADL) {
14931 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
14932 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
14933}
14934
14937 bool HadMultipleCandidates) {
14938 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
14939 // the FoundDecl as it impedes TransformMemberExpr.
14940 // We go a bit further here: if there's no difference in UnderlyingDecl,
14941 // then using FoundDecl vs Method shouldn't make a difference either.
14942 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
14943 FoundDecl = Method;
14944 // Convert the expression to match the conversion function's implicit object
14945 // parameter.
14946 ExprResult Exp;
14947 if (Method->isExplicitObjectMemberFunction())
14949 else
14951 E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
14952 if (Exp.isInvalid())
14953 return true;
14954
14955 if (Method->getParent()->isLambda() &&
14956 Method->getConversionType()->isBlockPointerType()) {
14957 // This is a lambda conversion to block pointer; check if the argument
14958 // was a LambdaExpr.
14959 Expr *SubE = E;
14960 auto *CE = dyn_cast<CastExpr>(SubE);
14961 if (CE && CE->getCastKind() == CK_NoOp)
14962 SubE = CE->getSubExpr();
14963 SubE = SubE->IgnoreParens();
14964 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
14965 SubE = BE->getSubExpr();
14966 if (isa<LambdaExpr>(SubE)) {
14967 // For the conversion to block pointer on a lambda expression, we
14968 // construct a special BlockLiteral instead; this doesn't really make
14969 // a difference in ARC, but outside of ARC the resulting block literal
14970 // follows the normal lifetime rules for block literals instead of being
14971 // autoreleased.
14975 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
14977
14978 // FIXME: This note should be produced by a CodeSynthesisContext.
14979 if (BlockExp.isInvalid())
14980 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
14981 return BlockExp;
14982 }
14983 }
14984 CallExpr *CE;
14985 QualType ResultType = Method->getReturnType();
14987 ResultType = ResultType.getNonLValueExprType(Context);
14988 if (Method->isExplicitObjectMemberFunction()) {
14989 ExprResult FnExpr =
14990 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
14991 HadMultipleCandidates, E->getBeginLoc());
14992 if (FnExpr.isInvalid())
14993 return ExprError();
14994 Expr *ObjectParam = Exp.get();
14995 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
14996 ResultType, VK, Exp.get()->getEndLoc(),
14998 CE->setUsesMemberSyntax(true);
14999 } else {
15000 MemberExpr *ME =
15001 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
15003 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
15004 HadMultipleCandidates, DeclarationNameInfo(),
15005 Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
15006
15007 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
15008 Exp.get()->getEndLoc(),
15010 }
15011
15012 if (CheckFunctionCall(Method, CE,
15013 Method->getType()->castAs<FunctionProtoType>()))
15014 return ExprError();
15015
15017}
15018
15021 const UnresolvedSetImpl &Fns,
15022 Expr *Input, bool PerformADL) {
15024 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15025 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15026 // TODO: provide better source location info.
15027 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15028
15029 if (checkPlaceholderForOverload(*this, Input))
15030 return ExprError();
15031
15032 Expr *Args[2] = { Input, nullptr };
15033 unsigned NumArgs = 1;
15034
15035 // For post-increment and post-decrement, add the implicit '0' as
15036 // the second argument, so that we know this is a post-increment or
15037 // post-decrement.
15038 if (Opc == UO_PostInc || Opc == UO_PostDec) {
15039 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15040 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
15041 SourceLocation());
15042 NumArgs = 2;
15043 }
15044
15045 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
15046
15047 if (Input->isTypeDependent()) {
15049 // [C++26][expr.unary.op][expr.pre.incr]
15050 // The * operator yields an lvalue of type
15051 // The pre/post increment operators yied an lvalue.
15052 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
15053 VK = VK_LValue;
15054
15055 if (Fns.empty())
15056 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
15057 OK_Ordinary, OpLoc, false,
15059
15060 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15062 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
15063 if (Fn.isInvalid())
15064 return ExprError();
15065 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
15066 Context.DependentTy, VK_PRValue, OpLoc,
15068 }
15069
15070 // Build an empty overload set.
15072
15073 // Add the candidates from the given function set.
15074 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
15075
15076 // Add operator candidates that are member functions.
15077 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15078
15079 // Add candidates from ADL.
15080 if (PerformADL) {
15081 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
15082 /*ExplicitTemplateArgs*/nullptr,
15083 CandidateSet);
15084 }
15085
15086 // Add builtin operator candidates.
15087 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15088
15089 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15090
15091 // Perform overload resolution.
15093 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15094 case OR_Success: {
15095 // We found a built-in operator or an overloaded operator.
15096 FunctionDecl *FnDecl = Best->Function;
15097
15098 if (FnDecl) {
15099 Expr *Base = nullptr;
15100 // We matched an overloaded operator. Build a call to that
15101 // operator.
15102
15103 // Convert the arguments.
15104 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15105 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
15106
15107 ExprResult InputInit;
15108 if (Method->isExplicitObjectMemberFunction())
15109 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
15110 else
15112 Input, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15113 if (InputInit.isInvalid())
15114 return ExprError();
15115 Base = Input = InputInit.get();
15116 } else {
15117 // Convert the arguments.
15118 ExprResult InputInit
15120 Context,
15121 FnDecl->getParamDecl(0)),
15123 Input);
15124 if (InputInit.isInvalid())
15125 return ExprError();
15126 Input = InputInit.get();
15127 }
15128
15129 // Build the actual expression node.
15130 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
15131 Base, HadMultipleCandidates,
15132 OpLoc);
15133 if (FnExpr.isInvalid())
15134 return ExprError();
15135
15136 // Determine the result type.
15137 QualType ResultTy = FnDecl->getReturnType();
15139 ResultTy = ResultTy.getNonLValueExprType(Context);
15140
15141 Args[0] = Input;
15143 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
15145 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15146
15147 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
15148 return ExprError();
15149
15150 if (CheckFunctionCall(FnDecl, TheCall,
15151 FnDecl->getType()->castAs<FunctionProtoType>()))
15152 return ExprError();
15153 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
15154 } else {
15155 // We matched a built-in operator. Convert the arguments, then
15156 // break out so that we will build the appropriate built-in
15157 // operator node.
15159 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
15162 if (InputRes.isInvalid())
15163 return ExprError();
15164 Input = InputRes.get();
15165 break;
15166 }
15167 }
15168
15170 // This is an erroneous use of an operator which can be overloaded by
15171 // a non-member function. Check for non-member operators which were
15172 // defined too late to be candidates.
15173 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
15174 // FIXME: Recover by calling the found function.
15175 return ExprError();
15176
15177 // No viable function; fall through to handling this as a
15178 // built-in operator, which will produce an error message for us.
15179 break;
15180
15181 case OR_Ambiguous:
15182 CandidateSet.NoteCandidates(
15183 PartialDiagnosticAt(OpLoc,
15184 PDiag(diag::err_ovl_ambiguous_oper_unary)
15186 << Input->getType() << Input->getSourceRange()),
15187 *this, OCD_AmbiguousCandidates, ArgsArray,
15188 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15189 return ExprError();
15190
15191 case OR_Deleted: {
15192 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15193 // object whose method was called. Later in NoteCandidates size of ArgsArray
15194 // is passed further and it eventually ends up compared to number of
15195 // function candidate parameters which never includes the object parameter,
15196 // so slice ArgsArray to make sure apples are compared to apples.
15197 StringLiteral *Msg = Best->Function->getDeletedMessage();
15198 CandidateSet.NoteCandidates(
15199 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15201 << (Msg != nullptr)
15202 << (Msg ? Msg->getString() : StringRef())
15203 << Input->getSourceRange()),
15204 *this, OCD_AllCandidates, ArgsArray.drop_front(),
15205 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15206 return ExprError();
15207 }
15208 }
15209
15210 // Either we found no viable overloaded operator or we matched a
15211 // built-in operator. In either case, fall through to trying to
15212 // build a built-in operation.
15213 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15214}
15215
15218 const UnresolvedSetImpl &Fns,
15219 ArrayRef<Expr *> Args, bool PerformADL) {
15220 SourceLocation OpLoc = CandidateSet.getLocation();
15221
15222 OverloadedOperatorKind ExtraOp =
15225 : OO_None;
15226
15227 // Add the candidates from the given function set. This also adds the
15228 // rewritten candidates using these functions if necessary.
15229 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15230
15231 // As template candidates are not deduced immediately,
15232 // persist the array in the overload set.
15233 ArrayRef<Expr *> ReversedArgs;
15234 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15235 CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15236 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
15237
15238 // Add operator candidates that are member functions.
15239 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15240 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15241 AddMemberOperatorCandidates(Op, OpLoc, ReversedArgs, CandidateSet,
15243
15244 // In C++20, also add any rewritten member candidates.
15245 if (ExtraOp) {
15246 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
15247 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15248 AddMemberOperatorCandidates(ExtraOp, OpLoc, ReversedArgs, CandidateSet,
15250 }
15251
15252 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15253 // performed for an assignment operator (nor for operator[] nor operator->,
15254 // which don't get here).
15255 if (Op != OO_Equal && PerformADL) {
15256 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15257 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15258 /*ExplicitTemplateArgs*/ nullptr,
15259 CandidateSet);
15260 if (ExtraOp) {
15261 DeclarationName ExtraOpName =
15262 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
15263 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
15264 /*ExplicitTemplateArgs*/ nullptr,
15265 CandidateSet);
15266 }
15267 }
15268
15269 // Add builtin operator candidates.
15270 //
15271 // FIXME: We don't add any rewritten candidates here. This is strictly
15272 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15273 // resulting in our selecting a rewritten builtin candidate. For example:
15274 //
15275 // enum class E { e };
15276 // bool operator!=(E, E) requires false;
15277 // bool k = E::e != E::e;
15278 //
15279 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15280 // it seems unreasonable to consider rewritten builtin candidates. A core
15281 // issue has been filed proposing to removed this requirement.
15282 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15283}
15284
15287 const UnresolvedSetImpl &Fns, Expr *LHS,
15288 Expr *RHS, bool PerformADL,
15289 bool AllowRewrittenCandidates,
15290 FunctionDecl *DefaultedFn) {
15291 Expr *Args[2] = { LHS, RHS };
15292 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15293
15294 if (!getLangOpts().CPlusPlus20)
15295 AllowRewrittenCandidates = false;
15296
15298
15299 // If either side is type-dependent, create an appropriate dependent
15300 // expression.
15301 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15302 if (Fns.empty()) {
15303 // If there are no functions to store, just build a dependent
15304 // BinaryOperator or CompoundAssignment.
15307 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
15308 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
15309 Context.DependentTy);
15311 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
15313 }
15314
15315 // FIXME: save results of ADL from here?
15316 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15317 // TODO: provide better source location info in DNLoc component.
15318 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15319 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15321 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
15322 if (Fn.isInvalid())
15323 return ExprError();
15324 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
15325 Context.DependentTy, VK_PRValue, OpLoc,
15327 }
15328
15329 // If this is the .* operator, which is not overloadable, just
15330 // create a built-in binary operator.
15331 if (Opc == BO_PtrMemD) {
15332 auto CheckPlaceholder = [&](Expr *&Arg) {
15334 if (Res.isUsable())
15335 Arg = Res.get();
15336 return !Res.isUsable();
15337 };
15338
15339 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15340 // expression that contains placeholders (in either the LHS or RHS).
15341 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15342 return ExprError();
15343 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15344 }
15345
15346 // Always do placeholder-like conversions on the RHS.
15347 if (checkPlaceholderForOverload(*this, Args[1]))
15348 return ExprError();
15349
15350 // Do placeholder-like conversion on the LHS; note that we should
15351 // not get here with a PseudoObject LHS.
15352 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15353 if (checkPlaceholderForOverload(*this, Args[0]))
15354 return ExprError();
15355
15356 // If this is the assignment operator, we only perform overload resolution
15357 // if the left-hand side is a class or enumeration type. This is actually
15358 // a hack. The standard requires that we do overload resolution between the
15359 // various built-in candidates, but as DR507 points out, this can lead to
15360 // problems. So we do it this way, which pretty much follows what GCC does.
15361 // Note that we go the traditional code path for compound assignment forms.
15362 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
15363 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15364
15365 // Build the overload set.
15368 Op, OpLoc, AllowRewrittenCandidates));
15369 if (DefaultedFn)
15370 CandidateSet.exclude(DefaultedFn);
15371 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15372
15373 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15374
15375 // Perform overload resolution.
15377 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15378 case OR_Success: {
15379 // We found a built-in operator or an overloaded operator.
15380 FunctionDecl *FnDecl = Best->Function;
15381
15382 bool IsReversed = Best->isReversed();
15383 if (IsReversed)
15384 std::swap(Args[0], Args[1]);
15385
15386 if (FnDecl) {
15387
15388 if (FnDecl->isInvalidDecl())
15389 return ExprError();
15390
15391 Expr *Base = nullptr;
15392 // We matched an overloaded operator. Build a call to that
15393 // operator.
15394
15395 OverloadedOperatorKind ChosenOp =
15397
15398 // C++2a [over.match.oper]p9:
15399 // If a rewritten operator== candidate is selected by overload
15400 // resolution for an operator@, its return type shall be cv bool
15401 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15402 !FnDecl->getReturnType()->isBooleanType()) {
15403 bool IsExtension =
15405 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15406 : diag::err_ovl_rewrite_equalequal_not_bool)
15407 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
15408 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15409 Diag(FnDecl->getLocation(), diag::note_declared_at);
15410 if (!IsExtension)
15411 return ExprError();
15412 }
15413
15414 if (AllowRewrittenCandidates && !IsReversed &&
15415 CandidateSet.getRewriteInfo().isReversible()) {
15416 // We could have reversed this operator, but didn't. Check if some
15417 // reversed form was a viable candidate, and if so, if it had a
15418 // better conversion for either parameter. If so, this call is
15419 // formally ambiguous, and allowing it is an extension.
15421 for (OverloadCandidate &Cand : CandidateSet) {
15422 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15423 allowAmbiguity(Context, Cand.Function, FnDecl)) {
15424 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15426 *this, OpLoc, Cand.Conversions[ArgIdx],
15427 Best->Conversions[ArgIdx]) ==
15429 AmbiguousWith.push_back(Cand.Function);
15430 break;
15431 }
15432 }
15433 }
15434 }
15435
15436 if (!AmbiguousWith.empty()) {
15437 bool AmbiguousWithSelf =
15438 AmbiguousWith.size() == 1 &&
15439 declaresSameEntity(AmbiguousWith.front(), FnDecl);
15440 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
15442 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15443 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15444 if (AmbiguousWithSelf) {
15445 Diag(FnDecl->getLocation(),
15446 diag::note_ovl_ambiguous_oper_binary_reversed_self);
15447 // Mark member== const or provide matching != to disallow reversed
15448 // args. Eg.
15449 // struct S { bool operator==(const S&); };
15450 // S()==S();
15451 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
15452 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15453 !MD->isConst() &&
15454 !MD->hasCXXExplicitFunctionObjectParameter() &&
15455 Context.hasSameUnqualifiedType(
15456 MD->getFunctionObjectParameterType(),
15457 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
15458 Context.hasSameUnqualifiedType(
15459 MD->getFunctionObjectParameterType(),
15460 Args[0]->getType()) &&
15461 Context.hasSameUnqualifiedType(
15462 MD->getFunctionObjectParameterType(),
15463 Args[1]->getType()))
15464 Diag(FnDecl->getLocation(),
15465 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15466 } else {
15467 Diag(FnDecl->getLocation(),
15468 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15469 for (auto *F : AmbiguousWith)
15470 Diag(F->getLocation(),
15471 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15472 }
15473 }
15474 }
15475
15476 // Check for nonnull = nullable.
15477 // This won't be caught in the arg's initialization: the parameter to
15478 // the assignment operator is not marked nonnull.
15479 if (Op == OO_Equal)
15481 Args[1]->getType(), OpLoc);
15482
15483 // Convert the arguments.
15484 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15485 // Best->Access is only meaningful for class members.
15486 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
15487
15488 ExprResult Arg0, Arg1;
15489 unsigned ParamIdx = 0;
15490 if (Method->isExplicitObjectMemberFunction()) {
15491 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
15492 ParamIdx = 1;
15493 } else {
15495 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15496 }
15499 Context, FnDecl->getParamDecl(ParamIdx)),
15500 SourceLocation(), Args[1]);
15501 if (Arg0.isInvalid() || Arg1.isInvalid())
15502 return ExprError();
15503
15504 Base = Args[0] = Arg0.getAs<Expr>();
15505 Args[1] = RHS = Arg1.getAs<Expr>();
15506 } else {
15507 // Convert the arguments.
15510 FnDecl->getParamDecl(0)),
15511 SourceLocation(), Args[0]);
15512 if (Arg0.isInvalid())
15513 return ExprError();
15514
15515 ExprResult Arg1 =
15518 FnDecl->getParamDecl(1)),
15519 SourceLocation(), Args[1]);
15520 if (Arg1.isInvalid())
15521 return ExprError();
15522 Args[0] = LHS = Arg0.getAs<Expr>();
15523 Args[1] = RHS = Arg1.getAs<Expr>();
15524 }
15525
15526 // Build the actual expression node.
15527 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
15528 Best->FoundDecl, Base,
15529 HadMultipleCandidates, OpLoc);
15530 if (FnExpr.isInvalid())
15531 return ExprError();
15532
15533 // Determine the result type.
15534 QualType ResultTy = FnDecl->getReturnType();
15536 ResultTy = ResultTy.getNonLValueExprType(Context);
15537
15538 CallExpr *TheCall;
15539 ArrayRef<const Expr *> ArgsArray(Args, 2);
15540 const Expr *ImplicitThis = nullptr;
15541
15542 // We always create a CXXOperatorCallExpr, even for explicit object
15543 // members; CodeGen should take care not to emit the this pointer.
15545 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
15547 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15548
15549 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
15550 Method && Method->isImplicitObjectMemberFunction()) {
15551 // Cut off the implicit 'this'.
15552 ImplicitThis = ArgsArray[0];
15553 ArgsArray = ArgsArray.slice(1);
15554 }
15555
15556 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
15557 FnDecl))
15558 return ExprError();
15559
15560 if (Op == OO_Equal) {
15561 // Check for a self move.
15562 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
15563 // lifetime check.
15565 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
15566 Args[1]);
15567 }
15568 if (ImplicitThis) {
15569 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
15570 QualType ThisTypeFromDecl = Context.getPointerType(
15571 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
15572
15573 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
15574 ThisTypeFromDecl);
15575 }
15576
15577 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
15578 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
15580
15581 ExprResult R = MaybeBindToTemporary(TheCall);
15582 if (R.isInvalid())
15583 return ExprError();
15584
15585 R = CheckForImmediateInvocation(R, FnDecl);
15586 if (R.isInvalid())
15587 return ExprError();
15588
15589 // For a rewritten candidate, we've already reversed the arguments
15590 // if needed. Perform the rest of the rewrite now.
15591 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15592 (Op == OO_Spaceship && IsReversed)) {
15593 if (Op == OO_ExclaimEqual) {
15594 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15595 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
15596 } else {
15597 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15598 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15599 Expr *ZeroLiteral =
15601
15604 Ctx.Entity = FnDecl;
15606
15608 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
15609 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15610 /*AllowRewrittenCandidates=*/false);
15611
15613 }
15614 if (R.isInvalid())
15615 return ExprError();
15616 } else {
15617 assert(ChosenOp == Op && "unexpected operator name");
15618 }
15619
15620 // Make a note in the AST if we did any rewriting.
15621 if (Best->RewriteKind != CRK_None)
15622 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15623
15624 return R;
15625 } else {
15626 // We matched a built-in operator. Convert the arguments, then
15627 // break out so that we will build the appropriate built-in
15628 // operator node.
15630 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15633 if (ArgsRes0.isInvalid())
15634 return ExprError();
15635 Args[0] = ArgsRes0.get();
15636
15638 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15641 if (ArgsRes1.isInvalid())
15642 return ExprError();
15643 Args[1] = ArgsRes1.get();
15644 break;
15645 }
15646 }
15647
15648 case OR_No_Viable_Function: {
15649 // C++ [over.match.oper]p9:
15650 // If the operator is the operator , [...] and there are no
15651 // viable functions, then the operator is assumed to be the
15652 // built-in operator and interpreted according to clause 5.
15653 if (Opc == BO_Comma)
15654 break;
15655
15656 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15657 // compare result using '==' and '<'.
15658 if (DefaultedFn && Opc == BO_Cmp) {
15659 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
15660 Args[1], DefaultedFn);
15661 if (E.isInvalid() || E.isUsable())
15662 return E;
15663 }
15664
15665 // For class as left operand for assignment or compound assignment
15666 // operator do not fall through to handling in built-in, but report that
15667 // no overloaded assignment operator found
15669 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
15670 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
15671 Args, OpLoc);
15672 DeferDiagsRAII DDR(*this,
15673 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
15674 if (Args[0]->getType()->isRecordType() &&
15675 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15676 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15678 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15679 if (Args[0]->getType()->isIncompleteType()) {
15680 Diag(OpLoc, diag::note_assign_lhs_incomplete)
15681 << Args[0]->getType()
15682 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15683 }
15684 } else {
15685 // This is an erroneous use of an operator which can be overloaded by
15686 // a non-member function. Check for non-member operators which were
15687 // defined too late to be candidates.
15688 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
15689 // FIXME: Recover by calling the found function.
15690 return ExprError();
15691
15692 // No viable function; try to create a built-in operation, which will
15693 // produce an error. Then, show the non-viable candidates.
15694 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15695 }
15696 assert(Result.isInvalid() &&
15697 "C++ binary operator overloading is missing candidates!");
15698 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
15699 return Result;
15700 }
15701
15702 case OR_Ambiguous:
15703 CandidateSet.NoteCandidates(
15704 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15706 << Args[0]->getType()
15707 << Args[1]->getType()
15708 << Args[0]->getSourceRange()
15709 << Args[1]->getSourceRange()),
15711 OpLoc);
15712 return ExprError();
15713
15714 case OR_Deleted: {
15715 if (isImplicitlyDeleted(Best->Function)) {
15716 FunctionDecl *DeletedFD = Best->Function;
15718 if (DFK.isSpecialMember()) {
15719 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15720 << Args[0]->getType() << DFK.asSpecialMember();
15721 } else {
15722 assert(DFK.isComparison());
15723 Diag(OpLoc, diag::err_ovl_deleted_comparison)
15724 << Args[0]->getType() << DeletedFD;
15725 }
15726
15727 // The user probably meant to call this special member. Just
15728 // explain why it's deleted.
15729 NoteDeletedFunction(DeletedFD);
15730 return ExprError();
15731 }
15732
15733 StringLiteral *Msg = Best->Function->getDeletedMessage();
15734 CandidateSet.NoteCandidates(
15736 OpLoc,
15737 PDiag(diag::err_ovl_deleted_oper)
15738 << getOperatorSpelling(Best->Function->getDeclName()
15739 .getCXXOverloadedOperator())
15740 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15741 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15743 OpLoc);
15744 return ExprError();
15745 }
15746 }
15747
15748 // We matched a built-in operator; build it.
15749 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15750}
15751
15753 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15754 FunctionDecl *DefaultedFn) {
15755 const ComparisonCategoryInfo *Info =
15756 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
15757 // If we're not producing a known comparison category type, we can't
15758 // synthesize a three-way comparison. Let the caller diagnose this.
15759 if (!Info)
15760 return ExprResult((Expr*)nullptr);
15761
15762 // If we ever want to perform this synthesis more generally, we will need to
15763 // apply the temporary materialization conversion to the operands.
15764 assert(LHS->isGLValue() && RHS->isGLValue() &&
15765 "cannot use prvalue expressions more than once");
15766 Expr *OrigLHS = LHS;
15767 Expr *OrigRHS = RHS;
15768
15769 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15770 // each of them multiple times below.
15771 LHS = new (Context)
15772 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15773 LHS->getObjectKind(), LHS);
15774 RHS = new (Context)
15775 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15776 RHS->getObjectKind(), RHS);
15777
15778 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
15779 DefaultedFn);
15780 if (Eq.isInvalid())
15781 return ExprError();
15782
15783 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
15784 true, DefaultedFn);
15785 if (Less.isInvalid())
15786 return ExprError();
15787
15789 if (Info->isPartial()) {
15790 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
15791 DefaultedFn);
15792 if (Greater.isInvalid())
15793 return ExprError();
15794 }
15795
15796 // Form the list of comparisons we're going to perform.
15797 struct Comparison {
15798 ExprResult Cmp;
15800 } Comparisons[4] =
15806 };
15807
15808 int I = Info->isPartial() ? 3 : 2;
15809
15810 // Combine the comparisons with suitable conditional expressions.
15812 for (; I >= 0; --I) {
15813 // Build a reference to the comparison category constant.
15814 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
15815 // FIXME: Missing a constant for a comparison category. Diagnose this?
15816 if (!VI)
15817 return ExprResult((Expr*)nullptr);
15818 ExprResult ThisResult =
15820 if (ThisResult.isInvalid())
15821 return ExprError();
15822
15823 // Build a conditional unless this is the final case.
15824 if (Result.get()) {
15825 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
15826 ThisResult.get(), Result.get());
15827 if (Result.isInvalid())
15828 return ExprError();
15829 } else {
15830 Result = ThisResult;
15831 }
15832 }
15833
15834 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15835 // bind the OpaqueValueExprs before they're (repeatedly) used.
15836 Expr *SyntacticForm = BinaryOperator::Create(
15837 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
15838 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
15840 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15841 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
15842}
15843
15845 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15846 MultiExprArg Args, SourceLocation LParenLoc) {
15847
15848 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15849 unsigned NumParams = Proto->getNumParams();
15850 unsigned NumArgsSlots =
15851 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
15852 // Build the full argument list for the method call (the implicit object
15853 // parameter is placed at the beginning of the list).
15854 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
15855 bool IsError = false;
15856 // Initialize the implicit object parameter.
15857 // Check the argument types.
15858 for (unsigned i = 0; i != NumParams; i++) {
15859 Expr *Arg;
15860 if (i < Args.size()) {
15861 Arg = Args[i];
15862 ExprResult InputInit =
15864 S.Context, Method->getParamDecl(i)),
15865 SourceLocation(), Arg);
15866 IsError |= InputInit.isInvalid();
15867 Arg = InputInit.getAs<Expr>();
15868 } else {
15869 ExprResult DefArg =
15870 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
15871 if (DefArg.isInvalid()) {
15872 IsError = true;
15873 break;
15874 }
15875 Arg = DefArg.getAs<Expr>();
15876 }
15877
15878 MethodArgs.push_back(Arg);
15879 }
15880 return IsError;
15881}
15882
15884 SourceLocation RLoc,
15885 Expr *Base,
15886 MultiExprArg ArgExpr) {
15888 Args.push_back(Base);
15889 for (auto *e : ArgExpr) {
15890 Args.push_back(e);
15891 }
15892 DeclarationName OpName =
15893 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
15894
15895 SourceRange Range = ArgExpr.empty()
15896 ? SourceRange{}
15897 : SourceRange(ArgExpr.front()->getBeginLoc(),
15898 ArgExpr.back()->getEndLoc());
15899
15900 // If either side is type-dependent, create an appropriate dependent
15901 // expression.
15903
15904 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15905 // CHECKME: no 'operator' keyword?
15906 DeclarationNameInfo OpNameInfo(OpName, LLoc);
15907 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15909 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
15910 if (Fn.isInvalid())
15911 return ExprError();
15912 // Can't add any actual overloads yet
15913
15914 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
15915 Context.DependentTy, VK_PRValue, RLoc,
15917 }
15918
15919 // Handle placeholders
15920 UnbridgedCastsSet UnbridgedCasts;
15921 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
15922 return ExprError();
15923 }
15924 // Build an empty overload set.
15926
15927 // Subscript can only be overloaded as a member function.
15928
15929 // Add operator candidates that are member functions.
15930 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15931
15932 // Add builtin operator candidates.
15933 if (Args.size() == 2)
15934 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15935
15936 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15937
15938 // Perform overload resolution.
15940 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
15941 case OR_Success: {
15942 // We found a built-in operator or an overloaded operator.
15943 FunctionDecl *FnDecl = Best->Function;
15944
15945 if (FnDecl) {
15946 // We matched an overloaded operator. Build a call to that
15947 // operator.
15948
15949 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
15950
15951 // Convert the arguments.
15953 SmallVector<Expr *, 2> MethodArgs;
15954
15955 // Initialize the object parameter.
15956 if (Method->isExplicitObjectMemberFunction()) {
15957 ExprResult Res =
15959 if (Res.isInvalid())
15960 return ExprError();
15961 Args[0] = Res.get();
15962 ArgExpr = Args;
15963 } else {
15965 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15966 if (Arg0.isInvalid())
15967 return ExprError();
15968
15969 MethodArgs.push_back(Arg0.get());
15970 }
15971
15973 *this, MethodArgs, Method, ArgExpr, LLoc);
15974 if (IsError)
15975 return ExprError();
15976
15977 // Build the actual expression node.
15978 DeclarationNameInfo OpLocInfo(OpName, LLoc);
15979 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15981 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
15982 OpLocInfo.getLoc(), OpLocInfo.getInfo());
15983 if (FnExpr.isInvalid())
15984 return ExprError();
15985
15986 // Determine the result type
15987 QualType ResultTy = FnDecl->getReturnType();
15989 ResultTy = ResultTy.getNonLValueExprType(Context);
15990
15992 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
15994
15995 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
15996 return ExprError();
15997
15998 if (CheckFunctionCall(Method, TheCall,
15999 Method->getType()->castAs<FunctionProtoType>()))
16000 return ExprError();
16001
16003 FnDecl);
16004 } else {
16005 // We matched a built-in operator. Convert the arguments, then
16006 // break out so that we will build the appropriate built-in
16007 // operator node.
16009 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
16012 if (ArgsRes0.isInvalid())
16013 return ExprError();
16014 Args[0] = ArgsRes0.get();
16015
16017 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
16020 if (ArgsRes1.isInvalid())
16021 return ExprError();
16022 Args[1] = ArgsRes1.get();
16023
16024 break;
16025 }
16026 }
16027
16028 case OR_No_Viable_Function: {
16030 CandidateSet.empty()
16031 ? (PDiag(diag::err_ovl_no_oper)
16032 << Args[0]->getType() << /*subscript*/ 0
16033 << Args[0]->getSourceRange() << Range)
16034 : (PDiag(diag::err_ovl_no_viable_subscript)
16035 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
16036 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
16037 OCD_AllCandidates, ArgExpr, "[]", LLoc);
16038 return ExprError();
16039 }
16040
16041 case OR_Ambiguous:
16042 if (Args.size() == 2) {
16043 CandidateSet.NoteCandidates(
16045 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
16046 << "[]" << Args[0]->getType() << Args[1]->getType()
16047 << Args[0]->getSourceRange() << Range),
16048 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16049 } else {
16050 CandidateSet.NoteCandidates(
16052 PDiag(diag::err_ovl_ambiguous_subscript_call)
16053 << Args[0]->getType()
16054 << Args[0]->getSourceRange() << Range),
16055 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16056 }
16057 return ExprError();
16058
16059 case OR_Deleted: {
16060 StringLiteral *Msg = Best->Function->getDeletedMessage();
16061 CandidateSet.NoteCandidates(
16063 PDiag(diag::err_ovl_deleted_oper)
16064 << "[]" << (Msg != nullptr)
16065 << (Msg ? Msg->getString() : StringRef())
16066 << Args[0]->getSourceRange() << Range),
16067 *this, OCD_AllCandidates, Args, "[]", LLoc);
16068 return ExprError();
16069 }
16070 }
16071
16072 // We matched a built-in operator; build it.
16073 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
16074}
16075
16077 SourceLocation LParenLoc,
16078 MultiExprArg Args,
16079 SourceLocation RParenLoc,
16080 Expr *ExecConfig, bool IsExecConfig,
16081 bool AllowRecovery) {
16082 assert(MemExprE->getType() == Context.BoundMemberTy ||
16083 MemExprE->getType() == Context.OverloadTy);
16084
16085 // Dig out the member expression. This holds both the object
16086 // argument and the member function we're referring to.
16087 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16088
16089 // Determine whether this is a call to a pointer-to-member function.
16090 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
16091 assert(op->getType() == Context.BoundMemberTy);
16092 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16093
16094 QualType fnType =
16095 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16096
16097 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16098 QualType resultType = proto->getCallResultType(Context);
16100
16101 // Check that the object type isn't more qualified than the
16102 // member function we're calling.
16103 Qualifiers funcQuals = proto->getMethodQuals();
16104
16105 QualType objectType = op->getLHS()->getType();
16106 if (op->getOpcode() == BO_PtrMemI)
16107 objectType = objectType->castAs<PointerType>()->getPointeeType();
16108 Qualifiers objectQuals = objectType.getQualifiers();
16109
16110 Qualifiers difference = objectQuals - funcQuals;
16111 difference.removeObjCGCAttr();
16112 difference.removeAddressSpace();
16113 if (difference) {
16114 std::string qualsString = difference.getAsString();
16115 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
16116 << fnType.getUnqualifiedType()
16117 << qualsString
16118 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
16119 }
16120
16122 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
16124
16125 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
16126 call, nullptr))
16127 return ExprError();
16128
16129 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
16130 return ExprError();
16131
16132 if (CheckOtherCall(call, proto))
16133 return ExprError();
16134
16135 return MaybeBindToTemporary(call);
16136 }
16137
16138 // We only try to build a recovery expr at this level if we can preserve
16139 // the return type, otherwise we return ExprError() and let the caller
16140 // recover.
16141 auto BuildRecoveryExpr = [&](QualType Type) {
16142 if (!AllowRecovery)
16143 return ExprError();
16144 std::vector<Expr *> SubExprs = {MemExprE};
16145 llvm::append_range(SubExprs, Args);
16146 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
16147 Type);
16148 };
16149 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
16150 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
16151 RParenLoc, CurFPFeatureOverrides());
16152
16153 UnbridgedCastsSet UnbridgedCasts;
16154 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16155 return ExprError();
16156
16157 MemberExpr *MemExpr;
16158 CXXMethodDecl *Method = nullptr;
16159 bool HadMultipleCandidates = false;
16160 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
16161 NestedNameSpecifier Qualifier = std::nullopt;
16162 if (isa<MemberExpr>(NakedMemExpr)) {
16163 MemExpr = cast<MemberExpr>(NakedMemExpr);
16165 FoundDecl = MemExpr->getFoundDecl();
16166 Qualifier = MemExpr->getQualifier();
16167 UnbridgedCasts.restore();
16168 } else {
16169 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
16170 Qualifier = UnresExpr->getQualifier();
16171
16172 QualType ObjectType = UnresExpr->getBaseType();
16173 Expr::Classification ObjectClassification
16175 : UnresExpr->getBase()->Classify(Context);
16176
16177 // Add overload candidates
16178 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16180
16181 // FIXME: avoid copy.
16182 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16183 if (UnresExpr->hasExplicitTemplateArgs()) {
16184 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16185 TemplateArgs = &TemplateArgsBuffer;
16186 }
16187
16189 E = UnresExpr->decls_end(); I != E; ++I) {
16190
16191 QualType ExplicitObjectType = ObjectType;
16192
16193 NamedDecl *Func = *I;
16194 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
16196 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
16197
16198 bool HasExplicitParameter = false;
16199 if (const auto *M = dyn_cast<FunctionDecl>(Func);
16200 M && M->hasCXXExplicitFunctionObjectParameter())
16201 HasExplicitParameter = true;
16202 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
16203 M &&
16204 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16205 HasExplicitParameter = true;
16206
16207 if (HasExplicitParameter)
16208 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
16209
16210 // Microsoft supports direct constructor calls.
16211 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
16213 CandidateSet,
16214 /*SuppressUserConversions*/ false);
16215 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
16216 // If explicit template arguments were provided, we can't call a
16217 // non-template member function.
16218 if (TemplateArgs)
16219 continue;
16220
16221 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
16222 ObjectClassification, Args, CandidateSet,
16223 /*SuppressUserConversions=*/false);
16224 } else {
16226 I.getPair(), ActingDC, TemplateArgs,
16227 ExplicitObjectType, ObjectClassification,
16228 Args, CandidateSet,
16229 /*SuppressUserConversions=*/false);
16230 }
16231 }
16232
16233 HadMultipleCandidates = (CandidateSet.size() > 1);
16234
16235 DeclarationName DeclName = UnresExpr->getMemberName();
16236
16237 UnbridgedCasts.restore();
16238
16240 bool Succeeded = false;
16241 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
16242 Best)) {
16243 case OR_Success:
16244 Method = cast<CXXMethodDecl>(Best->Function);
16245 FoundDecl = Best->FoundDecl;
16246 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
16247 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
16248 break;
16249 // If FoundDecl is different from Method (such as if one is a template
16250 // and the other a specialization), make sure DiagnoseUseOfDecl is
16251 // called on both.
16252 // FIXME: This would be more comprehensively addressed by modifying
16253 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16254 // being used.
16255 if (Method != FoundDecl.getDecl() &&
16257 break;
16258 Succeeded = true;
16259 break;
16260
16262 CandidateSet.NoteCandidates(
16264 UnresExpr->getMemberLoc(),
16265 PDiag(diag::err_ovl_no_viable_member_function_in_call)
16266 << DeclName << MemExprE->getSourceRange()),
16267 *this, OCD_AllCandidates, Args);
16268 break;
16269 case OR_Ambiguous:
16270 CandidateSet.NoteCandidates(
16271 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16272 PDiag(diag::err_ovl_ambiguous_member_call)
16273 << DeclName << MemExprE->getSourceRange()),
16274 *this, OCD_AmbiguousCandidates, Args);
16275 break;
16276 case OR_Deleted:
16278 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
16279 CandidateSet, Best->Function, Args, /*IsMember=*/true);
16280 break;
16281 }
16282 // Overload resolution fails, try to recover.
16283 if (!Succeeded)
16284 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
16285
16286 ExprResult Res =
16287 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
16288 if (Res.isInvalid())
16289 return ExprError();
16290 MemExprE = Res.get();
16291
16292 // If overload resolution picked a static member
16293 // build a non-member call based on that function.
16294 if (Method->isStatic()) {
16295 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
16296 ExecConfig, IsExecConfig);
16297 }
16298
16299 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
16300 }
16301
16302 QualType ResultType = Method->getReturnType();
16304 ResultType = ResultType.getNonLValueExprType(Context);
16305
16306 assert(Method && "Member call to something that isn't a method?");
16307 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16308
16309 CallExpr *TheCall = nullptr;
16311 if (Method->isExplicitObjectMemberFunction()) {
16312 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
16313 NewArgs))
16314 return ExprError();
16315
16316 // Build the actual expression node.
16317 ExprResult FnExpr =
16318 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
16319 HadMultipleCandidates, MemExpr->getExprLoc());
16320 if (FnExpr.isInvalid())
16321 return ExprError();
16322
16323 TheCall =
16324 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
16325 CurFPFeatureOverrides(), Proto->getNumParams());
16326 TheCall->setUsesMemberSyntax(true);
16327 } else {
16328 // Convert the object argument (for a non-static member function call).
16330 MemExpr->getBase(), Qualifier, FoundDecl, Method);
16331 if (ObjectArg.isInvalid())
16332 return ExprError();
16333 MemExpr->setBase(ObjectArg.get());
16334 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
16335 RParenLoc, CurFPFeatureOverrides(),
16336 Proto->getNumParams());
16337 }
16338
16339 // Check for a valid return type.
16340 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
16341 TheCall, Method))
16342 return BuildRecoveryExpr(ResultType);
16343
16344 // Convert the rest of the arguments
16345 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
16346 RParenLoc))
16347 return BuildRecoveryExpr(ResultType);
16348
16349 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16350
16351 if (CheckFunctionCall(Method, TheCall, Proto))
16352 return ExprError();
16353
16354 // In the case the method to call was not selected by the overloading
16355 // resolution process, we still need to handle the enable_if attribute. Do
16356 // that here, so it will not hide previous -- and more relevant -- errors.
16357 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
16358 if (const EnableIfAttr *Attr =
16359 CheckEnableIf(Method, LParenLoc, Args, true)) {
16360 Diag(MemE->getMemberLoc(),
16361 diag::err_ovl_no_viable_member_function_in_call)
16362 << Method << Method->getSourceRange();
16363 Diag(Method->getLocation(),
16364 diag::note_ovl_candidate_disabled_by_function_cond_attr)
16365 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16366 return ExprError();
16367 }
16368 }
16369
16371 TheCall->getDirectCallee()->isPureVirtual()) {
16372 const FunctionDecl *MD = TheCall->getDirectCallee();
16373
16374 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
16376 Diag(MemExpr->getBeginLoc(),
16377 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16379 << MD->getParent();
16380
16381 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
16382 if (getLangOpts().AppleKext)
16383 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
16384 << MD->getParent() << MD->getDeclName();
16385 }
16386 }
16387
16388 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
16389 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16390 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16391 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
16392 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16393 MemExpr->getMemberLoc());
16394 }
16395
16397 TheCall->getDirectCallee());
16398}
16399
16402 SourceLocation LParenLoc,
16403 MultiExprArg Args,
16404 SourceLocation RParenLoc) {
16405 if (checkPlaceholderForOverload(*this, Obj))
16406 return ExprError();
16407 ExprResult Object = Obj;
16408
16409 UnbridgedCastsSet UnbridgedCasts;
16410 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16411 return ExprError();
16412
16413 assert(Object.get()->getType()->isRecordType() &&
16414 "Requires object type argument");
16415
16416 // C++ [over.call.object]p1:
16417 // If the primary-expression E in the function call syntax
16418 // evaluates to a class object of type "cv T", then the set of
16419 // candidate functions includes at least the function call
16420 // operators of T. The function call operators of T are obtained by
16421 // ordinary lookup of the name operator() in the context of
16422 // (E).operator().
16423 OverloadCandidateSet CandidateSet(LParenLoc,
16425 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
16426
16427 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
16428 diag::err_incomplete_object_call, Object.get()))
16429 return true;
16430
16431 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16432 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16435
16436 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16437 Oper != OperEnd; ++Oper) {
16438 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
16439 Object.get()->Classify(Context), Args, CandidateSet,
16440 /*SuppressUserConversion=*/false);
16441 }
16442
16443 // When calling a lambda, both the call operator, and
16444 // the conversion operator to function pointer
16445 // are considered. But when constraint checking
16446 // on the call operator fails, it will also fail on the
16447 // conversion operator as the constraints are always the same.
16448 // As the user probably does not intend to perform a surrogate call,
16449 // we filter them out to produce better error diagnostics, ie to avoid
16450 // showing 2 failed overloads instead of one.
16451 bool IgnoreSurrogateFunctions = false;
16452 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16453 const OverloadCandidate &Candidate = *CandidateSet.begin();
16454 if (!Candidate.Viable &&
16456 IgnoreSurrogateFunctions = true;
16457 }
16458
16459 // C++ [over.call.object]p2:
16460 // In addition, for each (non-explicit in C++0x) conversion function
16461 // declared in T of the form
16462 //
16463 // operator conversion-type-id () cv-qualifier;
16464 //
16465 // where cv-qualifier is the same cv-qualification as, or a
16466 // greater cv-qualification than, cv, and where conversion-type-id
16467 // denotes the type "pointer to function of (P1,...,Pn) returning
16468 // R", or the type "reference to pointer to function of
16469 // (P1,...,Pn) returning R", or the type "reference to function
16470 // of (P1,...,Pn) returning R", a surrogate call function [...]
16471 // is also considered as a candidate function. Similarly,
16472 // surrogate call functions are added to the set of candidate
16473 // functions for each conversion function declared in an
16474 // accessible base class provided the function is not hidden
16475 // within T by another intervening declaration.
16476 const auto &Conversions = Record->getVisibleConversionFunctions();
16477 for (auto I = Conversions.begin(), E = Conversions.end();
16478 !IgnoreSurrogateFunctions && I != E; ++I) {
16479 NamedDecl *D = *I;
16480 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
16481 if (isa<UsingShadowDecl>(D))
16482 D = cast<UsingShadowDecl>(D)->getTargetDecl();
16483
16484 // Skip over templated conversion functions; they aren't
16485 // surrogates.
16487 continue;
16488
16490 if (!Conv->isExplicit()) {
16491 // Strip the reference type (if any) and then the pointer type (if
16492 // any) to get down to what might be a function type.
16493 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16494 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16495 ConvType = ConvPtrType->getPointeeType();
16496
16497 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16498 {
16499 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
16500 Object.get(), Args, CandidateSet);
16501 }
16502 }
16503 }
16504
16505 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16506
16507 // Perform overload resolution.
16509 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
16510 Best)) {
16511 case OR_Success:
16512 // Overload resolution succeeded; we'll build the appropriate call
16513 // below.
16514 break;
16515
16516 case OR_No_Viable_Function: {
16518 CandidateSet.empty()
16519 ? (PDiag(diag::err_ovl_no_oper)
16520 << Object.get()->getType() << /*call*/ 1
16521 << Object.get()->getSourceRange())
16522 : (PDiag(diag::err_ovl_no_viable_object_call)
16523 << Object.get()->getType() << Object.get()->getSourceRange());
16524 CandidateSet.NoteCandidates(
16525 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
16526 OCD_AllCandidates, Args);
16527 break;
16528 }
16529 case OR_Ambiguous:
16530 if (!R.isAmbiguous())
16531 CandidateSet.NoteCandidates(
16532 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16533 PDiag(diag::err_ovl_ambiguous_object_call)
16534 << Object.get()->getType()
16535 << Object.get()->getSourceRange()),
16536 *this, OCD_AmbiguousCandidates, Args);
16537 break;
16538
16539 case OR_Deleted: {
16540 // FIXME: Is this diagnostic here really necessary? It seems that
16541 // 1. we don't have any tests for this diagnostic, and
16542 // 2. we already issue err_deleted_function_use for this later on anyway.
16543 StringLiteral *Msg = Best->Function->getDeletedMessage();
16544 CandidateSet.NoteCandidates(
16545 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16546 PDiag(diag::err_ovl_deleted_object_call)
16547 << Object.get()->getType() << (Msg != nullptr)
16548 << (Msg ? Msg->getString() : StringRef())
16549 << Object.get()->getSourceRange()),
16550 *this, OCD_AllCandidates, Args);
16551 break;
16552 }
16553 }
16554
16555 if (Best == CandidateSet.end())
16556 return true;
16557
16558 UnbridgedCasts.restore();
16559
16560 if (Best->Function == nullptr) {
16561 // Since there is no function declaration, this is one of the
16562 // surrogate candidates. Dig out the conversion function.
16563 CXXConversionDecl *Conv
16565 Best->Conversions[0].UserDefined.ConversionFunction);
16566
16567 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
16568 Best->FoundDecl);
16569 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
16570 return ExprError();
16571 assert(Conv == Best->FoundDecl.getDecl() &&
16572 "Found Decl & conversion-to-functionptr should be same, right?!");
16573 // We selected one of the surrogate functions that converts the
16574 // object parameter to a function pointer. Perform the conversion
16575 // on the object argument, then let BuildCallExpr finish the job.
16576
16577 // Create an implicit member expr to refer to the conversion operator.
16578 // and then call it.
16579 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
16580 Conv, HadMultipleCandidates);
16581 if (Call.isInvalid())
16582 return ExprError();
16583 // Record usage of conversion in an implicit cast.
16585 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
16586 nullptr, VK_PRValue, CurFPFeatureOverrides());
16587
16588 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
16589 }
16590
16591 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
16592
16593 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16594 // that calls this method, using Object for the implicit object
16595 // parameter and passing along the remaining arguments.
16596 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16597
16598 // An error diagnostic has already been printed when parsing the declaration.
16599 if (Method->isInvalidDecl())
16600 return ExprError();
16601
16602 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16603 unsigned NumParams = Proto->getNumParams();
16604
16605 DeclarationNameInfo OpLocInfo(
16606 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
16607 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16608 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16609 Obj, HadMultipleCandidates,
16610 OpLocInfo.getLoc(),
16611 OpLocInfo.getInfo());
16612 if (NewFn.isInvalid())
16613 return true;
16614
16615 SmallVector<Expr *, 8> MethodArgs;
16616 MethodArgs.reserve(NumParams + 1);
16617
16618 bool IsError = false;
16619
16620 // Initialize the object parameter.
16622 if (Method->isExplicitObjectMemberFunction()) {
16623 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
16624 } else {
16626 Object.get(), /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16627 if (ObjRes.isInvalid())
16628 IsError = true;
16629 else
16630 Object = ObjRes;
16631 MethodArgs.push_back(Object.get());
16632 }
16633
16635 *this, MethodArgs, Method, Args, LParenLoc);
16636
16637 // If this is a variadic call, handle args passed through "...".
16638 if (Proto->isVariadic()) {
16639 // Promote the arguments (C99 6.5.2.2p7).
16640 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16642 Args[i], VariadicCallType::Method, nullptr);
16643 IsError |= Arg.isInvalid();
16644 MethodArgs.push_back(Arg.get());
16645 }
16646 }
16647
16648 if (IsError)
16649 return true;
16650
16651 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16652
16653 // Once we've built TheCall, all of the expressions are properly owned.
16654 QualType ResultTy = Method->getReturnType();
16656 ResultTy = ResultTy.getNonLValueExprType(Context);
16657
16659 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
16661
16662 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
16663 return true;
16664
16665 if (CheckFunctionCall(Method, TheCall, Proto))
16666 return true;
16667
16669}
16670
16672 SourceLocation OpLoc,
16673 bool *NoArrowOperatorFound) {
16674 assert(Base->getType()->isRecordType() &&
16675 "left-hand side must have class type");
16676
16678 return ExprError();
16679
16680 SourceLocation Loc = Base->getExprLoc();
16681
16682 // C++ [over.ref]p1:
16683 //
16684 // [...] An expression x->m is interpreted as (x.operator->())->m
16685 // for a class object x of type T if T::operator->() exists and if
16686 // the operator is selected as the best match function by the
16687 // overload resolution mechanism (13.3).
16688 DeclarationName OpName =
16689 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
16691
16692 if (RequireCompleteType(Loc, Base->getType(),
16693 diag::err_typecheck_incomplete_tag, Base))
16694 return ExprError();
16695
16696 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16697 LookupQualifiedName(R, Base->getType()->castAsRecordDecl());
16699
16700 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16701 Oper != OperEnd; ++Oper) {
16702 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
16703 {}, CandidateSet,
16704 /*SuppressUserConversion=*/false);
16705 }
16706
16707 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16708
16709 // Perform overload resolution.
16711 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
16712 case OR_Success:
16713 // Overload resolution succeeded; we'll build the call below.
16714 break;
16715
16716 case OR_No_Viable_Function: {
16717 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
16718 if (CandidateSet.empty()) {
16719 QualType BaseType = Base->getType();
16720 if (NoArrowOperatorFound) {
16721 // Report this specific error to the caller instead of emitting a
16722 // diagnostic, as requested.
16723 *NoArrowOperatorFound = true;
16724 return ExprError();
16725 }
16726 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16727 << BaseType << Base->getSourceRange();
16728 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16729 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16730 << FixItHint::CreateReplacement(OpLoc, ".");
16731 }
16732 } else
16733 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16734 << "operator->" << Base->getSourceRange();
16735 CandidateSet.NoteCandidates(*this, Base, Cands);
16736 return ExprError();
16737 }
16738 case OR_Ambiguous:
16739 if (!R.isAmbiguous())
16740 CandidateSet.NoteCandidates(
16741 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16742 << "->" << Base->getType()
16743 << Base->getSourceRange()),
16745 return ExprError();
16746
16747 case OR_Deleted: {
16748 StringLiteral *Msg = Best->Function->getDeletedMessage();
16749 CandidateSet.NoteCandidates(
16750 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16751 << "->" << (Msg != nullptr)
16752 << (Msg ? Msg->getString() : StringRef())
16753 << Base->getSourceRange()),
16754 *this, OCD_AllCandidates, Base);
16755 return ExprError();
16756 }
16757 }
16758
16759 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
16760
16761 // Convert the object parameter.
16762 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16763
16764 if (Method->isExplicitObjectMemberFunction()) {
16766 if (R.isInvalid())
16767 return ExprError();
16768 Base = R.get();
16769 } else {
16771 Base, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16772 if (BaseResult.isInvalid())
16773 return ExprError();
16774 Base = BaseResult.get();
16775 }
16776
16777 // Build the operator call.
16778 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16779 Base, HadMultipleCandidates, OpLoc);
16780 if (FnExpr.isInvalid())
16781 return ExprError();
16782
16783 QualType ResultTy = Method->getReturnType();
16785 ResultTy = ResultTy.getNonLValueExprType(Context);
16786
16787 CallExpr *TheCall =
16788 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
16789 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
16790
16791 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
16792 return ExprError();
16793
16794 if (CheckFunctionCall(Method, TheCall,
16795 Method->getType()->castAs<FunctionProtoType>()))
16796 return ExprError();
16797
16799}
16800
16802 DeclarationNameInfo &SuffixInfo,
16803 ArrayRef<Expr*> Args,
16804 SourceLocation LitEndLoc,
16805 TemplateArgumentListInfo *TemplateArgs) {
16806 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16807
16808 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16810 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
16811 TemplateArgs);
16812
16813 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16814
16815 // Perform overload resolution. This will usually be trivial, but might need
16816 // to perform substitutions for a literal operator template.
16818 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
16819 case OR_Success:
16820 case OR_Deleted:
16821 break;
16822
16824 CandidateSet.NoteCandidates(
16825 PartialDiagnosticAt(UDSuffixLoc,
16826 PDiag(diag::err_ovl_no_viable_function_in_call)
16827 << R.getLookupName()),
16828 *this, OCD_AllCandidates, Args);
16829 return ExprError();
16830
16831 case OR_Ambiguous:
16832 CandidateSet.NoteCandidates(
16833 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
16834 << R.getLookupName()),
16835 *this, OCD_AmbiguousCandidates, Args);
16836 return ExprError();
16837 }
16838
16839 FunctionDecl *FD = Best->Function;
16840 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
16841 nullptr, HadMultipleCandidates,
16842 SuffixInfo.getLoc(),
16843 SuffixInfo.getInfo());
16844 if (Fn.isInvalid())
16845 return true;
16846
16847 // Check the argument types. This should almost always be a no-op, except
16848 // that array-to-pointer decay is applied to string literals.
16849 Expr *ConvArgs[2];
16850 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16853 SourceLocation(), Args[ArgIdx]);
16854 if (InputInit.isInvalid())
16855 return true;
16856 ConvArgs[ArgIdx] = InputInit.get();
16857 }
16858
16859 QualType ResultTy = FD->getReturnType();
16861 ResultTy = ResultTy.getNonLValueExprType(Context);
16862
16864 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
16865 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
16866
16867 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
16868 return ExprError();
16869
16870 if (CheckFunctionCall(FD, UDL, nullptr))
16871 return ExprError();
16872
16874}
16875
16878 SourceLocation RangeLoc,
16879 const DeclarationNameInfo &NameInfo,
16880 LookupResult &MemberLookup,
16881 OverloadCandidateSet *CandidateSet,
16882 Expr *Range, ExprResult *CallExpr) {
16883 Scope *S = nullptr;
16884
16886 if (!MemberLookup.empty()) {
16887 ExprResult MemberRef =
16888 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
16889 /*IsPtr=*/false, CXXScopeSpec(),
16890 /*TemplateKWLoc=*/SourceLocation(),
16891 /*FirstQualifierInScope=*/nullptr,
16892 MemberLookup,
16893 /*TemplateArgs=*/nullptr, S);
16894 if (MemberRef.isInvalid()) {
16895 *CallExpr = ExprError();
16896 return FRS_DiagnosticIssued;
16897 }
16898 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
16899 if (CallExpr->isInvalid()) {
16900 *CallExpr = ExprError();
16901 return FRS_DiagnosticIssued;
16902 }
16903 } else {
16904 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16906 NameInfo, UnresolvedSet<0>());
16907 if (FnR.isInvalid())
16908 return FRS_DiagnosticIssued;
16910
16911 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
16912 CandidateSet, CallExpr);
16913 if (CandidateSet->empty() || CandidateSetError) {
16914 *CallExpr = ExprError();
16915 return FRS_NoViableFunction;
16916 }
16918 OverloadingResult OverloadResult =
16919 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
16920
16921 if (OverloadResult == OR_No_Viable_Function) {
16922 *CallExpr = ExprError();
16923 return FRS_NoViableFunction;
16924 }
16925 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
16926 Loc, nullptr, CandidateSet, &Best,
16927 OverloadResult,
16928 /*AllowTypoCorrection=*/false);
16929 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16930 *CallExpr = ExprError();
16931 return FRS_DiagnosticIssued;
16932 }
16933 }
16934 return FRS_Success;
16935}
16936
16938 FunctionDecl *Fn) {
16939 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
16940 ExprResult SubExpr =
16941 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
16942 if (SubExpr.isInvalid())
16943 return ExprError();
16944 if (SubExpr.get() == PE->getSubExpr())
16945 return PE;
16946
16947 return new (Context)
16948 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16949 }
16950
16951 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
16952 ExprResult SubExpr =
16953 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
16954 if (SubExpr.isInvalid())
16955 return ExprError();
16956 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16957 SubExpr.get()->getType()) &&
16958 "Implicit cast type cannot be determined from overload");
16959 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16960 if (SubExpr.get() == ICE->getSubExpr())
16961 return ICE;
16962
16963 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
16964 SubExpr.get(), nullptr, ICE->getValueKind(),
16966 }
16967
16968 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
16969 if (!GSE->isResultDependent()) {
16970 ExprResult SubExpr =
16971 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
16972 if (SubExpr.isInvalid())
16973 return ExprError();
16974 if (SubExpr.get() == GSE->getResultExpr())
16975 return GSE;
16976
16977 // Replace the resulting type information before rebuilding the generic
16978 // selection expression.
16979 ArrayRef<Expr *> A = GSE->getAssocExprs();
16980 SmallVector<Expr *, 4> AssocExprs(A);
16981 unsigned ResultIdx = GSE->getResultIndex();
16982 AssocExprs[ResultIdx] = SubExpr.get();
16983
16984 if (GSE->isExprPredicate())
16986 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
16987 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16988 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16989 ResultIdx);
16991 Context, GSE->getGenericLoc(), GSE->getControllingType(),
16992 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16993 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16994 ResultIdx);
16995 }
16996 // Rather than fall through to the unreachable, return the original generic
16997 // selection expression.
16998 return GSE;
16999 }
17000
17001 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
17002 assert(UnOp->getOpcode() == UO_AddrOf &&
17003 "Can only take the address of an overloaded function");
17004 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
17005 if (!Method->isImplicitObjectMemberFunction()) {
17006 // Do nothing: the address of static and
17007 // explicit object member functions is a (non-member) function pointer.
17008 } else {
17009 // Fix the subexpression, which really has to be an
17010 // UnresolvedLookupExpr holding an overloaded member function
17011 // or template.
17012 ExprResult SubExpr =
17013 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17014 if (SubExpr.isInvalid())
17015 return ExprError();
17016 if (SubExpr.get() == UnOp->getSubExpr())
17017 return UnOp;
17018
17019 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
17020 SubExpr.get(), Method))
17021 return ExprError();
17022
17023 assert(isa<DeclRefExpr>(SubExpr.get()) &&
17024 "fixed to something other than a decl ref");
17025 NestedNameSpecifier Qualifier =
17026 cast<DeclRefExpr>(SubExpr.get())->getQualifier();
17027 assert(Qualifier &&
17028 "fixed to a member ref with no nested name qualifier");
17029
17030 // We have taken the address of a pointer to member
17031 // function. Perform the computation here so that we get the
17032 // appropriate pointer to member type.
17033 QualType MemPtrType = Context.getMemberPointerType(
17034 Fn->getType(), Qualifier,
17035 cast<CXXRecordDecl>(Method->getDeclContext()));
17036 // Under the MS ABI, lock down the inheritance model now.
17037 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
17038 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
17039
17040 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
17041 MemPtrType, VK_PRValue, OK_Ordinary,
17042 UnOp->getOperatorLoc(), false,
17044 }
17045 }
17046 ExprResult SubExpr =
17047 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17048 if (SubExpr.isInvalid())
17049 return ExprError();
17050 if (SubExpr.get() == UnOp->getSubExpr())
17051 return UnOp;
17052
17053 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
17054 SubExpr.get());
17055 }
17056
17057 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
17058 if (Found.getAccess() == AS_none) {
17060 }
17061 // FIXME: avoid copy.
17062 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17063 if (ULE->hasExplicitTemplateArgs()) {
17064 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
17065 TemplateArgs = &TemplateArgsBuffer;
17066 }
17067
17068 QualType Type = Fn->getType();
17069 ExprValueKind ValueKind =
17070 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
17071 ? VK_LValue
17072 : VK_PRValue;
17073
17074 // FIXME: Duplicated from BuildDeclarationNameExpr.
17075 if (unsigned BID = Fn->getBuiltinID()) {
17076 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
17077 Type = Context.BuiltinFnTy;
17078 ValueKind = VK_PRValue;
17079 }
17080 }
17081
17083 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
17084 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
17085 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17086 return DRE;
17087 }
17088
17089 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
17090 // FIXME: avoid copy.
17091 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17092 if (MemExpr->hasExplicitTemplateArgs()) {
17093 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
17094 TemplateArgs = &TemplateArgsBuffer;
17095 }
17096
17097 Expr *Base;
17098
17099 // If we're filling in a static method where we used to have an
17100 // implicit member access, rewrite to a simple decl ref.
17101 if (MemExpr->isImplicitAccess()) {
17102 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17104 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
17105 MemExpr->getQualifierLoc(), Found.getDecl(),
17106 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17107 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17108 return DRE;
17109 } else {
17110 SourceLocation Loc = MemExpr->getMemberLoc();
17111 if (MemExpr->getQualifier())
17112 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17113 Base =
17114 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
17115 }
17116 } else
17117 Base = MemExpr->getBase();
17118
17119 ExprValueKind valueKind;
17120 QualType type;
17121 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17122 valueKind = VK_LValue;
17123 type = Fn->getType();
17124 } else {
17125 valueKind = VK_PRValue;
17126 type = Context.BoundMemberTy;
17127 }
17128
17129 return BuildMemberExpr(
17130 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
17131 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
17132 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
17133 type, valueKind, OK_Ordinary, TemplateArgs);
17134 }
17135
17136 llvm_unreachable("Invalid reference to overloaded function");
17137}
17138
17144
17145bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17147 if (!PartialOverloading || !Function)
17148 return true;
17149 if (Function->isVariadic())
17150 return false;
17151 if (const auto *Proto =
17152 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
17153 if (Proto->isTemplateVariadic())
17154 return false;
17155 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17156 if (const auto *Proto =
17157 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
17158 if (Proto->isTemplateVariadic())
17159 return false;
17160 return true;
17161}
17162
17164 DeclarationName Name,
17165 OverloadCandidateSet &CandidateSet,
17166 FunctionDecl *Fn, MultiExprArg Args,
17167 bool IsMember) {
17168 StringLiteral *Msg = Fn->getDeletedMessage();
17169 CandidateSet.NoteCandidates(
17170 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
17171 << IsMember << Name << (Msg != nullptr)
17172 << (Msg ? Msg->getString() : StringRef())
17173 << Range),
17174 *this, OCD_AllCandidates, Args);
17175}
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 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 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:463
bool isFloat() const
Definition APValue.h:468
bool isInt() const
Definition APValue.h:467
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:956
APFloat & getFloat()
Definition APValue.h:503
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
const ConstantArrayType * getAsConstantArrayType(QualType T) const
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType LongTy
unsigned getIntWidth(QualType T) const
CanQualType Int128Ty
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
DeclarationNameTable DeclarationNames
Definition ASTContext.h:794
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:944
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:910
CanQualType Float128Ty
CanQualType UnsignedLongTy
QualType getRestrictType(QualType T) const
Return the uniqued reference to the type for a restrict qualified type.
CanQualType CharTy
CanQualType IntTy
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
CanQualType SignedCharTy
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
QualType getObjCIdType() const
Represents the Objective-CC id type.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
bool isSameTemplateParameterList(const TemplateParameterList *X, const TemplateParameterList *Y) const
Determine whether two template parameter lists are similar enough that they may be used in declaratio...
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType UnsignedInt128Ty
CanQualType VoidTy
CanQualType UnsignedCharTy
CanQualType UnsignedIntTy
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
CanQualType UnsignedLongLongTy
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
CanQualType UnsignedShortTy
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
CanQualType ShortTy
CanQualType Char32Ty
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getCVRQualifiedType(QualType T, unsigned CVR) const
Return a type with additional const, volatile, or restrict qualifiers.
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:909
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:3893
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:3723
QualType getElementType() const
Definition TypeBase.h:3735
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8091
Attr - This represents one attribute.
Definition Attr.h:46
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4038
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2179
StringRef getOpcodeStr() const
Definition Expr.h:4104
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2132
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:4982
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4179
Pointer to a block type.
Definition TypeBase.h:3543
This class is used for builtin types like 'int'.
Definition TypeBase.h:3165
Kind getKind() const
Definition TypeBase.h:3213
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:2604
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3019
bool isConvertingConstructor(bool AllowExplicit) const
Whether this constructor is a converting constructor (C++ [class.conv.ctor]), which can be used for u...
Definition DeclCXX.cpp:3056
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2939
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition DeclCXX.h:2975
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:2979
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:179
static CXXMemberCallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RP, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0)
Definition ExprCXX.cpp:692
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition DeclCXX.cpp:2703
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition DeclCXX.cpp:2710
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2820
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2255
static CXXOperatorCallExpr * Create(const ASTContext &Ctx, OverloadedOperatorKind OpKind, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation OperatorLoc, FPOptionsOverride FPFeatures, ADLCallKind UsesADL=NotADL)
Definition ExprCXX.cpp:624
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1018
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition DeclCXX.cpp:1977
bool hasDefinition() const
Definition DeclCXX.h:561
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1736
A rewritten comparison expression that was originally written using operator syntax.
Definition ExprCXX.h:286
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:73
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:178
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2943
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:1516
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3126
void setUsesMemberSyntax(bool V=true)
Definition Expr.h:3107
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition Expr.h:3325
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:3276
QualType getElementType() const
Definition TypeBase.h:3286
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:5004
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3761
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:349
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4388
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4407
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4404
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
void setHadMultipleCandidates(bool V=true)
Sets the flag telling whether this expression refers to a function that was resolved from an overload...
Definition Expr.h:1463
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition DeclBase.cpp:285
T * getAttr() const
Definition DeclBase.h:573
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:546
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
bool isInvalidDecl() const
Definition DeclBase.h:588
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:559
SourceLocation getLocation() const
Definition DeclBase.h:439
DeclContext * getDeclContext()
Definition DeclBase.h:448
AccessSpecifier getAccess() const
Definition DeclBase.h:507
specific_attr_iterator< T > specific_attr_end() const
Definition DeclBase.h:569
specific_attr_iterator< T > specific_attr_begin() const
Definition DeclBase.h:564
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
DeclarationNameLoc - Additional source/type location info for a declaration name.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
TemplateDecl * getCXXDeductionGuideTemplate() const
If this name is the name of a C++ deduction guide, return the template associated with that name.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:831
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:855
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition Diagnostic.h:777
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition Diagnostic.h:762
OverloadsShown getShowOverloads() const
Definition Diagnostic.h:753
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:592
RAII object that enters a new expression evaluation context.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1924
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition DeclCXX.h:1948
ExplicitSpecKind getKind() const
Definition DeclCXX.h:1932
const Expr * getExpr() const
Definition DeclCXX.h:1933
static ExplicitSpecifier getFromDecl(FunctionDecl *Function)
Definition DeclCXX.cpp:2354
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition ExprCXX.cpp:1464
The return type of classify().
Definition Expr.h:337
bool isLValue() const
Definition Expr.h:387
bool isPRValue() const
Definition Expr.h:390
bool isXValue() const
Definition Expr.h:388
static Classification makeSimpleLValue()
Create a simple, modifiable lvalue.
Definition Expr.h:395
bool isRValue() const
Definition Expr.h:391
This represents one expression.
Definition Expr.h:112
bool isIntegerConstantExpr(const ASTContext &Ctx) const
bool isGLValue() const
Definition Expr.h:287
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3094
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:444
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3085
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:3338
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4208
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:831
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:835
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:451
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:811
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4047
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:276
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:476
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition Expr.h:412
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:523
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:434
ExtVectorType - Extended vector type.
Definition TypeBase.h:4268
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:4193
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3762
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:3666
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3865
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:4264
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4313
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3747
param_iterator param_begin()
Definition Decl.h:2786
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3133
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4329
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4257
unsigned getNumNonObjectParams() const
Definition Decl.cpp:3869
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:4130
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:3710
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:3715
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3826
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:5269
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5773
unsigned getNumParams() const
Definition TypeBase.h:5547
Qualifiers getMethodQuals() const
Definition TypeBase.h:5695
QualType getParamType(unsigned i) const
Definition TypeBase.h:5549
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5673
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5709
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:4576
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4647
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4504
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4465
ExtInfo getExtInfo() const
Definition TypeBase.h:4821
CallingConv getCallConv() const
Definition TypeBase.h:4820
QualType getReturnType() const
Definition TypeBase.h:4805
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4833
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:4604
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:3853
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2072
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:621
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:672
void setBad(BadConversionSequence::FailureKind Failure, Expr *FromExpr, QualType ToType)
Sets this sequence as a bad conversion for an explicit argument.
Definition Overload.h:769
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition Overload.h:676
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:826
AmbiguousConversionSequence Ambiguous
When ConversionKind == AmbiguousConversion, provides the details of the ambiguous conversion.
Definition Overload.h:680
void setInitializerListContainerType(QualType T, bool IA)
Definition Overload.h:811
bool hasInitializerListContainerType() const
Definition Overload.h:808
unsigned getKindRank() const
Return a ranking of the implicit conversion sequence kind, where smaller ranks represent better conve...
Definition Overload.h:733
bool isInitializerListOfIncompleteArray() const
Definition Overload.h:815
BadConversionSequence Bad
When ConversionKind == BadConversion, provides the details of the bad conversion.
Definition Overload.h:684
QualType getInitializerListContainerType() const
Definition Overload.h:818
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition Expr.h:5299
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition Expr.h:5414
unsigned getNumInits() const
Definition Expr.h:5329
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:2495
const Expr * getInit(unsigned Init) const
Definition Expr.h:5353
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:2513
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:974
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3618
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:4352
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3364
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3553
NestedNameSpecifier getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition Expr.h:3475
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3447
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition Expr.h:3461
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition Expr.h:3582
Expr * getBase() const
Definition Expr.h:3441
void setBase(Expr *E)
Definition Expr.h:3440
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1793
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3559
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition Expr.h:3451
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3654
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3686
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5450
QualType getPointeeType() const
Definition TypeBase.h:3672
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:7854
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition TypeBase.h:7910
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition TypeBase.h:7999
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:7968
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:7922
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:7962
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1841
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:7974
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1178
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1159
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:1359
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:1457
ConversionSequenceList allocateConversionSequences(unsigned NumConversions)
Allocate storage for conversion sequences for NumConversions conversions.
Definition Overload.h:1391
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:1407
OperatorRewriteInfo getRewriteInfo() const
Definition Overload.h:1349
bool shouldDeferTemplateArgumentDeduction(const LangOptions &Opts) const
Definition Overload.h:1548
@ CSK_AddressOfOverloadSet
C++ [over.match.call.general] Resolve a call through the address of an overload set.
Definition Overload.h:1184
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition Overload.h:1180
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition Overload.h:1175
@ CSK_Normal
Normal lookup.
Definition Overload.h:1163
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition Overload.h:1170
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1375
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:1367
SourceLocation getLocation() const
Definition Overload.h:1347
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions={})
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition Overload.h:1422
void InjectNonDeducedTemplateCandidates(Sema &S)
CandidateSetKind getKind() const
Definition Overload.h:1348
size_t nonDeferredCandidatesCount() const
Definition Overload.h:1382
SmallVector< OverloadCandidate *, 32 > CompleteCandidates(Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, SourceLocation OpLoc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition ExprCXX.h:3128
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition ExprCXX.h:3280
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3189
NestedNameSpecifier getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition ExprCXX.h:3244
SourceLocation getNameLoc() const
Gets the location of the name.
Definition ExprCXX.h:3241
UnresolvedSetImpl::iterator decls_iterator
Definition ExprCXX.h:3219
decls_iterator decls_begin() const
Definition ExprCXX.h:3221
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition ExprCXX.h:3232
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition ExprCXX.h:3254
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition ExprCXX.h:3250
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition ExprCXX.h:3342
decls_iterator decls_end() const
Definition ExprCXX.h:3224
DeclarationName getName() const
Gets the name looked up.
Definition ExprCXX.h:3238
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:277
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2182
Represents a parameter to a function.
Definition Decl.h:1790
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3058
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:301
std::string getAsString() const
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3329
QualType getPointeeType() const
Definition TypeBase.h:3339
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5076
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8376
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8370
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8381
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3556
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition TypeBase.h:1225
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8292
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8418
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8332
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:8477
QualType getCanonicalType() const
Definition TypeBase.h:8344
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8386
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:8446
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8365
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8413
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8338
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1332
bool isAtLeastAsQualifiedAs(QualType Other, const ASTContext &Ctx) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition TypeBase.h:8457
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8324
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8232
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8239
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4660
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:3636
Represents a struct/union/class.
Definition Decl.h:4324
field_range fields() const
Definition Decl.h:4527
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3574
QualType getPointeeType() const
Definition TypeBase.h:3592
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:1500
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
Definition SemaARM.cpp:1544
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:10303
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:6350
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6379
RAII class to control scope of DeferDiags.
Definition Sema.h:10038
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:12450
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12484
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:855
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:10056
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:9327
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9354
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition Sema.h:9339
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9335
void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc, ArrayRef< Expr * > Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition SemaExpr.cpp:411
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr * > Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
bool IsStringInit(Expr *Init, const ArrayType *AT)
Definition SemaInit.cpp: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:1443
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:10386
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10389
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10395
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10393
@ AR_dependent
Definition Sema.h:1658
@ AR_accessible
Definition Sema.h:1656
@ AR_inaccessible
Definition Sema.h:1657
@ AR_delayed
Definition Sema.h:1659
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:2047
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:1654
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition Sema.h:1283
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn if we're implicitly casting from a _Nullable pointer type to a _Nonnull one.
Definition Sema.cpp:680
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:224
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:923
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:1488
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
bool FunctionParamTypesAreEqual(ArrayRef< QualType > Old, ArrayRef< QualType > New, unsigned *ArgPos=nullptr, bool Reversed=false)
FunctionParamTypesAreEqual - This routine checks two function proto types for equality of their param...
ExprResult PerformImplicitObjectArgumentInitialization(Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method)
PerformObjectArgumentInitialization - Perform initialization of the implicit object parameter for the...
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:754
ASTContext & getASTContext() const
Definition Sema.h:926
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:10774
@ FRS_DiagnosticIssued
Definition Sema.h:10776
@ FRS_NoViableFunction
Definition Sema.h:10775
llvm::SmallSetVector< CXXRecordDecl *, 16 > AssociatedClassSet
Definition Sema.h:9320
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:10107
void DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range, DeclarationName Name, OverloadCandidateSet &CandidateSet, FunctionDecl *Fn, MultiExprArg Args, bool IsMember=false)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1191
bool IsComplexPromotion(QualType FromType, QualType ToType)
Determine if a conversion is a complex promotion.
bool pushCodeSynthesisContext(CodeSynthesisContext Ctx)
Module * getOwningModule(const Decl *Entity)
Get the module owning an entity.
Definition Sema.h:3579
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:12148
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:919
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B)
Determine if A and B are equivalent internal linkage declarations from different modules,...
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args={}, DeclContext *LookupCtx=nullptr)
Diagnose an empty lookup.
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, FunctionDecl *DefaultedFn)
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck=false, bool ForceUnprivileged=false)
Checks access for a hierarchy conversion.
bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, const Expr *Op, const CXXMethodDecl *MD)
AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, DeclAccessPair FoundDecl)
Perform access-control checking on a previously-unresolved member access which has now been resolved ...
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false, bool StrictPackMatch=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
const LangOptions & LangOpts
Definition Sema.h:1281
bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType)
IsMemberPointerConversion - Determines whether the conversion of the expression From,...
ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef< Expr * > Arg, SourceLocation RParenLoc, Expr *Config=nullptr, bool IsExecConfig=false, ADLCallKind UsesADL=ADLCallKind::NotADL)
BuildResolvedCallExpr - Build a call to a resolved expression, i.e.
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
SemaHLSL & HLSL()
Definition Sema.h:1453
llvm::SmallSetVector< DeclContext *, 16 > AssociatedNamespaceSet
Definition Sema.h:9319
MemberPointerConversionDirection
Definition Sema.h:10227
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:10414
MemberPointerConversionResult CheckMemberPointerConversion(QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind, CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange, bool IgnoreBaseAccess, MemberPointerConversionDirection Direction)
CheckMemberPointerConversion - Check the member pointer conversion from the expression From to the ty...
Expr * BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit)
Build a CXXThisExpr and mark it referenced in the current context.
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add the overload candidates named by callee and/or found by argument dependent lookup to the given ov...
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:639
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition Sema.h:15479
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:6969
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:1416
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, SourceLocation Loc={}, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8173
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:13937
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:7467
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:13670
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:15434
bool CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity &Entity, InitListExpr *From)
Determine whether we can perform aggregate initialization for the purposes of overload resolution.
bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL,...
void AddFunctionCandidates(const UnresolvedSetImpl &Functions, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, bool SuppressUserConversions=false, bool PartialOverloading=false, bool FirstArgumentIsBase=false)
Add all of the function declarations in the given function set to the overload candidate set.
bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess, bool Diagnose=true)
CheckPointerConversion - Check the pointer conversion from the expression From to the type ToType.
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:123
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
void NoteAllOverloadCandidates(Expr *E, QualType DestType=QualType(), bool TakingAddress=false)
AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, DeclAccessPair FoundDecl)
void AddNonMemberOperatorCandidates(const UnresolvedSetImpl &Functions, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
Add all of the non-member operator function declarations in the given function set to the overload ca...
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6735
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6704
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:10219
SourceManager & SourceMgr
Definition Sema.h:1286
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
DiagnosticsEngine & Diags
Definition Sema.h:1285
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:515
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
bool ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false, bool Complain=false, SourceRange OpRangeForComplaining=SourceRange(), QualType DestTypeForComplaining=QualType(), unsigned DiagIDForComplaining=0)
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
void AddSurrogateCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, const FunctionProtoType *Proto, Expr *Object, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddSurrogateCandidate - Adds a "surrogate" candidate function that converts the given Object to a fun...
MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs=nullptr)
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
bool IsFunctionConversion(QualType FromType, QualType ToType) const
Determine whether the conversion from FromType to ToType is a valid conversion of ExtInfo/ExtProtoInf...
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(const NamedDecl *D1, ArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, ArrayRef< AssociatedConstraint > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, SourceLocation RangeLoc, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr)
Build a call to 'begin' or 'end' for a C++11 for-range statement.
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6412
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:1423
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:8655
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:362
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:338
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:350
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1799
StringRef getString() const
Definition Expr.h:1867
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition TargetInfo.h: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:1833
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2485
bool isBlockPointerType() const
Definition TypeBase.h:8549
bool isVoidType() const
Definition TypeBase.h:8891
bool isBooleanType() const
Definition TypeBase.h:9021
bool isObjCBuiltinType() const
Definition TypeBase.h:8755
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2226
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:1952
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:788
bool isIncompleteArrayType() const
Definition TypeBase.h:8636
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2206
bool isFloat16Type() const
Definition TypeBase.h:8900
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:2116
bool isRValueReferenceType() const
Definition TypeBase.h:8561
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:8632
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9051
bool isArrayType() const
Definition TypeBase.h:8628
bool isCharType() const
Definition Type.cpp:2133
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition TypeBase.h:8959
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isArithmeticType() const
Definition Type.cpp:2338
bool isPointerType() const
Definition TypeBase.h:8529
bool isArrayParameterType() const
Definition TypeBase.h:8644
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8935
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2574
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9178
bool isReferenceType() const
Definition TypeBase.h:8553
bool isEnumeralType() const
Definition TypeBase.h:8660
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2104
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8725
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:9009
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2169
bool isExtVectorBoolType() const
Definition TypeBase.h:8676
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8712
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2791
bool isLValueReferenceType() const
Definition TypeBase.h:8557
bool isBitIntType() const
Definition TypeBase.h:8800
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2783
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2412
bool isAnyComplexType() const
Definition TypeBase.h:8664
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8947
bool isHalfType() const
Definition TypeBase.h:8895
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:8873
bool isQueueT() const
Definition TypeBase.h:8781
bool isMemberPointerType() const
Definition TypeBase.h:8610
bool isObjCIdType() const
Definition TypeBase.h:8737
bool isMatrixType() const
Definition TypeBase.h:8692
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9027
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2510
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isEventT() const
Definition TypeBase.h:8773
bool isBFloat16Type() const
Definition TypeBase.h:8912
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2436
bool isFunctionType() const
Definition TypeBase.h:8525
bool isObjCObjectPointerType() const
Definition TypeBase.h:8704
bool isVectorType() const
Definition TypeBase.h:8668
bool isObjCClassType() const
Definition TypeBase.h:8743
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2321
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2595
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2922
bool isHLSLAttributedResourceType() const
Definition TypeBase.h:8848
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:2254
bool isAnyPointerType() const
Definition TypeBase.h:8537
TypeClass getTypeClass() const
Definition TypeBase.h:2385
bool isSamplerT() const
Definition TypeBase.h:8769
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9111
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:8928
bool isRecordType() const
Definition TypeBase.h:8656
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition Expr.cpp:1429
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:5039
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:1405
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3390
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition ExprCXX.h:3459
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:432
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4126
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition ExprCXX.h:4234
QualType getBaseType() const
Definition ExprCXX.h:4208
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition ExprCXX.h:4218
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition ExprCXX.h:4199
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:4244
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition ExprCXX.h:4238
A set of unresolved declarations.
ArrayRef< DeclAccessPair > pairs() const
void addDecl(NamedDecl *D)
The iterator over UnresolvedSets.
A set of unresolved declarations.
A call to a literal operator (C++11 [over.literal]) written as a user-defined literal (C++11 [lit....
Definition ExprCXX.h:640
static UserDefinedLiteral * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation LitEndLoc, SourceLocation SuffixLoc, FPOptionsOverride FPFeatures)
Definition ExprCXX.cpp:966
QualType getType() const
Definition Decl.h:723
unsigned getNumElements() const
Definition TypeBase.h:4191
QualType getElementType() const
Definition TypeBase.h:4190
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
TemplateArgument SecondArg
The second template argument to which the template argument deduction failure refers.
TemplateParameter Param
The template parameter to which a template argument deduction failure refers.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
TemplateArgument FirstArg
The first template argument to which the template argument deduction failure refers.
ConstraintSatisfaction AssociatedConstraintsSatisfaction
The constraint satisfaction details resulting from the associated constraints satisfaction tests.
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
unsigned CallArgIndex
The index of the function argument that caused a deduction failure.
specific_attr_iterator - Iterates over a subrange of an AttrVec, only providing attributes that are o...
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition limits.h:64
Definition SPIR.cpp:47
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
@ Warning
Present this diagnostic as a warning.
@ Error
Present this diagnostic as an error.
bool Ret(InterpState &S, CodePtr &PC)
Definition Interp.h:224
void checkAssignmentLifetime(Sema &SemaRef, const AssignedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for assigning to the ent...
The JSON file list parser is used to communicate input to InstallAPI.
ImplicitConversionRank GetDimensionConversionRank(ImplicitConversionRank Base, ImplicitConversionKind Dimension)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ OO_None
Not an overloaded operator.
@ NUM_OVERLOADED_OPERATORS
OverloadKind
Definition Sema.h:810
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:821
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:817
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:813
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:858
@ ovl_fail_final_conversion_not_exact
This conversion function template specialization candidate is not viable because the final conversion...
Definition Overload.h:886
@ ovl_fail_enable_if
This candidate function was not viable because an enable_if attribute disabled it.
Definition Overload.h:895
@ ovl_fail_illegal_constructor
This conversion candidate was not considered because it is an illegal instantiation of a constructor ...
Definition Overload.h:878
@ ovl_fail_bad_final_conversion
This conversion candidate is not viable because its result type is not implicitly convertible to the ...
Definition Overload.h:882
@ 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:923
@ ovl_fail_too_few_arguments
Definition Overload.h:860
@ ovl_fail_addr_not_available
This candidate was not viable because its address could not be taken.
Definition Overload.h:902
@ ovl_fail_too_many_arguments
Definition Overload.h:859
@ ovl_non_default_multiversion_function
This candidate was not viable because it is a non-default multiversioned function.
Definition Overload.h:910
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition Overload.h:919
@ ovl_fail_bad_conversion
Definition Overload.h:861
@ ovl_fail_bad_target
(CUDA) This candidate was not viable because the callee was not accessible from the caller's target (...
Definition Overload.h:891
@ ovl_fail_bad_deduction
Definition Overload.h:862
@ ovl_fail_inhctor_slice
This inherited constructor is not viable because it would slice the argument.
Definition Overload.h:906
@ ovl_fail_object_addrspace_mismatch
This constructor/conversion candidate fail due to an address space mismatch between the object being ...
Definition Overload.h:915
@ ovl_fail_explicit
This candidate constructor or conversion function is explicit but the context doesn't permit explicit...
Definition Overload.h:899
@ ovl_fail_trivial_conversion
This conversion candidate was not considered because it duplicates the work of a trivial or derived-t...
Definition Overload.h:867
@ Comparison
A comparison.
Definition Sema.h:666
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1782
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition TypeBase.h:1785
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1788
ImplicitConversionRank
ImplicitConversionRank - The rank of an implicit conversion kind.
Definition Overload.h: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:1042
OverloadCandidateParamOrder
The parameter ordering that will be used for the candidate.
Definition Overload.h:84
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ AS_public
Definition Specifiers.h:124
@ AS_none
Definition Specifiers.h:127
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
OverloadsShown
Specifies which overload candidates to display when overload resolution fails.
@ Ovl_Best
Show just the "best" overload candidates.
llvm::MutableArrayRef< ImplicitConversionSequence > ConversionSequenceList
A list of implicit conversion sequences for the arguments of an OverloadCandidate.
Definition Overload.h:928
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
OverloadCandidateRewriteKind
The kinds of rewrite we perform on overload candidates.
Definition Overload.h:89
@ CRK_Reversed
Candidate is a rewritten candidate with a reversed order of parameters.
Definition Overload.h:97
@ CRK_None
Candidate is not a rewritten candidate.
Definition Overload.h:91
@ CRK_DifferentOperator
Candidate is a rewritten candidate with a different operator name.
Definition Overload.h:94
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ Result
The result type of a method or function.
Definition TypeBase.h:905
const FunctionProtoType * T
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition Overload.h:139
@ ICK_Floating_Promotion
Floating point promotions (C++ [conv.fpprom])
Definition Overload.h:127
@ ICK_Boolean_Conversion
Boolean conversions (C++ [conv.bool])
Definition Overload.h:151
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition Overload.h:133
@ ICK_HLSL_Vector_Splat
Definition Overload.h: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:688
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:711
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:732
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:690
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:728
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:586
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:215
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:426
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:139
bool shouldEnforceArgLimit(bool PartialOverloading, FunctionDecl *Function)
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:149
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
NarrowingKind
NarrowingKind - The kind of narrowing conversion being performed by a standard conversion sequence ac...
Definition Overload.h: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:310
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition Template.h:306
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:368
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:418
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:413
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:416
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:389
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:375
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:411
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:420
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:408
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:378
@ Invalid
The declaration was invalid; do nothing.
Definition Sema.h:372
@ Success
Template argument deduction was successful.
Definition Sema.h:370
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:392
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:381
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:395
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:384
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:405
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:422
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:399
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:402
@ 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:1518
@ None
The alignment was not explicit in code.
Definition ASTContext.h:178
CCEKind
Contexts in which a converted constant expression is required.
Definition Sema.h:825
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:828
@ Noexcept
Condition in a noexcept(bool) specifier.
Definition Sema.h:833
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:831
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:829
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:832
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:5882
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:447
__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:521
ConversionSet::const_iterator const_iterator
Definition Overload.h:557
SmallVector< std::pair< NamedDecl *, FunctionDecl * >, 4 > ConversionSet
Definition Overload.h:522
void addConversion(NamedDecl *Found, FunctionDecl *D)
Definition Overload.h:548
void copyFrom(const AmbiguousConversionSequence &)
const Expr * ConstraintExpr
Definition Decl.h:88
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:89
QualType getToType() const
Definition Overload.h:606
QualType getFromType() const
Definition Overload.h:605
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:1101
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:645
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:647
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:633
Extra information about a function prototype.
Definition TypeBase.h:5354
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5359
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition Overload.h:1194
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:1216
bool isReversible() const
Determines whether this operator could be implemented by a function with reversed parameter order.
Definition Overload.h:1243
SourceLocation OpLoc
The source location of the operator.
Definition Overload.h:1205
bool AllowRewrittenCandidates
Whether we should include rewritten candidates in the overload set.
Definition Overload.h:1207
OverloadCandidateRewriteKind getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO)
Determine the kind of rewrite that should be performed for this candidate.
Definition Overload.h:1233
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:932
unsigned StrictPackMatch
Have we matched any packs on the parameter side, versus any non-packs on the argument side,...
Definition Overload.h:997
unsigned IgnoreObjectArgument
IgnoreObjectArgument - True to indicate that the first argument's conversion, which for this function...
Definition Overload.h:988
bool TryToFixBadConversion(unsigned Idx, Sema &S)
Definition Overload.h:1062
bool NotValidBecauseConstraintExprHasError() const
bool isReversed() const
Definition Overload.h:1036
unsigned IsADLCandidate
True if the candidate was found using ADL.
Definition Overload.h:1001
unsigned IsSurrogate
IsSurrogate - True to indicate that this candidate is a surrogate for a conversion to a function poin...
Definition Overload.h:978
QualType BuiltinParamTypes[3]
BuiltinParamTypes - Provides the parameter types of a built-in overload candidate.
Definition Overload.h:946
DeclAccessPair FoundDecl
FoundDecl - The original declaration that was looked up / invented / otherwise found,...
Definition Overload.h:942
FunctionDecl * Function
Function - The actual function that this candidate represents.
Definition Overload.h:937
unsigned RewriteKind
Whether this is a rewritten candidate, and if so, of what kind?
Definition Overload.h:1009
ConversionFixItGenerator Fix
The FixIt hints which can be used to fix the Bad candidate.
Definition Overload.h:958
unsigned Best
Whether this candidate is the best viable function, or tied for being the best viable function.
Definition Overload.h:972
StandardConversionSequence FinalConversion
FinalConversion - For a conversion function (where Function is a CXXConversionDecl),...
Definition Overload.h:1027
unsigned getNumParams() const
Definition Overload.h:1075
unsigned HasFinalConversion
Whether FinalConversion has been set.
Definition Overload.h:1005
unsigned TookAddressOfOverload
Definition Overload.h:991
unsigned FailureKind
FailureKind - The reason why this candidate is not viable.
Definition Overload.h:1014
unsigned ExplicitCallArguments
The number of call arguments that were explicitly provided, to be used while performing partial order...
Definition Overload.h:1018
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition Overload.h:955
DeductionFailureInfo DeductionFailure
Definition Overload.h:1021
unsigned Viable
Viable - True to indicate that this overload candidate is viable.
Definition Overload.h:962
CXXConversionDecl * Surrogate
Surrogate - The conversion function for which this candidate is a surrogate, but only if IsSurrogate ...
Definition Overload.h:950
OverloadCandidateRewriteKind getRewriteKind() const
Get RewriteKind value in OverloadCandidateRewriteKind type (This function is to workaround the spurio...
Definition Overload.h:1032
bool SuppressUserConversions
Do not consider any user-defined conversions when constructing the initializing sequence.
Definition Sema.h:10506
bool OnlyInitializeNonUserDefinedConversions
Before constructing the initializing sequence, we check whether the parameter type and argument type ...
Definition Sema.h:10513
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13098
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13186
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13224
Abstract class used to diagnose incomplete types.
Definition Sema.h:8254
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:476
StandardConversionSequence Before
Represents the standard conversion that occurs before the actual user-defined conversion.
Definition Overload.h:488
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition Overload.h:510
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition Overload.h:501
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition Overload.h:505
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition Overload.h:496
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition Overload.h:515
void dump() const
dump - Print this user-defined conversion sequence to standard error.
Describes an entity that is being assigned.