clang 24.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"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/ExprObjC.h"
23#include "clang/AST/Type.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Overload.h"
35#include "clang/Sema/SemaARM.h"
36#include "clang/Sema/SemaCUDA.h"
38#include "clang/Sema/SemaObjC.h"
39#include "clang/Sema/Template.h"
41#include "llvm/ADT/DenseSet.h"
42#include "llvm/ADT/STLExtras.h"
43#include "llvm/ADT/STLForwardCompat.h"
44#include "llvm/ADT/ScopeExit.h"
45#include "llvm/ADT/SmallPtrSet.h"
46#include "llvm/ADT/SmallVector.h"
47#include <algorithm>
48#include <cassert>
49#include <cstddef>
50#include <cstdlib>
51#include <optional>
52
53using namespace clang;
54using namespace sema;
55
57
59 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
60 return P->hasAttr<PassObjectSizeAttr>();
61 });
62}
63
64/// A convenience routine for creating a decayed reference to a function.
66 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
67 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
68 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
69 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
70 return ExprError();
71 // If FoundDecl is different from Fn (such as if one is a template
72 // and the other a specialization), make sure DiagnoseUseOfDecl is
73 // called on both.
74 // FIXME: This would be more comprehensively addressed by modifying
75 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
76 // being used.
77 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
78 return ExprError();
79 DeclRefExpr *DRE = new (S.Context)
80 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
81 if (HadMultipleCandidates)
82 DRE->setHadMultipleCandidates(true);
83
85 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
86 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
87 S.ResolveExceptionSpec(Loc, FPT);
88 DRE->setType(Fn->getType());
89 }
90 }
91 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
92 CK_FunctionToPointerDecay);
93}
94
95static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
96 bool InOverloadResolution,
98 bool CStyle,
99 bool AllowObjCWritebackConversion);
100
102 QualType &ToType,
103 bool InOverloadResolution,
105 bool CStyle);
107IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
109 OverloadCandidateSet& Conversions,
110 AllowedExplicit AllowExplicit,
111 bool AllowObjCConversionOnExplicit);
112
115 const StandardConversionSequence& SCS1,
116 const StandardConversionSequence& SCS2);
117
120 const StandardConversionSequence& SCS1,
121 const StandardConversionSequence& SCS2);
122
125 const StandardConversionSequence &SCS1,
126 const StandardConversionSequence &SCS2);
127
130 const StandardConversionSequence& SCS1,
131 const StandardConversionSequence& SCS2);
132
133/// GetConversionRank - Retrieve the implicit conversion rank
134/// corresponding to the given implicit conversion kind.
136 static const ImplicitConversionRank Rank[] = {
163 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
164 // it was omitted by the patch that added
165 // ICK_Zero_Event_Conversion
166 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
167 // it was omitted by the patch that added
168 // ICK_Zero_Queue_Conversion
177 };
178 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
179 return Rank[(int)Kind];
180}
181
200
201/// GetImplicitConversionName - Return the name of this kind of
202/// implicit conversion.
204 static const char *const Name[] = {
205 "No conversion",
206 "Lvalue-to-rvalue",
207 "Array-to-pointer",
208 "Function-to-pointer",
209 "Function pointer conversion",
210 "Qualification",
211 "Integral promotion",
212 "Floating point promotion",
213 "Complex promotion",
214 "Integral conversion",
215 "Floating conversion",
216 "Complex conversion",
217 "Floating-integral conversion",
218 "Pointer conversion",
219 "Pointer-to-member conversion",
220 "Boolean conversion",
221 "Compatible-types conversion",
222 "Derived-to-base conversion",
223 "Vector conversion",
224 "SVE Vector conversion",
225 "RVV Vector conversion",
226 "Vector splat",
227 "Complex-real conversion",
228 "Block Pointer conversion",
229 "Transparent Union Conversion",
230 "Writeback conversion",
231 "OpenCL Zero Event Conversion",
232 "OpenCL Zero Queue Conversion",
233 "C specific type conversion",
234 "Incompatible pointer conversion",
235 "Fixed point conversion",
236 "HLSL vector truncation",
237 "HLSL matrix truncation",
238 "Non-decaying array conversion",
239 "HLSL vector splat",
240 "HLSL matrix splat",
241 };
242 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
243 return Name[Kind];
244}
245
246/// StandardConversionSequence - Set the standard conversion
247/// sequence to the identity conversion.
265
266/// getRank - Retrieve the rank of this standard conversion sequence
267/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
268/// implicit conversions.
281
282/// isPointerConversionToBool - Determines whether this conversion is
283/// a conversion of a pointer or pointer-to-member to bool. This is
284/// used as part of the ranking of standard conversion sequences
285/// (C++ 13.3.3.2p4).
287 // Note that FromType has not necessarily been transformed by the
288 // array-to-pointer or function-to-pointer implicit conversions, so
289 // check for their presence as well as checking whether FromType is
290 // a pointer.
291 if (getToType(1)->isBooleanType() &&
292 (getFromType()->isPointerType() ||
293 getFromType()->isMemberPointerType() ||
294 getFromType()->isObjCObjectPointerType() ||
295 getFromType()->isBlockPointerType() ||
297 return true;
298
299 return false;
300}
301
302/// isPointerConversionToVoidPointer - Determines whether this
303/// conversion is a conversion of a pointer to a void pointer. This is
304/// used as part of the ranking of standard conversion sequences (C++
305/// 13.3.3.2p4).
306bool
309 QualType FromType = getFromType();
310 QualType ToType = getToType(1);
311
312 // Note that FromType has not necessarily been transformed by the
313 // array-to-pointer implicit conversion, so check for its presence
314 // and redo the conversion to get a pointer.
316 FromType = Context.getArrayDecayedType(FromType);
317
318 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
319 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
320 return ToPtrType->getPointeeType()->isVoidType();
321
322 return false;
323}
324
325/// Skip any implicit casts which could be either part of a narrowing conversion
326/// or after one in an implicit conversion.
328 const Expr *Converted) {
329 // We can have cleanups wrapping the converted expression; these need to be
330 // preserved so that destructors run if necessary.
331 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
332 Expr *Inner =
333 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
334 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
335 EWC->getObjects());
336 }
337
338 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
339 switch (ICE->getCastKind()) {
340 case CK_NoOp:
341 case CK_IntegralCast:
342 case CK_IntegralToBoolean:
343 case CK_IntegralToFloating:
344 case CK_BooleanToSignedIntegral:
345 case CK_FloatingToIntegral:
346 case CK_FloatingToBoolean:
347 case CK_FloatingCast:
348 Converted = ICE->getSubExpr();
349 continue;
350
351 default:
352 return Converted;
353 }
354 }
355
356 return Converted;
357}
358
359/// Check if this standard conversion sequence represents a narrowing
360/// conversion, according to C++11 [dcl.init.list]p7.
361///
362/// \param Ctx The AST context.
363/// \param Converted The result of applying this standard conversion sequence.
364/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
365/// value of the expression prior to the narrowing conversion.
366/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
367/// type of the expression prior to the narrowing conversion.
368/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
369/// from floating point types to integral types should be ignored.
370/// \param AllowRelaxedEval If true constant expression evaluation is relaxed
371/// to conform MSVC compiler behavior.
373 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
374 QualType &ConstantType, bool IgnoreFloatToIntegralConversion,
375 bool AllowRelaxedEval) const {
376 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
377 "narrowing check outside C++");
378
379 // C++11 [dcl.init.list]p7:
380 // A narrowing conversion is an implicit conversion ...
381 QualType FromType = getToType(0);
382 QualType ToType = getToType(1);
383
384 // A conversion to an enumeration type is narrowing if the conversion to
385 // the underlying type is narrowing. This only arises for expressions of
386 // the form 'Enum{init}'.
387 if (const auto *ED = ToType->getAsEnumDecl())
388 ToType = ED->getIntegerType();
389
390 switch (Second) {
391 // 'bool' is an integral type; dispatch to the right place to handle it.
393 if (FromType->isRealFloatingType())
394 goto FloatingIntegralConversion;
396 goto IntegralConversion;
397 // -- from a pointer type or pointer-to-member type to bool, or
398 return NK_Type_Narrowing;
399
400 // -- from a floating-point type to an integer type, or
401 //
402 // -- from an integer type or unscoped enumeration type to a floating-point
403 // type, except where the source is a constant expression and the actual
404 // value after conversion will fit into the target type and will produce
405 // the original value when converted back to the original type, or
407 FloatingIntegralConversion:
408 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
409 return NK_Type_Narrowing;
410 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
411 ToType->isRealFloatingType()) {
412 if (IgnoreFloatToIntegralConversion)
413 return NK_Not_Narrowing;
414 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
415 assert(Initializer && "Unknown conversion expression");
416
417 // If it's value-dependent, we can't tell whether it's narrowing.
418 if (Initializer->isValueDependent())
420
421 if (std::optional<llvm::APSInt> IntConstantValue =
422 Initializer->getIntegerConstantExpr(Ctx)) {
423 // Convert the integer to the floating type.
424 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
425 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
426 llvm::APFloat::rmNearestTiesToEven);
427 // And back.
428 llvm::APSInt ConvertedValue = *IntConstantValue;
429 bool ignored;
430 llvm::APFloat::opStatus Status = Result.convertToInteger(
431 ConvertedValue, llvm::APFloat::rmTowardZero, &ignored);
432 // If the converted-back integer has unspecified value, or if the
433 // resulting value is different, this was a narrowing conversion.
434 if (Status == llvm::APFloat::opInvalidOp ||
435 *IntConstantValue != ConvertedValue) {
436 ConstantValue = APValue(*IntConstantValue);
437 ConstantType = Initializer->getType();
439 }
440 } else {
441 // Variables are always narrowings.
443 }
444 }
445 return NK_Not_Narrowing;
446
447 // -- from long double to double or float, or from double to float, except
448 // where the source is a constant expression and the actual value after
449 // conversion is within the range of values that can be represented (even
450 // if it cannot be represented exactly), or
452 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
453 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
454 // FromType is larger than ToType.
455 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
456
457 // If it's value-dependent, we can't tell whether it's narrowing.
458 if (Initializer->isValueDependent())
460
462 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
463 ((Ctx.getLangOpts().CPlusPlus &&
464 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue,
465 AllowRelaxedEval)))) {
466 // Constant!
467 if (Ctx.getLangOpts().C23)
468 ConstantValue = R.Val;
469 assert(ConstantValue.isFloat());
470 llvm::APFloat FloatVal = ConstantValue.getFloat();
471 // Convert the source value into the target type.
472 bool ignored;
473 llvm::APFloat Converted = FloatVal;
474 llvm::APFloat::opStatus ConvertStatus =
475 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
476 llvm::APFloat::rmNearestTiesToEven, &ignored);
477 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
478 llvm::APFloat::rmNearestTiesToEven, &ignored);
479 if (Ctx.getLangOpts().C23) {
480 if (FloatVal.isNaN() && Converted.isNaN() &&
481 !FloatVal.isSignaling() && !Converted.isSignaling()) {
482 // Quiet NaNs are considered the same value, regardless of
483 // payloads.
484 return NK_Not_Narrowing;
485 }
486 // For normal values, check exact equality.
487 if (!Converted.bitwiseIsEqual(FloatVal)) {
488 ConstantType = Initializer->getType();
490 }
491 } else {
492 // If there was no overflow, the source value is within the range of
493 // values that can be represented.
494 if (ConvertStatus & llvm::APFloat::opOverflow) {
495 ConstantType = Initializer->getType();
497 }
498 }
499 } else {
501 }
502 }
503 return NK_Not_Narrowing;
504
505 // -- from an integer type or unscoped enumeration type to an integer type
506 // that cannot represent all the values of the original type, except where
507 // (CWG2627) -- the source is a bit-field whose width w is less than that
508 // of its type (or, for an enumeration type, its underlying type) and the
509 // target type can represent all the values of a hypothetical extended
510 // integer type with width w and with the same signedness as the original
511 // type or
512 // -- the source is a constant expression and the actual value after
513 // conversion will fit into the target type and will produce the original
514 // value when converted back to the original type.
516 IntegralConversion: {
517 assert(FromType->isIntegralOrUnscopedEnumerationType());
518 assert(ToType->isIntegralOrUnscopedEnumerationType());
519 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
520 unsigned FromWidth = Ctx.getIntWidth(FromType);
521 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
522 const unsigned ToWidth = Ctx.getIntWidth(ToType);
523
524 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
525 bool ToSigned, unsigned ToWidth) {
526 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
527 !(FromSigned && !ToSigned);
528 };
529
530 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
531 return NK_Not_Narrowing;
532
533 // Not all values of FromType can be represented in ToType.
534 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
535
536 bool DependentBitField = false;
537 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
538 if (BitField->getBitWidth()->isValueDependent())
539 DependentBitField = true;
540 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
541 BitFieldWidth < FromWidth) {
542 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
543 return NK_Not_Narrowing;
544
545 // The initializer will be truncated to the bit-field width
546 FromWidth = BitFieldWidth;
547 }
548 }
549
550 // If it's value-dependent, we can't tell whether it's narrowing.
551 if (Initializer->isValueDependent())
553
554 std::optional<llvm::APSInt> OptInitializerValue =
555 Initializer->getIntegerConstantExpr(Ctx, AllowRelaxedEval);
556 if (!OptInitializerValue) {
557 // If the bit-field width was dependent, it might end up being small
558 // enough to fit in the target type (unless the target type is unsigned
559 // and the source type is signed, in which case it will never fit)
560 if (DependentBitField && !(FromSigned && !ToSigned))
562
563 // Otherwise, such a conversion is always narrowing
565 }
566 llvm::APSInt &InitializerValue = *OptInitializerValue;
567 bool Narrowing = false;
568 if (FromWidth < ToWidth) {
569 // Negative -> unsigned is narrowing. Otherwise, more bits is never
570 // narrowing.
571 if (InitializerValue.isSigned() && InitializerValue.isNegative())
572 Narrowing = true;
573 } else {
574 // Add a bit to the InitializerValue so we don't have to worry about
575 // signed vs. unsigned comparisons.
576 InitializerValue =
577 InitializerValue.extend(InitializerValue.getBitWidth() + 1);
578 // Convert the initializer to and from the target width and signed-ness.
579 llvm::APSInt ConvertedValue = InitializerValue;
580 ConvertedValue = ConvertedValue.trunc(ToWidth);
581 ConvertedValue.setIsSigned(ToSigned);
582 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
583 ConvertedValue.setIsSigned(InitializerValue.isSigned());
584 // If the result is different, this was a narrowing conversion.
585 if (ConvertedValue != InitializerValue)
586 Narrowing = true;
587 }
588 if (Narrowing) {
589 ConstantType = Initializer->getType();
590 ConstantValue = APValue(InitializerValue);
592 }
593
594 return NK_Not_Narrowing;
595 }
596 case ICK_Complex_Real:
597 if (FromType->isComplexType() && !ToType->isComplexType())
598 return NK_Type_Narrowing;
599 return NK_Not_Narrowing;
600
602 if (Ctx.getLangOpts().C23) {
603 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
605 if (Initializer->EvaluateAsRValue(R, Ctx)) {
606 ConstantValue = R.Val;
607 assert(ConstantValue.isFloat());
608 llvm::APFloat FloatVal = ConstantValue.getFloat();
609 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
610 // value, the unqualified versions of the type of the initializer and
611 // the corresponding real type of the object declared shall be
612 // compatible.
613 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
614 ConstantType = Initializer->getType();
616 }
617 }
618 }
619 return NK_Not_Narrowing;
620 default:
621 // Other kinds of conversions are not narrowings.
622 return NK_Not_Narrowing;
623 }
624}
625
626/// dump - Print this standard conversion sequence to standard
627/// error. Useful for debugging overloading issues.
628LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
629 raw_ostream &OS = llvm::errs();
630 bool PrintedSomething = false;
631 if (First != ICK_Identity) {
633 PrintedSomething = true;
634 }
635
636 if (Second != ICK_Identity) {
637 if (PrintedSomething) {
638 OS << " -> ";
639 }
641
642 if (CopyConstructor) {
643 OS << " (by copy constructor)";
644 } else if (DirectBinding) {
645 OS << " (direct reference binding)";
646 } else if (ReferenceBinding) {
647 OS << " (reference binding)";
648 }
649 PrintedSomething = true;
650 }
651
652 if (Third != ICK_Identity) {
653 if (PrintedSomething) {
654 OS << " -> ";
655 }
657 PrintedSomething = true;
658 }
659
660 if (!PrintedSomething) {
661 OS << "No conversions required";
662 }
663}
664
665/// dump - Print this user-defined conversion sequence to standard
666/// error. Useful for debugging overloading issues.
668 raw_ostream &OS = llvm::errs();
669 if (Before.First || Before.Second || Before.Third) {
670 Before.dump();
671 OS << " -> ";
672 }
674 OS << '\'' << *ConversionFunction << '\'';
675 else
676 OS << "aggregate initialization";
677 if (After.First || After.Second || After.Third) {
678 OS << " -> ";
679 After.dump();
680 }
681}
682
683/// dump - Print this implicit conversion sequence to standard
684/// error. Useful for debugging overloading issues.
686 raw_ostream &OS = llvm::errs();
688 OS << "Worst list element conversion: ";
689 switch (ConversionKind) {
691 OS << "Standard conversion: ";
692 Standard.dump();
693 break;
695 OS << "User-defined conversion: ";
696 UserDefined.dump();
697 break;
699 OS << "Ellipsis conversion";
700 break;
702 OS << "Ambiguous conversion";
703 break;
704 case BadConversion:
705 OS << "Bad conversion";
706 break;
707 }
708
709 OS << "\n";
710}
711
715
717 conversions().~ConversionSet();
718}
719
720void
726
727namespace {
728 // Structure used by DeductionFailureInfo to store
729 // template argument information.
730 struct DFIArguments {
731 TemplateArgument FirstArg;
732 TemplateArgument SecondArg;
733 };
734 // Structure used by DeductionFailureInfo to store
735 // template parameter and template argument information.
736 struct DFIParamWithArguments : DFIArguments {
737 TemplateParameter Param;
738 };
739 // Structure used by DeductionFailureInfo to store template argument
740 // information and the index of the problematic call argument.
741 struct DFIDeducedMismatchArgs : DFIArguments {
742 TemplateArgumentList *TemplateArgs;
743 unsigned CallArgIndex;
744 };
745 // Structure used by DeductionFailureInfo to store information about
746 // unsatisfied constraints.
747 struct CNSInfo {
748 TemplateArgumentList *TemplateArgs;
749 ConstraintSatisfaction Satisfaction;
750 };
751}
752
753/// Convert from Sema's representation of template deduction information
754/// to the form used in overload-candidate information.
758 TemplateDeductionInfo &Info) {
760 Result.Result = static_cast<unsigned>(TDK);
761 Result.HasDiagnostic = false;
762 switch (TDK) {
769 Result.Data = nullptr;
770 break;
771
773 Result.Data = Info.Param.getOpaqueValue();
774 break;
776 Result.Data = Info.Param.getOpaqueValue();
777 if (Info.hasSFINAEDiagnostic()) {
781 Result.HasDiagnostic = true;
782 }
783 break;
784
787 // FIXME: Should allocate from normal heap so that we can free this later.
788 auto *Saved = new (Context) DFIDeducedMismatchArgs;
789 Saved->FirstArg = Info.FirstArg;
790 Saved->SecondArg = Info.SecondArg;
791 Saved->TemplateArgs = Info.takeSugared();
792 Saved->CallArgIndex = Info.CallArgIndex;
793 Result.Data = Saved;
794 break;
795 }
796
798 // FIXME: Should allocate from normal heap so that we can free this later.
799 DFIArguments *Saved = new (Context) DFIArguments;
800 Saved->FirstArg = Info.FirstArg;
801 Saved->SecondArg = Info.SecondArg;
802 Result.Data = Saved;
803 break;
804 }
805
807 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
810 // FIXME: Should allocate from normal heap so that we can free this later.
811 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
812 Saved->Param = Info.Param;
813 Saved->FirstArg = Info.FirstArg;
814 Saved->SecondArg = Info.SecondArg;
815 Result.Data = Saved;
816 break;
817 }
818
820 Result.Data = Info.takeSugared();
821 if (Info.hasSFINAEDiagnostic()) {
825 Result.HasDiagnostic = true;
826 }
827 break;
828
830 CNSInfo *Saved = new (Context) CNSInfo;
831 Saved->TemplateArgs = Info.takeSugared();
832 Saved->Satisfaction = std::move(Info.AssociatedConstraintsSatisfaction);
833 Result.Data = Saved;
834 break;
835 }
836
840 llvm_unreachable("not a deduction failure");
841 }
842
843 return Result;
844}
845
847 switch (static_cast<TemplateDeductionResult>(Result)) {
856 break;
857
864 // FIXME: Destroy the data?
865 Data = nullptr;
866 break;
867
870 // FIXME: Destroy the template argument list?
871 Data = nullptr;
873 Diag->~PartialDiagnosticAt();
874 HasDiagnostic = false;
875 }
876 break;
877
879 // FIXME: Destroy the template argument list?
880 static_cast<CNSInfo *>(Data)->Satisfaction.~ConstraintSatisfaction();
881 Data = nullptr;
883 Diag->~PartialDiagnosticAt();
884 HasDiagnostic = false;
885 }
886 break;
887
888 // Unhandled
891 break;
892 }
893}
894
896 if (HasDiagnostic)
897 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
898 return nullptr;
899}
900
934
970
1002
1034
1036 switch (static_cast<TemplateDeductionResult>(Result)) {
1039 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1040
1041 default:
1042 return std::nullopt;
1043 }
1044}
1045
1047 const FunctionDecl *Y) {
1048 if (!X || !Y)
1049 return false;
1050 if (X->getNumParams() != Y->getNumParams())
1051 return false;
1052 // FIXME: when do rewritten comparison operators
1053 // with explicit object parameters correspond?
1054 // https://cplusplus.github.io/CWG/issues/2797.html
1055 for (unsigned I = 0; I < X->getNumParams(); ++I)
1056 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1057 Y->getParamDecl(I)->getType()))
1058 return false;
1059 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1060 auto *FTY = Y->getDescribedFunctionTemplate();
1061 if (!FTY)
1062 return false;
1063 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1064 FTY->getTemplateParameters()))
1065 return false;
1066 }
1067 return true;
1068}
1069
1071 Expr *FirstOperand, FunctionDecl *EqFD) {
1072 assert(EqFD->getOverloadedOperator() ==
1073 OverloadedOperatorKind::OO_EqualEqual);
1074 // C++2a [over.match.oper]p4:
1075 // A non-template function or function template F named operator== is a
1076 // rewrite target with first operand o unless a search for the name operator!=
1077 // in the scope S from the instantiation context of the operator expression
1078 // finds a function or function template that would correspond
1079 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1080 // scope of the class type of o if F is a class member, and the namespace
1081 // scope of which F is a member otherwise. A function template specialization
1082 // named operator== is a rewrite target if its function template is a rewrite
1083 // target.
1085 OverloadedOperatorKind::OO_ExclaimEqual);
1086 if (isa<CXXMethodDecl>(EqFD)) {
1087 // If F is a class member, search scope is class type of first operand.
1088 QualType RHS = FirstOperand->getType();
1089 auto *RHSRec = RHS->getAsCXXRecordDecl();
1090 if (!RHSRec)
1091 return true;
1092 LookupResult Members(S, NotEqOp, OpLoc,
1094 S.LookupQualifiedName(Members, RHSRec);
1095 Members.suppressAccessDiagnostics();
1096 for (NamedDecl *Op : Members)
1097 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1098 return false;
1099 return true;
1100 }
1101 // Otherwise the search scope is the namespace scope of which F is a member.
1102 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1103 auto *NotEqFD = Op->getAsFunction();
1104 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1105 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1106 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1108 cast<Decl>(Op->getLexicalDeclContext())))
1109 return false;
1110 }
1111 return true;
1112}
1113
1115 OverloadedOperatorKind Op) const {
1117 return false;
1118 return Op == OO_EqualEqual || Op == OO_Spaceship;
1119}
1120
1122 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) const {
1123 auto Op = FD->getOverloadedOperator();
1124 if (!allowsReversed(Op))
1125 return false;
1126 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1127 assert(OriginalArgs.size() == 2);
1129 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1130 return false;
1131 }
1132 // Don't bother adding a reversed candidate that can never be a better
1133 // match than the non-reversed version.
1134 return FD->getNumNonObjectParams() != 2 ||
1136 FD->getParamDecl(1)->getType()) ||
1137 FD->hasAttr<EnableIfAttr>();
1138}
1139
1140void OverloadCandidateSet::destroyCandidates() {
1141 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1142 for (auto &C : i->Conversions)
1143 C.~ImplicitConversionSequence();
1144 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1145 i->DeductionFailure.Destroy();
1146 }
1147}
1148
1150 destroyCandidates();
1151 SlabAllocator.Reset();
1152 NumInlineBytesUsed = 0;
1153 Candidates.clear();
1154 Functions.clear();
1155 Kind = CSK;
1156 FirstDeferredCandidate = nullptr;
1157 DeferredCandidatesCount = 0;
1158 HasDeferredTemplateConstructors = false;
1159 ResolutionByPerfectCandidateIsDisabled = false;
1160}
1161
1162namespace {
1163 class UnbridgedCastsSet {
1164 struct Entry {
1165 Expr **Addr;
1166 Expr *Saved;
1167 };
1168 SmallVector<Entry, 2> Entries;
1169
1170 public:
1171 void save(Sema &S, Expr *&E) {
1172 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1173 Entry entry = { &E, E };
1174 Entries.push_back(entry);
1175 E = S.ObjC().stripARCUnbridgedCast(E);
1176 }
1177
1178 void restore() {
1179 for (SmallVectorImpl<Entry>::iterator
1180 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1181 *i->Addr = i->Saved;
1182 }
1183 };
1184}
1185
1186/// checkPlaceholderForOverload - Do any interesting placeholder-like
1187/// preprocessing on the given expression.
1188///
1189/// \param unbridgedCasts a collection to which to add unbridged casts;
1190/// without this, they will be immediately diagnosed as errors
1191///
1192/// Return true on unrecoverable error.
1193static bool
1195 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1196 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1197 // We can't handle overloaded expressions here because overload
1198 // resolution might reasonably tweak them.
1199 if (placeholder->getKind() == BuiltinType::Overload) return false;
1200
1201 // If the context potentially accepts unbridged ARC casts, strip
1202 // the unbridged cast and add it to the collection for later restoration.
1203 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1204 unbridgedCasts) {
1205 unbridgedCasts->save(S, E);
1206 return false;
1207 }
1208
1209 // Go ahead and check everything else.
1210 ExprResult result = S.CheckPlaceholderExpr(E);
1211 if (result.isInvalid())
1212 return true;
1213
1214 E = result.get();
1215 return false;
1216 }
1217
1218 // Nothing to do.
1219 return false;
1220}
1221
1222/// checkArgPlaceholdersForOverload - Check a set of call operands for
1223/// placeholders.
1225 UnbridgedCastsSet &unbridged) {
1226 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1227 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1228 return true;
1229
1230 return false;
1231}
1232
1234 const LookupResult &Old, NamedDecl *&Match,
1235 bool NewIsUsingDecl) {
1236 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1237 I != E; ++I) {
1238 NamedDecl *OldD = *I;
1239
1240 bool OldIsUsingDecl = false;
1241 if (isa<UsingShadowDecl>(OldD)) {
1242 OldIsUsingDecl = true;
1243
1244 // We can always introduce two using declarations into the same
1245 // context, even if they have identical signatures.
1246 if (NewIsUsingDecl) continue;
1247
1248 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1249 }
1250
1251 // A using-declaration does not conflict with another declaration
1252 // if one of them is hidden.
1253 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1254 continue;
1255
1256 // If either declaration was introduced by a using declaration,
1257 // we'll need to use slightly different rules for matching.
1258 // Essentially, these rules are the normal rules, except that
1259 // function templates hide function templates with different
1260 // return types or template parameter lists.
1261 bool UseMemberUsingDeclRules =
1262 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1263 !New->getFriendObjectKind();
1264
1265 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1266 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1267 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1269 continue;
1270 }
1271
1272 if (!isa<FunctionTemplateDecl>(OldD) &&
1273 !shouldLinkPossiblyHiddenDecl(*I, New))
1274 continue;
1275
1276 Match = *I;
1277 return OverloadKind::Match;
1278 }
1279
1280 // Builtins that have custom typechecking or have a reference should
1281 // not be overloadable or redeclarable.
1282 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1283 Match = *I;
1285 }
1286 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1287 // We can overload with these, which can show up when doing
1288 // redeclaration checks for UsingDecls.
1289 assert(Old.getLookupKind() == LookupUsingDeclName);
1290 } else if (isa<TagDecl>(OldD)) {
1291 // We can always overload with tags by hiding them.
1292 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1293 // Optimistically assume that an unresolved using decl will
1294 // overload; if it doesn't, we'll have to diagnose during
1295 // template instantiation.
1296 //
1297 // Exception: if the scope is dependent and this is not a class
1298 // member, the using declaration can only introduce an enumerator.
1299 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1300 Match = *I;
1302 }
1303 } else {
1304 // (C++ 13p1):
1305 // Only function declarations can be overloaded; object and type
1306 // declarations cannot be overloaded.
1307 Match = *I;
1309 }
1310 }
1311
1312 // C++ [temp.friend]p1:
1313 // For a friend function declaration that is not a template declaration:
1314 // -- if the name of the friend is a qualified or unqualified template-id,
1315 // [...], otherwise
1316 // -- if the name of the friend is a qualified-id and a matching
1317 // non-template function is found in the specified class or namespace,
1318 // the friend declaration refers to that function, otherwise,
1319 // -- if the name of the friend is a qualified-id and a matching function
1320 // template is found in the specified class or namespace, the friend
1321 // declaration refers to the deduced specialization of that function
1322 // template, otherwise
1323 // -- the name shall be an unqualified-id [...]
1324 // If we get here for a qualified friend declaration, we've just reached the
1325 // third bullet. If the type of the friend is dependent, skip this lookup
1326 // until instantiation.
1327 if (New->getFriendObjectKind() && New->getQualifier() &&
1328 !New->getDescribedFunctionTemplate() &&
1329 !New->getDependentSpecializationInfo() &&
1330 !New->getType()->isDependentType()) {
1331 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1332 TemplateSpecResult.addAllDecls(Old);
1333 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1334 /*QualifiedFriend*/true)) {
1335 New->setInvalidDecl();
1337 }
1338
1339 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1340 return OverloadKind::Match;
1341 }
1342
1344}
1345
1346template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1347 assert(D && "function decl should not be null");
1348 if (auto *A = D->getAttr<AttrT>())
1349 return !A->isImplicit();
1350 return false;
1351}
1352
1354 FunctionDecl *Old,
1355 bool UseMemberUsingDeclRules,
1356 bool ConsiderCudaAttrs,
1357 bool UseOverrideRules = false) {
1358 // C++ [basic.start.main]p2: This function shall not be overloaded.
1359 if (New->isMain())
1360 return false;
1361
1362 // MSVCRT user defined entry points cannot be overloaded.
1363 if (New->isMSVCRTEntryPoint())
1364 return false;
1365
1366 NamedDecl *OldDecl = Old;
1367 NamedDecl *NewDecl = New;
1369 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1370
1371 // C++ [temp.fct]p2:
1372 // A function template can be overloaded with other function templates
1373 // and with normal (non-template) functions.
1374 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1375 return true;
1376
1377 // Is the function New an overload of the function Old?
1378 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1379 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1380
1381 // Compare the signatures (C++ 1.3.10) of the two functions to
1382 // determine whether they are overloads. If we find any mismatch
1383 // in the signature, they are overloads.
1384
1385 // If either of these functions is a K&R-style function (no
1386 // prototype), then we consider them to have matching signatures.
1387 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1389 return false;
1390
1391 const auto *OldType = cast<FunctionProtoType>(OldQType);
1392 const auto *NewType = cast<FunctionProtoType>(NewQType);
1393
1394 // The signature of a function includes the types of its
1395 // parameters (C++ 1.3.10), which includes the presence or absence
1396 // of the ellipsis; see C++ DR 357).
1397 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1398 return true;
1399
1400 // For member-like friends, the enclosing class is part of the signature.
1401 if ((New->isMemberLikeConstrainedFriend() ||
1403 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1404 return true;
1405
1406 // Compare the parameter lists.
1407 // This can only be done once we have establish that friend functions
1408 // inhabit the same context, otherwise we might tried to instantiate
1409 // references to non-instantiated entities during constraint substitution.
1410 // GH78101.
1411 if (NewTemplate) {
1412 OldDecl = OldTemplate;
1413 NewDecl = NewTemplate;
1414 // C++ [temp.over.link]p4:
1415 // The signature of a function template consists of its function
1416 // signature, its return type and its template parameter list. The names
1417 // of the template parameters are significant only for establishing the
1418 // relationship between the template parameters and the rest of the
1419 // signature.
1420 //
1421 // We check the return type and template parameter lists for function
1422 // templates first; the remaining checks follow.
1423 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1424 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1425 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1426 bool SameReturnType = SemaRef.Context.hasSameType(
1427 Old->getDeclaredReturnType(), New->getDeclaredReturnType());
1428 // FIXME(GH58571): Match template parameter list even for non-constrained
1429 // template heads. This currently ensures that the code prior to C++20 is
1430 // not newly broken.
1431 bool ConstraintsInTemplateHead =
1434 // C++ [namespace.udecl]p11:
1435 // The set of declarations named by a using-declarator that inhabits a
1436 // class C does not include member functions and member function
1437 // templates of a base class that "correspond" to (and thus would
1438 // conflict with) a declaration of a function or function template in
1439 // C.
1440 // Comparing return types is not required for the "correspond" check to
1441 // decide whether a member introduced by a shadow declaration is hidden.
1442 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1443 !SameTemplateParameterList)
1444 return true;
1445 if (!UseMemberUsingDeclRules &&
1446 (!SameTemplateParameterList || !SameReturnType))
1447 return true;
1448 }
1449
1450 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1451 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1452
1453 int OldParamsOffset = 0;
1454 int NewParamsOffset = 0;
1455
1456 // When determining if a method is an overload from a base class, act as if
1457 // the implicit object parameter are of the same type.
1458
1459 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1461 auto ThisType = M->getFunctionObjectParameterReferenceType();
1462 if (ThisType.isConstQualified())
1463 Q.removeConst();
1464 return Q;
1465 }
1466
1467 // We do not allow overloading based off of '__restrict'.
1468 Q.removeRestrict();
1469
1470 // We may not have applied the implicit const for a constexpr member
1471 // function yet (because we haven't yet resolved whether this is a static
1472 // or non-static member function). Add it now, on the assumption that this
1473 // is a redeclaration of OldMethod.
1474 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1475 (M->isConstexpr() || M->isConsteval()) &&
1476 !isa<CXXConstructorDecl>(NewMethod))
1477 Q.addConst();
1478 return Q;
1479 };
1480
1481 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1482 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1483 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1484
1485 if (OldMethod->isExplicitObjectMemberFunction()) {
1486 BS.Quals.removeVolatile();
1487 DS.Quals.removeVolatile();
1488 }
1489
1490 return BS.Quals == DS.Quals;
1491 };
1492
1493 auto CompareType = [&](QualType Base, QualType D) {
1494 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1495 auto DS = D.getNonReferenceType().getCanonicalType().split();
1496
1497 if (!AreQualifiersEqual(BS, DS))
1498 return false;
1499
1500 if (OldMethod->isImplicitObjectMemberFunction() &&
1501 OldMethod->getParent() != NewMethod->getParent()) {
1502 CanQualType ParentType =
1503 SemaRef.Context.getCanonicalTagType(OldMethod->getParent());
1504 if (ParentType.getTypePtr() != BS.Ty)
1505 return false;
1506 BS.Ty = DS.Ty;
1507 }
1508
1509 // FIXME: should we ignore some type attributes here?
1510 if (BS.Ty != DS.Ty)
1511 return false;
1512
1513 if (Base->isLValueReferenceType())
1514 return D->isLValueReferenceType();
1515 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1516 };
1517
1518 // If the function is a class member, its signature includes the
1519 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1520 auto DiagnoseInconsistentRefQualifiers = [&]() {
1521 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1522 return false;
1523 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1524 return false;
1525 if (OldMethod->isExplicitObjectMemberFunction() ||
1526 NewMethod->isExplicitObjectMemberFunction())
1527 return false;
1528 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1529 NewMethod->getRefQualifier() == RQ_None)) {
1530 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1531 << OldMethod->getRefQualifier() << NewMethod->getRefQualifier();
1532 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1533 return true;
1534 }
1535 return false;
1536 };
1537
1538 // We look at the parameters first, as it is the common case.
1539 // However we should not emit diagnostic before checking
1540 // the overloads do not differ by constraints or other discriminant.
1541 bool ShouldDiagnoseInconsistentRefQualifiers = false;
1542 bool HaveInconsistentQualifiers = false;
1543
1544 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1545 OldParamsOffset++;
1546 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1547 NewParamsOffset++;
1548
1549 if (OldType->getNumParams() - OldParamsOffset !=
1550 NewType->getNumParams() - NewParamsOffset ||
1552 {OldType->param_type_begin() + OldParamsOffset,
1553 OldType->param_type_end()},
1554 {NewType->param_type_begin() + NewParamsOffset,
1555 NewType->param_type_end()},
1556 nullptr)) {
1557 return true;
1558 }
1559
1560 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1561 !NewMethod->isStatic()) {
1562 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1563 const CXXMethodDecl *New) {
1564 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1565 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1566
1567 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1568 return F->getRefQualifier() == RQ_None &&
1569 !F->isExplicitObjectMemberFunction();
1570 };
1571
1572 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1573 CompareType(OldObjectType.getNonReferenceType(),
1574 NewObjectType.getNonReferenceType()))
1575 return true;
1576 return CompareType(OldObjectType, NewObjectType);
1577 }(OldMethod, NewMethod);
1578
1579 if (!HaveCorrespondingObjectParameters) {
1580 ShouldDiagnoseInconsistentRefQualifiers = true;
1581 // CWG2554
1582 // and, if at least one is an explicit object member function, ignoring
1583 // object parameters
1584 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1585 !OldMethod->isExplicitObjectMemberFunction()))
1586 HaveInconsistentQualifiers = true;
1587 }
1588 }
1589
1590 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1591 NewMethod->isImplicitObjectMemberFunction())
1592 ShouldDiagnoseInconsistentRefQualifiers = true;
1593
1594 if (!UseOverrideRules &&
1595 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1596 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1597 OldRC = Old->getTrailingRequiresClause();
1598 if (!NewRC != !OldRC)
1599 return true;
1600 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1601 return true;
1602 if (NewRC &&
1603 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC.ConstraintExpr,
1604 NewDecl, NewRC.ConstraintExpr))
1605 return true;
1606 }
1607
1608 // Though pass_object_size is placed on parameters and takes an argument, we
1609 // consider it to be a function-level modifier for the sake of function
1610 // identity. Either the function has one or more parameters with
1611 // pass_object_size or it doesn't.
1614 return true;
1615
1616 // enable_if attributes are an order-sensitive part of the signature.
1618 NewI = New->specific_attr_begin<EnableIfAttr>(),
1619 NewE = New->specific_attr_end<EnableIfAttr>(),
1620 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1621 OldE = Old->specific_attr_end<EnableIfAttr>();
1622 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1623 if (NewI == NewE || OldI == OldE)
1624 return true;
1625 llvm::FoldingSetNodeID NewID, OldID;
1626 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1627 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1628 if (NewID != OldID)
1629 return true;
1630 }
1631
1632 if ((ShouldDiagnoseInconsistentRefQualifiers &&
1633 DiagnoseInconsistentRefQualifiers()) ||
1634 HaveInconsistentQualifiers)
1635 return true;
1636
1637 // At this point, it is known that the two functions have the same signature.
1638 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1639 // Don't allow overloading of destructors. (In theory we could, but it
1640 // would be a giant change to clang.)
1642 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1643 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1644 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1645 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1646 "Unexpected invalid target.");
1647
1648 // Allow overloading of functions with same signature and different CUDA
1649 // target attributes.
1650 if (NewTarget != OldTarget) {
1651 // Special case: non-constexpr function is allowed to override
1652 // constexpr virtual function
1653 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1654 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1659 return false;
1660 }
1661 return true;
1662 }
1663 }
1664 }
1665 }
1666
1667 // The signatures match; this is not an overload.
1668 return false;
1669}
1670
1672 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1673 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1674 ConsiderCudaAttrs);
1675}
1676
1678 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1679 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1680 /*UseMemberUsingDeclRules=*/false,
1681 /*ConsiderCudaAttrs=*/true,
1682 /*UseOverrideRules=*/true);
1683}
1684
1685/// Tries a user-defined conversion from From to ToType.
1686///
1687/// Produces an implicit conversion sequence for when a standard conversion
1688/// is not an option. See TryImplicitConversion for more information.
1691 bool SuppressUserConversions,
1692 AllowedExplicit AllowExplicit,
1693 bool InOverloadResolution,
1694 bool CStyle,
1695 bool AllowObjCWritebackConversion,
1696 bool AllowObjCConversionOnExplicit) {
1698
1699 if (SuppressUserConversions) {
1700 // We're not in the case above, so there is no conversion that
1701 // we can perform.
1703 return ICS;
1704 }
1705
1706 // Attempt user-defined conversion.
1707 OverloadCandidateSet Conversions(From->getExprLoc(),
1709 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1710 Conversions, AllowExplicit,
1711 AllowObjCConversionOnExplicit)) {
1712 case OR_Success:
1713 case OR_Deleted:
1714 ICS.setUserDefined();
1715 // C++ [over.ics.user]p4:
1716 // A conversion of an expression of class type to the same class
1717 // type is given Exact Match rank, and a conversion of an
1718 // expression of class type to a base class of that type is
1719 // given Conversion rank, in spite of the fact that a copy
1720 // constructor (i.e., a user-defined conversion function) is
1721 // called for those cases.
1723 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1724 QualType FromType;
1725 SourceLocation FromLoc;
1726 // C++11 [over.ics.list]p6, per DR2137:
1727 // C++17 [over.ics.list]p6:
1728 // If C is not an initializer-list constructor and the initializer list
1729 // has a single element of type cv U, where U is X or a class derived
1730 // from X, the implicit conversion sequence has Exact Match rank if U is
1731 // X, or Conversion rank if U is derived from X.
1732 bool FromListInit = false;
1733 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1734 InitList && InitList->getNumInits() == 1 &&
1736 const Expr *SingleInit = InitList->getInit(0);
1737 FromType = SingleInit->getType();
1738 FromLoc = SingleInit->getBeginLoc();
1739 FromListInit = true;
1740 } else {
1741 FromType = From->getType();
1742 FromLoc = From->getBeginLoc();
1743 }
1744 QualType FromCanon =
1746 QualType ToCanon
1748 if ((FromCanon == ToCanon ||
1749 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1750 // Turn this into a "standard" conversion sequence, so that it
1751 // gets ranked with standard conversion sequences.
1753 ICS.setStandard();
1755 ICS.Standard.setFromType(FromType);
1756 ICS.Standard.setAllToTypes(ToType);
1757 ICS.Standard.FromBracedInitList = FromListInit;
1760 if (ToCanon != FromCanon)
1762 }
1763 }
1764 break;
1765
1766 case OR_Ambiguous:
1767 ICS.setAmbiguous();
1768 ICS.Ambiguous.setFromType(From->getType());
1769 ICS.Ambiguous.setToType(ToType);
1770 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1771 Cand != Conversions.end(); ++Cand)
1772 if (Cand->Best)
1773 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1774 break;
1775
1776 // Fall through.
1779 break;
1780 }
1781
1782 return ICS;
1783}
1784
1785/// TryImplicitConversion - Attempt to perform an implicit conversion
1786/// from the given expression (Expr) to the given type (ToType). This
1787/// function returns an implicit conversion sequence that can be used
1788/// to perform the initialization. Given
1789///
1790/// void f(float f);
1791/// void g(int i) { f(i); }
1792///
1793/// this routine would produce an implicit conversion sequence to
1794/// describe the initialization of f from i, which will be a standard
1795/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1796/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1797//
1798/// Note that this routine only determines how the conversion can be
1799/// performed; it does not actually perform the conversion. As such,
1800/// it will not produce any diagnostics if no conversion is available,
1801/// but will instead return an implicit conversion sequence of kind
1802/// "BadConversion".
1803///
1804/// If @p SuppressUserConversions, then user-defined conversions are
1805/// not permitted.
1806/// If @p AllowExplicit, then explicit user-defined conversions are
1807/// permitted.
1808///
1809/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1810/// writeback conversion, which allows __autoreleasing id* parameters to
1811/// be initialized with __strong id* or __weak id* arguments.
1812static ImplicitConversionSequence
1814 bool SuppressUserConversions,
1815 AllowedExplicit AllowExplicit,
1816 bool InOverloadResolution,
1817 bool CStyle,
1818 bool AllowObjCWritebackConversion,
1819 bool AllowObjCConversionOnExplicit) {
1821 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1822 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1823 ICS.setStandard();
1824 return ICS;
1825 }
1826
1827 if (!S.getLangOpts().CPlusPlus) {
1829 return ICS;
1830 }
1831
1832 // C++ [over.ics.user]p4:
1833 // A conversion of an expression of class type to the same class
1834 // type is given Exact Match rank, and a conversion of an
1835 // expression of class type to a base class of that type is
1836 // given Conversion rank, in spite of the fact that a copy/move
1837 // constructor (i.e., a user-defined conversion function) is
1838 // called for those cases.
1839 QualType FromType = From->getType();
1840 if (ToType->isRecordType() &&
1841 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1842 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1843 ICS.setStandard();
1845 ICS.Standard.setFromType(FromType);
1846 ICS.Standard.setAllToTypes(ToType);
1847
1848 // We don't actually check at this point whether there is a valid
1849 // copy/move constructor, since overloading just assumes that it
1850 // exists. When we actually perform initialization, we'll find the
1851 // appropriate constructor to copy the returned object, if needed.
1852 ICS.Standard.CopyConstructor = nullptr;
1853
1854 // In HLSL, a conversion of an expression of class type to the same class
1855 // type needs implicit LvaluetoRvalue conversion.
1856 if (S.getLangOpts().HLSL)
1858
1859 // Determine whether this is considered a derived-to-base conversion.
1860 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1862
1863 return ICS;
1864 }
1865
1866 if (S.getLangOpts().HLSL) {
1867 // Handle conversion of the HLSL resource types.
1868 const Type *FromTy = FromType->getUnqualifiedDesugaredType();
1869 if (FromTy->isHLSLAttributedResourceType()) {
1870 // Attributed resource types can convert to other attributed
1871 // resource types with the same attributes and contained types,
1872 // or to __hlsl_resource_t without any attributes.
1873 bool CanConvert = false;
1874 const Type *ToTy = ToType->getUnqualifiedDesugaredType();
1875 if (ToTy->isHLSLAttributedResourceType()) {
1876 auto *ToResType = cast<HLSLAttributedResourceType>(ToTy);
1877 auto *FromResType = cast<HLSLAttributedResourceType>(FromTy);
1878 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1879 FromResType->getWrappedType()) &&
1880 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1881 FromResType->getContainedType()) &&
1882 ToResType->getAttrs() == FromResType->getAttrs())
1883 CanConvert = true;
1884 } else if (ToTy->isHLSLResourceType()) {
1885 CanConvert = true;
1886 }
1887 if (CanConvert) {
1888 ICS.setStandard();
1890 ICS.Standard.setFromType(FromType);
1891 ICS.Standard.setAllToTypes(ToType);
1892 return ICS;
1893 }
1894 }
1895 }
1896
1897 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1898 AllowExplicit, InOverloadResolution, CStyle,
1899 AllowObjCWritebackConversion,
1900 AllowObjCConversionOnExplicit);
1901}
1902
1903ImplicitConversionSequence
1905 bool SuppressUserConversions,
1906 AllowedExplicit AllowExplicit,
1907 bool InOverloadResolution,
1908 bool CStyle,
1909 bool AllowObjCWritebackConversion) {
1910 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1911 AllowExplicit, InOverloadResolution, CStyle,
1912 AllowObjCWritebackConversion,
1913 /*AllowObjCConversionOnExplicit=*/false);
1914}
1915
1917 AssignmentAction Action,
1918 bool AllowExplicit) {
1919 if (checkPlaceholderForOverload(*this, From))
1920 return ExprError();
1921
1922 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1923 bool AllowObjCWritebackConversion =
1924 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1925 Action == AssignmentAction::Sending);
1926 if (getLangOpts().ObjC)
1927 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1928 From->getType(), From);
1930 *this, From, ToType,
1931 /*SuppressUserConversions=*/false,
1932 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1933 /*InOverloadResolution=*/false,
1934 /*CStyle=*/false, AllowObjCWritebackConversion,
1935 /*AllowObjCConversionOnExplicit=*/false);
1936 return PerformImplicitConversion(From, ToType, ICS, Action);
1937}
1938
1940 QualType &ResultTy) const {
1941 bool Changed = IsFunctionConversion(FromType, ToType);
1942 if (Changed)
1943 ResultTy = ToType;
1944 return Changed;
1945}
1946
1947bool Sema::IsFunctionConversion(QualType FromType, QualType ToType) const {
1948 if (Context.hasSameUnqualifiedType(FromType, ToType))
1949 return false;
1950
1951 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1952 // or F(t noexcept) -> F(t)
1953 // where F adds one of the following at most once:
1954 // - a pointer
1955 // - a member pointer
1956 // - a block pointer
1957 // Changes here need matching changes in FindCompositePointerType.
1958 CanQualType CanTo = Context.getCanonicalType(ToType);
1959 CanQualType CanFrom = Context.getCanonicalType(FromType);
1960 Type::TypeClass TyClass = CanTo->getTypeClass();
1961 if (TyClass != CanFrom->getTypeClass()) return false;
1962 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1963 if (TyClass == Type::Pointer) {
1964 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1965 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1966 } else if (TyClass == Type::BlockPointer) {
1967 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1968 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1969 } else if (TyClass == Type::MemberPointer) {
1970 auto ToMPT = CanTo.castAs<MemberPointerType>();
1971 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1972 // A function pointer conversion cannot change the class of the function.
1973 if (!declaresSameEntity(ToMPT->getMostRecentCXXRecordDecl(),
1974 FromMPT->getMostRecentCXXRecordDecl()))
1975 return false;
1976 CanTo = ToMPT->getPointeeType();
1977 CanFrom = FromMPT->getPointeeType();
1978 } else {
1979 return false;
1980 }
1981
1982 TyClass = CanTo->getTypeClass();
1983 if (TyClass != CanFrom->getTypeClass()) return false;
1984 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1985 return false;
1986 }
1987
1988 const auto *FromFn = cast<FunctionType>(CanFrom);
1989 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1990
1991 const auto *ToFn = cast<FunctionType>(CanTo);
1992 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1993
1994 bool Changed = false;
1995
1996 // Drop 'noreturn' if not present in target type.
1997 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1998 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1999 Changed = true;
2000 }
2001
2002 const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn);
2003 const auto *ToFPT = dyn_cast<FunctionProtoType>(ToFn);
2004
2005 if (FromFPT && ToFPT) {
2006 if (FromFPT->hasCFIUncheckedCallee() != ToFPT->hasCFIUncheckedCallee()) {
2007 QualType NewTy = Context.getFunctionType(
2008 FromFPT->getReturnType(), FromFPT->getParamTypes(),
2009 FromFPT->getExtProtoInfo().withCFIUncheckedCallee(
2010 ToFPT->hasCFIUncheckedCallee()));
2011 FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());
2012 FromFn = FromFPT;
2013 Changed = true;
2014 }
2015 }
2016
2017 // Drop 'noexcept' if not present in target type.
2018 if (FromFPT && ToFPT) {
2019 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
2020 FromFn = cast<FunctionType>(
2021 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
2022 EST_None)
2023 .getTypePtr());
2024 Changed = true;
2025 }
2026
2027 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
2028 // only if the ExtParameterInfo lists of the two function prototypes can be
2029 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
2031 bool CanUseToFPT, CanUseFromFPT;
2032 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
2033 CanUseFromFPT, NewParamInfos) &&
2034 CanUseToFPT && !CanUseFromFPT) {
2035 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2036 ExtInfo.ExtParameterInfos =
2037 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2038 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
2039 FromFPT->getParamTypes(), ExtInfo);
2040 FromFn = QT->getAs<FunctionType>();
2041 Changed = true;
2042 }
2043
2044 if (Context.hasAnyFunctionEffects()) {
2045 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
2046
2047 // Transparently add/drop effects; here we are concerned with
2048 // language rules/canonicalization. Adding/dropping effects is a warning.
2049 const auto FromFX = FromFPT->getFunctionEffects();
2050 const auto ToFX = ToFPT->getFunctionEffects();
2051 if (FromFX != ToFX) {
2052 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2053 ExtInfo.FunctionEffects = ToFX;
2054 QualType QT = Context.getFunctionType(
2055 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
2056 FromFn = QT->getAs<FunctionType>();
2057 Changed = true;
2058 }
2059 }
2060 }
2061
2062 if (!Changed)
2063 return false;
2064
2065 assert(QualType(FromFn, 0).isCanonical());
2066 if (QualType(FromFn, 0) != CanTo) return false;
2067
2068 return true;
2069}
2070
2071/// Determine whether the conversion from FromType to ToType is a valid
2072/// floating point conversion.
2073///
2074static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2075 QualType ToType) {
2076 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2077 return false;
2078 // FIXME: disable conversions between long double, __ibm128 and __float128
2079 // if their representation is different until there is back end support
2080 // We of course allow this conversion if long double is really double.
2081
2082 // Conversions between bfloat16 and float16 are currently not supported.
2083 if ((FromType->isBFloat16Type() &&
2084 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2085 (ToType->isBFloat16Type() &&
2086 (FromType->isFloat16Type() || FromType->isHalfType())))
2087 return false;
2088
2089 // Conversions between IEEE-quad and IBM-extended semantics are not
2090 // permitted.
2091 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
2092 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2093 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2094 &ToSem == &llvm::APFloat::IEEEquad()) ||
2095 (&FromSem == &llvm::APFloat::IEEEquad() &&
2096 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2097 return false;
2098 return true;
2099}
2100
2102 QualType ToType,
2104 Expr *From) {
2105 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2106 return true;
2107
2108 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2110 return true;
2111 }
2112
2113 if (IsFloatingPointConversion(S, FromType, ToType)) {
2115 return true;
2116 }
2117
2118 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2120 return true;
2121 }
2122
2123 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2125 ToType->isRealFloatingType())) {
2127 return true;
2128 }
2129
2130 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2132 return true;
2133 }
2134
2135 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2136 ToType->isIntegralType(S.Context)) {
2138 return true;
2139 }
2140
2141 return false;
2142}
2143
2144/// Determine whether the conversion from FromType to ToType is a valid
2145/// matrix conversion.
2146///
2147/// \param ICK Will be set to the matrix conversion kind, if this is a matrix
2148/// conversion.
2149static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType,
2151 ImplicitConversionKind &ElConv, Expr *From,
2152 bool InOverloadResolution, bool CStyle) {
2153 // Implicit conversions for matrices are an HLSL feature not present in C/C++.
2154 if (!S.getLangOpts().HLSL)
2155 return false;
2156
2157 auto *ToMatrixType = ToType->getAs<ConstantMatrixType>();
2158 auto *FromMatrixType = FromType->getAs<ConstantMatrixType>();
2159
2160 // If both arguments are matrix, handle possible matrix truncation and
2161 // element conversion.
2162 if (ToMatrixType && FromMatrixType) {
2163 unsigned FromCols = FromMatrixType->getNumColumns();
2164 unsigned ToCols = ToMatrixType->getNumColumns();
2165 if (FromCols < ToCols)
2166 return false;
2167
2168 unsigned FromRows = FromMatrixType->getNumRows();
2169 unsigned ToRows = ToMatrixType->getNumRows();
2170 if (FromRows < ToRows)
2171 return false;
2172
2173 if (FromRows == ToRows && FromCols == ToCols)
2174 ElConv = ICK_Identity;
2175 else
2177
2178 QualType FromElTy = FromMatrixType->getElementType();
2179 QualType ToElTy = ToMatrixType->getElementType();
2180 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2181 return true;
2182 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2183 }
2184
2185 // Matrix splat from any arithmetic type to a matrix.
2186 if (ToMatrixType && FromType->isArithmeticType()) {
2187 ElConv = ICK_HLSL_Matrix_Splat;
2188 QualType ToElTy = ToMatrixType->getElementType();
2189 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK, From);
2190 }
2191 if (FromMatrixType && !ToMatrixType) {
2193 QualType FromElTy = FromMatrixType->getElementType();
2194 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2195 return true;
2196 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2197 }
2198
2199 return false;
2200}
2201
2202/// Determine whether the conversion from FromType to ToType is a valid
2203/// vector conversion.
2204///
2205/// \param ICK Will be set to the vector conversion kind, if this is a vector
2206/// conversion.
2207static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2209 ImplicitConversionKind &ElConv, Expr *From,
2210 bool InOverloadResolution, bool CStyle) {
2211 // We need at least one of these types to be a vector type to have a vector
2212 // conversion.
2213 if (!ToType->isVectorType() && !FromType->isVectorType())
2214 return false;
2215
2216 // Identical types require no conversions.
2217 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2218 return false;
2219
2220 // HLSL allows implicit truncation of vector types.
2221 if (S.getLangOpts().HLSL) {
2222 auto *ToExtType = ToType->getAs<ExtVectorType>();
2223 auto *FromExtType = FromType->getAs<ExtVectorType>();
2224
2225 // If both arguments are vectors, handle possible vector truncation and
2226 // element conversion.
2227 if (ToExtType && FromExtType) {
2228 unsigned FromElts = FromExtType->getNumElements();
2229 unsigned ToElts = ToExtType->getNumElements();
2230 if (FromElts < ToElts)
2231 return false;
2232 if (FromElts == ToElts)
2233 ElConv = ICK_Identity;
2234 else
2236
2237 QualType FromElTy = FromExtType->getElementType();
2238 QualType ToElTy = ToExtType->getElementType();
2239 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2240 return true;
2241 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2242 }
2243 if (FromExtType && !ToExtType) {
2245 QualType FromElTy = FromExtType->getElementType();
2246 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2247 return true;
2248 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2249 }
2250 // Fallthrough for the case where ToType is a vector and FromType is not.
2251 }
2252
2253 // There are no conversions between extended vector types, only identity.
2254 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2255 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2256 // Implicit conversions require the same number of elements.
2257 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2258 return false;
2259
2260 // Permit implicit conversions from integral values to boolean vectors.
2261 if (ToType->isExtVectorBoolType() &&
2262 FromExtType->getElementType()->isIntegerType()) {
2264 return true;
2265 }
2266 // There are no other conversions between extended vector types.
2267 return false;
2268 }
2269
2270 // Vector splat from any arithmetic type to a vector.
2271 if (FromType->isArithmeticType()) {
2272 if (S.getLangOpts().HLSL) {
2273 ElConv = ICK_HLSL_Vector_Splat;
2274 QualType ToElTy = ToExtType->getElementType();
2275 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK,
2276 From);
2277 }
2278 ICK = ICK_Vector_Splat;
2279 return true;
2280 }
2281 }
2282
2283 if (ToType->isSVESizelessBuiltinType() ||
2284 FromType->isSVESizelessBuiltinType())
2285 if (S.ARM().areCompatibleSveTypes(FromType, ToType) ||
2286 S.ARM().areLaxCompatibleSveTypes(FromType, ToType)) {
2288 return true;
2289 }
2290
2291 if (ToType->isRVVSizelessBuiltinType() ||
2292 FromType->isRVVSizelessBuiltinType())
2293 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2294 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2296 return true;
2297 }
2298
2299 // We can perform the conversion between vector types in the following cases:
2300 // 1)vector types are equivalent AltiVec and GCC vector types
2301 // 2)lax vector conversions are permitted and the vector types are of the
2302 // same size
2303 // 3)the destination type does not have the ARM MVE strict-polymorphism
2304 // attribute, which inhibits lax vector conversion for overload resolution
2305 // only
2306 if (ToType->isVectorType() && FromType->isVectorType()) {
2307 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2308 (S.isLaxVectorConversion(FromType, ToType) &&
2309 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2310 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2311 S.isLaxVectorConversion(FromType, ToType) &&
2312 S.anyAltivecTypes(FromType, ToType) &&
2313 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2314 !InOverloadResolution && !CStyle) {
2315 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2316 << FromType << ToType;
2317 }
2319 return true;
2320 }
2321 }
2322
2323 return false;
2324}
2325
2326static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2327 bool InOverloadResolution,
2328 StandardConversionSequence &SCS,
2329 bool CStyle);
2330
2331static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
2332 QualType ToType,
2333 bool InOverloadResolution,
2334 StandardConversionSequence &SCS,
2335 bool CStyle);
2336
2337/// IsStandardConversion - Determines whether there is a standard
2338/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2339/// expression From to the type ToType. Standard conversion sequences
2340/// only consider non-class types; for conversions that involve class
2341/// types, use TryImplicitConversion. If a conversion exists, SCS will
2342/// contain the standard conversion sequence required to perform this
2343/// conversion and this routine will return true. Otherwise, this
2344/// routine will return false and the value of SCS is unspecified.
2345static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2346 bool InOverloadResolution,
2348 bool CStyle,
2349 bool AllowObjCWritebackConversion) {
2350 QualType FromType = From->getType();
2351
2352 // Standard conversions (C++ [conv])
2354 SCS.IncompatibleObjC = false;
2355 SCS.setFromType(FromType);
2356 SCS.CopyConstructor = nullptr;
2357
2358 // There are no standard conversions for class types in C++, so
2359 // abort early. When overloading in C, however, we do permit them.
2360 if (S.getLangOpts().CPlusPlus &&
2361 (FromType->isRecordType() || ToType->isRecordType()))
2362 return false;
2363
2364 // The first conversion can be an lvalue-to-rvalue conversion,
2365 // array-to-pointer conversion, or function-to-pointer conversion
2366 // (C++ 4p1).
2367
2368 if (FromType == S.Context.OverloadTy) {
2369 DeclAccessPair AccessPair;
2370 if (FunctionDecl *Fn
2371 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2372 AccessPair)) {
2373 // We were able to resolve the address of the overloaded function,
2374 // so we can convert to the type of that function.
2375 FromType = Fn->getType();
2376 SCS.setFromType(FromType);
2377
2378 // we can sometimes resolve &foo<int> regardless of ToType, so check
2379 // if the type matches (identity) or we are converting to bool
2381 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2382 // if the function type matches except for [[noreturn]], it's ok
2383 if (!S.IsFunctionConversion(FromType,
2385 // otherwise, only a boolean conversion is standard
2386 if (!ToType->isBooleanType())
2387 return false;
2388 }
2389
2390 // Check if the "from" expression is taking the address of an overloaded
2391 // function and recompute the FromType accordingly. Take advantage of the
2392 // fact that non-static member functions *must* have such an address-of
2393 // expression.
2394 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2395 if (Method && !Method->isStatic() &&
2396 !Method->isExplicitObjectMemberFunction()) {
2397 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2398 "Non-unary operator on non-static member address");
2399 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2400 == UO_AddrOf &&
2401 "Non-address-of operator on non-static member address");
2402 FromType = S.Context.getMemberPointerType(
2403 FromType, /*Qualifier=*/std::nullopt, Method->getParent());
2404 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2405 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2406 UO_AddrOf &&
2407 "Non-address-of operator for overloaded function expression");
2408 FromType = S.Context.getPointerType(FromType);
2409 }
2410 } else {
2411 return false;
2412 }
2413 }
2414
2415 bool argIsLValue = From->isGLValue();
2416 // To handle conversion from ArrayParameterType to ConstantArrayType
2417 // this block must be above the one below because Array parameters
2418 // do not decay and when handling HLSLOutArgExprs and
2419 // the From expression is an LValue.
2420 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2421 ToType->isConstantArrayType()) {
2422 // HLSL constant array parameters do not decay, so if the argument is a
2423 // constant array and the parameter is an ArrayParameterType we have special
2424 // handling here.
2425 if (ToType->isArrayParameterType()) {
2426 FromType = S.Context.getArrayParameterType(FromType);
2427 } else if (FromType->isArrayParameterType()) {
2428 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2429 FromType = APT->getConstantArrayType(S.Context);
2430 }
2431
2433
2434 // Don't consider qualifiers, which include things like address spaces
2435 if (FromType.getCanonicalType().getUnqualifiedType() !=
2437 return false;
2438
2439 SCS.setAllToTypes(ToType);
2440 return true;
2441 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2442 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2443 // Lvalue-to-rvalue conversion (C++11 4.1):
2444 // A glvalue (3.10) of a non-function, non-array type T can
2445 // be converted to a prvalue.
2446
2448
2449 // C11 6.3.2.1p2:
2450 // ... if the lvalue has atomic type, the value has the non-atomic version
2451 // of the type of the lvalue ...
2452 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2453 FromType = Atomic->getValueType();
2454
2455 // If T is a non-class type, the type of the rvalue is the
2456 // cv-unqualified version of T. Otherwise, the type of the rvalue
2457 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2458 // just strip the qualifiers because they don't matter.
2459 FromType = FromType.getUnqualifiedType();
2460 } else if (FromType->isArrayType()) {
2461 // Array-to-pointer conversion (C++ 4.2)
2463
2464 // An lvalue or rvalue of type "array of N T" or "array of unknown
2465 // bound of T" can be converted to an rvalue of type "pointer to
2466 // T" (C++ 4.2p1).
2467 FromType = S.Context.getArrayDecayedType(FromType);
2468
2469 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2470 // This conversion is deprecated in C++03 (D.4)
2472
2473 // For the purpose of ranking in overload resolution
2474 // (13.3.3.1.1), this conversion is considered an
2475 // array-to-pointer conversion followed by a qualification
2476 // conversion (4.4). (C++ 4.2p2)
2477 SCS.Second = ICK_Identity;
2480 SCS.setAllToTypes(FromType);
2481 return true;
2482 }
2483 } else if (FromType->isFunctionType() && argIsLValue) {
2484 // Function-to-pointer conversion (C++ 4.3).
2486
2487 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2488 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2490 return false;
2491
2492 // An lvalue of function type T can be converted to an rvalue of
2493 // type "pointer to T." The result is a pointer to the
2494 // function. (C++ 4.3p1).
2495 FromType = S.Context.getPointerType(FromType);
2496 } else {
2497 // We don't require any conversions for the first step.
2498 SCS.First = ICK_Identity;
2499 }
2500 SCS.setToType(0, FromType);
2501
2502 // The second conversion can be an integral promotion, floating
2503 // point promotion, integral conversion, floating point conversion,
2504 // floating-integral conversion, pointer conversion,
2505 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2506 // For overloading in C, this can also be a "compatible-type"
2507 // conversion.
2508 bool IncompatibleObjC = false;
2510 ImplicitConversionKind DimensionICK = ICK_Identity;
2511 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2512 // The unqualified versions of the types are the same: there's no
2513 // conversion to do.
2514 SCS.Second = ICK_Identity;
2515 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2516 // Integral promotion (C++ 4.5).
2518 FromType = ToType.getUnqualifiedType();
2519 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2520 // Floating point promotion (C++ 4.6).
2522 FromType = ToType.getUnqualifiedType();
2523 } else if (S.IsComplexPromotion(FromType, ToType)) {
2524 // Complex promotion (Clang extension)
2526 FromType = ToType.getUnqualifiedType();
2527 } else if (S.IsOverflowBehaviorTypePromotion(FromType, ToType)) {
2528 // OverflowBehaviorType promotions
2530 FromType = ToType.getUnqualifiedType();
2531 } else if (S.IsOverflowBehaviorTypeConversion(FromType, ToType)) {
2532 // OverflowBehaviorType conversions
2534 FromType = ToType.getUnqualifiedType();
2535 } else if (ToType->isBooleanType() &&
2536 (FromType->isArithmeticType() || FromType->isAnyPointerType() ||
2537 FromType->isBlockPointerType() ||
2538 FromType->isMemberPointerType())) {
2539 // Boolean conversions (C++ 4.12).
2541 FromType = S.Context.BoolTy;
2542 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2543 ToType->isIntegralType(S.Context)) {
2544 // Integral conversions (C++ 4.7).
2546 FromType = ToType.getUnqualifiedType();
2547 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2548 // Complex conversions (C99 6.3.1.6)
2550 FromType = ToType.getUnqualifiedType();
2551 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2552 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2553 // Complex-real conversions (C99 6.3.1.7)
2555 FromType = ToType.getUnqualifiedType();
2556 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2557 // Floating point conversions (C++ 4.8).
2559 FromType = ToType.getUnqualifiedType();
2560 } else if ((FromType->isRealFloatingType() &&
2561 ToType->isIntegralType(S.Context)) ||
2563 ToType->isRealFloatingType())) {
2564
2565 // Floating-integral conversions (C++ 4.9).
2567 FromType = ToType.getUnqualifiedType();
2568 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2570 } else if (AllowObjCWritebackConversion &&
2571 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2573 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2574 FromType, IncompatibleObjC)) {
2575 // Pointer conversions (C++ 4.10).
2577 SCS.IncompatibleObjC = IncompatibleObjC;
2578 FromType = FromType.getUnqualifiedType();
2579 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2580 InOverloadResolution, FromType)) {
2581 // Pointer to member conversions (4.11).
2583 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2584 From, InOverloadResolution, CStyle)) {
2585 SCS.Second = SecondICK;
2586 SCS.Dimension = DimensionICK;
2587 FromType = ToType.getUnqualifiedType();
2588 } else if (IsMatrixConversion(S, FromType, ToType, SecondICK, DimensionICK,
2589 From, InOverloadResolution, CStyle)) {
2590 SCS.Second = SecondICK;
2591 SCS.Dimension = DimensionICK;
2592 FromType = ToType.getUnqualifiedType();
2593 } else if (!S.getLangOpts().CPlusPlus &&
2594 S.Context.typesAreCompatible(ToType, FromType)) {
2595 // Compatible conversions (Clang extension for C function overloading)
2597 FromType = ToType.getUnqualifiedType();
2599 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2601 FromType = ToType;
2602 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2603 CStyle)) {
2604 // tryAtomicConversion has updated the standard conversion sequence
2605 // appropriately.
2606 return true;
2608 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2609 return true;
2610 } else if (ToType->isEventT() &&
2612 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2614 FromType = ToType;
2615 } else if (ToType->isQueueT() &&
2617 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2619 FromType = ToType;
2620 } else if (ToType->isSamplerT() &&
2623 FromType = ToType;
2624 } else if ((ToType->isFixedPointType() &&
2625 FromType->isConvertibleToFixedPointType()) ||
2626 (FromType->isFixedPointType() &&
2627 ToType->isConvertibleToFixedPointType())) {
2629 FromType = ToType;
2630 } else {
2631 // No second conversion required.
2632 SCS.Second = ICK_Identity;
2633 }
2634 SCS.setToType(1, FromType);
2635
2636 // The third conversion can be a function pointer conversion or a
2637 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2638 bool ObjCLifetimeConversion;
2639 if (S.TryFunctionConversion(FromType, ToType, FromType)) {
2640 // Function pointer conversions (removing 'noexcept') including removal of
2641 // 'noreturn' (Clang extension).
2643 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2644 ObjCLifetimeConversion)) {
2646 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2647 FromType = ToType;
2648 } else {
2649 // No conversion required
2650 SCS.Third = ICK_Identity;
2651 }
2652
2653 // C++ [over.best.ics]p6:
2654 // [...] Any difference in top-level cv-qualification is
2655 // subsumed by the initialization itself and does not constitute
2656 // a conversion. [...]
2657 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2658 QualType CanonTo = S.Context.getCanonicalType(ToType);
2659 if (CanonFrom.getLocalUnqualifiedType()
2660 == CanonTo.getLocalUnqualifiedType() &&
2661 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2662 FromType = ToType;
2663 CanonFrom = CanonTo;
2664 }
2665
2666 SCS.setToType(2, FromType);
2667
2668 if (CanonFrom == CanonTo)
2669 return true;
2670
2671 // If we have not converted the argument type to the parameter type,
2672 // this is a bad conversion sequence, unless we're resolving an overload in C.
2673 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2674 return false;
2675
2676 ExprResult ER = ExprResult{From};
2677 AssignConvertType Conv =
2679 /*Diagnose=*/false,
2680 /*DiagnoseCFAudited=*/false,
2681 /*ConvertRHS=*/false);
2682 ImplicitConversionKind SecondConv;
2683 switch (Conv) {
2685 case AssignConvertType::
2686 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2687 SecondConv = ICK_C_Only_Conversion;
2688 break;
2689 // For our purposes, discarding qualifiers is just as bad as using an
2690 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2691 // qualifiers, as well.
2696 break;
2697 default:
2698 return false;
2699 }
2700
2701 // First can only be an lvalue conversion, so we pretend that this was the
2702 // second conversion. First should already be valid from earlier in the
2703 // function.
2704 SCS.Second = SecondConv;
2705 SCS.setToType(1, ToType);
2706
2707 // Third is Identity, because Second should rank us worse than any other
2708 // conversion. This could also be ICK_Qualification, but it's simpler to just
2709 // lump everything in with the second conversion, and we don't gain anything
2710 // from making this ICK_Qualification.
2711 SCS.Third = ICK_Identity;
2712 SCS.setToType(2, ToType);
2713 return true;
2714}
2715
2716static bool
2718 QualType &ToType,
2719 bool InOverloadResolution,
2721 bool CStyle) {
2722
2723 const RecordType *UT = ToType->getAsUnionType();
2724 if (!UT)
2725 return false;
2726 // The field to initialize within the transparent union.
2727 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2728 if (!UD->hasAttr<TransparentUnionAttr>())
2729 return false;
2730 // It's compatible if the expression matches any of the fields.
2731 for (const auto *it : UD->fields()) {
2732 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2733 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2734 ToType = it->getType();
2735 return true;
2736 }
2737 }
2738 return false;
2739}
2740
2741bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2742 const BuiltinType *To = ToType->getAs<BuiltinType>();
2743 // All integers are built-in.
2744 if (!To) {
2745 return false;
2746 }
2747
2748 // An rvalue of type char, signed char, unsigned char, short int, or
2749 // unsigned short int can be converted to an rvalue of type int if
2750 // int can represent all the values of the source type; otherwise,
2751 // the source rvalue can be converted to an rvalue of type unsigned
2752 // int (C++ 4.5p1).
2753 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2754 !FromType->isEnumeralType()) {
2755 if ( // We can promote any signed, promotable integer type to an int
2756 (FromType->isSignedIntegerType() ||
2757 // We can promote any unsigned integer type whose size is
2758 // less than int to an int.
2759 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2760 return To->getKind() == BuiltinType::Int;
2761 }
2762
2763 return To->getKind() == BuiltinType::UInt;
2764 }
2765
2766 // C++11 [conv.prom]p3:
2767 // A prvalue of an unscoped enumeration type whose underlying type is not
2768 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2769 // following types that can represent all the values of the enumeration
2770 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2771 // unsigned int, long int, unsigned long int, long long int, or unsigned
2772 // long long int. If none of the types in that list can represent all the
2773 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2774 // type can be converted to an rvalue a prvalue of the extended integer type
2775 // with lowest integer conversion rank (4.13) greater than the rank of long
2776 // long in which all the values of the enumeration can be represented. If
2777 // there are two such extended types, the signed one is chosen.
2778 // C++11 [conv.prom]p4:
2779 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2780 // can be converted to a prvalue of its underlying type. Moreover, if
2781 // integral promotion can be applied to its underlying type, a prvalue of an
2782 // unscoped enumeration type whose underlying type is fixed can also be
2783 // converted to a prvalue of the promoted underlying type.
2784 if (const auto *FromED = FromType->getAsEnumDecl()) {
2785 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2786 // provided for a scoped enumeration.
2787 if (FromED->isScoped())
2788 return false;
2789
2790 // We can perform an integral promotion to the underlying type of the enum,
2791 // even if that's not the promoted type. Note that the check for promoting
2792 // the underlying type is based on the type alone, and does not consider
2793 // the bitfield-ness of the actual source expression.
2794 if (FromED->isFixed()) {
2795 QualType Underlying = FromED->getIntegerType();
2796 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2797 IsIntegralPromotion(nullptr, Underlying, ToType);
2798 }
2799
2800 // We have already pre-calculated the promotion type, so this is trivial.
2801 if (ToType->isIntegerType() &&
2802 isCompleteType(From->getBeginLoc(), FromType))
2803 return Context.hasSameUnqualifiedType(ToType, FromED->getPromotionType());
2804
2805 // C++ [conv.prom]p5:
2806 // If the bit-field has an enumerated type, it is treated as any other
2807 // value of that type for promotion purposes.
2808 //
2809 // ... so do not fall through into the bit-field checks below in C++.
2810 if (getLangOpts().CPlusPlus)
2811 return false;
2812 }
2813
2814 // C++0x [conv.prom]p2:
2815 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2816 // to an rvalue a prvalue of the first of the following types that can
2817 // represent all the values of its underlying type: int, unsigned int,
2818 // long int, unsigned long int, long long int, or unsigned long long int.
2819 // If none of the types in that list can represent all the values of its
2820 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2821 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2822 // type.
2823 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2824 ToType->isIntegerType()) {
2825 // Determine whether the type we're converting from is signed or
2826 // unsigned.
2827 bool FromIsSigned = FromType->isSignedIntegerType();
2828 uint64_t FromSize = Context.getTypeSize(FromType);
2829
2830 // The types we'll try to promote to, in the appropriate
2831 // order. Try each of these types.
2832 QualType PromoteTypes[6] = {
2833 Context.IntTy, Context.UnsignedIntTy,
2834 Context.LongTy, Context.UnsignedLongTy ,
2835 Context.LongLongTy, Context.UnsignedLongLongTy
2836 };
2837 for (int Idx = 0; Idx < 6; ++Idx) {
2838 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2839 if (FromSize < ToSize ||
2840 (FromSize == ToSize &&
2841 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2842 // We found the type that we can promote to. If this is the
2843 // type we wanted, we have a promotion. Otherwise, no
2844 // promotion.
2845 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2846 }
2847 }
2848 }
2849
2850 // An rvalue for an integral bit-field (9.6) can be converted to an
2851 // rvalue of type int if int can represent all the values of the
2852 // bit-field; otherwise, it can be converted to unsigned int if
2853 // unsigned int can represent all the values of the bit-field. If
2854 // the bit-field is larger yet, no integral promotion applies to
2855 // it. If the bit-field has an enumerated type, it is treated as any
2856 // other value of that type for promotion purposes (C++ 4.5p3).
2857 // FIXME: We should delay checking of bit-fields until we actually perform the
2858 // conversion.
2859 //
2860 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2861 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2862 // bit-fields and those whose underlying type is larger than int) for GCC
2863 // compatibility.
2864 if (From) {
2865 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2866 std::optional<llvm::APSInt> BitWidth;
2867 if (FromType->isIntegralType(Context) &&
2868 (BitWidth =
2869 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2870 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2871 ToSize = Context.getTypeSize(ToType);
2872
2873 // Are we promoting to an int from a bitfield that fits in an int?
2874 if (*BitWidth < ToSize ||
2875 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2876 return To->getKind() == BuiltinType::Int;
2877 }
2878
2879 // Are we promoting to an unsigned int from an unsigned bitfield
2880 // that fits into an unsigned int?
2881 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2882 return To->getKind() == BuiltinType::UInt;
2883 }
2884
2885 return false;
2886 }
2887 }
2888 }
2889
2890 // An rvalue of type bool can be converted to an rvalue of type int,
2891 // with false becoming zero and true becoming one (C++ 4.5p4).
2892 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2893 return true;
2894 }
2895
2896 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2897 // integral type.
2898 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2899 ToType->isIntegerType())
2900 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2901
2902 return false;
2903}
2904
2906 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2907 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2908 /// An rvalue of type float can be converted to an rvalue of type
2909 /// double. (C++ 4.6p1).
2910 if (FromBuiltin->getKind() == BuiltinType::Float &&
2911 ToBuiltin->getKind() == BuiltinType::Double)
2912 return true;
2913
2914 // C99 6.3.1.5p1:
2915 // When a float is promoted to double or long double, or a
2916 // double is promoted to long double [...].
2917 if (!getLangOpts().CPlusPlus &&
2918 (FromBuiltin->getKind() == BuiltinType::Float ||
2919 FromBuiltin->getKind() == BuiltinType::Double) &&
2920 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2921 ToBuiltin->getKind() == BuiltinType::Float128 ||
2922 ToBuiltin->getKind() == BuiltinType::Ibm128))
2923 return true;
2924
2925 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2926 // or not native half types are enabled.
2927 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2928 (ToBuiltin->getKind() == BuiltinType::Float ||
2929 ToBuiltin->getKind() == BuiltinType::Double))
2930 return true;
2931
2932 // Half can be promoted to float.
2933 if (!getLangOpts().NativeHalfType &&
2934 FromBuiltin->getKind() == BuiltinType::Half &&
2935 ToBuiltin->getKind() == BuiltinType::Float)
2936 return true;
2937 }
2938
2939 return false;
2940}
2941
2943 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2944 if (!FromComplex)
2945 return false;
2946
2947 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2948 if (!ToComplex)
2949 return false;
2950
2951 return IsFloatingPointPromotion(FromComplex->getElementType(),
2952 ToComplex->getElementType()) ||
2953 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2954 ToComplex->getElementType());
2955}
2956
2958 if (!getLangOpts().OverflowBehaviorTypes)
2959 return false;
2960
2961 if (!FromType->isOverflowBehaviorType() || !ToType->isOverflowBehaviorType())
2962 return false;
2963
2964 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2965}
2966
2968 QualType ToType) {
2969 if (!getLangOpts().OverflowBehaviorTypes)
2970 return false;
2971
2972 if (FromType->isOverflowBehaviorType() && !ToType->isOverflowBehaviorType()) {
2973 if (ToType->isBooleanType())
2974 return false;
2975 // Don't allow implicit conversion from OverflowBehaviorType to scoped enum
2976 if (const EnumType *ToEnumType = ToType->getAs<EnumType>()) {
2977 const EnumDecl *ToED = ToEnumType->getDecl()->getDefinitionOrSelf();
2978 if (ToED->isScoped())
2979 return false;
2980 }
2981 return true;
2982 }
2983
2984 if (!FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2985 return true;
2986
2987 if (FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2988 return Context.getTypeSize(FromType) > Context.getTypeSize(ToType);
2989
2990 return false;
2991}
2992
2993/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2994/// the pointer type FromPtr to a pointer to type ToPointee, with the
2995/// same type qualifiers as FromPtr has on its pointee type. ToType,
2996/// if non-empty, will be a pointer to ToType that may or may not have
2997/// the right set of qualifiers on its pointee.
2998///
2999static QualType
3001 QualType ToPointee, QualType ToType,
3002 ASTContext &Context,
3003 bool StripObjCLifetime = false) {
3004 assert((FromPtr->getTypeClass() == Type::Pointer ||
3005 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
3006 "Invalid similarly-qualified pointer type");
3007
3008 /// Conversions to 'id' subsume cv-qualifier conversions.
3009 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
3010 return ToType.getUnqualifiedType();
3011
3012 QualType CanonFromPointee
3013 = Context.getCanonicalType(FromPtr->getPointeeType());
3014 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
3015 Qualifiers Quals = CanonFromPointee.getQualifiers();
3016
3017 if (StripObjCLifetime)
3018 Quals.removeObjCLifetime();
3019
3020 // Exact qualifier match -> return the pointer type we're converting to.
3021 if (CanonToPointee.getLocalQualifiers() == Quals) {
3022 // ToType is exactly what we need. Return it.
3023 if (!ToType.isNull())
3024 return ToType.getUnqualifiedType();
3025
3026 // Build a pointer to ToPointee. It has the right qualifiers
3027 // already.
3028 if (isa<ObjCObjectPointerType>(ToType))
3029 return Context.getObjCObjectPointerType(ToPointee);
3030 return Context.getPointerType(ToPointee);
3031 }
3032
3033 // Just build a canonical type that has the right qualifiers.
3034 QualType QualifiedCanonToPointee
3035 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
3036
3037 if (isa<ObjCObjectPointerType>(ToType))
3038 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
3039 return Context.getPointerType(QualifiedCanonToPointee);
3040}
3041
3043 bool InOverloadResolution,
3044 ASTContext &Context) {
3045 // Handle value-dependent integral null pointer constants correctly.
3046 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
3047 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
3049 return !InOverloadResolution;
3050
3051 return Expr->isNullPointerConstant(Context,
3052 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3054}
3055
3057 bool InOverloadResolution,
3058 QualType& ConvertedType,
3059 bool &IncompatibleObjC) {
3060 IncompatibleObjC = false;
3061 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
3062 IncompatibleObjC))
3063 return true;
3064
3065 // Conversion from a null pointer constant to any Objective-C pointer type.
3066 if (ToType->isObjCObjectPointerType() &&
3067 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3068 ConvertedType = ToType;
3069 return true;
3070 }
3071
3072 // Blocks: Block pointers can be converted to void*.
3073 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
3074 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
3075 ConvertedType = ToType;
3076 return true;
3077 }
3078 // Blocks: A null pointer constant can be converted to a block
3079 // pointer type.
3080 if (ToType->isBlockPointerType() &&
3081 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3082 ConvertedType = ToType;
3083 return true;
3084 }
3085
3086 // If the left-hand-side is nullptr_t, the right side can be a null
3087 // pointer constant.
3088 if (ToType->isNullPtrType() &&
3089 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3090 ConvertedType = ToType;
3091 return true;
3092 }
3093
3094 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
3095 if (!ToTypePtr)
3096 return false;
3097
3098 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
3099 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3100 ConvertedType = ToType;
3101 return true;
3102 }
3103
3104 // Beyond this point, both types need to be pointers
3105 // , including objective-c pointers.
3106 QualType ToPointeeType = ToTypePtr->getPointeeType();
3107 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
3108 !getLangOpts().ObjCAutoRefCount) {
3109 ConvertedType = BuildSimilarlyQualifiedPointerType(
3110 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
3111 Context);
3112 return true;
3113 }
3114 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
3115 if (!FromTypePtr)
3116 return false;
3117
3118 QualType FromPointeeType = FromTypePtr->getPointeeType();
3119
3120 // If the unqualified pointee types are the same, this can't be a
3121 // pointer conversion, so don't do all of the work below.
3122 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
3123 return false;
3124
3125 // An rvalue of type "pointer to cv T," where T is an object type,
3126 // can be converted to an rvalue of type "pointer to cv void" (C++
3127 // 4.10p2).
3128 if (FromPointeeType->isIncompleteOrObjectType() &&
3129 ToPointeeType->isVoidType()) {
3130 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3131 ToPointeeType,
3132 ToType, Context,
3133 /*StripObjCLifetime=*/true);
3134 return true;
3135 }
3136
3137 // MSVC allows implicit function to void* type conversion.
3138 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
3139 ToPointeeType->isVoidType()) {
3140 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3141 ToPointeeType,
3142 ToType, Context);
3143 return true;
3144 }
3145
3146 // When we're overloading in C, we allow a special kind of pointer
3147 // conversion for compatible-but-not-identical pointee types.
3148 if (!getLangOpts().CPlusPlus &&
3149 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
3150 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3151 ToPointeeType,
3152 ToType, Context);
3153 return true;
3154 }
3155
3156 // C++ [conv.ptr]p3:
3157 //
3158 // An rvalue of type "pointer to cv D," where D is a class type,
3159 // can be converted to an rvalue of type "pointer to cv B," where
3160 // B is a base class (clause 10) of D. If B is an inaccessible
3161 // (clause 11) or ambiguous (10.2) base class of D, a program that
3162 // necessitates this conversion is ill-formed. The result of the
3163 // conversion is a pointer to the base class sub-object of the
3164 // derived class object. The null pointer value is converted to
3165 // the null pointer value of the destination type.
3166 //
3167 // Note that we do not check for ambiguity or inaccessibility
3168 // here. That is handled by CheckPointerConversion.
3169 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3170 ToPointeeType->isRecordType() &&
3171 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
3172 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
3173 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3174 ToPointeeType,
3175 ToType, Context);
3176 return true;
3177 }
3178
3179 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3180 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
3181 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3182 ToPointeeType,
3183 ToType, Context);
3184 return true;
3185 }
3186
3187 return false;
3188}
3189
3190/// Adopt the given qualifiers for the given type.
3192 Qualifiers TQs = T.getQualifiers();
3193
3194 // Check whether qualifiers already match.
3195 if (TQs == Qs)
3196 return T;
3197
3198 if (Qs.compatiblyIncludes(TQs, Context))
3199 return Context.getQualifiedType(T, Qs);
3200
3201 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
3202}
3203
3205 QualType& ConvertedType,
3206 bool &IncompatibleObjC) {
3207 if (!getLangOpts().ObjC)
3208 return false;
3209
3210 // The set of qualifiers on the type we're converting from.
3211 Qualifiers FromQualifiers = FromType.getQualifiers();
3212
3213 // First, we handle all conversions on ObjC object pointer types.
3214 const ObjCObjectPointerType* ToObjCPtr =
3215 ToType->getAs<ObjCObjectPointerType>();
3216 const ObjCObjectPointerType *FromObjCPtr =
3217 FromType->getAs<ObjCObjectPointerType>();
3218
3219 if (ToObjCPtr && FromObjCPtr) {
3220 // If the pointee types are the same (ignoring qualifications),
3221 // then this is not a pointer conversion.
3222 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
3223 FromObjCPtr->getPointeeType()))
3224 return false;
3225
3226 // Conversion between Objective-C pointers.
3227 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3228 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3229 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3230 if (getLangOpts().CPlusPlus && LHS && RHS &&
3232 FromObjCPtr->getPointeeType(), getASTContext()))
3233 return false;
3234 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3235 ToObjCPtr->getPointeeType(),
3236 ToType, Context);
3237 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3238 return true;
3239 }
3240
3241 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3242 // Okay: this is some kind of implicit downcast of Objective-C
3243 // interfaces, which is permitted. However, we're going to
3244 // complain about it.
3245 IncompatibleObjC = true;
3246 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3247 ToObjCPtr->getPointeeType(),
3248 ToType, Context);
3249 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3250 return true;
3251 }
3252 }
3253 // Beyond this point, both types need to be C pointers or block pointers.
3254 QualType ToPointeeType;
3255 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3256 ToPointeeType = ToCPtr->getPointeeType();
3257 else if (const BlockPointerType *ToBlockPtr =
3258 ToType->getAs<BlockPointerType>()) {
3259 // Objective C++: We're able to convert from a pointer to any object
3260 // to a block pointer type.
3261 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3262 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3263 return true;
3264 }
3265 ToPointeeType = ToBlockPtr->getPointeeType();
3266 }
3267 else if (FromType->getAs<BlockPointerType>() &&
3268 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3269 // Objective C++: We're able to convert from a block pointer type to a
3270 // pointer to any object.
3271 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3272 return true;
3273 }
3274 else
3275 return false;
3276
3277 QualType FromPointeeType;
3278 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3279 FromPointeeType = FromCPtr->getPointeeType();
3280 else if (const BlockPointerType *FromBlockPtr =
3281 FromType->getAs<BlockPointerType>())
3282 FromPointeeType = FromBlockPtr->getPointeeType();
3283 else
3284 return false;
3285
3286 // If we have pointers to pointers, recursively check whether this
3287 // is an Objective-C conversion.
3288 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3289 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3290 IncompatibleObjC)) {
3291 // We always complain about this conversion.
3292 IncompatibleObjC = true;
3293 ConvertedType = Context.getPointerType(ConvertedType);
3294 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3295 return true;
3296 }
3297 // Allow conversion of pointee being objective-c pointer to another one;
3298 // as in I* to id.
3299 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3300 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3301 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3302 IncompatibleObjC)) {
3303
3304 ConvertedType = Context.getPointerType(ConvertedType);
3305 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3306 return true;
3307 }
3308
3309 // If we have pointers to functions or blocks, check whether the only
3310 // differences in the argument and result types are in Objective-C
3311 // pointer conversions. If so, we permit the conversion (but
3312 // complain about it).
3313 const FunctionProtoType *FromFunctionType
3314 = FromPointeeType->getAs<FunctionProtoType>();
3315 const FunctionProtoType *ToFunctionType
3316 = ToPointeeType->getAs<FunctionProtoType>();
3317 if (FromFunctionType && ToFunctionType) {
3318 // If the function types are exactly the same, this isn't an
3319 // Objective-C pointer conversion.
3320 if (Context.getCanonicalType(FromPointeeType)
3321 == Context.getCanonicalType(ToPointeeType))
3322 return false;
3323
3324 // Perform the quick checks that will tell us whether these
3325 // function types are obviously different.
3326 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3327 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3328 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3329 return false;
3330
3331 bool HasObjCConversion = false;
3332 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3333 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3334 // Okay, the types match exactly. Nothing to do.
3335 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3336 ToFunctionType->getReturnType(),
3337 ConvertedType, IncompatibleObjC)) {
3338 // Okay, we have an Objective-C pointer conversion.
3339 HasObjCConversion = true;
3340 } else {
3341 // Function types are too different. Abort.
3342 return false;
3343 }
3344
3345 // Check argument types.
3346 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3347 ArgIdx != NumArgs; ++ArgIdx) {
3348 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3349 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3350 if (Context.getCanonicalType(FromArgType)
3351 == Context.getCanonicalType(ToArgType)) {
3352 // Okay, the types match exactly. Nothing to do.
3353 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3354 ConvertedType, IncompatibleObjC)) {
3355 // Okay, we have an Objective-C pointer conversion.
3356 HasObjCConversion = true;
3357 } else {
3358 // Argument types are too different. Abort.
3359 return false;
3360 }
3361 }
3362
3363 if (HasObjCConversion) {
3364 // We had an Objective-C conversion. Allow this pointer
3365 // conversion, but complain about it.
3366 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3367 IncompatibleObjC = true;
3368 return true;
3369 }
3370 }
3371
3372 return false;
3373}
3374
3376 QualType& ConvertedType) {
3377 QualType ToPointeeType;
3378 if (const BlockPointerType *ToBlockPtr =
3379 ToType->getAs<BlockPointerType>())
3380 ToPointeeType = ToBlockPtr->getPointeeType();
3381 else
3382 return false;
3383
3384 QualType FromPointeeType;
3385 if (const BlockPointerType *FromBlockPtr =
3386 FromType->getAs<BlockPointerType>())
3387 FromPointeeType = FromBlockPtr->getPointeeType();
3388 else
3389 return false;
3390 // We have pointer to blocks, check whether the only
3391 // differences in the argument and result types are in Objective-C
3392 // pointer conversions. If so, we permit the conversion.
3393
3394 const FunctionProtoType *FromFunctionType
3395 = FromPointeeType->getAs<FunctionProtoType>();
3396 const FunctionProtoType *ToFunctionType
3397 = ToPointeeType->getAs<FunctionProtoType>();
3398
3399 if (!FromFunctionType || !ToFunctionType)
3400 return false;
3401
3402 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3403 return true;
3404
3405 // Perform the quick checks that will tell us whether these
3406 // function types are obviously different.
3407 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3408 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3409 return false;
3410
3411 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3412 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3413 if (FromEInfo != ToEInfo)
3414 return false;
3415
3416 bool IncompatibleObjC = false;
3417 if (Context.hasSameType(FromFunctionType->getReturnType(),
3418 ToFunctionType->getReturnType())) {
3419 // Okay, the types match exactly. Nothing to do.
3420 } else {
3421 QualType RHS = FromFunctionType->getReturnType();
3422 QualType LHS = ToFunctionType->getReturnType();
3423 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3424 !RHS.hasQualifiers() && LHS.hasQualifiers())
3425 LHS = LHS.getUnqualifiedType();
3426
3427 if (Context.hasSameType(RHS,LHS)) {
3428 // OK exact match.
3429 } else if (isObjCPointerConversion(RHS, LHS,
3430 ConvertedType, IncompatibleObjC)) {
3431 if (IncompatibleObjC)
3432 return false;
3433 // Okay, we have an Objective-C pointer conversion.
3434 }
3435 else
3436 return false;
3437 }
3438
3439 // Check argument types.
3440 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3441 ArgIdx != NumArgs; ++ArgIdx) {
3442 IncompatibleObjC = false;
3443 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3444 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3445 if (Context.hasSameType(FromArgType, ToArgType)) {
3446 // Okay, the types match exactly. Nothing to do.
3447 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3448 ConvertedType, IncompatibleObjC)) {
3449 if (IncompatibleObjC)
3450 return false;
3451 // Okay, we have an Objective-C pointer conversion.
3452 } else
3453 // Argument types are too different. Abort.
3454 return false;
3455 }
3456
3458 bool CanUseToFPT, CanUseFromFPT;
3459 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3460 CanUseToFPT, CanUseFromFPT,
3461 NewParamInfos))
3462 return false;
3463
3464 ConvertedType = ToType;
3465 return true;
3466}
3467
3468enum {
3476};
3477
3478/// Attempts to get the FunctionProtoType from a Type. Handles
3479/// MemberFunctionPointers properly.
3481 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3482 return FPT;
3483
3484 if (auto *MPT = FromType->getAs<MemberPointerType>())
3485 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3486
3487 return nullptr;
3488}
3489
3491 QualType FromType, QualType ToType) {
3492 // If either type is not valid, include no extra info.
3493 if (FromType.isNull() || ToType.isNull()) {
3494 PDiag << ft_default;
3495 return;
3496 }
3497
3498 // Get the function type from the pointers.
3499 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3500 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3501 *ToMember = ToType->castAs<MemberPointerType>();
3502 if (!declaresSameEntity(FromMember->getMostRecentCXXRecordDecl(),
3503 ToMember->getMostRecentCXXRecordDecl())) {
3505 if (ToMember->isSugared())
3506 PDiag << Context.getCanonicalTagType(
3507 ToMember->getMostRecentCXXRecordDecl());
3508 else
3509 PDiag << ToMember->getQualifier();
3510 if (FromMember->isSugared())
3511 PDiag << Context.getCanonicalTagType(
3512 FromMember->getMostRecentCXXRecordDecl());
3513 else
3514 PDiag << FromMember->getQualifier();
3515 return;
3516 }
3517 FromType = FromMember->getPointeeType();
3518 ToType = ToMember->getPointeeType();
3519 }
3520
3521 if (FromType->isPointerType())
3522 FromType = FromType->getPointeeType();
3523 if (ToType->isPointerType())
3524 ToType = ToType->getPointeeType();
3525
3526 // Remove references.
3527 FromType = FromType.getNonReferenceType();
3528 ToType = ToType.getNonReferenceType();
3529
3530 // Don't print extra info for non-specialized template functions.
3531 if (FromType->isInstantiationDependentType() &&
3532 !FromType->getAs<TemplateSpecializationType>()) {
3533 PDiag << ft_default;
3534 return;
3535 }
3536
3537 // No extra info for same types.
3538 if (Context.hasSameType(FromType, ToType)) {
3539 PDiag << ft_default;
3540 return;
3541 }
3542
3543 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3544 *ToFunction = tryGetFunctionProtoType(ToType);
3545
3546 // Both types need to be function types.
3547 if (!FromFunction || !ToFunction) {
3548 PDiag << ft_default;
3549 return;
3550 }
3551
3552 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3553 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3554 << FromFunction->getNumParams();
3555 return;
3556 }
3557
3558 // Handle different parameter types.
3559 unsigned ArgPos;
3560 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3561 PDiag << ft_parameter_mismatch << ArgPos + 1
3562 << ToFunction->getParamType(ArgPos)
3563 << FromFunction->getParamType(ArgPos);
3564 return;
3565 }
3566
3567 // Handle different return type.
3568 if (!Context.hasSameType(FromFunction->getReturnType(),
3569 ToFunction->getReturnType())) {
3570 PDiag << ft_return_type << ToFunction->getReturnType()
3571 << FromFunction->getReturnType();
3572 return;
3573 }
3574
3575 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3576 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3577 << FromFunction->getMethodQuals();
3578 return;
3579 }
3580
3581 // Handle exception specification differences on canonical type (in C++17
3582 // onwards).
3584 ->isNothrow() !=
3585 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3586 ->isNothrow()) {
3587 PDiag << ft_noexcept;
3588 return;
3589 }
3590
3591 // Unable to find a difference, so add no extra info.
3592 PDiag << ft_default;
3593}
3594
3596 ArrayRef<QualType> New, unsigned *ArgPos,
3597 bool Reversed) {
3598 assert(llvm::size(Old) == llvm::size(New) &&
3599 "Can't compare parameters of functions with different number of "
3600 "parameters!");
3601
3602 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3603 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3604 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3605
3606 // Ignore address spaces in pointee type. This is to disallow overloading
3607 // on __ptr32/__ptr64 address spaces.
3608 QualType OldType =
3609 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3610 QualType NewType =
3611 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3612
3613 if (!Context.hasSameType(OldType, NewType)) {
3614 if (ArgPos)
3615 *ArgPos = Idx;
3616 return false;
3617 }
3618 }
3619 return true;
3620}
3621
3623 const FunctionProtoType *NewType,
3624 unsigned *ArgPos, bool Reversed) {
3625 return FunctionParamTypesAreEqual(OldType->param_types(),
3626 NewType->param_types(), ArgPos, Reversed);
3627}
3628
3630 const FunctionDecl *NewFunction,
3631 unsigned *ArgPos,
3632 bool Reversed) {
3633
3634 if (OldFunction->getNumNonObjectParams() !=
3635 NewFunction->getNumNonObjectParams())
3636 return false;
3637
3638 unsigned OldIgnore =
3640 unsigned NewIgnore =
3642
3643 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3644 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3645
3646 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3647 NewPT->param_types().slice(NewIgnore),
3648 ArgPos, Reversed);
3649}
3650
3652 CastKind &Kind,
3653 CXXCastPath& BasePath,
3654 bool IgnoreBaseAccess,
3655 bool Diagnose) {
3656 QualType FromType = From->getType();
3657 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3658
3659 Kind = CK_BitCast;
3660
3661 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3664 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3665 DiagRuntimeBehavior(From->getExprLoc(), From,
3666 PDiag(diag::warn_impcast_bool_to_null_pointer)
3667 << ToType << From->getSourceRange());
3668 else if (!isUnevaluatedContext())
3669 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3670 << ToType << From->getSourceRange();
3671 }
3672 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3673 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3674 QualType FromPointeeType = FromPtrType->getPointeeType(),
3675 ToPointeeType = ToPtrType->getPointeeType();
3676
3677 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3678 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3679 // We must have a derived-to-base conversion. Check an
3680 // ambiguous or inaccessible conversion.
3681 unsigned InaccessibleID = 0;
3682 unsigned AmbiguousID = 0;
3683 if (Diagnose) {
3684 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3685 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3686 }
3688 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3689 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3690 &BasePath, IgnoreBaseAccess))
3691 return true;
3692
3693 // The conversion was successful.
3694 Kind = CK_DerivedToBase;
3695 }
3696
3697 if (Diagnose && !IsCStyleOrFunctionalCast &&
3698 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3699 assert(getLangOpts().MSVCCompat &&
3700 "this should only be possible with MSVCCompat!");
3701 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3702 << From->getSourceRange();
3703 }
3704 }
3705 } else if (const ObjCObjectPointerType *ToPtrType =
3706 ToType->getAs<ObjCObjectPointerType>()) {
3707 if (const ObjCObjectPointerType *FromPtrType =
3708 FromType->getAs<ObjCObjectPointerType>()) {
3709 // Objective-C++ conversions are always okay.
3710 // FIXME: We should have a different class of conversions for the
3711 // Objective-C++ implicit conversions.
3712 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3713 return false;
3714 } else if (FromType->isBlockPointerType()) {
3715 Kind = CK_BlockPointerToObjCPointerCast;
3716 } else {
3717 Kind = CK_CPointerToObjCPointerCast;
3718 }
3719 } else if (ToType->isBlockPointerType()) {
3720 if (!FromType->isBlockPointerType())
3721 Kind = CK_AnyPointerToBlockPointerCast;
3722 }
3723
3724 // We shouldn't fall into this case unless it's valid for other
3725 // reasons.
3727 Kind = CK_NullToPointer;
3728
3729 return false;
3730}
3731
3733 QualType ToType,
3734 bool InOverloadResolution,
3735 QualType &ConvertedType) {
3736 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3737 if (!ToTypePtr)
3738 return false;
3739
3740 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3742 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3744 ConvertedType = ToType;
3745 return true;
3746 }
3747
3748 // Otherwise, both types have to be member pointers.
3749 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3750 if (!FromTypePtr)
3751 return false;
3752
3753 // A pointer to member of B can be converted to a pointer to member of D,
3754 // where D is derived from B (C++ 4.11p2).
3755 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3756 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3757
3758 if (!declaresSameEntity(FromClass, ToClass) &&
3759 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3760 ConvertedType = Context.getMemberPointerType(
3761 FromTypePtr->getPointeeType(), FromTypePtr->getQualifier(), ToClass);
3762 return true;
3763 }
3764
3765 return false;
3766}
3767
3769 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3770 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3771 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3772 // Lock down the inheritance model right now in MS ABI, whether or not the
3773 // pointee types are the same.
3774 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3775 (void)isCompleteType(CheckLoc, FromType);
3776 (void)isCompleteType(CheckLoc, QualType(ToPtrType, 0));
3777 }
3778
3779 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3780 if (!FromPtrType) {
3781 // This must be a null pointer to member pointer conversion
3782 Kind = CK_NullToMemberPointer;
3784 }
3785
3786 // T == T, modulo cv
3788 !Context.hasSameUnqualifiedType(FromPtrType->getPointeeType(),
3789 ToPtrType->getPointeeType()))
3791
3792 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3793 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3794
3795 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3796 const CXXRecordDecl *Cls) {
3797 if (declaresSameEntity(Qual.getAsRecordDecl(), Cls))
3798 PD << Qual;
3799 else
3800 PD << Context.getCanonicalTagType(Cls);
3801 };
3802 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3803 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3804 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3805 return PD;
3806 };
3807
3808 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3810 std::swap(Base, Derived);
3811
3812 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3813 /*DetectVirtual=*/true);
3814 if (!IsDerivedFrom(OpRange.getBegin(), Derived, Base, Paths))
3816
3817 if (Paths.isAmbiguous(Context.getCanonicalTagType(Base))) {
3818 PartialDiagnostic PD = PDiag(diag::err_ambiguous_memptr_conv);
3819 PD << int(Direction);
3820 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3821 Diag(CheckLoc, PD);
3823 }
3824
3825 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3826 PartialDiagnostic PD = PDiag(diag::err_memptr_conv_via_virtual);
3827 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3828 Diag(CheckLoc, PD);
3830 }
3831
3832 // Must be a base to derived member conversion.
3833 BuildBasePathArray(Paths, BasePath);
3835 ? CK_DerivedToBaseMemberPointer
3836 : CK_BaseToDerivedMemberPointer;
3837
3838 if (!IgnoreBaseAccess)
3839 switch (CheckBaseClassAccess(
3840 CheckLoc, Base, Derived, Paths.front(),
3842 ? diag::err_upcast_to_inaccessible_base
3843 : diag::err_downcast_from_inaccessible_base,
3844 [&](PartialDiagnostic &PD) {
3845 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3846 DerivedQual = ToPtrType->getQualifier();
3847 if (Direction == MemberPointerConversionDirection::Upcast)
3848 std::swap(BaseQual, DerivedQual);
3849 DiagCls(PD, DerivedQual, Derived);
3850 DiagCls(PD, BaseQual, Base);
3851 })) {
3853 case Sema::AR_delayed:
3854 case Sema::AR_dependent:
3855 // Optimistically assume that the delayed and dependent cases
3856 // will work out.
3857 break;
3858
3861 }
3862
3864}
3865
3866/// Determine whether the lifetime conversion between the two given
3867/// qualifiers sets is nontrivial.
3869 Qualifiers ToQuals) {
3870 // Converting anything to const __unsafe_unretained is trivial.
3871 if (ToQuals.hasConst() &&
3873 return false;
3874
3875 return true;
3876}
3877
3878/// Perform a single iteration of the loop for checking if a qualification
3879/// conversion is valid.
3880///
3881/// Specifically, check whether any change between the qualifiers of \p
3882/// FromType and \p ToType is permissible, given knowledge about whether every
3883/// outer layer is const-qualified.
3885 bool CStyle, bool IsTopLevel,
3886 bool &PreviousToQualsIncludeConst,
3887 bool &ObjCLifetimeConversion,
3888 const ASTContext &Ctx) {
3889 Qualifiers FromQuals = FromType.getQualifiers();
3890 Qualifiers ToQuals = ToType.getQualifiers();
3891
3892 // Ignore __unaligned qualifier.
3893 FromQuals.removeUnaligned();
3894
3895 // Objective-C ARC:
3896 // Check Objective-C lifetime conversions.
3897 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3898 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3899 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3900 ObjCLifetimeConversion = true;
3901 FromQuals.removeObjCLifetime();
3902 ToQuals.removeObjCLifetime();
3903 } else {
3904 // Qualification conversions cannot cast between different
3905 // Objective-C lifetime qualifiers.
3906 return false;
3907 }
3908 }
3909
3910 // Allow addition/removal of GC attributes but not changing GC attributes.
3911 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3912 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3913 FromQuals.removeObjCGCAttr();
3914 ToQuals.removeObjCGCAttr();
3915 }
3916
3917 // __ptrauth qualifiers must match exactly.
3918 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3919 return false;
3920
3921 // -- for every j > 0, if const is in cv 1,j then const is in cv
3922 // 2,j, and similarly for volatile.
3923 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3924 return false;
3925
3926 // If address spaces mismatch:
3927 // - in top level it is only valid to convert to addr space that is a
3928 // superset in all cases apart from C-style casts where we allow
3929 // conversions between overlapping address spaces.
3930 // - in non-top levels it is not a valid conversion.
3931 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3932 (!IsTopLevel ||
3933 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
3934 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
3935 return false;
3936
3937 // -- if the cv 1,j and cv 2,j are different, then const is in
3938 // every cv for 0 < k < j.
3939 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3940 !PreviousToQualsIncludeConst)
3941 return false;
3942
3943 // The following wording is from C++20, where the result of the conversion
3944 // is T3, not T2.
3945 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3946 // "array of unknown bound of"
3947 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3948 return false;
3949
3950 // -- if the resulting P3,i is different from P1,i [...], then const is
3951 // added to every cv 3_k for 0 < k < i.
3952 if (!CStyle && FromType->isConstantArrayType() &&
3953 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3954 return false;
3955
3956 // Keep track of whether all prior cv-qualifiers in the "to" type
3957 // include const.
3958 PreviousToQualsIncludeConst =
3959 PreviousToQualsIncludeConst && ToQuals.hasConst();
3960 return true;
3961}
3962
3963bool
3965 bool CStyle, bool &ObjCLifetimeConversion) {
3966 FromType = Context.getCanonicalType(FromType);
3967 ToType = Context.getCanonicalType(ToType);
3968 ObjCLifetimeConversion = false;
3969
3970 // If FromType and ToType are the same type, this is not a
3971 // qualification conversion.
3972 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3973 return false;
3974
3975 // (C++ 4.4p4):
3976 // A conversion can add cv-qualifiers at levels other than the first
3977 // in multi-level pointers, subject to the following rules: [...]
3978 bool PreviousToQualsIncludeConst = true;
3979 bool UnwrappedAnyPointer = false;
3980 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3981 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3982 !UnwrappedAnyPointer,
3983 PreviousToQualsIncludeConst,
3984 ObjCLifetimeConversion, getASTContext()))
3985 return false;
3986 UnwrappedAnyPointer = true;
3987 }
3988
3989 // We are left with FromType and ToType being the pointee types
3990 // after unwrapping the original FromType and ToType the same number
3991 // of times. If we unwrapped any pointers, and if FromType and
3992 // ToType have the same unqualified type (since we checked
3993 // qualifiers above), then this is a qualification conversion.
3994 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3995}
3996
3997/// - Determine whether this is a conversion from a scalar type to an
3998/// atomic type.
3999///
4000/// If successful, updates \c SCS's second and third steps in the conversion
4001/// sequence to finish the conversion.
4002static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
4003 bool InOverloadResolution,
4005 bool CStyle) {
4006 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
4007 if (!ToAtomic)
4008 return false;
4009
4011 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
4012 InOverloadResolution, InnerSCS,
4013 CStyle, /*AllowObjCWritebackConversion=*/false))
4014 return false;
4015
4016 SCS.Second = InnerSCS.Second;
4017 SCS.setToType(1, InnerSCS.getToType(1));
4018 SCS.Third = InnerSCS.Third;
4021 SCS.setToType(2, InnerSCS.getToType(2));
4022 return true;
4023}
4024
4026 QualType ToType,
4027 bool InOverloadResolution,
4029 bool CStyle) {
4030 const OverflowBehaviorType *ToOBT = ToType->getAs<OverflowBehaviorType>();
4031 if (!ToOBT)
4032 return false;
4033
4034 // Check for incompatible OBT kinds (e.g., trap vs wrap)
4035 QualType FromType = From->getType();
4036 if (!S.Context.areCompatibleOverflowBehaviorTypes(FromType, ToType))
4037 return false;
4038
4040 if (!IsStandardConversion(S, From, ToOBT->getUnderlyingType(),
4041 InOverloadResolution, InnerSCS, CStyle,
4042 /*AllowObjCWritebackConversion=*/false))
4043 return false;
4044
4045 SCS.Second = InnerSCS.Second;
4046 SCS.setToType(1, InnerSCS.getToType(1));
4047 SCS.Third = InnerSCS.Third;
4050 SCS.setToType(2, InnerSCS.getToType(2));
4051 return true;
4052}
4053
4056 QualType Type) {
4057 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
4058 if (CtorType->getNumParams() > 0) {
4059 QualType FirstArg = CtorType->getParamType(0);
4060 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
4061 return true;
4062 }
4063 return false;
4064}
4065
4066static OverloadingResult
4068 CXXRecordDecl *To,
4070 OverloadCandidateSet &CandidateSet,
4071 bool AllowExplicit) {
4073 for (auto *D : S.LookupConstructors(To)) {
4074 auto Info = getConstructorInfo(D);
4075 if (!Info)
4076 continue;
4077
4078 bool Usable = !Info.Constructor->isInvalidDecl() &&
4079 S.isInitListConstructor(Info.Constructor);
4080 if (Usable) {
4081 bool SuppressUserConversions = false;
4082 if (Info.ConstructorTmpl)
4083 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
4084 /*ExplicitArgs*/ nullptr, From,
4085 CandidateSet, SuppressUserConversions,
4086 /*PartialOverloading*/ false,
4087 AllowExplicit);
4088 else
4089 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
4090 CandidateSet, SuppressUserConversions,
4091 /*PartialOverloading*/ false, AllowExplicit);
4092 }
4093 }
4094
4095 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4096
4098 switch (auto Result =
4099 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4100 case OR_Deleted:
4101 case OR_Success: {
4102 // Record the standard conversion we used and the conversion function.
4104 QualType ThisType = Constructor->getFunctionObjectParameterType();
4105 // Initializer lists don't have conversions as such.
4107 User.HadMultipleCandidates = HadMultipleCandidates;
4109 User.FoundConversionFunction = Best->FoundDecl;
4111 User.After.setFromType(ThisType);
4112 User.After.setAllToTypes(ToType);
4113 return Result;
4114 }
4115
4117 return OR_No_Viable_Function;
4118 case OR_Ambiguous:
4119 return OR_Ambiguous;
4120 }
4121
4122 llvm_unreachable("Invalid OverloadResult!");
4123}
4124
4125/// Determines whether there is a user-defined conversion sequence
4126/// (C++ [over.ics.user]) that converts expression From to the type
4127/// ToType. If such a conversion exists, User will contain the
4128/// user-defined conversion sequence that performs such a conversion
4129/// and this routine will return true. Otherwise, this routine returns
4130/// false and User is unspecified.
4131///
4132/// \param AllowExplicit true if the conversion should consider C++0x
4133/// "explicit" conversion functions as well as non-explicit conversion
4134/// functions (C++0x [class.conv.fct]p2).
4135///
4136/// \param AllowObjCConversionOnExplicit true if the conversion should
4137/// allow an extra Objective-C pointer conversion on uses of explicit
4138/// constructors. Requires \c AllowExplicit to also be set.
4139static OverloadingResult
4142 OverloadCandidateSet &CandidateSet,
4143 AllowedExplicit AllowExplicit,
4144 bool AllowObjCConversionOnExplicit) {
4145 assert(AllowExplicit != AllowedExplicit::None ||
4146 !AllowObjCConversionOnExplicit);
4148
4149 // Whether we will only visit constructors.
4150 bool ConstructorsOnly = false;
4151
4152 // If the type we are conversion to is a class type, enumerate its
4153 // constructors.
4154 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
4155 // C++ [over.match.ctor]p1:
4156 // When objects of class type are direct-initialized (8.5), or
4157 // copy-initialized from an expression of the same or a
4158 // derived class type (8.5), overload resolution selects the
4159 // constructor. [...] For copy-initialization, the candidate
4160 // functions are all the converting constructors (12.3.1) of
4161 // that class. The argument list is the expression-list within
4162 // the parentheses of the initializer.
4163 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
4164 (From->getType()->isRecordType() &&
4165 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
4166 ConstructorsOnly = true;
4167
4168 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
4169 // We're not going to find any constructors.
4170 } else if (auto *ToRecordDecl =
4171 dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
4172 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
4173
4174 Expr **Args = &From;
4175 unsigned NumArgs = 1;
4176 bool ListInitializing = false;
4177 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
4178 // But first, see if there is an init-list-constructor that will work.
4180 S, From, ToType, ToRecordDecl, User, CandidateSet,
4181 AllowExplicit == AllowedExplicit::All);
4183 return Result;
4184 // Never mind.
4185 CandidateSet.clear(
4187
4188 // If we're list-initializing, we pass the individual elements as
4189 // arguments, not the entire list.
4190 Args = InitList->getInits();
4191 NumArgs = InitList->getNumInits();
4192 ListInitializing = true;
4193 }
4194
4195 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
4196 auto Info = getConstructorInfo(D);
4197 if (!Info)
4198 continue;
4199
4200 bool Usable = !Info.Constructor->isInvalidDecl();
4201 if (!ListInitializing)
4202 Usable = Usable && Info.Constructor->isConvertingConstructor(
4203 /*AllowExplicit*/ true);
4204 if (Usable) {
4205 bool SuppressUserConversions = !ConstructorsOnly;
4206 // C++20 [over.best.ics.general]/4.5:
4207 // if the target is the first parameter of a constructor [of class
4208 // X] and the constructor [...] is a candidate by [...] the second
4209 // phase of [over.match.list] when the initializer list has exactly
4210 // one element that is itself an initializer list, [...] and the
4211 // conversion is to X or reference to cv X, user-defined conversion
4212 // sequences are not considered.
4213 if (SuppressUserConversions && ListInitializing) {
4214 SuppressUserConversions =
4215 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
4216 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
4217 ToType);
4218 }
4219 if (Info.ConstructorTmpl)
4221 Info.ConstructorTmpl, Info.FoundDecl,
4222 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
4223 CandidateSet, SuppressUserConversions,
4224 /*PartialOverloading*/ false,
4225 AllowExplicit == AllowedExplicit::All);
4226 else
4227 // Allow one user-defined conversion when user specifies a
4228 // From->ToType conversion via an static cast (c-style, etc).
4229 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4230 llvm::ArrayRef(Args, NumArgs), CandidateSet,
4231 SuppressUserConversions,
4232 /*PartialOverloading*/ false,
4233 AllowExplicit == AllowedExplicit::All);
4234 }
4235 }
4236 }
4237 }
4238
4239 // Enumerate conversion functions, if we're allowed to.
4240 if (ConstructorsOnly || isa<InitListExpr>(From)) {
4241 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
4242 // No conversion functions from incomplete types.
4243 } else if (const RecordType *FromRecordType =
4244 From->getType()->getAsCanonical<RecordType>()) {
4245 if (auto *FromRecordDecl =
4246 dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
4247 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4248 // Add all of the conversion functions as candidates.
4249 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4250 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4251 DeclAccessPair FoundDecl = I.getPair();
4252 NamedDecl *D = FoundDecl.getDecl();
4253 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
4254 if (isa<UsingShadowDecl>(D))
4255 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4256
4257 CXXConversionDecl *Conv;
4258 FunctionTemplateDecl *ConvTemplate;
4259 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
4260 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4261 else
4262 Conv = cast<CXXConversionDecl>(D);
4263
4264 if (ConvTemplate)
4266 ConvTemplate, FoundDecl, ActingContext, From, ToType,
4267 CandidateSet, AllowObjCConversionOnExplicit,
4268 AllowExplicit != AllowedExplicit::None);
4269 else
4270 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
4271 CandidateSet, AllowObjCConversionOnExplicit,
4272 AllowExplicit != AllowedExplicit::None);
4273 }
4274 }
4275 }
4276
4277 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4278
4280 switch (auto Result =
4281 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4282 case OR_Success:
4283 case OR_Deleted:
4284 // Record the standard conversion we used and the conversion function.
4286 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
4287 // C++ [over.ics.user]p1:
4288 // If the user-defined conversion is specified by a
4289 // constructor (12.3.1), the initial standard conversion
4290 // sequence converts the source type to the type required by
4291 // the argument of the constructor.
4292 //
4293 if (isa<InitListExpr>(From)) {
4294 // Initializer lists don't have conversions as such.
4296 User.Before.FromBracedInitList = true;
4297 } else {
4298 if (Best->Conversions[0].isEllipsis())
4299 User.EllipsisConversion = true;
4300 else {
4301 User.Before = Best->Conversions[0].Standard;
4302 User.EllipsisConversion = false;
4303 }
4304 }
4305 User.HadMultipleCandidates = HadMultipleCandidates;
4307 User.FoundConversionFunction = Best->FoundDecl;
4309 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4310 User.After.setAllToTypes(ToType);
4311 return Result;
4312 }
4313 if (CXXConversionDecl *Conversion
4314 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4315
4316 assert(Best->HasFinalConversion);
4317
4318 // C++ [over.ics.user]p1:
4319 //
4320 // [...] If the user-defined conversion is specified by a
4321 // conversion function (12.3.2), the initial standard
4322 // conversion sequence converts the source type to the
4323 // implicit object parameter of the conversion function.
4324 User.Before = Best->Conversions[0].Standard;
4325 User.HadMultipleCandidates = HadMultipleCandidates;
4326 User.ConversionFunction = Conversion;
4327 User.FoundConversionFunction = Best->FoundDecl;
4328 User.EllipsisConversion = false;
4329
4330 // C++ [over.ics.user]p2:
4331 // The second standard conversion sequence converts the
4332 // result of the user-defined conversion to the target type
4333 // for the sequence. Since an implicit conversion sequence
4334 // is an initialization, the special rules for
4335 // initialization by user-defined conversion apply when
4336 // selecting the best user-defined conversion for a
4337 // user-defined conversion sequence (see 13.3.3 and
4338 // 13.3.3.1).
4339 User.After = Best->FinalConversion;
4340 return Result;
4341 }
4342 llvm_unreachable("Not a constructor or conversion function?");
4343
4345 return OR_No_Viable_Function;
4346
4347 case OR_Ambiguous:
4348 return OR_Ambiguous;
4349 }
4350
4351 llvm_unreachable("Invalid OverloadResult!");
4352}
4353
4354bool
4357 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4359 OverloadingResult OvResult =
4360 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4361 CandidateSet, AllowedExplicit::None, false);
4362
4363 if (!(OvResult == OR_Ambiguous ||
4364 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4365 return false;
4366
4367 auto Cands = CandidateSet.CompleteCandidates(
4368 *this,
4370 From);
4371 if (OvResult == OR_Ambiguous)
4372 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4373 << From->getType() << ToType << From->getSourceRange();
4374 else { // OR_No_Viable_Function && !CandidateSet.empty()
4375 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4376 diag::err_typecheck_nonviable_condition_incomplete,
4377 From->getType(), From->getSourceRange()))
4378 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4379 << false << From->getType() << From->getSourceRange() << ToType;
4380 }
4381
4382 CandidateSet.NoteCandidates(
4383 *this, From, Cands);
4384 return true;
4385}
4386
4387// Helper for compareConversionFunctions that gets the FunctionType that the
4388// conversion-operator return value 'points' to, or nullptr.
4389static const FunctionType *
4391 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4392 const PointerType *RetPtrTy =
4393 ConvFuncTy->getReturnType()->getAs<PointerType>();
4394
4395 if (!RetPtrTy)
4396 return nullptr;
4397
4398 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4399}
4400
4401/// Compare the user-defined conversion functions or constructors
4402/// of two user-defined conversion sequences to determine whether any ordering
4403/// is possible.
4406 FunctionDecl *Function2) {
4407 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4408 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4409 if (!Conv1 || !Conv2)
4411
4412 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4414
4415 // Objective-C++:
4416 // If both conversion functions are implicitly-declared conversions from
4417 // a lambda closure type to a function pointer and a block pointer,
4418 // respectively, always prefer the conversion to a function pointer,
4419 // because the function pointer is more lightweight and is more likely
4420 // to keep code working.
4421 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4422 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4423 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4424 if (Block1 != Block2)
4425 return Block1 ? ImplicitConversionSequence::Worse
4427 }
4428
4429 // In order to support multiple calling conventions for the lambda conversion
4430 // operator (such as when the free and member function calling convention is
4431 // different), prefer the 'free' mechanism, followed by the calling-convention
4432 // of operator(). The latter is in place to support the MSVC-like solution of
4433 // defining ALL of the possible conversions in regards to calling-convention.
4434 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4435 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4436
4437 if (Conv1FuncRet && Conv2FuncRet &&
4438 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4439 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4440 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4441
4442 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4443 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4444
4445 CallingConv CallOpCC =
4446 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4448 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4450 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4451
4452 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4453 for (CallingConv CC : PrefOrder) {
4454 if (Conv1CC == CC)
4456 if (Conv2CC == CC)
4458 }
4459 }
4460
4462}
4463
4470
4471/// CompareImplicitConversionSequences - Compare two implicit
4472/// conversion sequences to determine whether one is better than the
4473/// other or if they are indistinguishable (C++ 13.3.3.2).
4476 const ImplicitConversionSequence& ICS1,
4477 const ImplicitConversionSequence& ICS2)
4478{
4479 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4480 // conversion sequences (as defined in 13.3.3.1)
4481 // -- a standard conversion sequence (13.3.3.1.1) is a better
4482 // conversion sequence than a user-defined conversion sequence or
4483 // an ellipsis conversion sequence, and
4484 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4485 // conversion sequence than an ellipsis conversion sequence
4486 // (13.3.3.1.3).
4487 //
4488 // C++0x [over.best.ics]p10:
4489 // For the purpose of ranking implicit conversion sequences as
4490 // described in 13.3.3.2, the ambiguous conversion sequence is
4491 // treated as a user-defined sequence that is indistinguishable
4492 // from any other user-defined conversion sequence.
4493
4494 // String literal to 'char *' conversion has been deprecated in C++03. It has
4495 // been removed from C++11. We still accept this conversion, if it happens at
4496 // the best viable function. Otherwise, this conversion is considered worse
4497 // than ellipsis conversion. Consider this as an extension; this is not in the
4498 // standard. For example:
4499 //
4500 // int &f(...); // #1
4501 // void f(char*); // #2
4502 // void g() { int &r = f("foo"); }
4503 //
4504 // In C++03, we pick #2 as the best viable function.
4505 // In C++11, we pick #1 as the best viable function, because ellipsis
4506 // conversion is better than string-literal to char* conversion (since there
4507 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4508 // convert arguments, #2 would be the best viable function in C++11.
4509 // If the best viable function has this conversion, a warning will be issued
4510 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4511
4512 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4515 // Ill-formedness must not differ
4516 ICS1.isBad() == ICS2.isBad())
4520
4521 if (ICS1.getKindRank() < ICS2.getKindRank())
4523 if (ICS2.getKindRank() < ICS1.getKindRank())
4525
4526 // The following checks require both conversion sequences to be of
4527 // the same kind.
4528 if (ICS1.getKind() != ICS2.getKind())
4530
4533
4534 // Two implicit conversion sequences of the same form are
4535 // indistinguishable conversion sequences unless one of the
4536 // following rules apply: (C++ 13.3.3.2p3):
4537
4538 // List-initialization sequence L1 is a better conversion sequence than
4539 // list-initialization sequence L2 if:
4540 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4541 // if not that,
4542 // — L1 and L2 convert to arrays of the same element type, and either the
4543 // number of elements n_1 initialized by L1 is less than the number of
4544 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4545 // an array of unknown bound and L1 does not,
4546 // even if one of the other rules in this paragraph would otherwise apply.
4547 if (!ICS1.isBad()) {
4548 bool StdInit1 = false, StdInit2 = false;
4551 nullptr);
4554 nullptr);
4555 if (StdInit1 != StdInit2)
4556 return StdInit1 ? ImplicitConversionSequence::Better
4558
4561 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4563 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4565 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4566 CAT2->getElementType())) {
4567 // Both to arrays of the same element type
4568 if (CAT1->getSize() != CAT2->getSize())
4569 // Different sized, the smaller wins
4570 return CAT1->getSize().ult(CAT2->getSize())
4575 // One is incomplete, it loses
4579 }
4580 }
4581 }
4582
4583 if (ICS1.isStandard())
4584 // Standard conversion sequence S1 is a better conversion sequence than
4585 // standard conversion sequence S2 if [...]
4587 ICS1.Standard, ICS2.Standard);
4588 else if (ICS1.isUserDefined()) {
4589 // With lazy template loading, it is possible to find non-canonical
4590 // FunctionDecls, depending on when redecl chains are completed. Make sure
4591 // to compare the canonical decls of conversion functions. This avoids
4592 // ambiguity problems for templated conversion operators.
4593 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4594 if (ConvFunc1)
4595 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4596 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4597 if (ConvFunc2)
4598 ConvFunc2 = ConvFunc2->getCanonicalDecl();
4599 // User-defined conversion sequence U1 is a better conversion
4600 // sequence than another user-defined conversion sequence U2 if
4601 // they contain the same user-defined conversion function or
4602 // constructor and if the second standard conversion sequence of
4603 // U1 is better than the second standard conversion sequence of
4604 // U2 (C++ 13.3.3.2p3).
4605 if (ConvFunc1 == ConvFunc2)
4607 ICS1.UserDefined.After,
4608 ICS2.UserDefined.After);
4609 else
4613 }
4614
4615 return Result;
4616}
4617
4618// Per 13.3.3.2p3, compare the given standard conversion sequences to
4619// determine if one is a proper subset of the other.
4622 const StandardConversionSequence& SCS1,
4623 const StandardConversionSequence& SCS2) {
4626
4627 // the identity conversion sequence is considered to be a subsequence of
4628 // any non-identity conversion sequence
4629 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4631 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4633
4634 if (SCS1.Second != SCS2.Second) {
4635 if (SCS1.Second == ICK_Identity)
4637 else if (SCS2.Second == ICK_Identity)
4639 else
4641 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4643
4644 if (SCS1.Third == SCS2.Third) {
4645 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4647 }
4648
4649 if (SCS1.Third == ICK_Identity)
4653
4654 if (SCS2.Third == ICK_Identity)
4658
4660}
4661
4662/// Determine whether one of the given reference bindings is better
4663/// than the other based on what kind of bindings they are.
4664static bool
4666 const StandardConversionSequence &SCS2) {
4667 // C++0x [over.ics.rank]p3b4:
4668 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4669 // implicit object parameter of a non-static member function declared
4670 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4671 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4672 // lvalue reference to a function lvalue and S2 binds an rvalue
4673 // reference*.
4674 //
4675 // FIXME: Rvalue references. We're going rogue with the above edits,
4676 // because the semantics in the current C++0x working paper (N3225 at the
4677 // time of this writing) break the standard definition of std::forward
4678 // and std::reference_wrapper when dealing with references to functions.
4679 // Proposed wording changes submitted to CWG for consideration.
4682 return false;
4683
4684 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4685 SCS2.IsLvalueReference) ||
4688}
4689
4695
4696/// Returns kind of fixed enum promotion the \a SCS uses.
4697static FixedEnumPromotion
4699
4700 if (SCS.Second != ICK_Integral_Promotion)
4702
4703 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4704 if (!Enum)
4706
4707 if (!Enum->isFixed())
4709
4710 QualType UnderlyingType = Enum->getIntegerType();
4711 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4713
4715}
4716
4717/// CompareStandardConversionSequences - Compare two standard
4718/// conversion sequences to determine whether one is better than the
4719/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4722 const StandardConversionSequence& SCS1,
4723 const StandardConversionSequence& SCS2)
4724{
4725 // Standard conversion sequence S1 is a better conversion sequence
4726 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4727
4728 // -- S1 is a proper subsequence of S2 (comparing the conversion
4729 // sequences in the canonical form defined by 13.3.3.1.1,
4730 // excluding any Lvalue Transformation; the identity conversion
4731 // sequence is considered to be a subsequence of any
4732 // non-identity conversion sequence) or, if not that,
4735 return CK;
4736
4737 // -- the rank of S1 is better than the rank of S2 (by the rules
4738 // defined below), or, if not that,
4739 ImplicitConversionRank Rank1 = SCS1.getRank();
4740 ImplicitConversionRank Rank2 = SCS2.getRank();
4741 if (Rank1 < Rank2)
4743 else if (Rank2 < Rank1)
4745
4746 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4747 // are indistinguishable unless one of the following rules
4748 // applies:
4749
4750 // A conversion that is not a conversion of a pointer, or
4751 // pointer to member, to bool is better than another conversion
4752 // that is such a conversion.
4754 return SCS2.isPointerConversionToBool()
4757
4758 // C++14 [over.ics.rank]p4b2:
4759 // This is retroactively applied to C++11 by CWG 1601.
4760 //
4761 // A conversion that promotes an enumeration whose underlying type is fixed
4762 // to its underlying type is better than one that promotes to the promoted
4763 // underlying type, if the two are different.
4766 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4767 FEP1 != FEP2)
4771
4772 // C++ [over.ics.rank]p4b2:
4773 //
4774 // If class B is derived directly or indirectly from class A,
4775 // conversion of B* to A* is better than conversion of B* to
4776 // void*, and conversion of A* to void* is better than conversion
4777 // of B* to void*.
4778 bool SCS1ConvertsToVoid
4780 bool SCS2ConvertsToVoid
4782 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4783 // Exactly one of the conversion sequences is a conversion to
4784 // a void pointer; it's the worse conversion.
4785 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4787 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4788 // Neither conversion sequence converts to a void pointer; compare
4789 // their derived-to-base conversions.
4791 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4792 return DerivedCK;
4793 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4794 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4795 // Both conversion sequences are conversions to void
4796 // pointers. Compare the source types to determine if there's an
4797 // inheritance relationship in their sources.
4798 QualType FromType1 = SCS1.getFromType();
4799 QualType FromType2 = SCS2.getFromType();
4800
4801 // Adjust the types we're converting from via the array-to-pointer
4802 // conversion, if we need to.
4803 if (SCS1.First == ICK_Array_To_Pointer)
4804 FromType1 = S.Context.getArrayDecayedType(FromType1);
4805 if (SCS2.First == ICK_Array_To_Pointer)
4806 FromType2 = S.Context.getArrayDecayedType(FromType2);
4807
4808 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4809 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4810
4811 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4813 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4815
4816 // Objective-C++: If one interface is more specific than the
4817 // other, it is the better one.
4818 const ObjCObjectPointerType* FromObjCPtr1
4819 = FromType1->getAs<ObjCObjectPointerType>();
4820 const ObjCObjectPointerType* FromObjCPtr2
4821 = FromType2->getAs<ObjCObjectPointerType>();
4822 if (FromObjCPtr1 && FromObjCPtr2) {
4823 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4824 FromObjCPtr2);
4825 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4826 FromObjCPtr1);
4827 if (AssignLeft != AssignRight) {
4828 return AssignLeft? ImplicitConversionSequence::Better
4830 }
4831 }
4832 }
4833
4834 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4835 // Check for a better reference binding based on the kind of bindings.
4836 if (isBetterReferenceBindingKind(SCS1, SCS2))
4838 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4840 }
4841
4842 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4843 // bullet 3).
4845 = CompareQualificationConversions(S, SCS1, SCS2))
4846 return QualCK;
4847
4850 return ObtCK;
4851
4852 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4853 // C++ [over.ics.rank]p3b4:
4854 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4855 // which the references refer are the same type except for
4856 // top-level cv-qualifiers, and the type to which the reference
4857 // initialized by S2 refers is more cv-qualified than the type
4858 // to which the reference initialized by S1 refers.
4859 QualType T1 = SCS1.getToType(2);
4860 QualType T2 = SCS2.getToType(2);
4861 T1 = S.Context.getCanonicalType(T1);
4862 T2 = S.Context.getCanonicalType(T2);
4863 Qualifiers T1Quals, T2Quals;
4864 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4865 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4866 if (UnqualT1 == UnqualT2) {
4867 // Objective-C++ ARC: If the references refer to objects with different
4868 // lifetimes, prefer bindings that don't change lifetime.
4874 }
4875
4876 // If the type is an array type, promote the element qualifiers to the
4877 // type for comparison.
4878 if (isa<ArrayType>(T1) && T1Quals)
4879 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4880 if (isa<ArrayType>(T2) && T2Quals)
4881 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4882 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4884 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4886 }
4887 }
4888
4889 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4890 // floating-to-integral conversion if the integral conversion
4891 // is between types of the same size.
4892 // For example:
4893 // void f(float);
4894 // void f(int);
4895 // int main {
4896 // long a;
4897 // f(a);
4898 // }
4899 // Here, MSVC will call f(int) instead of generating a compile error
4900 // as clang will do in standard mode.
4901 if (S.getLangOpts().MSVCCompat &&
4904 SCS2.Second == ICK_Floating_Integral &&
4905 S.Context.getTypeSize(SCS1.getFromType()) ==
4906 S.Context.getTypeSize(SCS1.getToType(2)))
4908
4909 // Prefer a compatible vector conversion over a lax vector conversion
4910 // For example:
4911 //
4912 // typedef float __v4sf __attribute__((__vector_size__(16)));
4913 // void f(vector float);
4914 // void f(vector signed int);
4915 // int main() {
4916 // __v4sf a;
4917 // f(a);
4918 // }
4919 // Here, we'd like to choose f(vector float) and not
4920 // report an ambiguous call error
4921 if (SCS1.Second == ICK_Vector_Conversion &&
4922 SCS2.Second == ICK_Vector_Conversion) {
4923 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4924 SCS1.getFromType(), SCS1.getToType(2));
4925 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4926 SCS2.getFromType(), SCS2.getToType(2));
4927
4928 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4929 return SCS1IsCompatibleVectorConversion
4932 }
4933
4934 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4936 bool SCS1IsCompatibleSVEVectorConversion =
4937 S.ARM().areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4938 bool SCS2IsCompatibleSVEVectorConversion =
4939 S.ARM().areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4940
4941 if (SCS1IsCompatibleSVEVectorConversion !=
4942 SCS2IsCompatibleSVEVectorConversion)
4943 return SCS1IsCompatibleSVEVectorConversion
4946 }
4947
4948 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4950 bool SCS1IsCompatibleRVVVectorConversion =
4952 bool SCS2IsCompatibleRVVVectorConversion =
4954
4955 if (SCS1IsCompatibleRVVVectorConversion !=
4956 SCS2IsCompatibleRVVVectorConversion)
4957 return SCS1IsCompatibleRVVVectorConversion
4960 }
4962}
4963
4964/// CompareOverflowBehaviorConversions - Compares two standard conversion
4965/// sequences to determine whether they can be ranked based on their
4966/// OverflowBehaviorType's underlying type.
4982
4983/// CompareQualificationConversions - Compares two standard conversion
4984/// sequences to determine whether they can be ranked based on their
4985/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4988 const StandardConversionSequence& SCS1,
4989 const StandardConversionSequence& SCS2) {
4990 // C++ [over.ics.rank]p3:
4991 // -- S1 and S2 differ only in their qualification conversion and
4992 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4993 // [C++98]
4994 // [...] and the cv-qualification signature of type T1 is a proper subset
4995 // of the cv-qualification signature of type T2, and S1 is not the
4996 // deprecated string literal array-to-pointer conversion (4.2).
4997 // [C++2a]
4998 // [...] where T1 can be converted to T2 by a qualification conversion.
4999 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
5000 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
5002
5003 // FIXME: the example in the standard doesn't use a qualification
5004 // conversion (!)
5005 QualType T1 = SCS1.getToType(2);
5006 QualType T2 = SCS2.getToType(2);
5007 T1 = S.Context.getCanonicalType(T1);
5008 T2 = S.Context.getCanonicalType(T2);
5009 assert(!T1->isReferenceType() && !T2->isReferenceType());
5010 Qualifiers T1Quals, T2Quals;
5011 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
5012 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
5013
5014 // If the types are the same, we won't learn anything by unwrapping
5015 // them.
5016 if (UnqualT1 == UnqualT2)
5018
5019 // Don't ever prefer a standard conversion sequence that uses the deprecated
5020 // string literal array to pointer conversion.
5021 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
5022 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
5023
5024 // Objective-C++ ARC:
5025 // Prefer qualification conversions not involving a change in lifetime
5026 // to qualification conversions that do change lifetime.
5029 CanPick1 = false;
5032 CanPick2 = false;
5033
5034 bool ObjCLifetimeConversion;
5035 if (CanPick1 &&
5036 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
5037 CanPick1 = false;
5038 // FIXME: In Objective-C ARC, we can have qualification conversions in both
5039 // directions, so we can't short-cut this second check in general.
5040 if (CanPick2 &&
5041 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
5042 CanPick2 = false;
5043
5044 if (CanPick1 != CanPick2)
5045 return CanPick1 ? ImplicitConversionSequence::Better
5048}
5049
5050/// CompareDerivedToBaseConversions - Compares two standard conversion
5051/// sequences to determine whether they can be ranked based on their
5052/// various kinds of derived-to-base conversions (C++
5053/// [over.ics.rank]p4b3). As part of these checks, we also look at
5054/// conversions between Objective-C interface types.
5057 const StandardConversionSequence& SCS1,
5058 const StandardConversionSequence& SCS2) {
5059 QualType FromType1 = SCS1.getFromType();
5060 QualType ToType1 = SCS1.getToType(1);
5061 QualType FromType2 = SCS2.getFromType();
5062 QualType ToType2 = SCS2.getToType(1);
5063
5064 // Adjust the types we're converting from via the array-to-pointer
5065 // conversion, if we need to.
5066 if (SCS1.First == ICK_Array_To_Pointer)
5067 FromType1 = S.Context.getArrayDecayedType(FromType1);
5068 if (SCS2.First == ICK_Array_To_Pointer)
5069 FromType2 = S.Context.getArrayDecayedType(FromType2);
5070
5071 // Canonicalize all of the types.
5072 FromType1 = S.Context.getCanonicalType(FromType1);
5073 ToType1 = S.Context.getCanonicalType(ToType1);
5074 FromType2 = S.Context.getCanonicalType(FromType2);
5075 ToType2 = S.Context.getCanonicalType(ToType2);
5076
5077 // C++ [over.ics.rank]p4b3:
5078 //
5079 // If class B is derived directly or indirectly from class A and
5080 // class C is derived directly or indirectly from B,
5081 //
5082 // Compare based on pointer conversions.
5083 if (SCS1.Second == ICK_Pointer_Conversion &&
5085 /*FIXME: Remove if Objective-C id conversions get their own rank*/
5086 FromType1->isPointerType() && FromType2->isPointerType() &&
5087 ToType1->isPointerType() && ToType2->isPointerType()) {
5088 QualType FromPointee1 =
5090 QualType ToPointee1 =
5092 QualType FromPointee2 =
5094 QualType ToPointee2 =
5096
5097 // -- conversion of C* to B* is better than conversion of C* to A*,
5098 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5099 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5101 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5103 }
5104
5105 // -- conversion of B* to A* is better than conversion of C* to A*,
5106 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
5107 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5109 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5111 }
5112 } else if (SCS1.Second == ICK_Pointer_Conversion &&
5114 const ObjCObjectPointerType *FromPtr1
5115 = FromType1->getAs<ObjCObjectPointerType>();
5116 const ObjCObjectPointerType *FromPtr2
5117 = FromType2->getAs<ObjCObjectPointerType>();
5118 const ObjCObjectPointerType *ToPtr1
5119 = ToType1->getAs<ObjCObjectPointerType>();
5120 const ObjCObjectPointerType *ToPtr2
5121 = ToType2->getAs<ObjCObjectPointerType>();
5122
5123 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
5124 // Apply the same conversion ranking rules for Objective-C pointer types
5125 // that we do for C++ pointers to class types. However, we employ the
5126 // Objective-C pseudo-subtyping relationship used for assignment of
5127 // Objective-C pointer types.
5128 bool FromAssignLeft
5129 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
5130 bool FromAssignRight
5131 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
5132 bool ToAssignLeft
5133 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
5134 bool ToAssignRight
5135 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
5136
5137 // A conversion to an a non-id object pointer type or qualified 'id'
5138 // type is better than a conversion to 'id'.
5139 if (ToPtr1->isObjCIdType() &&
5140 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
5142 if (ToPtr2->isObjCIdType() &&
5143 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
5145
5146 // A conversion to a non-id object pointer type is better than a
5147 // conversion to a qualified 'id' type
5148 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
5150 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
5152
5153 // A conversion to an a non-Class object pointer type or qualified 'Class'
5154 // type is better than a conversion to 'Class'.
5155 if (ToPtr1->isObjCClassType() &&
5156 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
5158 if (ToPtr2->isObjCClassType() &&
5159 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
5161
5162 // A conversion to a non-Class object pointer type is better than a
5163 // conversion to a qualified 'Class' type.
5164 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
5166 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
5168
5169 // -- "conversion of C* to B* is better than conversion of C* to A*,"
5170 if (S.Context.hasSameType(FromType1, FromType2) &&
5171 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
5172 (ToAssignLeft != ToAssignRight)) {
5173 if (FromPtr1->isSpecialized()) {
5174 // "conversion of B<A> * to B * is better than conversion of B * to
5175 // C *.
5176 bool IsFirstSame =
5177 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
5178 bool IsSecondSame =
5179 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
5180 if (IsFirstSame) {
5181 if (!IsSecondSame)
5183 } else if (IsSecondSame)
5185 }
5186 return ToAssignLeft? ImplicitConversionSequence::Worse
5188 }
5189
5190 // -- "conversion of B* to A* is better than conversion of C* to A*,"
5191 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
5192 (FromAssignLeft != FromAssignRight))
5193 return FromAssignLeft? ImplicitConversionSequence::Better
5195 }
5196 }
5197
5198 // Ranking of member-pointer types.
5199 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
5200 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
5201 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
5202 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
5203 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
5204 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
5205 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
5206 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5207 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5208 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5209 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5210 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5211 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5212 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5214 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5216 }
5217 // conversion of B::* to C::* is better than conversion of A::* to C::*
5218 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5219 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5221 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5223 }
5224 }
5225
5226 if (SCS1.Second == ICK_Derived_To_Base) {
5227 // -- conversion of C to B is better than conversion of C to A,
5228 // -- binding of an expression of type C to a reference of type
5229 // B& is better than binding an expression of type C to a
5230 // reference of type A&,
5231 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5232 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5233 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
5235 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
5237 }
5238
5239 // -- conversion of B to A is better than conversion of C to A.
5240 // -- binding of an expression of type B to a reference of type
5241 // A& is better than binding an expression of type C to a
5242 // reference of type A&,
5243 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5244 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5245 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
5247 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
5249 }
5250 }
5251
5253}
5254
5256 if (!T.getQualifiers().hasUnaligned())
5257 return T;
5258
5259 Qualifiers Q;
5260 T = Ctx.getUnqualifiedArrayType(T, Q);
5261 Q.removeUnaligned();
5262 return Ctx.getQualifiedType(T, Q);
5263}
5264
5267 QualType OrigT1, QualType OrigT2,
5268 ReferenceConversions *ConvOut) {
5269 assert(!OrigT1->isReferenceType() &&
5270 "T1 must be the pointee type of the reference type");
5271 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5272
5273 QualType T1 = Context.getCanonicalType(OrigT1);
5274 QualType T2 = Context.getCanonicalType(OrigT2);
5275 Qualifiers T1Quals, T2Quals;
5276 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
5277 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
5278
5279 ReferenceConversions ConvTmp;
5280 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5281 Conv = ReferenceConversions();
5282
5283 // C++2a [dcl.init.ref]p4:
5284 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5285 // reference-related to "cv2 T2" if T1 is similar to T2, or
5286 // T1 is a base class of T2.
5287 // "cv1 T1" is reference-compatible with "cv2 T2" if
5288 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5289 // "pointer to cv1 T1" via a standard conversion sequence.
5290
5291 // Check for standard conversions we can apply to pointers: derived-to-base
5292 // conversions, ObjC pointer conversions, and function pointer conversions.
5293 // (Qualification conversions are checked last.)
5294 if (UnqualT1 == UnqualT2) {
5295 // Nothing to do.
5296 } else if (isCompleteType(Loc, OrigT2) &&
5297 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
5298 Conv |= ReferenceConversions::DerivedToBase;
5299 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5300 UnqualT2->isObjCObjectOrInterfaceType() &&
5301 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
5302 Conv |= ReferenceConversions::ObjC;
5303 else if (UnqualT2->isFunctionType() &&
5304 IsFunctionConversion(UnqualT2, UnqualT1)) {
5305 Conv |= ReferenceConversions::Function;
5306 // No need to check qualifiers; function types don't have them.
5307 return Ref_Compatible;
5308 }
5309 bool ConvertedReferent = Conv != 0;
5310
5311 // We can have a qualification conversion. Compute whether the types are
5312 // similar at the same time.
5313 bool PreviousToQualsIncludeConst = true;
5314 bool TopLevel = true;
5315 do {
5316 if (T1 == T2)
5317 break;
5318
5319 // We will need a qualification conversion.
5320 Conv |= ReferenceConversions::Qualification;
5321
5322 // Track whether we performed a qualification conversion anywhere other
5323 // than the top level. This matters for ranking reference bindings in
5324 // overload resolution.
5325 if (!TopLevel)
5326 Conv |= ReferenceConversions::NestedQualification;
5327
5328 // MS compiler ignores __unaligned qualifier for references; do the same.
5329 T1 = withoutUnaligned(Context, T1);
5330 T2 = withoutUnaligned(Context, T2);
5331
5332 // If we find a qualifier mismatch, the types are not reference-compatible,
5333 // but are still be reference-related if they're similar.
5334 bool ObjCLifetimeConversion = false;
5335 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5336 PreviousToQualsIncludeConst,
5337 ObjCLifetimeConversion, getASTContext()))
5338 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5339 ? Ref_Related
5341
5342 // FIXME: Should we track this for any level other than the first?
5343 if (ObjCLifetimeConversion)
5344 Conv |= ReferenceConversions::ObjCLifetime;
5345
5346 TopLevel = false;
5347 } while (Context.UnwrapSimilarTypes(T1, T2));
5348
5349 // At this point, if the types are reference-related, we must either have the
5350 // same inner type (ignoring qualifiers), or must have already worked out how
5351 // to convert the referent.
5352 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5355}
5356
5357/// Look for a user-defined conversion to a value reference-compatible
5358/// with DeclType. Return true if something definite is found.
5359static bool
5361 QualType DeclType, SourceLocation DeclLoc,
5362 Expr *Init, QualType T2, bool AllowRvalues,
5363 bool AllowExplicit) {
5364 assert(T2->isRecordType() && "Can only find conversions of record types.");
5365 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5366 OverloadCandidateSet CandidateSet(
5368 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5369 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5370 NamedDecl *D = *I;
5372 if (isa<UsingShadowDecl>(D))
5373 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5374
5375 FunctionTemplateDecl *ConvTemplate
5376 = dyn_cast<FunctionTemplateDecl>(D);
5377 CXXConversionDecl *Conv;
5378 if (ConvTemplate)
5379 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5380 else
5381 Conv = cast<CXXConversionDecl>(D);
5382
5383 if (AllowRvalues) {
5384 // If we are initializing an rvalue reference, don't permit conversion
5385 // functions that return lvalues.
5386 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5387 const ReferenceType *RefType
5389 if (RefType && !RefType->getPointeeType()->isFunctionType())
5390 continue;
5391 }
5392
5393 if (!ConvTemplate &&
5395 DeclLoc,
5396 Conv->getConversionType()
5401 continue;
5402 } else {
5403 // If the conversion function doesn't return a reference type,
5404 // it can't be considered for this conversion. An rvalue reference
5405 // is only acceptable if its referencee is a function type.
5406
5407 const ReferenceType *RefType =
5409 if (!RefType ||
5410 (!RefType->isLValueReferenceType() &&
5411 !RefType->getPointeeType()->isFunctionType()))
5412 continue;
5413 }
5414
5415 if (ConvTemplate)
5417 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5418 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5419 else
5421 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5422 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5423 }
5424
5425 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5426
5428 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5429 case OR_Success:
5430
5431 assert(Best->HasFinalConversion);
5432
5433 // C++ [over.ics.ref]p1:
5434 //
5435 // [...] If the parameter binds directly to the result of
5436 // applying a conversion function to the argument
5437 // expression, the implicit conversion sequence is a
5438 // user-defined conversion sequence (13.3.3.1.2), with the
5439 // second standard conversion sequence either an identity
5440 // conversion or, if the conversion function returns an
5441 // entity of a type that is a derived class of the parameter
5442 // type, a derived-to-base Conversion.
5443 if (!Best->FinalConversion.DirectBinding)
5444 return false;
5445
5446 ICS.setUserDefined();
5447 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5448 ICS.UserDefined.After = Best->FinalConversion;
5449 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5450 ICS.UserDefined.ConversionFunction = Best->Function;
5451 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5452 ICS.UserDefined.EllipsisConversion = false;
5453 assert(ICS.UserDefined.After.ReferenceBinding &&
5455 "Expected a direct reference binding!");
5456 return true;
5457
5458 case OR_Ambiguous:
5459 ICS.setAmbiguous();
5460 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5461 Cand != CandidateSet.end(); ++Cand)
5462 if (Cand->Best)
5463 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5464 return true;
5465
5467 case OR_Deleted:
5468 // There was no suitable conversion, or we found a deleted
5469 // conversion; continue with other checks.
5470 return false;
5471 }
5472
5473 llvm_unreachable("Invalid OverloadResult!");
5474}
5475
5476/// Compute an implicit conversion sequence for reference
5477/// initialization.
5478static ImplicitConversionSequence
5480 SourceLocation DeclLoc,
5481 bool SuppressUserConversions,
5482 bool AllowExplicit) {
5483 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5484
5485 // Most paths end in a failed conversion.
5488
5489 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5490 QualType T2 = Init->getType();
5491
5492 // If the initializer is the address of an overloaded function, try
5493 // to resolve the overloaded function. If all goes well, T2 is the
5494 // type of the resulting function.
5495 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5498 false, Found))
5499 T2 = Fn->getType();
5500 }
5501
5502 // Compute some basic properties of the types and the initializer.
5503 bool isRValRef = DeclType->isRValueReferenceType();
5504 Expr::Classification InitCategory = Init->Classify(S.Context);
5505
5507 Sema::ReferenceCompareResult RefRelationship =
5508 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5509
5510 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5511 ICS.setStandard();
5513 // FIXME: A reference binding can be a function conversion too. We should
5514 // consider that when ordering reference-to-function bindings.
5515 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5517 : (RefConv & Sema::ReferenceConversions::ObjC)
5519 : ICK_Identity;
5521 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5522 // a reference binding that performs a non-top-level qualification
5523 // conversion as a qualification conversion, not as an identity conversion.
5524 ICS.Standard.Third = (RefConv &
5525 Sema::ReferenceConversions::NestedQualification)
5527 : ICK_Identity;
5528 ICS.Standard.setFromType(T2);
5529 ICS.Standard.setToType(0, T2);
5530 ICS.Standard.setToType(1, T1);
5531 ICS.Standard.setToType(2, T1);
5532 ICS.Standard.ReferenceBinding = true;
5533 ICS.Standard.DirectBinding = BindsDirectly;
5534 ICS.Standard.IsLvalueReference = !isRValRef;
5536 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5539 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5540 ICS.Standard.FromBracedInitList = false;
5541 ICS.Standard.CopyConstructor = nullptr;
5543 };
5544
5545 // C++0x [dcl.init.ref]p5:
5546 // A reference to type "cv1 T1" is initialized by an expression
5547 // of type "cv2 T2" as follows:
5548
5549 // -- If reference is an lvalue reference and the initializer expression
5550 if (!isRValRef) {
5551 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5552 // reference-compatible with "cv2 T2," or
5553 //
5554 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5555 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5556 // C++ [over.ics.ref]p1:
5557 // When a parameter of reference type binds directly (8.5.3)
5558 // to an argument expression, the implicit conversion sequence
5559 // is the identity conversion, unless the argument expression
5560 // has a type that is a derived class of the parameter type,
5561 // in which case the implicit conversion sequence is a
5562 // derived-to-base Conversion (13.3.3.1).
5563 SetAsReferenceBinding(/*BindsDirectly=*/true);
5564
5565 // Nothing more to do: the inaccessibility/ambiguity check for
5566 // derived-to-base conversions is suppressed when we're
5567 // computing the implicit conversion sequence (C++
5568 // [over.best.ics]p2).
5569 return ICS;
5570 }
5571
5572 // -- has a class type (i.e., T2 is a class type), where T1 is
5573 // not reference-related to T2, and can be implicitly
5574 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5575 // is reference-compatible with "cv3 T3" 92) (this
5576 // conversion is selected by enumerating the applicable
5577 // conversion functions (13.3.1.6) and choosing the best
5578 // one through overload resolution (13.3)),
5579 if (!SuppressUserConversions && T2->isRecordType() &&
5580 S.isCompleteType(DeclLoc, T2) &&
5581 RefRelationship == Sema::Ref_Incompatible) {
5582 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5583 Init, T2, /*AllowRvalues=*/false,
5584 AllowExplicit))
5585 return ICS;
5586 }
5587 }
5588
5589 // -- Otherwise, the reference shall be an lvalue reference to a
5590 // non-volatile const type (i.e., cv1 shall be const), or the reference
5591 // shall be an rvalue reference.
5592 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5593 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5595 return ICS;
5596 }
5597
5598 // -- If the initializer expression
5599 //
5600 // -- is an xvalue, class prvalue, array prvalue or function
5601 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5602 if (RefRelationship == Sema::Ref_Compatible &&
5603 (InitCategory.isXValue() ||
5604 (InitCategory.isPRValue() &&
5605 (T2->isRecordType() || T2->isArrayType())) ||
5606 (InitCategory.isLValue() && T2->isFunctionType()))) {
5607 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5608 // binding unless we're binding to a class prvalue.
5609 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5610 // allow the use of rvalue references in C++98/03 for the benefit of
5611 // standard library implementors; therefore, we need the xvalue check here.
5612 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5613 !(InitCategory.isPRValue() || T2->isRecordType()));
5614 return ICS;
5615 }
5616
5617 // -- has a class type (i.e., T2 is a class type), where T1 is not
5618 // reference-related to T2, and can be implicitly converted to
5619 // an xvalue, class prvalue, or function lvalue of type
5620 // "cv3 T3", where "cv1 T1" is reference-compatible with
5621 // "cv3 T3",
5622 //
5623 // then the reference is bound to the value of the initializer
5624 // expression in the first case and to the result of the conversion
5625 // in the second case (or, in either case, to an appropriate base
5626 // class subobject).
5627 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5628 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5629 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5630 Init, T2, /*AllowRvalues=*/true,
5631 AllowExplicit)) {
5632 // In the second case, if the reference is an rvalue reference
5633 // and the second standard conversion sequence of the
5634 // user-defined conversion sequence includes an lvalue-to-rvalue
5635 // conversion, the program is ill-formed.
5636 if (ICS.isUserDefined() && isRValRef &&
5639
5640 return ICS;
5641 }
5642
5643 // A temporary of function type cannot be created; don't even try.
5644 if (T1->isFunctionType())
5645 return ICS;
5646
5647 // -- Otherwise, a temporary of type "cv1 T1" is created and
5648 // initialized from the initializer expression using the
5649 // rules for a non-reference copy initialization (8.5). The
5650 // reference is then bound to the temporary. If T1 is
5651 // reference-related to T2, cv1 must be the same
5652 // cv-qualification as, or greater cv-qualification than,
5653 // cv2; otherwise, the program is ill-formed.
5654 if (RefRelationship == Sema::Ref_Related) {
5655 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5656 // we would be reference-compatible or reference-compatible with
5657 // added qualification. But that wasn't the case, so the reference
5658 // initialization fails.
5659 //
5660 // Note that we only want to check address spaces and cvr-qualifiers here.
5661 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5662 Qualifiers T1Quals = T1.getQualifiers();
5663 Qualifiers T2Quals = T2.getQualifiers();
5664 T1Quals.removeObjCGCAttr();
5665 T1Quals.removeObjCLifetime();
5666 T2Quals.removeObjCGCAttr();
5667 T2Quals.removeObjCLifetime();
5668 // MS compiler ignores __unaligned qualifier for references; do the same.
5669 T1Quals.removeUnaligned();
5670 T2Quals.removeUnaligned();
5671 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5672 return ICS;
5673 }
5674
5675 // If at least one of the types is a class type, the types are not
5676 // related, and we aren't allowed any user conversions, the
5677 // reference binding fails. This case is important for breaking
5678 // recursion, since TryImplicitConversion below will attempt to
5679 // create a temporary through the use of a copy constructor.
5680 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5681 (T1->isRecordType() || T2->isRecordType()))
5682 return ICS;
5683
5684 // If T1 is reference-related to T2 and the reference is an rvalue
5685 // reference, the initializer expression shall not be an lvalue.
5686 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5687 Init->Classify(S.Context).isLValue()) {
5689 return ICS;
5690 }
5691
5692 // C++ [over.ics.ref]p2:
5693 // When a parameter of reference type is not bound directly to
5694 // an argument expression, the conversion sequence is the one
5695 // required to convert the argument expression to the
5696 // underlying type of the reference according to
5697 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5698 // to copy-initializing a temporary of the underlying type with
5699 // the argument expression. Any difference in top-level
5700 // cv-qualification is subsumed by the initialization itself
5701 // and does not constitute a conversion.
5702 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5703 AllowedExplicit::None,
5704 /*InOverloadResolution=*/false,
5705 /*CStyle=*/false,
5706 /*AllowObjCWritebackConversion=*/false,
5707 /*AllowObjCConversionOnExplicit=*/false);
5708
5709 // Of course, that's still a reference binding.
5710 if (ICS.isStandard()) {
5711 ICS.Standard.ReferenceBinding = true;
5712 ICS.Standard.IsLvalueReference = !isRValRef;
5713 ICS.Standard.BindsToFunctionLvalue = false;
5714 ICS.Standard.BindsToRvalue = true;
5717 } else if (ICS.isUserDefined()) {
5718 const ReferenceType *LValRefType =
5721
5722 // C++ [over.ics.ref]p3:
5723 // Except for an implicit object parameter, for which see 13.3.1, a
5724 // standard conversion sequence cannot be formed if it requires [...]
5725 // binding an rvalue reference to an lvalue other than a function
5726 // lvalue.
5727 // Note that the function case is not possible here.
5728 if (isRValRef && LValRefType) {
5730 return ICS;
5731 }
5732
5734 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5736 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5740 }
5741
5742 return ICS;
5743}
5744
5745static ImplicitConversionSequence
5746TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5747 bool SuppressUserConversions,
5748 bool InOverloadResolution,
5749 bool AllowObjCWritebackConversion,
5750 bool AllowExplicit = false);
5751
5752/// TryListConversion - Try to copy-initialize a value of type ToType from the
5753/// initializer list From.
5754static ImplicitConversionSequence
5756 bool SuppressUserConversions,
5757 bool InOverloadResolution,
5758 bool AllowObjCWritebackConversion) {
5759 // C++11 [over.ics.list]p1:
5760 // When an argument is an initializer list, it is not an expression and
5761 // special rules apply for converting it to a parameter type.
5762
5764 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5765
5766 // We need a complete type for what follows. With one C++20 exception,
5767 // incomplete types can never be initialized from init lists.
5768 QualType InitTy = ToType;
5769 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5770 if (AT && S.getLangOpts().CPlusPlus20)
5771 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5772 // C++20 allows list initialization of an incomplete array type.
5773 InitTy = IAT->getElementType();
5774 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5775 return Result;
5776
5777 // C++20 [over.ics.list]/2:
5778 // If the initializer list is a designated-initializer-list, a conversion
5779 // is only possible if the parameter has an aggregate type
5780 //
5781 // FIXME: The exception for reference initialization here is not part of the
5782 // language rules, but follow other compilers in adding it as a tentative DR
5783 // resolution.
5784 bool IsDesignatedInit = From->hasDesignatedInit();
5785 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5786 IsDesignatedInit)
5787 return Result;
5788
5789 // Per DR1467 and DR2137:
5790 // If the parameter type is an aggregate class X and the initializer list
5791 // has a single element of type cv U, where U is X or a class derived from
5792 // X, the implicit conversion sequence is the one required to convert the
5793 // element to the parameter type.
5794 //
5795 // Otherwise, if the parameter type is a character array [... ]
5796 // and the initializer list has a single element that is an
5797 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5798 // implicit conversion sequence is the identity conversion.
5799 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5800 if (ToType->isRecordType() && ToType->isAggregateType()) {
5801 QualType InitType = From->getInit(0)->getType();
5802 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5803 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5804 return TryCopyInitialization(S, From->getInit(0), ToType,
5805 SuppressUserConversions,
5806 InOverloadResolution,
5807 AllowObjCWritebackConversion);
5808 }
5809
5810 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5811 InitializedEntity Entity =
5813 /*Consumed=*/false);
5814 if (S.CanPerformCopyInitialization(Entity, From)) {
5815 Result.setStandard();
5816 Result.Standard.setAsIdentityConversion();
5817 Result.Standard.setFromType(ToType);
5818 Result.Standard.setAllToTypes(ToType);
5819 return Result;
5820 }
5821 }
5822 }
5823
5824 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5825 // C++11 [over.ics.list]p2:
5826 // If the parameter type is std::initializer_list<X> or "array of X" and
5827 // all the elements can be implicitly converted to X, the implicit
5828 // conversion sequence is the worst conversion necessary to convert an
5829 // element of the list to X.
5830 //
5831 // C++14 [over.ics.list]p3:
5832 // Otherwise, if the parameter type is "array of N X", if the initializer
5833 // list has exactly N elements or if it has fewer than N elements and X is
5834 // default-constructible, and if all the elements of the initializer list
5835 // can be implicitly converted to X, the implicit conversion sequence is
5836 // the worst conversion necessary to convert an element of the list to X.
5837 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5838 unsigned e = From->getNumInits();
5841 QualType());
5842 QualType ContTy = ToType;
5843 bool IsUnbounded = false;
5844 if (AT) {
5845 InitTy = AT->getElementType();
5846 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5847 if (CT->getSize().ult(e)) {
5848 // Too many inits, fatally bad
5850 ToType);
5851 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5852 return Result;
5853 }
5854 if (CT->getSize().ugt(e)) {
5855 // Need an init from empty {}, is there one?
5856 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5857 From->getEndLoc(), /*isExplicit=*/false);
5858 EmptyList.setType(S.Context.VoidTy);
5859 DfltElt = TryListConversion(
5860 S, &EmptyList, InitTy, SuppressUserConversions,
5861 InOverloadResolution, AllowObjCWritebackConversion);
5862 if (DfltElt.isBad()) {
5863 // No {} init, fatally bad
5865 ToType);
5866 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5867 return Result;
5868 }
5869 }
5870 } else {
5871 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5872 IsUnbounded = true;
5873 if (!e) {
5874 // Cannot convert to zero-sized.
5876 ToType);
5877 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5878 return Result;
5879 }
5880 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5881 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5883 }
5884 }
5885
5886 Result.setStandard();
5887 Result.Standard.setAsIdentityConversion();
5888 Result.Standard.setFromType(InitTy);
5889 Result.Standard.setAllToTypes(InitTy);
5890 for (unsigned i = 0; i < e; ++i) {
5891 Expr *Init = From->getInit(i);
5893 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5894 AllowObjCWritebackConversion);
5895
5896 // Keep the worse conversion seen so far.
5897 // FIXME: Sequences are not totally ordered, so 'worse' can be
5898 // ambiguous. CWG has been informed.
5900 Result) ==
5902 Result = ICS;
5903 // Bail as soon as we find something unconvertible.
5904 if (Result.isBad()) {
5905 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5906 return Result;
5907 }
5908 }
5909 }
5910
5911 // If we needed any implicit {} initialization, compare that now.
5912 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5913 // has been informed that this might not be the best thing.
5914 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5915 S, From->getEndLoc(), DfltElt, Result) ==
5917 Result = DfltElt;
5918 // Record the type being initialized so that we may compare sequences
5919 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5920 return Result;
5921 }
5922
5923 // C++14 [over.ics.list]p4:
5924 // C++11 [over.ics.list]p3:
5925 // Otherwise, if the parameter is a non-aggregate class X and overload
5926 // resolution chooses a single best constructor [...] the implicit
5927 // conversion sequence is a user-defined conversion sequence. If multiple
5928 // constructors are viable but none is better than the others, the
5929 // implicit conversion sequence is a user-defined conversion sequence.
5930 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5931 // This function can deal with initializer lists.
5932 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5933 AllowedExplicit::None,
5934 InOverloadResolution, /*CStyle=*/false,
5935 AllowObjCWritebackConversion,
5936 /*AllowObjCConversionOnExplicit=*/false);
5937 }
5938
5939 // C++14 [over.ics.list]p5:
5940 // C++11 [over.ics.list]p4:
5941 // Otherwise, if the parameter has an aggregate type which can be
5942 // initialized from the initializer list [...] the implicit conversion
5943 // sequence is a user-defined conversion sequence.
5944 if (ToType->isAggregateType()) {
5945 // Type is an aggregate, argument is an init list. At this point it comes
5946 // down to checking whether the initialization works.
5947 // FIXME: Find out whether this parameter is consumed or not.
5948 InitializedEntity Entity =
5950 /*Consumed=*/false);
5952 From)) {
5953 Result.setUserDefined();
5954 Result.UserDefined.Before.setAsIdentityConversion();
5955 // Initializer lists don't have a type.
5956 Result.UserDefined.Before.setFromType(QualType());
5957 Result.UserDefined.Before.setAllToTypes(QualType());
5958
5959 Result.UserDefined.After.setAsIdentityConversion();
5960 Result.UserDefined.After.setFromType(ToType);
5961 Result.UserDefined.After.setAllToTypes(ToType);
5962 Result.UserDefined.ConversionFunction = nullptr;
5963 }
5964 return Result;
5965 }
5966
5967 // C++14 [over.ics.list]p6:
5968 // C++11 [over.ics.list]p5:
5969 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5970 if (ToType->isReferenceType()) {
5971 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5972 // mention initializer lists in any way. So we go by what list-
5973 // initialization would do and try to extrapolate from that.
5974
5975 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5976
5977 // If the initializer list has a single element that is reference-related
5978 // to the parameter type, we initialize the reference from that.
5979 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5980 Expr *Init = From->getInit(0);
5981
5982 QualType T2 = Init->getType();
5983
5984 // If the initializer is the address of an overloaded function, try
5985 // to resolve the overloaded function. If all goes well, T2 is the
5986 // type of the resulting function.
5987 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5990 Init, ToType, false, Found))
5991 T2 = Fn->getType();
5992 }
5993
5994 // Compute some basic properties of the types and the initializer.
5995 Sema::ReferenceCompareResult RefRelationship =
5996 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5997
5998 if (RefRelationship >= Sema::Ref_Related) {
5999 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
6000 SuppressUserConversions,
6001 /*AllowExplicit=*/false);
6002 }
6003 }
6004
6005 // Otherwise, we bind the reference to a temporary created from the
6006 // initializer list.
6007 Result = TryListConversion(S, From, T1, SuppressUserConversions,
6008 InOverloadResolution,
6009 AllowObjCWritebackConversion);
6010 if (Result.isFailure())
6011 return Result;
6012 assert(!Result.isEllipsis() &&
6013 "Sub-initialization cannot result in ellipsis conversion.");
6014
6015 // Can we even bind to a temporary?
6016 if (ToType->isRValueReferenceType() ||
6017 (T1.isConstQualified() && !T1.isVolatileQualified())) {
6018 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
6019 Result.UserDefined.After;
6020 SCS.ReferenceBinding = true;
6022 SCS.BindsToRvalue = true;
6023 SCS.BindsToFunctionLvalue = false;
6026 SCS.FromBracedInitList = false;
6027
6028 } else
6030 From, ToType);
6031 return Result;
6032 }
6033
6034 // C++14 [over.ics.list]p7:
6035 // C++11 [over.ics.list]p6:
6036 // Otherwise, if the parameter type is not a class:
6037 if (!ToType->isRecordType()) {
6038 // - if the initializer list has one element that is not itself an
6039 // initializer list, the implicit conversion sequence is the one
6040 // required to convert the element to the parameter type.
6041 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
6042 // single integer.
6043 unsigned NumInits = From->getNumInits();
6044 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)) &&
6045 !isa<EmbedExpr>(From->getInit(0))) {
6047 S, From->getInit(0), ToType, SuppressUserConversions,
6048 InOverloadResolution, AllowObjCWritebackConversion);
6049 if (Result.isStandard())
6050 Result.Standard.FromBracedInitList = true;
6051 }
6052 // - if the initializer list has no elements, the implicit conversion
6053 // sequence is the identity conversion.
6054 else if (NumInits == 0) {
6055 Result.setStandard();
6056 Result.Standard.setAsIdentityConversion();
6057 Result.Standard.setFromType(ToType);
6058 Result.Standard.setAllToTypes(ToType);
6059 }
6060 return Result;
6061 }
6062
6063 // C++14 [over.ics.list]p8:
6064 // C++11 [over.ics.list]p7:
6065 // In all cases other than those enumerated above, no conversion is possible
6066 return Result;
6067}
6068
6069/// TryCopyInitialization - Try to copy-initialize a value of type
6070/// ToType from the expression From. Return the implicit conversion
6071/// sequence required to pass this argument, which may be a bad
6072/// conversion sequence (meaning that the argument cannot be passed to
6073/// a parameter of this type). If @p SuppressUserConversions, then we
6074/// do not permit any user-defined conversion sequences.
6075static ImplicitConversionSequence
6077 bool SuppressUserConversions,
6078 bool InOverloadResolution,
6079 bool AllowObjCWritebackConversion,
6080 bool AllowExplicit) {
6081 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
6082 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
6083 InOverloadResolution,AllowObjCWritebackConversion);
6084
6085 if (ToType->isReferenceType())
6086 return TryReferenceInit(S, From, ToType,
6087 /*FIXME:*/ From->getBeginLoc(),
6088 SuppressUserConversions, AllowExplicit);
6089
6090 return TryImplicitConversion(S, From, ToType,
6091 SuppressUserConversions,
6092 AllowedExplicit::None,
6093 InOverloadResolution,
6094 /*CStyle=*/false,
6095 AllowObjCWritebackConversion,
6096 /*AllowObjCConversionOnExplicit=*/false);
6097}
6098
6099static bool TryCopyInitialization(const CanQualType FromQTy,
6100 const CanQualType ToQTy,
6101 Sema &S,
6102 SourceLocation Loc,
6103 ExprValueKind FromVK) {
6104 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
6106 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
6107
6108 return !ICS.isBad();
6109}
6110
6111/// TryObjectArgumentInitialization - Try to initialize the object
6112/// parameter of the given member function (@c Method) from the
6113/// expression @p From.
6115 Sema &S, SourceLocation Loc, QualType FromType,
6116 Expr::Classification FromClassification, CXXMethodDecl *Method,
6117 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
6118 QualType ExplicitParameterType = QualType(),
6119 bool SuppressUserConversion = false) {
6120
6121 // We need to have an object of class type.
6122 if (const auto *PT = FromType->getAs<PointerType>()) {
6123 FromType = PT->getPointeeType();
6124
6125 // When we had a pointer, it's implicitly dereferenced, so we
6126 // better have an lvalue.
6127 assert(FromClassification.isLValue());
6128 }
6129
6130 auto ValueKindFromClassification = [](Expr::Classification C) {
6131 if (C.isPRValue())
6132 return clang::VK_PRValue;
6133 if (C.isXValue())
6134 return VK_XValue;
6135 return clang::VK_LValue;
6136 };
6137
6138 if (Method->isExplicitObjectMemberFunction()) {
6139 if (ExplicitParameterType.isNull())
6140 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
6141 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
6142 ValueKindFromClassification(FromClassification));
6144 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
6145 /*InOverloadResolution=*/true, false);
6146 if (ICS.isBad())
6147 ICS.Bad.FromExpr = nullptr;
6148 return ICS;
6149 }
6150
6151 assert(FromType->isRecordType());
6152
6153 CanQualType ClassType = S.Context.getCanonicalTagType(ActingContext);
6154 // C++98 [class.dtor]p2:
6155 // A destructor can be invoked for a const, volatile or const volatile
6156 // object.
6157 // C++98 [over.match.funcs]p4:
6158 // For static member functions, the implicit object parameter is considered
6159 // to match any object (since if the function is selected, the object is
6160 // discarded).
6161 Qualifiers Quals = Method->getMethodQualifiers();
6162 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
6163 Quals.addConst();
6164 Quals.addVolatile();
6165 }
6166
6167 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
6168
6169 // Set up the conversion sequence as a "bad" conversion, to allow us
6170 // to exit early.
6172
6173 // C++0x [over.match.funcs]p4:
6174 // For non-static member functions, the type of the implicit object
6175 // parameter is
6176 //
6177 // - "lvalue reference to cv X" for functions declared without a
6178 // ref-qualifier or with the & ref-qualifier
6179 // - "rvalue reference to cv X" for functions declared with the &&
6180 // ref-qualifier
6181 //
6182 // where X is the class of which the function is a member and cv is the
6183 // cv-qualification on the member function declaration.
6184 //
6185 // However, when finding an implicit conversion sequence for the argument, we
6186 // are not allowed to perform user-defined conversions
6187 // (C++ [over.match.funcs]p5). We perform a simplified version of
6188 // reference binding here, that allows class rvalues to bind to
6189 // non-constant references.
6190
6191 // First check the qualifiers.
6192 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
6193 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
6194 if (ImplicitParamType.getCVRQualifiers() !=
6195 FromTypeCanon.getLocalCVRQualifiers() &&
6196 !ImplicitParamType.isAtLeastAsQualifiedAs(
6197 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
6199 FromType, ImplicitParamType);
6200 return ICS;
6201 }
6202
6203 if (FromTypeCanon.hasAddressSpace()) {
6204 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
6205 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6206 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
6207 S.getASTContext())) {
6209 FromType, ImplicitParamType);
6210 return ICS;
6211 }
6212 }
6213
6214 // Check that we have either the same type or a derived type. It
6215 // affects the conversion rank.
6216 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
6217 ImplicitConversionKind SecondKind;
6218 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6219 SecondKind = ICK_Identity;
6220 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
6221 SecondKind = ICK_Derived_To_Base;
6222 } else if (!Method->isExplicitObjectMemberFunction()) {
6224 FromType, ImplicitParamType);
6225 return ICS;
6226 }
6227
6228 // Check the ref-qualifier.
6229 switch (Method->getRefQualifier()) {
6230 case RQ_None:
6231 // Do nothing; we don't care about lvalueness or rvalueness.
6232 break;
6233
6234 case RQ_LValue:
6235 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6236 // non-const lvalue reference cannot bind to an rvalue
6238 ImplicitParamType);
6239 return ICS;
6240 }
6241 break;
6242
6243 case RQ_RValue:
6244 if (!FromClassification.isRValue()) {
6245 // rvalue reference cannot bind to an lvalue
6247 ImplicitParamType);
6248 return ICS;
6249 }
6250 break;
6251 }
6252
6253 // Success. Mark this as a reference binding.
6254 ICS.setStandard();
6256 ICS.Standard.Second = SecondKind;
6257 ICS.Standard.setFromType(FromType);
6258 ICS.Standard.setAllToTypes(ImplicitParamType);
6259 ICS.Standard.ReferenceBinding = true;
6260 ICS.Standard.DirectBinding = true;
6261 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6262 ICS.Standard.BindsToFunctionLvalue = false;
6263 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6264 ICS.Standard.FromBracedInitList = false;
6266 = (Method->getRefQualifier() == RQ_None);
6267 return ICS;
6268}
6269
6270/// PerformObjectArgumentInitialization - Perform initialization of
6271/// the implicit object parameter for the given Method with the given
6272/// expression.
6274 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6276 QualType FromRecordType, DestType;
6277 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6278
6279 if (getLangOpts().HLSL &&
6282 From = ImplicitCastExpr::Create(Context, CastType, CK_LValueToRValue, From,
6283 /*BasePath=*/nullptr, VK_PRValue,
6285 }
6286
6287 Expr::Classification FromClassification;
6288 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6289 FromRecordType = PT->getPointeeType();
6290 DestType = Method->getThisType();
6291 FromClassification = Expr::Classification::makeSimpleLValue();
6292 } else {
6293 FromRecordType = From->getType();
6294 DestType = ImplicitParamRecordType;
6295 FromClassification = From->Classify(Context);
6296
6297 // CWG2813 [expr.call]p6:
6298 // If the function is an implicit object member function, the object
6299 // expression of the class member access shall be a glvalue [...]
6300 if (From->isPRValue()) {
6301 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
6302 Method->getRefQualifier() !=
6304 }
6305 }
6306
6307 // Note that we always use the true parent context when performing
6308 // the actual argument initialization.
6310 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
6311 Method->getParent());
6312 if (ICS.isBad()) {
6313 switch (ICS.Bad.Kind) {
6315 Qualifiers FromQs = FromRecordType.getQualifiers();
6316 Qualifiers ToQs = DestType.getQualifiers();
6317 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6318 if (CVR) {
6319 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
6320 << Method->getDeclName() << FromRecordType << (CVR - 1)
6321 << From->getSourceRange();
6322 Diag(Method->getLocation(), diag::note_previous_decl)
6323 << Method->getDeclName();
6324 return ExprError();
6325 }
6326 break;
6327 }
6328
6331 bool IsRValueQualified =
6332 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6333 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
6334 << Method->getDeclName() << FromClassification.isRValue()
6335 << IsRValueQualified;
6336 Diag(Method->getLocation(), diag::note_previous_decl)
6337 << Method->getDeclName();
6338 return ExprError();
6339 }
6340
6343 break;
6344
6347 llvm_unreachable("Lists are not objects");
6348 }
6349
6350 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
6351 << ImplicitParamRecordType << FromRecordType
6352 << From->getSourceRange();
6353 }
6354
6355 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6356 ExprResult FromRes =
6357 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6358 if (FromRes.isInvalid())
6359 return ExprError();
6360 From = FromRes.get();
6361 }
6362
6363 if (!Context.hasSameType(From->getType(), DestType)) {
6364 CastKind CK;
6365 QualType PteeTy = DestType->getPointeeType();
6366 LangAS DestAS =
6367 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6368 if (FromRecordType.getAddressSpace() != DestAS)
6369 CK = CK_AddressSpaceConversion;
6370 else
6371 CK = CK_NoOp;
6372 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6373 }
6374 return From;
6375}
6376
6377/// TryContextuallyConvertToBool - Attempt to contextually convert the
6378/// expression From to bool (C++0x [conv]p3).
6381 // C++ [dcl.init]/17.8:
6382 // - Otherwise, if the initialization is direct-initialization, the source
6383 // type is std::nullptr_t, and the destination type is bool, the initial
6384 // value of the object being initialized is false.
6385 if (From->getType()->isNullPtrType())
6387 S.Context.BoolTy,
6388 From->isGLValue());
6389
6390 // All other direct-initialization of bool is equivalent to an implicit
6391 // conversion to bool in which explicit conversions are permitted.
6392 return TryImplicitConversion(S, From, S.Context.BoolTy,
6393 /*SuppressUserConversions=*/false,
6394 AllowedExplicit::Conversions,
6395 /*InOverloadResolution=*/false,
6396 /*CStyle=*/false,
6397 /*AllowObjCWritebackConversion=*/false,
6398 /*AllowObjCConversionOnExplicit=*/false);
6399}
6400
6402 if (checkPlaceholderForOverload(*this, From))
6403 return ExprError();
6404 if (From->getType() == Context.AMDGPUFeaturePredicateTy)
6405 return AMDGPU().ExpandAMDGPUPredicateBuiltIn(From);
6406
6408 if (!ICS.isBad())
6409 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6412 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6413 << From->getType() << From->getSourceRange();
6414 return ExprError();
6415}
6416
6417/// Check that the specified conversion is permitted in a converted constant
6418/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6419/// is acceptable.
6422 // Since we know that the target type is an integral or unscoped enumeration
6423 // type, most conversion kinds are impossible. All possible First and Third
6424 // conversions are fine.
6425 switch (SCS.Second) {
6426 case ICK_Identity:
6428 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6430 return true;
6431
6433 // Conversion from an integral or unscoped enumeration type to bool is
6434 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6435 // conversion, so we allow it in a converted constant expression.
6436 //
6437 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6438 // a lot of popular code. We should at least add a warning for this
6439 // (non-conforming) extension.
6441 SCS.getToType(2)->isBooleanType();
6442
6444 case ICK_Pointer_Member:
6445 // C++1z: null pointer conversions and null member pointer conversions are
6446 // only permitted if the source type is std::nullptr_t.
6447 return SCS.getFromType()->isNullPtrType();
6448
6461 case ICK_Vector_Splat:
6462 case ICK_Complex_Real:
6472 return false;
6473
6478 llvm_unreachable("found a first conversion kind in Second");
6479
6481 case ICK_Qualification:
6482 llvm_unreachable("found a third conversion kind in Second");
6483
6485 break;
6486 }
6487
6488 llvm_unreachable("unknown conversion kind");
6489}
6490
6491/// BuildConvertedConstantExpression - Check that the expression From is a
6492/// converted constant expression of type T, perform the conversion but
6493/// does not evaluate the expression
6495 QualType T, CCEKind CCE,
6496 NamedDecl *Dest,
6497 APValue &PreNarrowingValue) {
6498 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6500 CCE == CCEKind::PackIndex);
6501 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6502 "converted constant expression outside C++11 or TTP matching");
6503
6504 if (checkPlaceholderForOverload(S, From))
6505 return ExprError();
6506
6507 if (From->containsErrors()) {
6508 if (S.Context.hasSameType(From->getType(), T))
6509 return From;
6510
6511 // The expression already has errors, so the correct cast kind can't be
6512 // determined. Use RecoveryExpr to keep the expected type T and mark the
6513 // result as invalid, preventing further cascading errors.
6514 return S.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(), {From},
6515 T);
6516 }
6517
6518 // C++1z [expr.const]p3:
6519 // A converted constant expression of type T is an expression,
6520 // implicitly converted to type T, where the converted
6521 // expression is a constant expression and the implicit conversion
6522 // sequence contains only [... list of conversions ...].
6524 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6526 : TryCopyInitialization(S, From, T,
6527 /*SuppressUserConversions=*/false,
6528 /*InOverloadResolution=*/false,
6529 /*AllowObjCWritebackConversion=*/false,
6530 /*AllowExplicit=*/false);
6531 StandardConversionSequence *SCS = nullptr;
6532 switch (ICS.getKind()) {
6534 SCS = &ICS.Standard;
6535 break;
6537 if (T->isRecordType())
6538 SCS = &ICS.UserDefined.Before;
6539 else
6540 SCS = &ICS.UserDefined.After;
6541 break;
6545 return S.Diag(From->getBeginLoc(),
6546 diag::err_typecheck_converted_constant_expression)
6547 << From->getType() << From->getSourceRange() << T;
6548 return ExprError();
6549
6552 llvm_unreachable("bad conversion in converted constant expression");
6553 }
6554
6555 // Check that we would only use permitted conversions.
6556 if (!CheckConvertedConstantConversions(S, *SCS)) {
6557 return S.Diag(From->getBeginLoc(),
6558 diag::err_typecheck_converted_constant_expression_disallowed)
6559 << From->getType() << From->getSourceRange() << T;
6560 }
6561 // [...] and where the reference binding (if any) binds directly.
6562 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6563 return S.Diag(From->getBeginLoc(),
6564 diag::err_typecheck_converted_constant_expression_indirect)
6565 << From->getType() << From->getSourceRange() << T;
6566 }
6567 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6568 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6569 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6570 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6571 // case explicitly.
6572 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6573 return S.Diag(From->getBeginLoc(),
6574 diag::err_reference_bind_to_bitfield_in_cce)
6575 << From->getSourceRange();
6576 }
6577
6578 // Usually we can simply apply the ImplicitConversionSequence we formed
6579 // earlier, but that's not guaranteed to work when initializing an object of
6580 // class type.
6582 bool IsTemplateArgument =
6584 if (T->isRecordType()) {
6585 assert(IsTemplateArgument &&
6586 "unexpected class type converted constant expr");
6590 SourceLocation(), From);
6591 } else {
6592 Result =
6594 }
6595 if (Result.isInvalid())
6596 return Result;
6597
6598 // C++2a [intro.execution]p5:
6599 // A full-expression is [...] a constant-expression [...]
6600 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6601 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6602 IsTemplateArgument);
6603 if (Result.isInvalid())
6604 return Result;
6605
6606 bool AllowRelaxedEval = S.getASTContext().getLangOpts().MSVCCompat;
6607
6608 // Check for a narrowing implicit conversion.
6609 bool ReturnPreNarrowingValue = false;
6610 QualType PreNarrowingType;
6611 switch (SCS->getNarrowingKind(
6612 S.Context, Result.get(), PreNarrowingValue, PreNarrowingType,
6613 /*IgnoreFloatToIntegralConversion*/ false, AllowRelaxedEval)) {
6615 // Implicit conversion to a narrower type, and the value is not a constant
6616 // expression. We'll diagnose this in a moment.
6617 case NK_Not_Narrowing:
6618 break;
6619
6621 if (CCE == CCEKind::ArrayBound &&
6622 PreNarrowingType->isIntegralOrEnumerationType() &&
6623 PreNarrowingValue.isInt()) {
6624 // Don't diagnose array bound narrowing here; we produce more precise
6625 // errors by allowing the un-narrowed value through.
6626 ReturnPreNarrowingValue = true;
6627 break;
6628 }
6629 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6630 << CCE << /*Constant*/ 1
6631 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6632 // If this is an SFINAE Context, treat the result as invalid so it stops
6633 // substitution at this point, respecting C++26 [temp.deduct.general]p7.
6634 // FIXME: Should do this whenever the above diagnostic is an error, but
6635 // without further changes this would degrade some other diagnostics.
6636 if (S.isSFINAEContext())
6637 return ExprError();
6638 break;
6639
6641 // Implicit conversion to a narrower type, but the expression is
6642 // value-dependent so we can't tell whether it's actually narrowing.
6643 // For matching the parameters of a TTP, the conversion is ill-formed
6644 // if it may narrow.
6645 if (CCE != CCEKind::TempArgStrict)
6646 break;
6647 [[fallthrough]];
6648 case NK_Type_Narrowing:
6649 // FIXME: It would be better to diagnose that the expression is not a
6650 // constant expression.
6651 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6652 << CCE << /*Constant*/ 0 << From->getType() << T;
6653 if (S.isSFINAEContext())
6654 return ExprError();
6655 break;
6656 }
6657 if (!ReturnPreNarrowingValue)
6658 PreNarrowingValue = {};
6659
6660 return Result;
6661}
6662
6663/// CheckConvertedConstantExpression - Check that the expression From is a
6664/// converted constant expression of type T, perform the conversion and produce
6665/// the converted expression, per C++11 [expr.const]p3.
6668 CCEKind CCE, bool RequireInt,
6669 NamedDecl *Dest) {
6670
6671 APValue PreNarrowingValue;
6673 PreNarrowingValue);
6674 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6675 Value = APValue();
6676 return Result;
6677 }
6678 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6679 RequireInt, PreNarrowingValue);
6680}
6681
6683 CCEKind CCE,
6684 NamedDecl *Dest) {
6685 APValue PreNarrowingValue;
6686 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6687 PreNarrowingValue);
6688}
6689
6691 APValue &Value, CCEKind CCE,
6692 NamedDecl *Dest) {
6693 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6694 Dest);
6695}
6696
6698 llvm::APSInt &Value,
6699 CCEKind CCE) {
6700 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6701
6702 APValue V;
6703 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6704 /*Dest=*/nullptr);
6705 if (!R.isInvalid() && !R.get()->isValueDependent())
6706 Value = V.getInt();
6707 return R;
6708}
6709
6712 CCEKind CCE, bool RequireInt,
6713 const APValue &PreNarrowingValue) {
6714
6715 ExprResult Result = E;
6716 // Check the expression is a constant expression.
6719 Expr::EvalResult Eval;
6720 Eval.Diag = &Notes;
6721 Eval.ExtendedDiag = &MSWarning;
6722
6723 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6724
6725 ConstantExprKind Kind;
6726 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6727 Kind = ConstantExprKind::ClassTemplateArgument;
6728 else if (CCE == CCEKind::TemplateArg)
6729 Kind = ConstantExprKind::NonClassTemplateArgument;
6730 else
6731 Kind = ConstantExprKind::Normal;
6732
6733 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6734 (RequireInt && !Eval.Val.isInt())) {
6735 // The expression can't be folded, so we can't keep it at this position in
6736 // the AST.
6737 Result = ExprError();
6738 } else {
6739 Value = Eval.Val;
6740 // For -fms-compatibility mode we relax some requirements
6741 // for constant folding in non-SFINAE contexts
6742 bool CantFold = isSFINAEContext() && !MSWarning.empty();
6743 if (Notes.empty() && !CantFold) {
6744 for (auto &Info : MSWarning)
6745 Diag(Info.first, Info.second);
6746 // It's a constant expression.
6747 Expr *E = Result.get();
6748 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6749 // We expect a ConstantExpr to have a value associated with it
6750 // by this point.
6751 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6752 "ConstantExpr has no value associated with it");
6753 (void)CE;
6754 } else {
6756 }
6757 if (!PreNarrowingValue.isAbsent())
6758 Value = std::move(PreNarrowingValue);
6759 return E;
6760 }
6761 }
6762
6763 // It's not a constant expression. Produce an appropriate diagnostic.
6764 if (Notes.size() == 1 &&
6765 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6766 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6767 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6768 diag::note_constexpr_invalid_template_arg) {
6769 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6770 for (unsigned I = 0; I < Notes.size(); ++I)
6771 Diag(Notes[I].first, Notes[I].second);
6772 } else {
6773 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6774 << CCE << E->getSourceRange();
6775 for (unsigned I = 0; I < Notes.size(); ++I)
6776 Diag(Notes[I].first, Notes[I].second);
6777 }
6778 return ExprError();
6779}
6780
6781/// dropPointerConversions - If the given standard conversion sequence
6782/// involves any pointer conversions, remove them. This may change
6783/// the result type of the conversion sequence.
6785 if (SCS.Second == ICK_Pointer_Conversion) {
6786 SCS.Second = ICK_Identity;
6787 SCS.Dimension = ICK_Identity;
6788 SCS.Third = ICK_Identity;
6789 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6790 }
6791}
6792
6793/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6794/// convert the expression From to an Objective-C pointer type.
6795static ImplicitConversionSequence
6797 // Do an implicit conversion to 'id'.
6800 = TryImplicitConversion(S, From, Ty,
6801 // FIXME: Are these flags correct?
6802 /*SuppressUserConversions=*/false,
6803 AllowedExplicit::Conversions,
6804 /*InOverloadResolution=*/false,
6805 /*CStyle=*/false,
6806 /*AllowObjCWritebackConversion=*/false,
6807 /*AllowObjCConversionOnExplicit=*/true);
6808
6809 // Strip off any final conversions to 'id'.
6810 switch (ICS.getKind()) {
6815 break;
6816
6819 break;
6820
6823 break;
6824 }
6825
6826 return ICS;
6827}
6828
6830 if (checkPlaceholderForOverload(*this, From))
6831 return ExprError();
6832
6833 QualType Ty = Context.getObjCIdType();
6836 if (!ICS.isBad())
6837 return PerformImplicitConversion(From, Ty, ICS,
6839 return ExprResult();
6840}
6841
6842static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6843 const Expr *Base = nullptr;
6844 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6845 "expected a member expression");
6846
6847 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6848 M && !M->isImplicitAccess())
6849 Base = M->getBase();
6850 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6851 M && !M->isImplicitAccess())
6852 Base = M->getBase();
6853
6854 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6855
6856 if (T->isPointerType())
6857 T = T->getPointeeType();
6858
6859 return T;
6860}
6861
6863 const FunctionDecl *Fun) {
6864 QualType ObjType = Obj->getType();
6865 if (ObjType->isPointerType()) {
6866 ObjType = ObjType->getPointeeType();
6867 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6869 /*CanOverflow=*/false, FPOptionsOverride());
6870 }
6871 return Obj;
6872}
6873
6881
6883 Expr *Object, MultiExprArg &Args,
6884 SmallVectorImpl<Expr *> &NewArgs) {
6885 assert(Method->isExplicitObjectMemberFunction() &&
6886 "Method is not an explicit member function");
6887 assert(NewArgs.empty() && "NewArgs should be empty");
6888
6889 NewArgs.reserve(Args.size() + 1);
6890 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6891 NewArgs.push_back(This);
6892 NewArgs.append(Args.begin(), Args.end());
6893 Args = NewArgs;
6895 Method, Object->getBeginLoc());
6896}
6897
6898/// Determine whether the provided type is an integral type, or an enumeration
6899/// type of a permitted flavor.
6901 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6902 : T->isIntegralOrUnscopedEnumerationType();
6903}
6904
6905static ExprResult
6908 QualType T, UnresolvedSetImpl &ViableConversions) {
6909
6910 if (Converter.Suppress)
6911 return ExprError();
6912
6913 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6914 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6915 CXXConversionDecl *Conv =
6916 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6918 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6919 }
6920 return From;
6921}
6922
6923static bool
6926 QualType T, bool HadMultipleCandidates,
6927 UnresolvedSetImpl &ExplicitConversions) {
6928 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6929 DeclAccessPair Found = ExplicitConversions[0];
6930 CXXConversionDecl *Conversion =
6931 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6932
6933 // The user probably meant to invoke the given explicit
6934 // conversion; use it.
6935 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6936 std::string TypeStr;
6937 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6938
6939 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6941 "static_cast<" + TypeStr + ">(")
6943 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6944 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6945
6946 // If we aren't in a SFINAE context, build a call to the
6947 // explicit conversion function.
6948 if (SemaRef.isSFINAEContext())
6949 return true;
6950
6951 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6952 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6953 HadMultipleCandidates);
6954 if (Result.isInvalid())
6955 return true;
6956
6957 // Replace the conversion with a RecoveryExpr, so we don't try to
6958 // instantiate it later, but can further diagnose here.
6959 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6960 From, Result.get()->getType());
6961 if (Result.isInvalid())
6962 return true;
6963 From = Result.get();
6964 }
6965 return false;
6966}
6967
6968static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6970 QualType T, bool HadMultipleCandidates,
6972 CXXConversionDecl *Conversion =
6973 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6974 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6975
6976 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6977 if (!Converter.SuppressConversion) {
6978 if (SemaRef.isSFINAEContext())
6979 return true;
6980
6981 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6982 << From->getSourceRange();
6983 }
6984
6985 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6986 HadMultipleCandidates);
6987 if (Result.isInvalid())
6988 return true;
6989 // Record usage of conversion in an implicit cast.
6990 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6991 CK_UserDefinedConversion, Result.get(),
6992 nullptr, Result.get()->getValueKind(),
6993 SemaRef.CurFPFeatureOverrides());
6994 return false;
6995}
6996
6998 Sema &SemaRef, SourceLocation Loc, Expr *From,
7000 if (!Converter.match(From->getType()) && !Converter.Suppress)
7001 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
7002 << From->getSourceRange();
7003
7004 return SemaRef.DefaultLvalueConversion(From);
7005}
7006
7007static void
7009 UnresolvedSetImpl &ViableConversions,
7010 OverloadCandidateSet &CandidateSet) {
7011 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
7012 NamedDecl *D = FoundDecl.getDecl();
7013 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7014 if (isa<UsingShadowDecl>(D))
7015 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7016
7017 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
7019 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
7020 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
7021 continue;
7022 }
7024 SemaRef.AddConversionCandidate(
7025 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
7026 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
7027 }
7028}
7029
7030/// Attempt to convert the given expression to a type which is accepted
7031/// by the given converter.
7032///
7033/// This routine will attempt to convert an expression of class type to a
7034/// type accepted by the specified converter. In C++11 and before, the class
7035/// must have a single non-explicit conversion function converting to a matching
7036/// type. In C++1y, there can be multiple such conversion functions, but only
7037/// one target type.
7038///
7039/// \param Loc The source location of the construct that requires the
7040/// conversion.
7041///
7042/// \param From The expression we're converting from.
7043///
7044/// \param Converter Used to control and diagnose the conversion process.
7045///
7046/// \returns The expression, converted to an integral or enumeration type if
7047/// successful.
7049 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
7050 // We can't perform any more checking for type-dependent expressions.
7051 if (From->isTypeDependent())
7052 return From;
7053
7054 // Process placeholders immediately.
7055 if (From->hasPlaceholderType()) {
7056 ExprResult result = CheckPlaceholderExpr(From);
7057 if (result.isInvalid())
7058 return result;
7059 From = result.get();
7060 }
7061
7062 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
7063 ExprResult Converted = DefaultLvalueConversion(From);
7064 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
7065 From = Converted.isUsable() ? Converted.get() : nullptr;
7066 // If the expression already has a matching type, we're golden.
7067 if (Converter.match(T))
7068 return Converted;
7069
7070 // FIXME: Check for missing '()' if T is a function type?
7071
7072 // We can only perform contextual implicit conversions on objects of class
7073 // type.
7074 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
7075 if (!RecordTy || !getLangOpts().CPlusPlus) {
7076 if (!Converter.Suppress)
7077 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
7078 return From;
7079 }
7080
7081 // We must have a complete class type.
7082 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
7083 ContextualImplicitConverter &Converter;
7084 Expr *From;
7085
7086 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
7087 : Converter(Converter), From(From) {}
7088
7089 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
7090 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
7091 }
7092 } IncompleteDiagnoser(Converter, From);
7093
7094 if (Converter.Suppress ? !isCompleteType(Loc, T)
7095 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
7096 return From;
7097
7098 // Look for a conversion to an integral or enumeration type.
7100 ViableConversions; // These are *potentially* viable in C++1y.
7101 UnresolvedSet<4> ExplicitConversions;
7102 const auto &Conversions = cast<CXXRecordDecl>(RecordTy->getDecl())
7103 ->getDefinitionOrSelf()
7104 ->getVisibleConversionFunctions();
7105
7106 bool HadMultipleCandidates =
7107 (std::distance(Conversions.begin(), Conversions.end()) > 1);
7108
7109 // To check that there is only one target type, in C++1y:
7110 QualType ToType;
7111 bool HasUniqueTargetType = true;
7112
7113 // Collect explicit or viable (potentially in C++1y) conversions.
7114 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
7115 NamedDecl *D = (*I)->getUnderlyingDecl();
7116 CXXConversionDecl *Conversion;
7117 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
7118 if (ConvTemplate) {
7120 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
7121 else
7122 continue; // C++11 does not consider conversion operator templates(?).
7123 } else
7124 Conversion = cast<CXXConversionDecl>(D);
7125
7126 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
7127 "Conversion operator templates are considered potentially "
7128 "viable in C++1y");
7129
7130 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
7131 if (Converter.match(CurToType) || ConvTemplate) {
7132
7133 if (Conversion->isExplicit()) {
7134 // FIXME: For C++1y, do we need this restriction?
7135 // cf. diagnoseNoViableConversion()
7136 if (!ConvTemplate)
7137 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
7138 } else {
7139 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
7140 if (ToType.isNull())
7141 ToType = CurToType.getUnqualifiedType();
7142 else if (HasUniqueTargetType &&
7143 (CurToType.getUnqualifiedType() != ToType))
7144 HasUniqueTargetType = false;
7145 }
7146 ViableConversions.addDecl(I.getDecl(), I.getAccess());
7147 }
7148 }
7149 }
7150
7151 if (getLangOpts().CPlusPlus14) {
7152 // C++1y [conv]p6:
7153 // ... An expression e of class type E appearing in such a context
7154 // is said to be contextually implicitly converted to a specified
7155 // type T and is well-formed if and only if e can be implicitly
7156 // converted to a type T that is determined as follows: E is searched
7157 // for conversion functions whose return type is cv T or reference to
7158 // cv T such that T is allowed by the context. There shall be
7159 // exactly one such T.
7160
7161 // If no unique T is found:
7162 if (ToType.isNull()) {
7163 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7164 HadMultipleCandidates,
7165 ExplicitConversions))
7166 return ExprError();
7167 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7168 }
7169
7170 // If more than one unique Ts are found:
7171 if (!HasUniqueTargetType)
7172 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7173 ViableConversions);
7174
7175 // If one unique T is found:
7176 // First, build a candidate set from the previously recorded
7177 // potentially viable conversions.
7179 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
7180 CandidateSet);
7181
7182 // Then, perform overload resolution over the candidate set.
7184 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
7185 case OR_Success: {
7186 // Apply this conversion.
7188 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
7189 if (recordConversion(*this, Loc, From, Converter, T,
7190 HadMultipleCandidates, Found))
7191 return ExprError();
7192 break;
7193 }
7194 case OR_Ambiguous:
7195 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7196 ViableConversions);
7198 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7199 HadMultipleCandidates,
7200 ExplicitConversions))
7201 return ExprError();
7202 [[fallthrough]];
7203 case OR_Deleted:
7204 // We'll complain below about a non-integral condition type.
7205 break;
7206 }
7207 } else {
7208 switch (ViableConversions.size()) {
7209 case 0: {
7210 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7211 HadMultipleCandidates,
7212 ExplicitConversions))
7213 return ExprError();
7214
7215 // We'll complain below about a non-integral condition type.
7216 break;
7217 }
7218 case 1: {
7219 // Apply this conversion.
7220 DeclAccessPair Found = ViableConversions[0];
7221 if (recordConversion(*this, Loc, From, Converter, T,
7222 HadMultipleCandidates, Found))
7223 return ExprError();
7224 break;
7225 }
7226 default:
7227 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7228 ViableConversions);
7229 }
7230 }
7231
7232 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7233}
7234
7235/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
7236/// an acceptable non-member overloaded operator for a call whose
7237/// arguments have types T1 (and, if non-empty, T2). This routine
7238/// implements the check in C++ [over.match.oper]p3b2 concerning
7239/// enumeration types.
7241 FunctionDecl *Fn,
7242 ArrayRef<Expr *> Args) {
7243 QualType T1 = Args[0]->getType();
7244 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
7245
7246 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7247 return true;
7248
7249 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7250 return true;
7251
7252 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7253 if (Proto->getNumParams() < 1)
7254 return false;
7255
7256 if (T1->isEnumeralType()) {
7257 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
7258 if (Context.hasSameUnqualifiedType(T1, ArgType))
7259 return true;
7260 }
7261
7262 if (Proto->getNumParams() < 2)
7263 return false;
7264
7265 if (!T2.isNull() && T2->isEnumeralType()) {
7266 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
7267 if (Context.hasSameUnqualifiedType(T2, ArgType))
7268 return true;
7269 }
7270
7271 return false;
7272}
7273
7276 return false;
7277
7278 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7279 return FD->isTargetMultiVersion();
7280
7281 if (!FD->isMultiVersion())
7282 return false;
7283
7284 // Among multiple target versions consider either the default,
7285 // or the first non-default in the absence of default version.
7286 unsigned SeenAt = 0;
7287 unsigned I = 0;
7288 bool HasDefault = false;
7290 FD, [&](const FunctionDecl *CurFD) {
7291 if (FD == CurFD)
7292 SeenAt = I;
7293 else if (CurFD->isTargetMultiVersionDefault())
7294 HasDefault = true;
7295 ++I;
7296 });
7297 return HasDefault || SeenAt != 0;
7298}
7299
7302 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7303 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7304 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7305 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7306 bool StrictPackMatch) {
7307 const FunctionProtoType *Proto
7308 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
7309 assert(Proto && "Functions without a prototype cannot be overloaded");
7310 assert(!Function->getDescribedFunctionTemplate() &&
7311 "Use AddTemplateOverloadCandidate for function templates");
7312
7313 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
7315 // If we get here, it's because we're calling a member function
7316 // that is named without a member access expression (e.g.,
7317 // "this->f") that was either written explicitly or created
7318 // implicitly. This can happen with a qualified call to a member
7319 // function, e.g., X::f(). We use an empty type for the implied
7320 // object argument (C++ [over.call.func]p3), and the acting context
7321 // is irrelevant.
7322 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
7324 CandidateSet, SuppressUserConversions,
7325 PartialOverloading, EarlyConversions, PO,
7326 StrictPackMatch);
7327 return;
7328 }
7329 // We treat a constructor like a non-member function, since its object
7330 // argument doesn't participate in overload resolution.
7331 }
7332
7333 if (!CandidateSet.isNewCandidate(Function, PO))
7334 return;
7335
7336 // C++11 [class.copy]p11: [DR1402]
7337 // A defaulted move constructor that is defined as deleted is ignored by
7338 // overload resolution.
7339 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
7340 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7341 Constructor->isMoveConstructor())
7342 return;
7343
7344 // Overload resolution is always an unevaluated context.
7347
7348 // C++ [over.match.oper]p3:
7349 // if no operand has a class type, only those non-member functions in the
7350 // lookup set that have a first parameter of type T1 or "reference to
7351 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7352 // is a right operand) a second parameter of type T2 or "reference to
7353 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7354 // candidate functions.
7355 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7357 return;
7358
7359 // Add this candidate
7360 OverloadCandidate &Candidate =
7361 CandidateSet.addCandidate(Args.size(), EarlyConversions);
7362 Candidate.FoundDecl = FoundDecl;
7363 Candidate.Function = Function;
7364 Candidate.Viable = true;
7365 Candidate.RewriteKind =
7366 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
7367 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
7368 Candidate.ExplicitCallArguments = Args.size();
7369 Candidate.StrictPackMatch = StrictPackMatch;
7370
7371 // Explicit functions are not actually candidates at all if we're not
7372 // allowing them in this context, but keep them around so we can point
7373 // to them in diagnostics.
7374 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7375 Candidate.Viable = false;
7376 Candidate.FailureKind = ovl_fail_explicit;
7377 return;
7378 }
7379
7380 // Functions with internal linkage are only viable in the same module unit.
7381 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7382 /// FIXME: Currently, the semantics of linkage in clang is slightly
7383 /// different from the semantics in C++ spec. In C++ spec, only names
7384 /// have linkage. So that all entities of the same should share one
7385 /// linkage. But in clang, different entities of the same could have
7386 /// different linkage.
7387 const NamedDecl *ND = Function;
7388 bool IsImplicitlyInstantiated = false;
7389 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7390 ND = SpecInfo->getTemplate();
7391 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7393 }
7394
7395 /// Don't remove inline functions with internal linkage from the overload
7396 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7397 /// However:
7398 /// - Inline functions with internal linkage are a common pattern in
7399 /// headers to avoid ODR issues.
7400 /// - The global module is meant to be a transition mechanism for C and C++
7401 /// headers, and the current rules as written work against that goal.
7402 const bool IsInlineFunctionInGMF =
7403 Function->isFromGlobalModule() &&
7404 (IsImplicitlyInstantiated || Function->isInlined());
7405
7406 // Don't exclude internal-linkage entities from the current TU's global
7407 // module fragment.
7408 const Module *CurrentModule = getCurrentModule();
7409 const bool IsCurrentUnitGMFDecl =
7410 Function->isFromGlobalModule() && CurrentModule &&
7411 Function->getOwningModule()->getTopLevelModule() ==
7412 CurrentModule->getTopLevelModule();
7413
7414 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF &&
7415 !IsCurrentUnitGMFDecl) {
7416 Candidate.Viable = false;
7418 return;
7419 }
7420 }
7421
7423 Candidate.Viable = false;
7425 return;
7426 }
7427
7428 if (Constructor) {
7429 // C++ [class.copy]p3:
7430 // A member function template is never instantiated to perform the copy
7431 // of a class object to an object of its class type.
7432 CanQualType ClassType =
7433 Context.getCanonicalTagType(Constructor->getParent());
7434 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7435 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7436 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7437 ClassType))) {
7438 Candidate.Viable = false;
7440 return;
7441 }
7442
7443 // C++ [over.match.funcs]p8: (proposed DR resolution)
7444 // A constructor inherited from class type C that has a first parameter
7445 // of type "reference to P" (including such a constructor instantiated
7446 // from a template) is excluded from the set of candidate functions when
7447 // constructing an object of type cv D if the argument list has exactly
7448 // one argument and D is reference-related to P and P is reference-related
7449 // to C.
7450 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7451 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7452 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7453 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7454 CanQualType C = Context.getCanonicalTagType(Constructor->getParent());
7455 CanQualType D = Context.getCanonicalTagType(Shadow->getParent());
7456 SourceLocation Loc = Args.front()->getExprLoc();
7457 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7458 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7459 Candidate.Viable = false;
7461 return;
7462 }
7463 }
7464
7465 // Check that the constructor is capable of constructing an object in the
7466 // destination address space.
7468 Constructor->getMethodQualifiers().getAddressSpace(),
7469 CandidateSet.getDestAS(), getASTContext())) {
7470 Candidate.Viable = false;
7472 }
7473 }
7474
7475 unsigned NumParams = Proto->getNumParams();
7476
7477 // (C++ 13.3.2p2): A candidate function having fewer than m
7478 // parameters is viable only if it has an ellipsis in its parameter
7479 // list (8.3.5).
7480 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7481 !Proto->isVariadic() &&
7482 shouldEnforceArgLimit(PartialOverloading, Function)) {
7483 Candidate.Viable = false;
7485 return;
7486 }
7487
7488 // (C++ 13.3.2p2): A candidate function having more than m parameters
7489 // is viable only if the (m+1)st parameter has a default argument
7490 // (8.3.6). For the purposes of overload resolution, the
7491 // parameter list is truncated on the right, so that there are
7492 // exactly m parameters.
7493 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7494 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7495 !PartialOverloading) {
7496 // Not enough arguments.
7497 Candidate.Viable = false;
7499 return;
7500 }
7501
7502 // (CUDA B.1): Check for invalid calls between targets.
7503 if (getLangOpts().CUDA) {
7504 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7505 // Skip the check for callers that are implicit members, because in this
7506 // case we may not yet know what the member's target is; the target is
7507 // inferred for the member automatically, based on the bases and fields of
7508 // the class.
7509 if (!(Caller && Caller->isImplicit()) &&
7510 !CUDA().IsAllowedCall(Caller, Function)) {
7511 Candidate.Viable = false;
7512 Candidate.FailureKind = ovl_fail_bad_target;
7513 return;
7514 }
7515 }
7516
7517 if (Function->getTrailingRequiresClause()) {
7518 ConstraintSatisfaction Satisfaction;
7519 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7520 /*ForOverloadResolution*/ true) ||
7521 !Satisfaction.IsSatisfied) {
7522 Candidate.Viable = false;
7524 return;
7525 }
7526 }
7527
7528 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7529 // Determine the implicit conversion sequences for each of the
7530 // arguments.
7531 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7532 unsigned ConvIdx =
7533 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7534 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7535 // We already formed a conversion sequence for this parameter during
7536 // template argument deduction.
7537 } else if (ArgIdx < NumParams) {
7538 // (C++ 13.3.2p3): for F to be a viable function, there shall
7539 // exist for each argument an implicit conversion sequence
7540 // (13.3.3.1) that converts that argument to the corresponding
7541 // parameter of F.
7542 QualType ParamType = Proto->getParamType(ArgIdx);
7543 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7544 if (ParamABI == ParameterABI::HLSLOut ||
7545 ParamABI == ParameterABI::HLSLInOut) {
7546 ParamType = ParamType.getNonReferenceType();
7547 if (ParamABI == ParameterABI::HLSLInOut &&
7548 Args[ArgIdx]->getType().getAddressSpace() ==
7550 Diag(Args[ArgIdx]->getBeginLoc(), diag::warn_hlsl_groupshared_inout);
7551 }
7552 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7553 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7554 /*InOverloadResolution=*/true,
7555 /*AllowObjCWritebackConversion=*/
7556 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7557 if (Candidate.Conversions[ConvIdx].isBad()) {
7558 Candidate.Viable = false;
7560 return;
7561 }
7562 } else {
7563 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7564 // argument for which there is no corresponding parameter is
7565 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7566 Candidate.Conversions[ConvIdx].setEllipsis();
7567 }
7568 }
7569
7570 if (EnableIfAttr *FailedAttr =
7571 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7572 Candidate.Viable = false;
7573 Candidate.FailureKind = ovl_fail_enable_if;
7574 Candidate.DeductionFailure.Data = FailedAttr;
7575 return;
7576 }
7577}
7578
7582 if (Methods.size() <= 1)
7583 return nullptr;
7584
7585 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7586 bool Match = true;
7587 ObjCMethodDecl *Method = Methods[b];
7588 unsigned NumNamedArgs = Sel.getNumArgs();
7589 // Method might have more arguments than selector indicates. This is due
7590 // to addition of c-style arguments in method.
7591 if (Method->param_size() > NumNamedArgs)
7592 NumNamedArgs = Method->param_size();
7593 if (Args.size() < NumNamedArgs)
7594 continue;
7595
7596 for (unsigned i = 0; i < NumNamedArgs; i++) {
7597 // We can't do any type-checking on a type-dependent argument.
7598 if (Args[i]->isTypeDependent()) {
7599 Match = false;
7600 break;
7601 }
7602
7603 ParmVarDecl *param = Method->parameters()[i];
7604 Expr *argExpr = Args[i];
7605 assert(argExpr && "SelectBestMethod(): missing expression");
7606
7607 // Strip the unbridged-cast placeholder expression off unless it's
7608 // a consumed argument.
7609 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7610 !param->hasAttr<CFConsumedAttr>())
7611 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7612
7613 // If the parameter is __unknown_anytype, move on to the next method.
7614 if (param->getType() == Context.UnknownAnyTy) {
7615 Match = false;
7616 break;
7617 }
7618
7619 ImplicitConversionSequence ConversionState
7620 = TryCopyInitialization(*this, argExpr, param->getType(),
7621 /*SuppressUserConversions*/false,
7622 /*InOverloadResolution=*/true,
7623 /*AllowObjCWritebackConversion=*/
7624 getLangOpts().ObjCAutoRefCount,
7625 /*AllowExplicit*/false);
7626 // This function looks for a reasonably-exact match, so we consider
7627 // incompatible pointer conversions to be a failure here.
7628 if (ConversionState.isBad() ||
7629 (ConversionState.isStandard() &&
7630 ConversionState.Standard.Second ==
7632 Match = false;
7633 break;
7634 }
7635 }
7636 // Promote additional arguments to variadic methods.
7637 if (Match && Method->isVariadic()) {
7638 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7639 if (Args[i]->isTypeDependent()) {
7640 Match = false;
7641 break;
7642 }
7644 Args[i], VariadicCallType::Method, nullptr);
7645 if (Arg.isInvalid()) {
7646 Match = false;
7647 break;
7648 }
7649 }
7650 } else {
7651 // Check for extra arguments to non-variadic methods.
7652 if (Args.size() != NumNamedArgs)
7653 Match = false;
7654 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7655 // Special case when selectors have no argument. In this case, select
7656 // one with the most general result type of 'id'.
7657 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7658 QualType ReturnT = Methods[b]->getReturnType();
7659 if (ReturnT->isObjCIdType())
7660 return Methods[b];
7661 }
7662 }
7663 }
7664
7665 if (Match)
7666 return Method;
7667 }
7668 return nullptr;
7669}
7670
7672 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7673 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7674 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7675 if (ThisArg) {
7676 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7677 assert(!isa<CXXConstructorDecl>(Method) &&
7678 "Shouldn't have `this` for ctors!");
7679 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7681 ThisArg, /*Qualifier=*/std::nullopt, Method, Method);
7682 if (R.isInvalid())
7683 return false;
7684 ConvertedThis = R.get();
7685 } else {
7686 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7687 (void)MD;
7688 assert((MissingImplicitThis || MD->isStatic() ||
7690 "Expected `this` for non-ctor instance methods");
7691 }
7692 ConvertedThis = nullptr;
7693 }
7694
7695 // Ignore any variadic arguments. Converting them is pointless, since the
7696 // user can't refer to them in the function condition.
7697 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7698
7699 // Convert the arguments.
7700 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7701 ExprResult R;
7703 S.Context, Function->getParamDecl(I)),
7704 SourceLocation(), Args[I]);
7705
7706 if (R.isInvalid())
7707 return false;
7708
7709 ConvertedArgs.push_back(R.get());
7710 }
7711
7712 if (Trap.hasErrorOccurred())
7713 return false;
7714
7715 // Push default arguments if needed.
7716 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7717 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7718 ParmVarDecl *P = Function->getParamDecl(i);
7719 if (!P->hasDefaultArg())
7720 return false;
7721 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
7722 if (R.isInvalid())
7723 return false;
7724 ConvertedArgs.push_back(R.get());
7725 }
7726
7727 if (Trap.hasErrorOccurred())
7728 return false;
7729 }
7730 return true;
7731}
7732
7734 SourceLocation CallLoc,
7735 ArrayRef<Expr *> Args,
7736 bool MissingImplicitThis) {
7737 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7738 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7739 return nullptr;
7740
7741 SFINAETrap Trap(*this);
7742 // Perform the access checking immediately so any access diagnostics are
7743 // caught by the SFINAE trap.
7744 llvm::scope_exit UndelayDiags(
7745 [&, CurrentState(DelayedDiagnostics.pushUndelayed())] {
7746 DelayedDiagnostics.popUndelayed(CurrentState);
7747 });
7748 SmallVector<Expr *, 16> ConvertedArgs;
7749 // FIXME: We should look into making enable_if late-parsed.
7750 Expr *DiscardedThis;
7752 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7753 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7754 return *EnableIfAttrs.begin();
7755
7756 for (auto *EIA : EnableIfAttrs) {
7758 // FIXME: This doesn't consider value-dependent cases, because doing so is
7759 // very difficult. Ideally, we should handle them more gracefully.
7760 if (EIA->getCond()->isValueDependent() ||
7761 !EIA->getCond()->EvaluateWithSubstitution(
7762 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7763 return EIA;
7764
7765 if (!Result.isInt() || !Result.getInt().getBoolValue())
7766 return EIA;
7767 }
7768 return nullptr;
7769}
7770
7771template <typename CheckFn>
7773 bool ArgDependent, SourceLocation Loc,
7774 CheckFn &&IsSuccessful) {
7776 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7777 if (ArgDependent == DIA->getArgDependent())
7778 Attrs.push_back(DIA);
7779 }
7780
7781 // Common case: No diagnose_if attributes, so we can quit early.
7782 if (Attrs.empty())
7783 return false;
7784
7785 auto WarningBegin = std::stable_partition(
7786 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7787 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7788 DIA->getWarningGroup().empty();
7789 });
7790
7791 // Note that diagnose_if attributes are late-parsed, so they appear in the
7792 // correct order (unlike enable_if attributes).
7793 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7794 IsSuccessful);
7795 if (ErrAttr != WarningBegin) {
7796 const DiagnoseIfAttr *DIA = *ErrAttr;
7797 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7798 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7799 << DIA->getParent() << DIA->getCond()->getSourceRange();
7800 return true;
7801 }
7802
7803 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7804 switch (Sev) {
7805 case DiagnoseIfAttr::DS_warning:
7807 case DiagnoseIfAttr::DS_error:
7808 return diag::Severity::Error;
7809 }
7810 llvm_unreachable("Fully covered switch above!");
7811 };
7812
7813 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7814 if (IsSuccessful(DIA)) {
7815 if (DIA->getWarningGroup().empty() &&
7816 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7817 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7818 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7819 << DIA->getParent() << DIA->getCond()->getSourceRange();
7820 } else {
7821 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7822 DIA->getWarningGroup());
7823 assert(DiagGroup);
7824 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7825 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7826 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7827 S.Diag(Loc, DiagID) << DIA->getMessage();
7828 }
7829 }
7830
7831 return false;
7832}
7833
7835 const Expr *ThisArg,
7837 SourceLocation Loc) {
7839 *this, Function, /*ArgDependent=*/true, Loc,
7840 [&](const DiagnoseIfAttr *DIA) {
7842 // It's sane to use the same Args for any redecl of this function, since
7843 // EvaluateWithSubstitution only cares about the position of each
7844 // argument in the arg list, not the ParmVarDecl* it maps to.
7845 if (!DIA->getCond()->EvaluateWithSubstitution(
7846 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7847 return false;
7848 return Result.isInt() && Result.getInt().getBoolValue();
7849 });
7850}
7851
7853 SourceLocation Loc) {
7855 *this, ND, /*ArgDependent=*/false, Loc,
7856 [&](const DiagnoseIfAttr *DIA) {
7857 bool Result;
7858 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7859 Result;
7860 });
7861}
7862
7864 ArrayRef<Expr *> Args,
7865 OverloadCandidateSet &CandidateSet,
7866 TemplateArgumentListInfo *ExplicitTemplateArgs,
7867 bool SuppressUserConversions,
7868 bool PartialOverloading,
7869 bool FirstArgumentIsBase) {
7870 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7871 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7872 ArrayRef<Expr *> FunctionArgs = Args;
7873
7874 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7875 FunctionDecl *FD =
7876 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7877
7878 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7879 QualType ObjectType;
7880 Expr::Classification ObjectClassification;
7881 if (Args.size() > 0) {
7882 if (Expr *E = Args[0]) {
7883 // Use the explicit base to restrict the lookup:
7884 ObjectType = E->getType();
7885 // Pointers in the object arguments are implicitly dereferenced, so we
7886 // always classify them as l-values.
7887 if (!ObjectType.isNull() && ObjectType->isPointerType())
7888 ObjectClassification = Expr::Classification::makeSimpleLValue();
7889 else
7890 ObjectClassification = E->Classify(Context);
7891 } // .. else there is an implicit base.
7892 FunctionArgs = Args.slice(1);
7893 }
7894 if (FunTmpl) {
7896 FunTmpl, F.getPair(),
7898 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7899 FunctionArgs, CandidateSet, SuppressUserConversions,
7900 PartialOverloading);
7901 } else {
7902 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7903 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7904 ObjectClassification, FunctionArgs, CandidateSet,
7905 SuppressUserConversions, PartialOverloading);
7906 }
7907 } else {
7908 // This branch handles both standalone functions and static methods.
7909
7910 // Slice the first argument (which is the base) when we access
7911 // static method as non-static.
7912 if (Args.size() > 0 &&
7913 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7914 !isa<CXXConstructorDecl>(FD)))) {
7915 assert(cast<CXXMethodDecl>(FD)->isStatic());
7916 FunctionArgs = Args.slice(1);
7917 }
7918 if (FunTmpl) {
7919 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7920 ExplicitTemplateArgs, FunctionArgs,
7921 CandidateSet, SuppressUserConversions,
7922 PartialOverloading);
7923 } else {
7924 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7925 SuppressUserConversions, PartialOverloading);
7926 }
7927 }
7928 }
7929}
7930
7932 Expr::Classification ObjectClassification,
7933 ArrayRef<Expr *> Args,
7934 OverloadCandidateSet &CandidateSet,
7935 bool SuppressUserConversions,
7937 NamedDecl *Decl = FoundDecl.getDecl();
7939
7941 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7942
7943 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7944 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7945 "Expected a member function template");
7946 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7947 /*ExplicitArgs*/ nullptr, ObjectType,
7948 ObjectClassification, Args, CandidateSet,
7949 SuppressUserConversions, false, PO);
7950 } else {
7951 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7952 ObjectType, ObjectClassification, Args, CandidateSet,
7953 SuppressUserConversions, false, {}, PO);
7954 }
7955}
7956
7959 CXXRecordDecl *ActingContext, QualType ObjectType,
7960 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7961 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7962 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7963 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7964 const FunctionProtoType *Proto
7965 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7966 assert(Proto && "Methods without a prototype cannot be overloaded");
7968 "Use AddOverloadCandidate for constructors");
7969
7970 if (!CandidateSet.isNewCandidate(Method, PO))
7971 return;
7972
7973 // C++11 [class.copy]p23: [DR1402]
7974 // A defaulted move assignment operator that is defined as deleted is
7975 // ignored by overload resolution.
7976 if (Method->isDefaulted() && Method->isDeleted() &&
7977 Method->isMoveAssignmentOperator())
7978 return;
7979
7980 // Overload resolution is always an unevaluated context.
7983
7984 bool IgnoreExplicitObject =
7985 (Method->isExplicitObjectMemberFunction() &&
7986 CandidateSet.getKind() ==
7988 bool ImplicitObjectMethodTreatedAsStatic =
7989 CandidateSet.getKind() ==
7991 Method->isImplicitObjectMemberFunction();
7992
7993 unsigned ExplicitOffset =
7994 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7995
7996 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7997 int(ImplicitObjectMethodTreatedAsStatic);
7998
7999 unsigned ExtraArgs =
8001 ? 0
8002 : 1;
8003
8004 // Add this candidate
8005 OverloadCandidate &Candidate =
8006 CandidateSet.addCandidate(Args.size() + ExtraArgs, EarlyConversions);
8007 Candidate.FoundDecl = FoundDecl;
8008 Candidate.Function = Method;
8009 Candidate.RewriteKind =
8010 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
8011 Candidate.TookAddressOfOverload =
8013 Candidate.ExplicitCallArguments = Args.size();
8014 Candidate.StrictPackMatch = StrictPackMatch;
8015
8016 // (C++ 13.3.2p2): A candidate function having fewer than m
8017 // parameters is viable only if it has an ellipsis in its parameter
8018 // list (8.3.5).
8019 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
8020 !Proto->isVariadic() &&
8021 shouldEnforceArgLimit(PartialOverloading, Method)) {
8022 Candidate.Viable = false;
8024 return;
8025 }
8026
8027 // (C++ 13.3.2p2): A candidate function having more than m parameters
8028 // is viable only if the (m+1)st parameter has a default argument
8029 // (8.3.6). For the purposes of overload resolution, the
8030 // parameter list is truncated on the right, so that there are
8031 // exactly m parameters.
8032 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
8033 ExplicitOffset +
8034 int(ImplicitObjectMethodTreatedAsStatic);
8035
8036 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
8037 // Not enough arguments.
8038 Candidate.Viable = false;
8040 return;
8041 }
8042
8043 Candidate.Viable = true;
8044
8045 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8046 if (!IgnoreExplicitObject) {
8047 if (ObjectType.isNull())
8048 Candidate.IgnoreObjectArgument = true;
8049 else if (Method->isStatic()) {
8050 // [over.best.ics.general]p8
8051 // When the parameter is the implicit object parameter of a static member
8052 // function, the implicit conversion sequence is a standard conversion
8053 // sequence that is neither better nor worse than any other standard
8054 // conversion sequence.
8055 //
8056 // This is a rule that was introduced in C++23 to support static lambdas.
8057 // We apply it retroactively because we want to support static lambdas as
8058 // an extension and it doesn't hurt previous code.
8059 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
8060 } else {
8061 // Determine the implicit conversion sequence for the object
8062 // parameter.
8063 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
8064 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8065 Method, ActingContext, /*InOverloadResolution=*/true);
8066 if (Candidate.Conversions[FirstConvIdx].isBad()) {
8067 Candidate.Viable = false;
8069 return;
8070 }
8071 }
8072 }
8073
8074 // (CUDA B.1): Check for invalid calls between targets.
8075 if (getLangOpts().CUDA)
8076 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
8077 Method)) {
8078 Candidate.Viable = false;
8079 Candidate.FailureKind = ovl_fail_bad_target;
8080 return;
8081 }
8082
8083 if (Method->getTrailingRequiresClause()) {
8084 ConstraintSatisfaction Satisfaction;
8085 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
8086 /*ForOverloadResolution*/ true) ||
8087 !Satisfaction.IsSatisfied) {
8088 Candidate.Viable = false;
8090 return;
8091 }
8092 }
8093
8094 // Determine the implicit conversion sequences for each of the
8095 // arguments.
8096 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
8097 unsigned ConvIdx =
8098 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
8099 if (Candidate.Conversions[ConvIdx].isInitialized()) {
8100 // We already formed a conversion sequence for this parameter during
8101 // template argument deduction.
8102 } else if (ArgIdx < NumParams) {
8103 // (C++ 13.3.2p3): for F to be a viable function, there shall
8104 // exist for each argument an implicit conversion sequence
8105 // (13.3.3.1) that converts that argument to the corresponding
8106 // parameter of F.
8107 QualType ParamType;
8108 if (ImplicitObjectMethodTreatedAsStatic) {
8109 ParamType = ArgIdx == 0
8110 ? Method->getFunctionObjectParameterReferenceType()
8111 : Proto->getParamType(ArgIdx - 1);
8112 } else {
8113 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
8114 }
8115 Candidate.Conversions[ConvIdx]
8116 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8117 SuppressUserConversions,
8118 /*InOverloadResolution=*/true,
8119 /*AllowObjCWritebackConversion=*/
8120 getLangOpts().ObjCAutoRefCount);
8121 if (Candidate.Conversions[ConvIdx].isBad()) {
8122 Candidate.Viable = false;
8124 return;
8125 }
8126 } else {
8127 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8128 // argument for which there is no corresponding parameter is
8129 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
8130 Candidate.Conversions[ConvIdx].setEllipsis();
8131 }
8132 }
8133
8134 if (EnableIfAttr *FailedAttr =
8135 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
8136 Candidate.Viable = false;
8137 Candidate.FailureKind = ovl_fail_enable_if;
8138 Candidate.DeductionFailure.Data = FailedAttr;
8139 return;
8140 }
8141
8143 Candidate.Viable = false;
8145 }
8146}
8147
8149 Sema &S, OverloadCandidateSet &CandidateSet,
8150 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8151 CXXRecordDecl *ActingContext,
8152 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8153 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8154 bool SuppressUserConversions, bool PartialOverloading,
8156
8157 // C++ [over.match.funcs]p7:
8158 // In each case where a candidate is a function template, candidate
8159 // function template specializations are generated using template argument
8160 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8161 // candidate functions in the usual way.113) A given name can refer to one
8162 // or more function templates and also to a set of overloaded non-template
8163 // functions. In such a case, the candidate functions generated from each
8164 // function template are combined with the set of non-template candidate
8165 // functions.
8166 TemplateDeductionInfo Info(CandidateSet.getLocation());
8167 auto *Method = cast<CXXMethodDecl>(MethodTmpl->getTemplatedDecl());
8168 FunctionDecl *Specialization = nullptr;
8169 ConversionSequenceList Conversions;
8171 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
8172 PartialOverloading, /*AggregateDeductionCandidate=*/false,
8173 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
8174 CandidateSet.getKind() ==
8176 [&](ArrayRef<QualType> ParamTypes,
8177 bool OnlyInitializeNonUserDefinedConversions) {
8178 return S.CheckNonDependentConversions(
8179 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
8180 Sema::CheckNonDependentConversionsFlag(
8181 SuppressUserConversions,
8182 OnlyInitializeNonUserDefinedConversions),
8183 ActingContext, ObjectType, ObjectClassification, PO);
8184 });
8186 OverloadCandidate &Candidate =
8187 CandidateSet.addCandidate(Conversions.size(), Conversions);
8188 Candidate.FoundDecl = FoundDecl;
8189 Candidate.Function = Method;
8190 Candidate.Viable = false;
8191 Candidate.RewriteKind =
8192 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8193 Candidate.IsSurrogate = false;
8194 Candidate.TookAddressOfOverload =
8195 CandidateSet.getKind() ==
8197
8198 Candidate.IgnoreObjectArgument =
8199 Method->isStatic() ||
8200 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
8201 Candidate.ExplicitCallArguments = Args.size();
8204 else {
8206 Candidate.DeductionFailure =
8208 }
8209 return;
8210 }
8211
8212 // Add the function template specialization produced by template argument
8213 // deduction as a candidate.
8214 assert(Specialization && "Missing member function template specialization?");
8216 "Specialization is not a member function?");
8218 cast<CXXMethodDecl>(Specialization), FoundDecl, ActingContext, ObjectType,
8219 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
8220 PartialOverloading, Conversions, PO, Info.hasStrictPackMatch());
8221}
8222
8224 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8225 CXXRecordDecl *ActingContext,
8226 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8227 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8228 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8229 bool PartialOverloading, OverloadCandidateParamOrder PO) {
8230 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
8231 return;
8232
8233 if (ExplicitTemplateArgs ||
8234 !CandidateSet.shouldDeferTemplateArgumentDeduction(*this)) {
8236 *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
8237 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
8238 SuppressUserConversions, PartialOverloading, PO);
8239 return;
8240 }
8241
8243 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
8244 Args, SuppressUserConversions, PartialOverloading, PO);
8245}
8246
8247/// Determine whether a given function template has a simple explicit specifier
8248/// or a non-value-dependent explicit-specification that evaluates to true.
8252
8257
8259 Sema &S, OverloadCandidateSet &CandidateSet,
8261 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8262 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
8264 bool AggregateCandidateDeduction) {
8265
8266 // If the function template has a non-dependent explicit specification,
8267 // exclude it now if appropriate; we are not permitted to perform deduction
8268 // and substitution in this case.
8269 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8270 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8271 Candidate.FoundDecl = FoundDecl;
8272 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8273 Candidate.Viable = false;
8274 Candidate.FailureKind = ovl_fail_explicit;
8275 return;
8276 }
8277
8278 // C++ [over.match.funcs]p7:
8279 // In each case where a candidate is a function template, candidate
8280 // function template specializations are generated using template argument
8281 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8282 // candidate functions in the usual way.113) A given name can refer to one
8283 // or more function templates and also to a set of overloaded non-template
8284 // functions. In such a case, the candidate functions generated from each
8285 // function template are combined with the set of non-template candidate
8286 // functions.
8287 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8288 FunctionTemplate->getTemplateDepth());
8289 FunctionDecl *Specialization = nullptr;
8290 ConversionSequenceList Conversions;
8292 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8293 PartialOverloading, AggregateCandidateDeduction,
8294 /*PartialOrdering=*/false,
8295 /*ObjectType=*/QualType(),
8296 /*ObjectClassification=*/Expr::Classification(),
8297 CandidateSet.getKind() ==
8299 [&](ArrayRef<QualType> ParamTypes,
8300 bool OnlyInitializeNonUserDefinedConversions) {
8301 return S.CheckNonDependentConversions(
8302 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8303 Sema::CheckNonDependentConversionsFlag(
8304 SuppressUserConversions,
8305 OnlyInitializeNonUserDefinedConversions),
8306 nullptr, QualType(), {}, PO);
8307 });
8309 OverloadCandidate &Candidate =
8310 CandidateSet.addCandidate(Conversions.size(), Conversions);
8311 Candidate.FoundDecl = FoundDecl;
8312 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8313 Candidate.Viable = false;
8314 Candidate.RewriteKind =
8315 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8316 Candidate.IsSurrogate = false;
8317 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
8318 // Ignore the object argument if there is one, since we don't have an object
8319 // type.
8320 Candidate.TookAddressOfOverload =
8321 CandidateSet.getKind() ==
8323
8324 Candidate.IgnoreObjectArgument =
8325 isa<CXXMethodDecl>(Candidate.Function) &&
8326 !cast<CXXMethodDecl>(Candidate.Function)
8327 ->isExplicitObjectMemberFunction() &&
8329
8330 Candidate.ExplicitCallArguments = Args.size();
8333 else {
8335 Candidate.DeductionFailure =
8337 }
8338 return;
8339 }
8340
8341 // Add the function template specialization produced by template argument
8342 // deduction as a candidate.
8343 assert(Specialization && "Missing function template specialization?");
8345 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8346 PartialOverloading, AllowExplicit,
8347 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
8348 Info.AggregateDeductionCandidateHasMismatchedArity,
8349 Info.hasStrictPackMatch());
8350}
8351
8354 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8355 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8356 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8357 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8358 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
8359 return;
8360
8361 bool DependentExplicitSpecifier = hasDependentExplicit(FunctionTemplate);
8362
8363 if (ExplicitTemplateArgs ||
8364 !CandidateSet.shouldDeferTemplateArgumentDeduction(*this) ||
8365 (isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl()) &&
8366 DependentExplicitSpecifier)) {
8367
8369 *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8370 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8371 IsADLCandidate, PO, AggregateCandidateDeduction);
8372
8373 if (DependentExplicitSpecifier)
8375 return;
8376 }
8377
8378 CandidateSet.AddDeferredTemplateCandidate(
8379 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8380 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8381 AggregateCandidateDeduction);
8382}
8383
8386 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8388 CheckNonDependentConversionsFlag UserConversionFlag,
8389 CXXRecordDecl *ActingContext, QualType ObjectType,
8390 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8391 // FIXME: The cases in which we allow explicit conversions for constructor
8392 // arguments never consider calling a constructor template. It's not clear
8393 // that is correct.
8394 const bool AllowExplicit = false;
8395
8396 bool ForOverloadSetAddressResolution =
8398 auto *FD = FunctionTemplate->getTemplatedDecl();
8399 auto *Method = dyn_cast<CXXMethodDecl>(FD);
8400 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8402 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8403
8404 if (Conversions.empty())
8405 Conversions =
8406 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
8407
8408 // Overload resolution is always an unevaluated context.
8411
8412 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8413 // require that, but this check should never result in a hard error, and
8414 // overload resolution is permitted to sidestep instantiations.
8415 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
8416 !ObjectType.isNull()) {
8417 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8418 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8419 !ParamTypes[0]->isDependentType()) {
8421 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8422 Method, ActingContext, /*InOverloadResolution=*/true,
8423 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8424 : QualType());
8425 if (Conversions[ConvIdx].isBad())
8426 return true;
8427 }
8428 }
8429
8430 // A speculative workaround for self-dependent constraint bugs that manifest
8431 // after CWG2369.
8432 // FIXME: Add references to the standard once P3606 is adopted.
8433 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8434 QualType ArgType) {
8435 ParamType = ParamType.getNonReferenceType();
8436 ArgType = ArgType.getNonReferenceType();
8437 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8438 if (PointerConv) {
8439 ParamType = ParamType->getPointeeType();
8440 ArgType = ArgType->getPointeeType();
8441 }
8442
8443 if (auto *RD = ParamType->getAsCXXRecordDecl();
8444 RD && RD->hasDefinition() &&
8445 llvm::any_of(LookupConstructors(RD), [](NamedDecl *ND) {
8446 auto Info = getConstructorInfo(ND);
8447 if (!Info)
8448 return false;
8449 CXXConstructorDecl *Ctor = Info.Constructor;
8450 /// isConvertingConstructor takes copy/move constructors into
8451 /// account!
8452 return !Ctor->isCopyOrMoveConstructor() &&
8454 /*AllowExplicit=*/true);
8455 }))
8456 return true;
8457 if (auto *RD = ArgType->getAsCXXRecordDecl();
8458 RD && RD->hasDefinition() &&
8459 !RD->getVisibleConversionFunctions().empty())
8460 return true;
8461
8462 return false;
8463 };
8464
8465 unsigned Offset =
8466 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8467 : 0;
8468
8469 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
8470 I != N; ++I) {
8471 QualType ParamType = ParamTypes[I + Offset];
8472 if (!ParamType->isDependentType()) {
8473 unsigned ConvIdx;
8475 ConvIdx = Args.size() - 1 - I;
8476 assert(Args.size() + ThisConversions == 2 &&
8477 "number of args (including 'this') must be exactly 2 for "
8478 "reversed order");
8479 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8480 // would also be 0. 'this' got ConvIdx = 1 previously.
8481 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8482 } else {
8483 // For members, 'this' got ConvIdx = 0 previously.
8484 ConvIdx = ThisConversions + I;
8485 }
8486 if (Conversions[ConvIdx].isInitialized())
8487 continue;
8488 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8489 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8490 continue;
8492 *this, Args[I], ParamType, UserConversionFlag.SuppressUserConversions,
8493 /*InOverloadResolution=*/true,
8494 /*AllowObjCWritebackConversion=*/
8495 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8496 if (Conversions[ConvIdx].isBad())
8497 return true;
8498 }
8499 }
8500
8501 return false;
8502}
8503
8504/// Determine whether this is an allowable conversion from the result
8505/// of an explicit conversion operator to the expected type, per C++
8506/// [over.match.conv]p1 and [over.match.ref]p1.
8507///
8508/// \param ConvType The return type of the conversion function.
8509///
8510/// \param ToType The type we are converting to.
8511///
8512/// \param AllowObjCPointerConversion Allow a conversion from one
8513/// Objective-C pointer to another.
8514///
8515/// \returns true if the conversion is allowable, false otherwise.
8517 QualType ConvType, QualType ToType,
8518 bool AllowObjCPointerConversion) {
8519 QualType ToNonRefType = ToType.getNonReferenceType();
8520
8521 // Easy case: the types are the same.
8522 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
8523 return true;
8524
8525 // Allow qualification conversions.
8526 bool ObjCLifetimeConversion;
8527 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
8528 ObjCLifetimeConversion))
8529 return true;
8530
8531 // If we're not allowed to consider Objective-C pointer conversions,
8532 // we're done.
8533 if (!AllowObjCPointerConversion)
8534 return false;
8535
8536 // Is this an Objective-C pointer conversion?
8537 bool IncompatibleObjC = false;
8538 QualType ConvertedType;
8539 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
8540 IncompatibleObjC);
8541}
8542
8544 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8545 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8546 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8547 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8548 assert(!Conversion->getDescribedFunctionTemplate() &&
8549 "Conversion function templates use AddTemplateConversionCandidate");
8550 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8551 if (!CandidateSet.isNewCandidate(Conversion))
8552 return;
8553
8554 // If the conversion function has an undeduced return type, trigger its
8555 // deduction now.
8556 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8557 if (DeduceReturnType(Conversion, From->getExprLoc()))
8558 return;
8559 ConvType = Conversion->getConversionType().getNonReferenceType();
8560 }
8561
8562 // If we don't allow any conversion of the result type, ignore conversion
8563 // functions that don't convert to exactly (possibly cv-qualified) T.
8564 if (!AllowResultConversion &&
8565 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
8566 return;
8567
8568 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8569 // operator is only a candidate if its return type is the target type or
8570 // can be converted to the target type with a qualification conversion.
8571 //
8572 // FIXME: Include such functions in the candidate list and explain why we
8573 // can't select them.
8574 if (Conversion->isExplicit() &&
8575 !isAllowableExplicitConversion(*this, ConvType, ToType,
8576 AllowObjCConversionOnExplicit))
8577 return;
8578
8579 // Overload resolution is always an unevaluated context.
8582
8583 // Add this candidate
8584 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8585 Candidate.FoundDecl = FoundDecl;
8586 Candidate.Function = Conversion;
8588 Candidate.FinalConversion.setFromType(ConvType);
8589 Candidate.FinalConversion.setAllToTypes(ToType);
8590 Candidate.HasFinalConversion = true;
8591 Candidate.Viable = true;
8592 Candidate.ExplicitCallArguments = 1;
8593 Candidate.StrictPackMatch = StrictPackMatch;
8594
8595 // Explicit functions are not actually candidates at all if we're not
8596 // allowing them in this context, but keep them around so we can point
8597 // to them in diagnostics.
8598 if (!AllowExplicit && Conversion->isExplicit()) {
8599 Candidate.Viable = false;
8600 Candidate.FailureKind = ovl_fail_explicit;
8601 return;
8602 }
8603
8604 // C++ [over.match.funcs]p4:
8605 // For conversion functions, the function is considered to be a member of
8606 // the class of the implicit implied object argument for the purpose of
8607 // defining the type of the implicit object parameter.
8608 //
8609 // Determine the implicit conversion sequence for the implicit
8610 // object parameter.
8611 QualType ObjectType = From->getType();
8612 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8613 ObjectType = FromPtrType->getPointeeType();
8614 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8615 // C++23 [over.best.ics.general]
8616 // However, if the target is [...]
8617 // - the object parameter of a user-defined conversion function
8618 // [...] user-defined conversion sequences are not considered.
8620 *this, CandidateSet.getLocation(), From->getType(),
8621 From->Classify(Context), Conversion, ConversionContext,
8622 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8623 /*SuppressUserConversion*/ true);
8624
8625 if (Candidate.Conversions[0].isBad()) {
8626 Candidate.Viable = false;
8628 return;
8629 }
8630
8631 if (Conversion->getTrailingRequiresClause()) {
8632 ConstraintSatisfaction Satisfaction;
8633 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8634 !Satisfaction.IsSatisfied) {
8635 Candidate.Viable = false;
8637 return;
8638 }
8639 }
8640
8641 // We won't go through a user-defined type conversion function to convert a
8642 // derived to base as such conversions are given Conversion Rank. They only
8643 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8644 QualType FromCanon
8645 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8646 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8647 if (FromCanon == ToCanon ||
8648 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8649 Candidate.Viable = false;
8651 return;
8652 }
8653
8654 // To determine what the conversion from the result of calling the
8655 // conversion function to the type we're eventually trying to
8656 // convert to (ToType), we need to synthesize a call to the
8657 // conversion function and attempt copy initialization from it. This
8658 // makes sure that we get the right semantics with respect to
8659 // lvalues/rvalues and the type. Fortunately, we can allocate this
8660 // call on the stack and we don't need its arguments to be
8661 // well-formed.
8662 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8663 VK_LValue, From->getBeginLoc());
8665 Context.getPointerType(Conversion->getType()),
8666 CK_FunctionToPointerDecay, &ConversionRef,
8668
8669 QualType ConversionType = Conversion->getConversionType();
8670 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8671 Candidate.Viable = false;
8673 return;
8674 }
8675
8676 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8677
8678 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8679
8680 // Introduce a temporary expression with the right type and value category
8681 // that we can use for deduction purposes.
8682 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8683
8685 TryCopyInitialization(*this, &FakeCall, ToType,
8686 /*SuppressUserConversions=*/true,
8687 /*InOverloadResolution=*/false,
8688 /*AllowObjCWritebackConversion=*/false);
8689
8690 switch (ICS.getKind()) {
8692 Candidate.FinalConversion = ICS.Standard;
8693 Candidate.HasFinalConversion = true;
8694
8695 // C++ [over.ics.user]p3:
8696 // If the user-defined conversion is specified by a specialization of a
8697 // conversion function template, the second standard conversion sequence
8698 // shall have exact match rank.
8699 if (Conversion->getPrimaryTemplate() &&
8701 Candidate.Viable = false;
8703 return;
8704 }
8705
8706 // C++0x [dcl.init.ref]p5:
8707 // In the second case, if the reference is an rvalue reference and
8708 // the second standard conversion sequence of the user-defined
8709 // conversion sequence includes an lvalue-to-rvalue conversion, the
8710 // program is ill-formed.
8711 if (ToType->isRValueReferenceType() &&
8713 Candidate.Viable = false;
8715 return;
8716 }
8717 break;
8718
8720 Candidate.Viable = false;
8722 return;
8723
8724 default:
8725 llvm_unreachable(
8726 "Can only end up with a standard conversion sequence or failure");
8727 }
8728
8729 if (EnableIfAttr *FailedAttr =
8730 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8731 Candidate.Viable = false;
8732 Candidate.FailureKind = ovl_fail_enable_if;
8733 Candidate.DeductionFailure.Data = FailedAttr;
8734 return;
8735 }
8736
8737 if (isNonViableMultiVersionOverload(Conversion)) {
8738 Candidate.Viable = false;
8740 }
8741}
8742
8744 Sema &S, OverloadCandidateSet &CandidateSet,
8746 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8747 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8748 bool AllowResultConversion) {
8749
8750 // If the function template has a non-dependent explicit specification,
8751 // exclude it now if appropriate; we are not permitted to perform deduction
8752 // and substitution in this case.
8753 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8754 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8755 Candidate.FoundDecl = FoundDecl;
8756 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8757 Candidate.Viable = false;
8758 Candidate.FailureKind = ovl_fail_explicit;
8759 return;
8760 }
8761
8762 QualType ObjectType = From->getType();
8763 Expr::Classification ObjectClassification = From->Classify(S.Context);
8764
8765 TemplateDeductionInfo Info(CandidateSet.getLocation());
8768 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8769 Specialization, Info);
8771 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8772 Candidate.FoundDecl = FoundDecl;
8773 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8774 Candidate.Viable = false;
8776 Candidate.ExplicitCallArguments = 1;
8777 Candidate.DeductionFailure =
8779 return;
8780 }
8781
8782 // Add the conversion function template specialization produced by
8783 // template argument deduction as a candidate.
8784 assert(Specialization && "Missing function template specialization?");
8785 S.AddConversionCandidate(Specialization, FoundDecl, ActingContext, From,
8786 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8787 AllowExplicit, AllowResultConversion,
8788 Info.hasStrictPackMatch());
8789}
8790
8793 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8794 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8795 bool AllowExplicit, bool AllowResultConversion) {
8796 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8797 "Only conversion function templates permitted here");
8798
8799 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8800 return;
8801
8802 if (!CandidateSet.shouldDeferTemplateArgumentDeduction(*this) ||
8803 CandidateSet.getKind() ==
8807 *this, CandidateSet, FunctionTemplate, FoundDecl, ActingDC, From,
8808 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8809 AllowResultConversion);
8810
8812 return;
8813 }
8814
8816 FunctionTemplate, FoundDecl, ActingDC, From, ToType,
8817 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8818}
8819
8821 DeclAccessPair FoundDecl,
8822 CXXRecordDecl *ActingContext,
8823 const FunctionProtoType *Proto,
8824 Expr *Object,
8825 ArrayRef<Expr *> Args,
8826 OverloadCandidateSet& CandidateSet) {
8827 if (!CandidateSet.isNewCandidate(Conversion))
8828 return;
8829
8830 // Overload resolution is always an unevaluated context.
8833
8834 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8835 Candidate.FoundDecl = FoundDecl;
8836 Candidate.Function = nullptr;
8837 Candidate.Surrogate = Conversion;
8838 Candidate.IsSurrogate = true;
8839 Candidate.Viable = true;
8840 Candidate.ExplicitCallArguments = Args.size();
8841
8842 // Determine the implicit conversion sequence for the implicit
8843 // object parameter.
8844 ImplicitConversionSequence ObjectInit;
8845 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8846 ObjectInit = TryCopyInitialization(*this, Object,
8847 Conversion->getParamDecl(0)->getType(),
8848 /*SuppressUserConversions=*/false,
8849 /*InOverloadResolution=*/true, false);
8850 } else {
8852 *this, CandidateSet.getLocation(), Object->getType(),
8853 Object->Classify(Context), Conversion, ActingContext);
8854 }
8855
8856 if (ObjectInit.isBad()) {
8857 Candidate.Viable = false;
8859 Candidate.Conversions[0] = ObjectInit;
8860 return;
8861 }
8862
8863 // The first conversion is actually a user-defined conversion whose
8864 // first conversion is ObjectInit's standard conversion (which is
8865 // effectively a reference binding). Record it as such.
8866 Candidate.Conversions[0].setUserDefined();
8867 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8868 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8869 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8870 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8871 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8872 Candidate.Conversions[0].UserDefined.After
8873 = Candidate.Conversions[0].UserDefined.Before;
8874 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8875
8876 // Find the
8877 unsigned NumParams = Proto->getNumParams();
8878
8879 // (C++ 13.3.2p2): A candidate function having fewer than m
8880 // parameters is viable only if it has an ellipsis in its parameter
8881 // list (8.3.5).
8882 if (Args.size() > NumParams && !Proto->isVariadic()) {
8883 Candidate.Viable = false;
8885 return;
8886 }
8887
8888 // Function types don't have any default arguments, so just check if
8889 // we have enough arguments.
8890 if (Args.size() < NumParams) {
8891 // Not enough arguments.
8892 Candidate.Viable = false;
8894 return;
8895 }
8896
8897 // Determine the implicit conversion sequences for each of the
8898 // arguments.
8899 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8900 if (ArgIdx < NumParams) {
8901 // (C++ 13.3.2p3): for F to be a viable function, there shall
8902 // exist for each argument an implicit conversion sequence
8903 // (13.3.3.1) that converts that argument to the corresponding
8904 // parameter of F.
8905 QualType ParamType = Proto->getParamType(ArgIdx);
8906 Candidate.Conversions[ArgIdx + 1]
8907 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8908 /*SuppressUserConversions=*/false,
8909 /*InOverloadResolution=*/false,
8910 /*AllowObjCWritebackConversion=*/
8911 getLangOpts().ObjCAutoRefCount);
8912 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8913 Candidate.Viable = false;
8915 return;
8916 }
8917 } else {
8918 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8919 // argument for which there is no corresponding parameter is
8920 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8921 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8922 }
8923 }
8924
8925 if (Conversion->getTrailingRequiresClause()) {
8926 ConstraintSatisfaction Satisfaction;
8927 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8928 /*ForOverloadResolution*/ true) ||
8929 !Satisfaction.IsSatisfied) {
8930 Candidate.Viable = false;
8932 return;
8933 }
8934 }
8935
8936 if (EnableIfAttr *FailedAttr =
8937 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8938 Candidate.Viable = false;
8939 Candidate.FailureKind = ovl_fail_enable_if;
8940 Candidate.DeductionFailure.Data = FailedAttr;
8941 return;
8942 }
8943}
8944
8946 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8947 OverloadCandidateSet &CandidateSet,
8948 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8949 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8950 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8951 ArrayRef<Expr *> FunctionArgs = Args;
8952
8953 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8954 FunctionDecl *FD =
8955 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8956
8957 // Don't consider rewritten functions if we're not rewriting.
8958 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8959 continue;
8960
8961 assert(!isa<CXXMethodDecl>(FD) &&
8962 "unqualified operator lookup found a member function");
8963
8964 if (FunTmpl) {
8965 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8966 FunctionArgs, CandidateSet);
8967 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
8968
8969 // As template candidates are not deduced immediately,
8970 // persist the array in the overload set.
8972 FunctionArgs[1], FunctionArgs[0]);
8973 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8974 Reversed, CandidateSet, false, false, true,
8975 ADLCallKind::NotADL,
8977 }
8978 } else {
8979 if (ExplicitTemplateArgs)
8980 continue;
8981 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8982 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8983 AddOverloadCandidate(FD, F.getPair(),
8984 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8985 false, false, true, false, ADLCallKind::NotADL, {},
8987 }
8988 }
8989}
8990
8992 SourceLocation OpLoc,
8993 ArrayRef<Expr *> Args,
8994 OverloadCandidateSet &CandidateSet,
8996 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8997
8998 // C++ [over.match.oper]p3:
8999 // For a unary operator @ with an operand of a type whose
9000 // cv-unqualified version is T1, and for a binary operator @ with
9001 // a left operand of a type whose cv-unqualified version is T1 and
9002 // a right operand of a type whose cv-unqualified version is T2,
9003 // three sets of candidate functions, designated member
9004 // candidates, non-member candidates and built-in candidates, are
9005 // constructed as follows:
9006 QualType T1 = Args[0]->getType();
9007
9008 // -- If T1 is a complete class type or a class currently being
9009 // defined, the set of member candidates is the result of the
9010 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
9011 // the set of member candidates is empty.
9012 if (T1->isRecordType()) {
9013 bool IsComplete = isCompleteType(OpLoc, T1);
9014 auto *T1RD = T1->getAsCXXRecordDecl();
9015 // Complete the type if it can be completed.
9016 // If the type is neither complete nor being defined, bail out now.
9017 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
9018 return;
9019
9020 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
9021 LookupQualifiedName(Operators, T1RD);
9022 Operators.suppressAccessDiagnostics();
9023
9024 for (LookupResult::iterator Oper = Operators.begin(),
9025 OperEnd = Operators.end();
9026 Oper != OperEnd; ++Oper) {
9027 if (Oper->getAsFunction() &&
9029 !CandidateSet.getRewriteInfo().shouldAddReversed(
9030 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
9031 continue;
9032 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
9033 Args[0]->Classify(Context), Args.slice(1),
9034 CandidateSet, /*SuppressUserConversion=*/false, PO);
9035 }
9036 }
9037}
9038
9040 OverloadCandidateSet& CandidateSet,
9041 bool IsAssignmentOperator,
9042 unsigned NumContextualBoolArguments) {
9043 // Overload resolution is always an unevaluated context.
9046
9047 // Add this candidate
9048 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
9049 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
9050 Candidate.Function = nullptr;
9051 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
9052
9053 // Determine the implicit conversion sequences for each of the
9054 // arguments.
9055 Candidate.Viable = true;
9056 Candidate.ExplicitCallArguments = Args.size();
9057 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9058 // C++ [over.match.oper]p4:
9059 // For the built-in assignment operators, conversions of the
9060 // left operand are restricted as follows:
9061 // -- no temporaries are introduced to hold the left operand, and
9062 // -- no user-defined conversions are applied to the left
9063 // operand to achieve a type match with the left-most
9064 // parameter of a built-in candidate.
9065 //
9066 // We block these conversions by turning off user-defined
9067 // conversions, since that is the only way that initialization of
9068 // a reference to a non-class type can occur from something that
9069 // is not of the same type.
9070 if (ArgIdx < NumContextualBoolArguments) {
9071 assert(ParamTys[ArgIdx] == Context.BoolTy &&
9072 "Contextual conversion to bool requires bool type");
9073 Candidate.Conversions[ArgIdx]
9074 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
9075 } else {
9076 Candidate.Conversions[ArgIdx]
9077 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
9078 ArgIdx == 0 && IsAssignmentOperator,
9079 /*InOverloadResolution=*/false,
9080 /*AllowObjCWritebackConversion=*/
9081 getLangOpts().ObjCAutoRefCount);
9082 }
9083 if (Candidate.Conversions[ArgIdx].isBad()) {
9084 Candidate.Viable = false;
9086 break;
9087 }
9088 }
9089}
9090
9091namespace {
9092
9093/// BuiltinCandidateTypeSet - A set of types that will be used for the
9094/// candidate operator functions for built-in operators (C++
9095/// [over.built]). The types are separated into pointer types and
9096/// enumeration types.
9097class BuiltinCandidateTypeSet {
9098 /// TypeSet - A set of types.
9099 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
9100
9101 /// PointerTypes - The set of pointer types that will be used in the
9102 /// built-in candidates.
9103 TypeSet PointerTypes;
9104
9105 /// MemberPointerTypes - The set of member pointer types that will be
9106 /// used in the built-in candidates.
9107 TypeSet MemberPointerTypes;
9108
9109 /// EnumerationTypes - The set of enumeration types that will be
9110 /// used in the built-in candidates.
9111 TypeSet EnumerationTypes;
9112
9113 /// The set of vector types that will be used in the built-in
9114 /// candidates.
9115 TypeSet VectorTypes;
9116
9117 /// The set of matrix types that will be used in the built-in
9118 /// candidates.
9119 TypeSet MatrixTypes;
9120
9121 /// The set of _BitInt types that will be used in the built-in candidates.
9122 TypeSet BitIntTypes;
9123
9124 /// A flag indicating non-record types are viable candidates
9125 bool HasNonRecordTypes;
9126
9127 /// A flag indicating whether either arithmetic or enumeration types
9128 /// were present in the candidate set.
9129 bool HasArithmeticOrEnumeralTypes;
9130
9131 /// A flag indicating whether the nullptr type was present in the
9132 /// candidate set.
9133 bool HasNullPtrType;
9134
9135 /// Sema - The semantic analysis instance where we are building the
9136 /// candidate type set.
9137 Sema &SemaRef;
9138
9139 /// Context - The AST context in which we will build the type sets.
9140 ASTContext &Context;
9141
9142 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9143 const Qualifiers &VisibleQuals);
9144 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
9145
9146public:
9147 /// iterator - Iterates through the types that are part of the set.
9148 typedef TypeSet::iterator iterator;
9149
9150 BuiltinCandidateTypeSet(Sema &SemaRef)
9151 : HasNonRecordTypes(false),
9152 HasArithmeticOrEnumeralTypes(false),
9153 HasNullPtrType(false),
9154 SemaRef(SemaRef),
9155 Context(SemaRef.Context) { }
9156
9157 void AddTypesConvertedFrom(QualType Ty,
9158 SourceLocation Loc,
9159 bool AllowUserConversions,
9160 bool AllowExplicitConversions,
9161 const Qualifiers &VisibleTypeConversionsQuals);
9162
9163 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
9164 llvm::iterator_range<iterator> member_pointer_types() {
9165 return MemberPointerTypes;
9166 }
9167 llvm::iterator_range<iterator> enumeration_types() {
9168 return EnumerationTypes;
9169 }
9170 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
9171 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
9172 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
9173
9174 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
9175 bool hasNonRecordTypes() { return HasNonRecordTypes; }
9176 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
9177 bool hasNullPtrType() const { return HasNullPtrType; }
9178};
9179
9180} // end anonymous namespace
9181
9182/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
9183/// the set of pointer types along with any more-qualified variants of
9184/// that type. For example, if @p Ty is "int const *", this routine
9185/// will add "int const *", "int const volatile *", "int const
9186/// restrict *", and "int const volatile restrict *" to the set of
9187/// pointer types. Returns true if the add of @p Ty itself succeeded,
9188/// false otherwise.
9189///
9190/// FIXME: what to do about extended qualifiers?
9191bool
9192BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9193 const Qualifiers &VisibleQuals) {
9194
9195 // Insert this type.
9196 if (!PointerTypes.insert(Ty))
9197 return false;
9198
9199 QualType PointeeTy;
9200 const PointerType *PointerTy = Ty->getAs<PointerType>();
9201 bool buildObjCPtr = false;
9202 if (!PointerTy) {
9203 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
9204 PointeeTy = PTy->getPointeeType();
9205 buildObjCPtr = true;
9206 } else {
9207 PointeeTy = PointerTy->getPointeeType();
9208 }
9209
9210 // Don't add qualified variants of arrays. For one, they're not allowed
9211 // (the qualifier would sink to the element type), and for another, the
9212 // only overload situation where it matters is subscript or pointer +- int,
9213 // and those shouldn't have qualifier variants anyway.
9214 if (PointeeTy->isArrayType())
9215 return true;
9216
9217 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9218 bool hasVolatile = VisibleQuals.hasVolatile();
9219 bool hasRestrict = VisibleQuals.hasRestrict();
9220
9221 // Iterate through all strict supersets of BaseCVR.
9222 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9223 if ((CVR | BaseCVR) != CVR) continue;
9224 // Skip over volatile if no volatile found anywhere in the types.
9225 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
9226
9227 // Skip over restrict if no restrict found anywhere in the types, or if
9228 // the type cannot be restrict-qualified.
9229 if ((CVR & Qualifiers::Restrict) &&
9230 (!hasRestrict ||
9231 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
9232 continue;
9233
9234 // Build qualified pointee type.
9235 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9236
9237 // Build qualified pointer type.
9238 QualType QPointerTy;
9239 if (!buildObjCPtr)
9240 QPointerTy = Context.getPointerType(QPointeeTy);
9241 else
9242 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
9243
9244 // Insert qualified pointer type.
9245 PointerTypes.insert(QPointerTy);
9246 }
9247
9248 return true;
9249}
9250
9251/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
9252/// to the set of pointer types along with any more-qualified variants of
9253/// that type. For example, if @p Ty is "int const *", this routine
9254/// will add "int const *", "int const volatile *", "int const
9255/// restrict *", and "int const volatile restrict *" to the set of
9256/// pointer types. Returns true if the add of @p Ty itself succeeded,
9257/// false otherwise.
9258///
9259/// FIXME: what to do about extended qualifiers?
9260bool
9261BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
9262 QualType Ty) {
9263 // Insert this type.
9264 if (!MemberPointerTypes.insert(Ty))
9265 return false;
9266
9267 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9268 assert(PointerTy && "type was not a member pointer type!");
9269
9270 QualType PointeeTy = PointerTy->getPointeeType();
9271 // Don't add qualified variants of arrays. For one, they're not allowed
9272 // (the qualifier would sink to the element type), and for another, the
9273 // only overload situation where it matters is subscript or pointer +- int,
9274 // and those shouldn't have qualifier variants anyway.
9275 if (PointeeTy->isArrayType())
9276 return true;
9277 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9278
9279 // Iterate through all strict supersets of the pointee type's CVR
9280 // qualifiers.
9281 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9282 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9283 if ((CVR | BaseCVR) != CVR) continue;
9284
9285 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9286 MemberPointerTypes.insert(Context.getMemberPointerType(
9287 QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9288 }
9289
9290 return true;
9291}
9292
9293/// AddTypesConvertedFrom - Add each of the types to which the type @p
9294/// Ty can be implicit converted to the given set of @p Types. We're
9295/// primarily interested in pointer types and enumeration types. We also
9296/// take member pointer types, for the conditional operator.
9297/// AllowUserConversions is true if we should look at the conversion
9298/// functions of a class type, and AllowExplicitConversions if we
9299/// should also include the explicit conversion functions of a class
9300/// type.
9301void
9302BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9303 SourceLocation Loc,
9304 bool AllowUserConversions,
9305 bool AllowExplicitConversions,
9306 const Qualifiers &VisibleQuals) {
9307 // Only deal with canonical types.
9308 Ty = Context.getCanonicalType(Ty);
9309
9310 // Look through reference types; they aren't part of the type of an
9311 // expression for the purposes of conversions.
9312 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9313 Ty = RefTy->getPointeeType();
9314
9315 // If we're dealing with an array type, decay to the pointer.
9316 if (Ty->isArrayType())
9317 Ty = SemaRef.Context.getArrayDecayedType(Ty);
9318
9319 // Otherwise, we don't care about qualifiers on the type.
9320 Ty = Ty.getLocalUnqualifiedType();
9321
9322 // Flag if we ever add a non-record type.
9323 bool TyIsRec = Ty->isRecordType();
9324 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9325
9326 // Flag if we encounter an arithmetic type.
9327 HasArithmeticOrEnumeralTypes =
9328 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9329
9330 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9331 PointerTypes.insert(Ty);
9332 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9333 // Insert our type, and its more-qualified variants, into the set
9334 // of types.
9335 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9336 return;
9337 } else if (Ty->isMemberPointerType()) {
9338 // Member pointers are far easier, since the pointee can't be converted.
9339 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9340 return;
9341 } else if (Ty->isEnumeralType()) {
9342 HasArithmeticOrEnumeralTypes = true;
9343 EnumerationTypes.insert(Ty);
9344 } else if (Ty->isBitIntType()) {
9345 HasArithmeticOrEnumeralTypes = true;
9346 BitIntTypes.insert(Ty);
9347 } else if (Ty->isVectorType()) {
9348 // We treat vector types as arithmetic types in many contexts as an
9349 // extension.
9350 HasArithmeticOrEnumeralTypes = true;
9351 VectorTypes.insert(Ty);
9352 } else if (Ty->isMatrixType()) {
9353 // Similar to vector types, we treat vector types as arithmetic types in
9354 // many contexts as an extension.
9355 HasArithmeticOrEnumeralTypes = true;
9356 MatrixTypes.insert(Ty);
9357 } else if (Ty->isNullPtrType()) {
9358 HasNullPtrType = true;
9359 } else if (AllowUserConversions && TyIsRec) {
9360 // No conversion functions in incomplete types.
9361 if (!SemaRef.isCompleteType(Loc, Ty))
9362 return;
9363
9364 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9365 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9366 if (isa<UsingShadowDecl>(D))
9367 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9368
9369 // Skip conversion function templates; they don't tell us anything
9370 // about which builtin types we can convert to.
9372 continue;
9373
9374 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
9375 if (AllowExplicitConversions || !Conv->isExplicit()) {
9376 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
9377 VisibleQuals);
9378 }
9379 }
9380 }
9381}
9382/// Helper function for adjusting address spaces for the pointer or reference
9383/// operands of builtin operators depending on the argument.
9388
9389/// Helper function for AddBuiltinOperatorCandidates() that adds
9390/// the volatile- and non-volatile-qualified assignment operators for the
9391/// given type to the candidate set.
9393 QualType T,
9394 ArrayRef<Expr *> Args,
9395 OverloadCandidateSet &CandidateSet) {
9396 QualType ParamTypes[2];
9397
9398 // T& operator=(T&, T)
9399 ParamTypes[0] = S.Context.getLValueReferenceType(
9401 ParamTypes[1] = T;
9402 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9403 /*IsAssignmentOperator=*/true);
9404
9406 // volatile T& operator=(volatile T&, T)
9407 ParamTypes[0] = S.Context.getLValueReferenceType(
9409 Args[0]));
9410 ParamTypes[1] = T;
9411 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9412 /*IsAssignmentOperator=*/true);
9413 }
9414}
9415
9416/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9417/// if any, found in visible type conversion functions found in ArgExpr's type.
9418static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9419 Qualifiers VRQuals;
9420 CXXRecordDecl *ClassDecl;
9421 if (const MemberPointerType *RHSMPType =
9422 ArgExpr->getType()->getAs<MemberPointerType>())
9423 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9424 else
9425 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9426 if (!ClassDecl) {
9427 // Just to be safe, assume the worst case.
9428 VRQuals.addVolatile();
9429 VRQuals.addRestrict();
9430 return VRQuals;
9431 }
9432 if (!ClassDecl->hasDefinition())
9433 return VRQuals;
9434
9435 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9436 if (isa<UsingShadowDecl>(D))
9437 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9438 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
9439 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
9440 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9441 CanTy = ResTypeRef->getPointeeType();
9442 // Need to go down the pointer/mempointer chain and add qualifiers
9443 // as see them.
9444 bool done = false;
9445 while (!done) {
9446 if (CanTy.isRestrictQualified())
9447 VRQuals.addRestrict();
9448 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9449 CanTy = ResTypePtr->getPointeeType();
9450 else if (const MemberPointerType *ResTypeMPtr =
9451 CanTy->getAs<MemberPointerType>())
9452 CanTy = ResTypeMPtr->getPointeeType();
9453 else
9454 done = true;
9455 if (CanTy.isVolatileQualified())
9456 VRQuals.addVolatile();
9457 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9458 return VRQuals;
9459 }
9460 }
9461 }
9462 return VRQuals;
9463}
9464
9465// Note: We're currently only handling qualifiers that are meaningful for the
9466// LHS of compound assignment overloading.
9468 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9469 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9470 // _Atomic
9471 if (Available.hasAtomic()) {
9472 Available.removeAtomic();
9473 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
9474 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9475 return;
9476 }
9477
9478 // volatile
9479 if (Available.hasVolatile()) {
9480 Available.removeVolatile();
9481 assert(!Applied.hasVolatile());
9482 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
9483 Callback);
9484 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9485 return;
9486 }
9487
9488 Callback(Applied);
9489}
9490
9492 QualifiersAndAtomic Quals,
9493 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9495 Callback);
9496}
9497
9499 QualifiersAndAtomic Quals,
9500 Sema &S) {
9501 if (Quals.hasAtomic())
9503 if (Quals.hasVolatile())
9506}
9507
9508namespace {
9509
9510/// Helper class to manage the addition of builtin operator overload
9511/// candidates. It provides shared state and utility methods used throughout
9512/// the process, as well as a helper method to add each group of builtin
9513/// operator overloads from the standard to a candidate set.
9514class BuiltinOperatorOverloadBuilder {
9515 // Common instance state available to all overload candidate addition methods.
9516 Sema &S;
9517 ArrayRef<Expr *> Args;
9518 QualifiersAndAtomic VisibleTypeConversionsQuals;
9519 bool HasArithmeticOrEnumeralCandidateType;
9520 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9521 OverloadCandidateSet &CandidateSet;
9522
9523 static constexpr int ArithmeticTypesCap = 26;
9524 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9525
9526 // Define some indices used to iterate over the arithmetic types in
9527 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9528 // types are that preserved by promotion (C++ [over.built]p2).
9529 unsigned FirstIntegralType,
9530 LastIntegralType;
9531 unsigned FirstPromotedIntegralType,
9532 LastPromotedIntegralType;
9533 unsigned FirstPromotedArithmeticType,
9534 LastPromotedArithmeticType;
9535 unsigned NumArithmeticTypes;
9536
9537 void InitArithmeticTypes() {
9538 // Start of promoted types.
9539 FirstPromotedArithmeticType = 0;
9540 ArithmeticTypes.push_back(S.Context.FloatTy);
9541 ArithmeticTypes.push_back(S.Context.DoubleTy);
9542 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
9544 ArithmeticTypes.push_back(S.Context.Float128Ty);
9546 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
9547
9548 // Start of integral types.
9549 FirstIntegralType = ArithmeticTypes.size();
9550 FirstPromotedIntegralType = ArithmeticTypes.size();
9551 ArithmeticTypes.push_back(S.Context.IntTy);
9552 ArithmeticTypes.push_back(S.Context.LongTy);
9553 ArithmeticTypes.push_back(S.Context.LongLongTy);
9557 ArithmeticTypes.push_back(S.Context.Int128Ty);
9558 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
9559 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
9560 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
9564 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
9565
9566 /// We add candidates for the unique, unqualified _BitInt types present in
9567 /// the candidate type set. The candidate set already handled ensuring the
9568 /// type is unqualified and canonical, but because we're adding from N
9569 /// different sets, we need to do some extra work to unique things. Insert
9570 /// the candidates into a unique set, then move from that set into the list
9571 /// of arithmetic types.
9572 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9573 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9574 for (QualType BitTy : Candidate.bitint_types())
9575 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
9576 }
9577 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
9578 LastPromotedIntegralType = ArithmeticTypes.size();
9579 LastPromotedArithmeticType = ArithmeticTypes.size();
9580 // End of promoted types.
9581
9582 ArithmeticTypes.push_back(S.Context.BoolTy);
9583 ArithmeticTypes.push_back(S.Context.CharTy);
9584 ArithmeticTypes.push_back(S.Context.WCharTy);
9585 if (S.Context.getLangOpts().Char8)
9586 ArithmeticTypes.push_back(S.Context.Char8Ty);
9587 ArithmeticTypes.push_back(S.Context.Char16Ty);
9588 ArithmeticTypes.push_back(S.Context.Char32Ty);
9589 ArithmeticTypes.push_back(S.Context.SignedCharTy);
9590 ArithmeticTypes.push_back(S.Context.ShortTy);
9591 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9592 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9593 LastIntegralType = ArithmeticTypes.size();
9594 NumArithmeticTypes = ArithmeticTypes.size();
9595 // End of integral types.
9596 // FIXME: What about complex? What about half?
9597
9598 // We don't know for sure how many bit-precise candidates were involved, so
9599 // we subtract those from the total when testing whether we're under the
9600 // cap or not.
9601 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9602 ArithmeticTypesCap &&
9603 "Enough inline storage for all arithmetic types.");
9604 }
9605
9606 /// Helper method to factor out the common pattern of adding overloads
9607 /// for '++' and '--' builtin operators.
9608 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9609 bool HasVolatile,
9610 bool HasRestrict) {
9611 QualType ParamTypes[2] = {
9612 S.Context.getLValueReferenceType(CandidateTy),
9613 S.Context.IntTy
9614 };
9615
9616 // Non-volatile version.
9617 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9618
9619 // Use a heuristic to reduce number of builtin candidates in the set:
9620 // add volatile version only if there are conversions to a volatile type.
9621 if (HasVolatile) {
9622 ParamTypes[0] =
9624 S.Context.getVolatileType(CandidateTy));
9625 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9626 }
9627
9628 // Add restrict version only if there are conversions to a restrict type
9629 // and our candidate type is a non-restrict-qualified pointer.
9630 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9631 !CandidateTy.isRestrictQualified()) {
9632 ParamTypes[0]
9635 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9636
9637 if (HasVolatile) {
9638 ParamTypes[0]
9640 S.Context.getCVRQualifiedType(CandidateTy,
9643 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9644 }
9645 }
9646
9647 }
9648
9649 /// Helper to add an overload candidate for a binary builtin with types \p L
9650 /// and \p R.
9651 void AddCandidate(QualType L, QualType R) {
9652 QualType LandR[2] = {L, R};
9653 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9654 }
9655
9656public:
9657 BuiltinOperatorOverloadBuilder(
9658 Sema &S, ArrayRef<Expr *> Args,
9659 QualifiersAndAtomic VisibleTypeConversionsQuals,
9660 bool HasArithmeticOrEnumeralCandidateType,
9661 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9662 OverloadCandidateSet &CandidateSet)
9663 : S(S), Args(Args),
9664 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9665 HasArithmeticOrEnumeralCandidateType(
9666 HasArithmeticOrEnumeralCandidateType),
9667 CandidateTypes(CandidateTypes),
9668 CandidateSet(CandidateSet) {
9669
9670 InitArithmeticTypes();
9671 }
9672
9673 // Increment is deprecated for bool since C++17.
9674 //
9675 // C++ [over.built]p3:
9676 //
9677 // For every pair (T, VQ), where T is an arithmetic type other
9678 // than bool, and VQ is either volatile or empty, there exist
9679 // candidate operator functions of the form
9680 //
9681 // VQ T& operator++(VQ T&);
9682 // T operator++(VQ T&, int);
9683 //
9684 // C++ [over.built]p4:
9685 //
9686 // For every pair (T, VQ), where T is an arithmetic type other
9687 // than bool, and VQ is either volatile or empty, there exist
9688 // candidate operator functions of the form
9689 //
9690 // VQ T& operator--(VQ T&);
9691 // T operator--(VQ T&, int);
9692 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9693 if (!HasArithmeticOrEnumeralCandidateType)
9694 return;
9695
9696 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9697 const auto TypeOfT = ArithmeticTypes[Arith];
9698 if (TypeOfT == S.Context.BoolTy) {
9699 if (Op == OO_MinusMinus)
9700 continue;
9701 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9702 continue;
9703 }
9704 addPlusPlusMinusMinusStyleOverloads(
9705 TypeOfT,
9706 VisibleTypeConversionsQuals.hasVolatile(),
9707 VisibleTypeConversionsQuals.hasRestrict());
9708 }
9709 }
9710
9711 // C++ [over.built]p5:
9712 //
9713 // For every pair (T, VQ), where T is a cv-qualified or
9714 // cv-unqualified object type, and VQ is either volatile or
9715 // empty, there exist candidate operator functions of the form
9716 //
9717 // T*VQ& operator++(T*VQ&);
9718 // T*VQ& operator--(T*VQ&);
9719 // T* operator++(T*VQ&, int);
9720 // T* operator--(T*VQ&, int);
9721 void addPlusPlusMinusMinusPointerOverloads() {
9722 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9723 // Skip pointer types that aren't pointers to object types.
9724 if (!PtrTy->getPointeeType()->isObjectType())
9725 continue;
9726
9727 addPlusPlusMinusMinusStyleOverloads(
9728 PtrTy,
9729 (!PtrTy.isVolatileQualified() &&
9730 VisibleTypeConversionsQuals.hasVolatile()),
9731 (!PtrTy.isRestrictQualified() &&
9732 VisibleTypeConversionsQuals.hasRestrict()));
9733 }
9734 }
9735
9736 // C++ [over.built]p6:
9737 // For every cv-qualified or cv-unqualified object type T, there
9738 // exist candidate operator functions of the form
9739 //
9740 // T& operator*(T*);
9741 //
9742 // C++ [over.built]p7:
9743 // For every function type T that does not have cv-qualifiers or a
9744 // ref-qualifier, there exist candidate operator functions of the form
9745 // T& operator*(T*);
9746 void addUnaryStarPointerOverloads() {
9747 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9748 QualType PointeeTy = ParamTy->getPointeeType();
9749 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9750 continue;
9751
9752 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9753 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9754 continue;
9755
9756 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9757 }
9758 }
9759
9760 // C++ [over.built]p9:
9761 // For every promoted arithmetic type T, there exist candidate
9762 // operator functions of the form
9763 //
9764 // T operator+(T);
9765 // T operator-(T);
9766 void addUnaryPlusOrMinusArithmeticOverloads() {
9767 if (!HasArithmeticOrEnumeralCandidateType)
9768 return;
9769
9770 for (unsigned Arith = FirstPromotedArithmeticType;
9771 Arith < LastPromotedArithmeticType; ++Arith) {
9772 QualType ArithTy = ArithmeticTypes[Arith];
9773 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9774 }
9775
9776 // Extension: We also add these operators for vector types.
9777 for (QualType VecTy : CandidateTypes[0].vector_types())
9778 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9779 }
9780
9781 // C++ [over.built]p8:
9782 // For every type T, there exist candidate operator functions of
9783 // the form
9784 //
9785 // T* operator+(T*);
9786 void addUnaryPlusPointerOverloads() {
9787 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9788 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9789 }
9790
9791 // C++ [over.built]p10:
9792 // For every promoted integral type T, there exist candidate
9793 // operator functions of the form
9794 //
9795 // T operator~(T);
9796 void addUnaryTildePromotedIntegralOverloads() {
9797 if (!HasArithmeticOrEnumeralCandidateType)
9798 return;
9799
9800 for (unsigned Int = FirstPromotedIntegralType;
9801 Int < LastPromotedIntegralType; ++Int) {
9802 QualType IntTy = ArithmeticTypes[Int];
9803 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9804 }
9805
9806 // Extension: We also add this operator for vector types.
9807 for (QualType VecTy : CandidateTypes[0].vector_types())
9808 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9809 }
9810
9811 // C++ [over.match.oper]p16:
9812 // For every pointer to member type T or type std::nullptr_t, there
9813 // exist candidate operator functions of the form
9814 //
9815 // bool operator==(T,T);
9816 // bool operator!=(T,T);
9817 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9818 /// Set of (canonical) types that we've already handled.
9819 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9820
9821 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9822 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9823 // Don't add the same builtin candidate twice.
9824 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9825 continue;
9826
9827 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9828 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9829 }
9830
9831 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9833 if (AddedTypes.insert(NullPtrTy).second) {
9834 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9835 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9836 }
9837 }
9838 }
9839 }
9840
9841 // C++ [over.built]p15:
9842 //
9843 // For every T, where T is an enumeration type or a pointer type,
9844 // there exist candidate operator functions of the form
9845 //
9846 // bool operator<(T, T);
9847 // bool operator>(T, T);
9848 // bool operator<=(T, T);
9849 // bool operator>=(T, T);
9850 // bool operator==(T, T);
9851 // bool operator!=(T, T);
9852 // R operator<=>(T, T)
9853 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9854 // C++ [over.match.oper]p3:
9855 // [...]the built-in candidates include all of the candidate operator
9856 // functions defined in 13.6 that, compared to the given operator, [...]
9857 // do not have the same parameter-type-list as any non-template non-member
9858 // candidate.
9859 //
9860 // Note that in practice, this only affects enumeration types because there
9861 // aren't any built-in candidates of record type, and a user-defined operator
9862 // must have an operand of record or enumeration type. Also, the only other
9863 // overloaded operator with enumeration arguments, operator=,
9864 // cannot be overloaded for enumeration types, so this is the only place
9865 // where we must suppress candidates like this.
9866 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9867 UserDefinedBinaryOperators;
9868
9869 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9870 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9871 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9872 CEnd = CandidateSet.end();
9873 C != CEnd; ++C) {
9874 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9875 continue;
9876
9877 if (C->Function->isFunctionTemplateSpecialization())
9878 continue;
9879
9880 // We interpret "same parameter-type-list" as applying to the
9881 // "synthesized candidate, with the order of the two parameters
9882 // reversed", not to the original function.
9883 bool Reversed = C->isReversed();
9884 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9885 ->getType()
9886 .getUnqualifiedType();
9887 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9888 ->getType()
9889 .getUnqualifiedType();
9890
9891 // Skip if either parameter isn't of enumeral type.
9892 if (!FirstParamType->isEnumeralType() ||
9893 !SecondParamType->isEnumeralType())
9894 continue;
9895
9896 // Add this operator to the set of known user-defined operators.
9897 UserDefinedBinaryOperators.insert(
9898 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9899 S.Context.getCanonicalType(SecondParamType)));
9900 }
9901 }
9902 }
9903
9904 /// Set of (canonical) types that we've already handled.
9905 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9906
9907 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9908 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9909 // Don't add the same builtin candidate twice.
9910 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9911 continue;
9912 if (IsSpaceship && PtrTy->isFunctionPointerType())
9913 continue;
9914
9915 QualType ParamTypes[2] = {PtrTy, PtrTy};
9916 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9917 }
9918 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9919 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9920
9921 // Don't add the same builtin candidate twice, or if a user defined
9922 // candidate exists.
9923 if (!AddedTypes.insert(CanonType).second ||
9924 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9925 CanonType)))
9926 continue;
9927 QualType ParamTypes[2] = {EnumTy, EnumTy};
9928 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9929 }
9930 }
9931 }
9932
9933 // C++ [over.built]p13:
9934 //
9935 // For every cv-qualified or cv-unqualified object type T
9936 // there exist candidate operator functions of the form
9937 //
9938 // T* operator+(T*, ptrdiff_t);
9939 // T& operator[](T*, ptrdiff_t); [BELOW]
9940 // T* operator-(T*, ptrdiff_t);
9941 // T* operator+(ptrdiff_t, T*);
9942 // T& operator[](ptrdiff_t, T*); [BELOW]
9943 //
9944 // C++ [over.built]p14:
9945 //
9946 // For every T, where T is a pointer to object type, there
9947 // exist candidate operator functions of the form
9948 //
9949 // ptrdiff_t operator-(T, T);
9950 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9951 /// Set of (canonical) types that we've already handled.
9952 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9953
9954 for (int Arg = 0; Arg < 2; ++Arg) {
9955 QualType AsymmetricParamTypes[2] = {
9958 };
9959 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9960 QualType PointeeTy = PtrTy->getPointeeType();
9961 if (!PointeeTy->isObjectType())
9962 continue;
9963
9964 AsymmetricParamTypes[Arg] = PtrTy;
9965 if (Arg == 0 || Op == OO_Plus) {
9966 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9967 // T* operator+(ptrdiff_t, T*);
9968 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9969 }
9970 if (Op == OO_Minus) {
9971 // ptrdiff_t operator-(T, T);
9972 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9973 continue;
9974
9975 QualType ParamTypes[2] = {PtrTy, PtrTy};
9976 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9977 }
9978 }
9979 }
9980 }
9981
9982 // C++ [over.built]p12:
9983 //
9984 // For every pair of promoted arithmetic types L and R, there
9985 // exist candidate operator functions of the form
9986 //
9987 // LR operator*(L, R);
9988 // LR operator/(L, R);
9989 // LR operator+(L, R);
9990 // LR operator-(L, R);
9991 // bool operator<(L, R);
9992 // bool operator>(L, R);
9993 // bool operator<=(L, R);
9994 // bool operator>=(L, R);
9995 // bool operator==(L, R);
9996 // bool operator!=(L, R);
9997 //
9998 // where LR is the result of the usual arithmetic conversions
9999 // between types L and R.
10000 //
10001 // C++ [over.built]p24:
10002 //
10003 // For every pair of promoted arithmetic types L and R, there exist
10004 // candidate operator functions of the form
10005 //
10006 // LR operator?(bool, L, R);
10007 //
10008 // where LR is the result of the usual arithmetic conversions
10009 // between types L and R.
10010 // Our candidates ignore the first parameter.
10011 void addGenericBinaryArithmeticOverloads() {
10012 if (!HasArithmeticOrEnumeralCandidateType)
10013 return;
10014
10015 for (unsigned Left = FirstPromotedArithmeticType;
10016 Left < LastPromotedArithmeticType; ++Left) {
10017 for (unsigned Right = FirstPromotedArithmeticType;
10018 Right < LastPromotedArithmeticType; ++Right) {
10019 QualType LandR[2] = { ArithmeticTypes[Left],
10020 ArithmeticTypes[Right] };
10021 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
10022 }
10023 }
10024
10025 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
10026 // conditional operator for vector types.
10027 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10028 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
10029 QualType LandR[2] = {Vec1Ty, Vec2Ty};
10030 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
10031 }
10032 }
10033
10034 /// Add binary operator overloads for each candidate matrix type M1, M2:
10035 /// * (M1, M1) -> M1
10036 /// * (M1, M1.getElementType()) -> M1
10037 /// * (M2.getElementType(), M2) -> M2
10038 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
10039 void addMatrixBinaryArithmeticOverloads() {
10040 if (!HasArithmeticOrEnumeralCandidateType)
10041 return;
10042
10043 for (QualType M1 : CandidateTypes[0].matrix_types()) {
10044 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
10045 AddCandidate(M1, M1);
10046 }
10047
10048 for (QualType M2 : CandidateTypes[1].matrix_types()) {
10049 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
10050 if (!CandidateTypes[0].containsMatrixType(M2))
10051 AddCandidate(M2, M2);
10052 }
10053 }
10054
10055 // C++2a [over.built]p14:
10056 //
10057 // For every integral type T there exists a candidate operator function
10058 // of the form
10059 //
10060 // std::strong_ordering operator<=>(T, T)
10061 //
10062 // C++2a [over.built]p15:
10063 //
10064 // For every pair of floating-point types L and R, there exists a candidate
10065 // operator function of the form
10066 //
10067 // std::partial_ordering operator<=>(L, R);
10068 //
10069 // FIXME: The current specification for integral types doesn't play nice with
10070 // the direction of p0946r0, which allows mixed integral and unscoped-enum
10071 // comparisons. Under the current spec this can lead to ambiguity during
10072 // overload resolution. For example:
10073 //
10074 // enum A : int {a};
10075 // auto x = (a <=> (long)42);
10076 //
10077 // error: call is ambiguous for arguments 'A' and 'long'.
10078 // note: candidate operator<=>(int, int)
10079 // note: candidate operator<=>(long, long)
10080 //
10081 // To avoid this error, this function deviates from the specification and adds
10082 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
10083 // arithmetic types (the same as the generic relational overloads).
10084 //
10085 // For now this function acts as a placeholder.
10086 void addThreeWayArithmeticOverloads() {
10087 addGenericBinaryArithmeticOverloads();
10088 }
10089
10090 // C++ [over.built]p17:
10091 //
10092 // For every pair of promoted integral types L and R, there
10093 // exist candidate operator functions of the form
10094 //
10095 // LR operator%(L, R);
10096 // LR operator&(L, R);
10097 // LR operator^(L, R);
10098 // LR operator|(L, R);
10099 // L operator<<(L, R);
10100 // L operator>>(L, R);
10101 //
10102 // where LR is the result of the usual arithmetic conversions
10103 // between types L and R.
10104 void addBinaryBitwiseArithmeticOverloads() {
10105 if (!HasArithmeticOrEnumeralCandidateType)
10106 return;
10107
10108 for (unsigned Left = FirstPromotedIntegralType;
10109 Left < LastPromotedIntegralType; ++Left) {
10110 for (unsigned Right = FirstPromotedIntegralType;
10111 Right < LastPromotedIntegralType; ++Right) {
10112 QualType LandR[2] = { ArithmeticTypes[Left],
10113 ArithmeticTypes[Right] };
10114 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
10115 }
10116 }
10117 }
10118
10119 // C++ [over.built]p20:
10120 //
10121 // For every pair (T, VQ), where T is an enumeration or
10122 // pointer to member type and VQ is either volatile or
10123 // empty, there exist candidate operator functions of the form
10124 //
10125 // VQ T& operator=(VQ T&, T);
10126 void addAssignmentMemberPointerOrEnumeralOverloads() {
10127 /// Set of (canonical) types that we've already handled.
10128 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10129
10130 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10131 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10132 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10133 continue;
10134
10135 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
10136 }
10137
10138 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10139 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10140 continue;
10141
10142 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
10143 }
10144 }
10145 }
10146
10147 // C++ [over.built]p19:
10148 //
10149 // For every pair (T, VQ), where T is any type and VQ is either
10150 // volatile or empty, there exist candidate operator functions
10151 // of the form
10152 //
10153 // T*VQ& operator=(T*VQ&, T*);
10154 //
10155 // C++ [over.built]p21:
10156 //
10157 // For every pair (T, VQ), where T is a cv-qualified or
10158 // cv-unqualified object type and VQ is either volatile or
10159 // empty, there exist candidate operator functions of the form
10160 //
10161 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
10162 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
10163 void addAssignmentPointerOverloads(bool isEqualOp) {
10164 /// Set of (canonical) types that we've already handled.
10165 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10166
10167 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10168 // If this is operator=, keep track of the builtin candidates we added.
10169 if (isEqualOp)
10170 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
10171 else if (!PtrTy->getPointeeType()->isObjectType())
10172 continue;
10173
10174 // non-volatile version
10175 QualType ParamTypes[2] = {
10177 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
10178 };
10179 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10180 /*IsAssignmentOperator=*/ isEqualOp);
10181
10182 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10183 VisibleTypeConversionsQuals.hasVolatile();
10184 if (NeedVolatile) {
10185 // volatile version
10186 ParamTypes[0] =
10188 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10189 /*IsAssignmentOperator=*/isEqualOp);
10190 }
10191
10192 if (!PtrTy.isRestrictQualified() &&
10193 VisibleTypeConversionsQuals.hasRestrict()) {
10194 // restrict version
10195 ParamTypes[0] =
10197 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10198 /*IsAssignmentOperator=*/isEqualOp);
10199
10200 if (NeedVolatile) {
10201 // volatile restrict version
10202 ParamTypes[0] =
10205 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10206 /*IsAssignmentOperator=*/isEqualOp);
10207 }
10208 }
10209 }
10210
10211 if (isEqualOp) {
10212 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10213 // Make sure we don't add the same candidate twice.
10214 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10215 continue;
10216
10217 QualType ParamTypes[2] = {
10219 PtrTy,
10220 };
10221
10222 // non-volatile version
10223 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10224 /*IsAssignmentOperator=*/true);
10225
10226 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10227 VisibleTypeConversionsQuals.hasVolatile();
10228 if (NeedVolatile) {
10229 // volatile version
10230 ParamTypes[0] = S.Context.getLValueReferenceType(
10231 S.Context.getVolatileType(PtrTy));
10232 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10233 /*IsAssignmentOperator=*/true);
10234 }
10235
10236 if (!PtrTy.isRestrictQualified() &&
10237 VisibleTypeConversionsQuals.hasRestrict()) {
10238 // restrict version
10239 ParamTypes[0] = S.Context.getLValueReferenceType(
10240 S.Context.getRestrictType(PtrTy));
10241 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10242 /*IsAssignmentOperator=*/true);
10243
10244 if (NeedVolatile) {
10245 // volatile restrict version
10246 ParamTypes[0] =
10249 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10250 /*IsAssignmentOperator=*/true);
10251 }
10252 }
10253 }
10254 }
10255 }
10256
10257 // C++ [over.built]p18:
10258 //
10259 // For every triple (L, VQ, R), where L is an arithmetic type,
10260 // VQ is either volatile or empty, and R is a promoted
10261 // arithmetic type, there exist candidate operator functions of
10262 // the form
10263 //
10264 // VQ L& operator=(VQ L&, R);
10265 // VQ L& operator*=(VQ L&, R);
10266 // VQ L& operator/=(VQ L&, R);
10267 // VQ L& operator+=(VQ L&, R);
10268 // VQ L& operator-=(VQ L&, R);
10269 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10270 if (!HasArithmeticOrEnumeralCandidateType)
10271 return;
10272
10273 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10274 for (unsigned Right = FirstPromotedArithmeticType;
10275 Right < LastPromotedArithmeticType; ++Right) {
10276 QualType ParamTypes[2];
10277 ParamTypes[1] = ArithmeticTypes[Right];
10279 S, ArithmeticTypes[Left], Args[0]);
10280
10282 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10283 ParamTypes[0] =
10284 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10285 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10286 /*IsAssignmentOperator=*/isEqualOp);
10287 });
10288 }
10289 }
10290
10291 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10292 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10293 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10294 QualType ParamTypes[2];
10295 ParamTypes[1] = Vec2Ty;
10296 // Add this built-in operator as a candidate (VQ is empty).
10297 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
10298 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10299 /*IsAssignmentOperator=*/isEqualOp);
10300
10301 // Add this built-in operator as a candidate (VQ is 'volatile').
10302 if (VisibleTypeConversionsQuals.hasVolatile()) {
10303 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
10304 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
10305 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10306 /*IsAssignmentOperator=*/isEqualOp);
10307 }
10308 }
10309 }
10310
10311 // C++ [over.built]p22:
10312 //
10313 // For every triple (L, VQ, R), where L is an integral type, VQ
10314 // is either volatile or empty, and R is a promoted integral
10315 // type, there exist candidate operator functions of the form
10316 //
10317 // VQ L& operator%=(VQ L&, R);
10318 // VQ L& operator<<=(VQ L&, R);
10319 // VQ L& operator>>=(VQ L&, R);
10320 // VQ L& operator&=(VQ L&, R);
10321 // VQ L& operator^=(VQ L&, R);
10322 // VQ L& operator|=(VQ L&, R);
10323 void addAssignmentIntegralOverloads() {
10324 if (!HasArithmeticOrEnumeralCandidateType)
10325 return;
10326
10327 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10328 for (unsigned Right = FirstPromotedIntegralType;
10329 Right < LastPromotedIntegralType; ++Right) {
10330 QualType ParamTypes[2];
10331 ParamTypes[1] = ArithmeticTypes[Right];
10333 S, ArithmeticTypes[Left], Args[0]);
10334
10336 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10337 ParamTypes[0] =
10338 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10339 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10340 });
10341 }
10342 }
10343 }
10344
10345 // C++ [over.operator]p23:
10346 //
10347 // There also exist candidate operator functions of the form
10348 //
10349 // bool operator!(bool);
10350 // bool operator&&(bool, bool);
10351 // bool operator||(bool, bool);
10352 void addExclaimOverload() {
10353 QualType ParamTy = S.Context.BoolTy;
10354 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
10355 /*IsAssignmentOperator=*/false,
10356 /*NumContextualBoolArguments=*/1);
10357 }
10358 void addAmpAmpOrPipePipeOverload() {
10359 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10360 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10361 /*IsAssignmentOperator=*/false,
10362 /*NumContextualBoolArguments=*/2);
10363 }
10364
10365 // C++ [over.built]p13:
10366 //
10367 // For every cv-qualified or cv-unqualified object type T there
10368 // exist candidate operator functions of the form
10369 //
10370 // T* operator+(T*, ptrdiff_t); [ABOVE]
10371 // T& operator[](T*, ptrdiff_t);
10372 // T* operator-(T*, ptrdiff_t); [ABOVE]
10373 // T* operator+(ptrdiff_t, T*); [ABOVE]
10374 // T& operator[](ptrdiff_t, T*);
10375 void addSubscriptOverloads() {
10376 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10377 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10378 QualType PointeeType = PtrTy->getPointeeType();
10379 if (!PointeeType->isObjectType())
10380 continue;
10381
10382 // T& operator[](T*, ptrdiff_t)
10383 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10384 }
10385
10386 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10387 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10388 QualType PointeeType = PtrTy->getPointeeType();
10389 if (!PointeeType->isObjectType())
10390 continue;
10391
10392 // T& operator[](ptrdiff_t, T*)
10393 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10394 }
10395 }
10396
10397 // C++ [over.built]p11:
10398 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10399 // C1 is the same type as C2 or is a derived class of C2, T is an object
10400 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10401 // there exist candidate operator functions of the form
10402 //
10403 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10404 //
10405 // where CV12 is the union of CV1 and CV2.
10406 void addArrowStarOverloads() {
10407 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10408 QualType C1Ty = PtrTy;
10409 QualType C1;
10410 QualifierCollector Q1;
10411 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
10412 if (!isa<RecordType>(C1))
10413 continue;
10414 // heuristic to reduce number of builtin candidates in the set.
10415 // Add volatile/restrict version only if there are conversions to a
10416 // volatile/restrict type.
10417 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10418 continue;
10419 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10420 continue;
10421 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10422 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
10423 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10424 *D2 = mptr->getMostRecentCXXRecordDecl();
10425 if (!declaresSameEntity(D1, D2) &&
10426 !S.IsDerivedFrom(CandidateSet.getLocation(), D1, D2))
10427 break;
10428 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10429 // build CV12 T&
10430 QualType T = mptr->getPointeeType();
10431 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10432 T.isVolatileQualified())
10433 continue;
10434 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10435 T.isRestrictQualified())
10436 continue;
10437 T = Q1.apply(S.Context, T);
10438 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10439 }
10440 }
10441 }
10442
10443 // Note that we don't consider the first argument, since it has been
10444 // contextually converted to bool long ago. The candidates below are
10445 // therefore added as binary.
10446 //
10447 // C++ [over.built]p25:
10448 // For every type T, where T is a pointer, pointer-to-member, or scoped
10449 // enumeration type, there exist candidate operator functions of the form
10450 //
10451 // T operator?(bool, T, T);
10452 //
10453 void addConditionalOperatorOverloads() {
10454 /// Set of (canonical) types that we've already handled.
10455 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10456
10457 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10458 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10459 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10460 continue;
10461
10462 QualType ParamTypes[2] = {PtrTy, PtrTy};
10463 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10464 }
10465
10466 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10467 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10468 continue;
10469
10470 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10471 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10472 }
10473
10474 if (S.getLangOpts().CPlusPlus11) {
10475 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10476 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10477 continue;
10478
10479 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10480 continue;
10481
10482 QualType ParamTypes[2] = {EnumTy, EnumTy};
10483 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10484 }
10485 }
10486 }
10487 }
10488};
10489
10490} // end anonymous namespace
10491
10493 SourceLocation OpLoc,
10494 ArrayRef<Expr *> Args,
10495 OverloadCandidateSet &CandidateSet) {
10496 // Find all of the types that the arguments can convert to, but only
10497 // if the operator we're looking at has built-in operator candidates
10498 // that make use of these types. Also record whether we encounter non-record
10499 // candidate types or either arithmetic or enumeral candidate types.
10500 QualifiersAndAtomic VisibleTypeConversionsQuals;
10501 VisibleTypeConversionsQuals.addConst();
10502 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10503 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
10504 if (Args[ArgIdx]->getType()->isAtomicType())
10505 VisibleTypeConversionsQuals.addAtomic();
10506 }
10507
10508 bool HasNonRecordCandidateType = false;
10509 bool HasArithmeticOrEnumeralCandidateType = false;
10511 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10512 CandidateTypes.emplace_back(*this);
10513 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
10514 OpLoc,
10515 true,
10516 (Op == OO_Exclaim ||
10517 Op == OO_AmpAmp ||
10518 Op == OO_PipePipe),
10519 VisibleTypeConversionsQuals);
10520 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10521 CandidateTypes[ArgIdx].hasNonRecordTypes();
10522 HasArithmeticOrEnumeralCandidateType =
10523 HasArithmeticOrEnumeralCandidateType ||
10524 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10525 }
10526
10527 // Exit early when no non-record types have been added to the candidate set
10528 // for any of the arguments to the operator.
10529 //
10530 // We can't exit early for !, ||, or &&, since there we have always have
10531 // 'bool' overloads.
10532 if (!HasNonRecordCandidateType &&
10533 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10534 return;
10535
10536 // Setup an object to manage the common state for building overloads.
10537 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10538 VisibleTypeConversionsQuals,
10539 HasArithmeticOrEnumeralCandidateType,
10540 CandidateTypes, CandidateSet);
10541
10542 // Dispatch over the operation to add in only those overloads which apply.
10543 switch (Op) {
10544 case OO_None:
10546 llvm_unreachable("Expected an overloaded operator");
10547
10548 case OO_New:
10549 case OO_Delete:
10550 case OO_Array_New:
10551 case OO_Array_Delete:
10552 case OO_Call:
10553 llvm_unreachable(
10554 "Special operators don't use AddBuiltinOperatorCandidates");
10555
10556 case OO_Comma:
10557 case OO_Arrow:
10558 case OO_Coawait:
10559 // C++ [over.match.oper]p3:
10560 // -- For the operator ',', the unary operator '&', the
10561 // operator '->', or the operator 'co_await', the
10562 // built-in candidates set is empty.
10563 break;
10564
10565 case OO_Plus: // '+' is either unary or binary
10566 if (Args.size() == 1)
10567 OpBuilder.addUnaryPlusPointerOverloads();
10568 [[fallthrough]];
10569
10570 case OO_Minus: // '-' is either unary or binary
10571 if (Args.size() == 1) {
10572 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10573 } else {
10574 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10575 OpBuilder.addGenericBinaryArithmeticOverloads();
10576 OpBuilder.addMatrixBinaryArithmeticOverloads();
10577 }
10578 break;
10579
10580 case OO_Star: // '*' is either unary or binary
10581 if (Args.size() == 1)
10582 OpBuilder.addUnaryStarPointerOverloads();
10583 else {
10584 OpBuilder.addGenericBinaryArithmeticOverloads();
10585 OpBuilder.addMatrixBinaryArithmeticOverloads();
10586 }
10587 break;
10588
10589 case OO_Slash:
10590 OpBuilder.addGenericBinaryArithmeticOverloads();
10591 break;
10592
10593 case OO_PlusPlus:
10594 case OO_MinusMinus:
10595 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10596 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10597 break;
10598
10599 case OO_EqualEqual:
10600 case OO_ExclaimEqual:
10601 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10602 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10603 OpBuilder.addGenericBinaryArithmeticOverloads();
10604 break;
10605
10606 case OO_Less:
10607 case OO_Greater:
10608 case OO_LessEqual:
10609 case OO_GreaterEqual:
10610 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10611 OpBuilder.addGenericBinaryArithmeticOverloads();
10612 break;
10613
10614 case OO_Spaceship:
10615 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10616 OpBuilder.addThreeWayArithmeticOverloads();
10617 break;
10618
10619 case OO_Percent:
10620 case OO_Caret:
10621 case OO_Pipe:
10622 case OO_LessLess:
10623 case OO_GreaterGreater:
10624 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10625 break;
10626
10627 case OO_Amp: // '&' is either unary or binary
10628 if (Args.size() == 1)
10629 // C++ [over.match.oper]p3:
10630 // -- For the operator ',', the unary operator '&', or the
10631 // operator '->', the built-in candidates set is empty.
10632 break;
10633
10634 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10635 break;
10636
10637 case OO_Tilde:
10638 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10639 break;
10640
10641 case OO_Equal:
10642 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10643 [[fallthrough]];
10644
10645 case OO_PlusEqual:
10646 case OO_MinusEqual:
10647 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10648 [[fallthrough]];
10649
10650 case OO_StarEqual:
10651 case OO_SlashEqual:
10652 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10653 break;
10654
10655 case OO_PercentEqual:
10656 case OO_LessLessEqual:
10657 case OO_GreaterGreaterEqual:
10658 case OO_AmpEqual:
10659 case OO_CaretEqual:
10660 case OO_PipeEqual:
10661 OpBuilder.addAssignmentIntegralOverloads();
10662 break;
10663
10664 case OO_Exclaim:
10665 OpBuilder.addExclaimOverload();
10666 break;
10667
10668 case OO_AmpAmp:
10669 case OO_PipePipe:
10670 OpBuilder.addAmpAmpOrPipePipeOverload();
10671 break;
10672
10673 case OO_Subscript:
10674 if (Args.size() == 2)
10675 OpBuilder.addSubscriptOverloads();
10676 break;
10677
10678 case OO_ArrowStar:
10679 OpBuilder.addArrowStarOverloads();
10680 break;
10681
10682 case OO_Conditional:
10683 OpBuilder.addConditionalOperatorOverloads();
10684 OpBuilder.addGenericBinaryArithmeticOverloads();
10685 break;
10686 }
10687}
10688
10689void
10691 SourceLocation Loc,
10692 ArrayRef<Expr *> Args,
10693 TemplateArgumentListInfo *ExplicitTemplateArgs,
10694 OverloadCandidateSet& CandidateSet,
10695 bool PartialOverloading) {
10696 ADLResult Fns;
10697
10698 // FIXME: This approach for uniquing ADL results (and removing
10699 // redundant candidates from the set) relies on pointer-equality,
10700 // which means we need to key off the canonical decl. However,
10701 // always going back to the canonical decl might not get us the
10702 // right set of default arguments. What default arguments are
10703 // we supposed to consider on ADL candidates, anyway?
10704
10705 // FIXME: Pass in the explicit template arguments?
10706 ArgumentDependentLookup(Name, Loc, Args, Fns);
10707
10708 ArrayRef<Expr *> ReversedArgs;
10709
10710 // Erase all of the candidates we already knew about.
10711 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10712 CandEnd = CandidateSet.end();
10713 Cand != CandEnd; ++Cand)
10714 if (Cand->Function) {
10715 FunctionDecl *Fn = Cand->Function;
10716 Fns.erase(Fn);
10717 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10718 Fns.erase(FunTmpl);
10719 }
10720
10721 // For each of the ADL candidates we found, add it to the overload
10722 // set.
10723 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10725
10726 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10727 if (ExplicitTemplateArgs)
10728 continue;
10729
10731 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10732 PartialOverloading, /*AllowExplicit=*/true,
10733 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10734 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10736 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10737 /*SuppressUserConversions=*/false, PartialOverloading,
10738 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10739 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10740 }
10741 } else {
10742 auto *FTD = cast<FunctionTemplateDecl>(*I);
10744 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10745 /*SuppressUserConversions=*/false, PartialOverloading,
10746 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10747 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10748 *this, Args, FTD->getTemplatedDecl())) {
10749
10750 // As template candidates are not deduced immediately,
10751 // persist the array in the overload set.
10752 if (ReversedArgs.empty())
10753 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
10754
10756 FTD, FoundDecl, ExplicitTemplateArgs, ReversedArgs, CandidateSet,
10757 /*SuppressUserConversions=*/false, PartialOverloading,
10758 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10760 }
10761 }
10762 }
10763}
10764
10765namespace {
10766enum class Comparison { Equal, Better, Worse };
10767}
10768
10769/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10770/// overload resolution.
10771///
10772/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10773/// Cand1's first N enable_if attributes have precisely the same conditions as
10774/// Cand2's first N enable_if attributes (where N = the number of enable_if
10775/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10776///
10777/// Note that you can have a pair of candidates such that Cand1's enable_if
10778/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10779/// worse than Cand1's.
10780static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10781 const FunctionDecl *Cand2) {
10782 // Common case: One (or both) decls don't have enable_if attrs.
10783 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10784 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10785 if (!Cand1Attr || !Cand2Attr) {
10786 if (Cand1Attr == Cand2Attr)
10787 return Comparison::Equal;
10788 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10789 }
10790
10791 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10792 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10793
10794 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10795 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10796 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10797 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10798
10799 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10800 // has fewer enable_if attributes than Cand2, and vice versa.
10801 if (!Cand1A)
10802 return Comparison::Worse;
10803 if (!Cand2A)
10804 return Comparison::Better;
10805
10806 Cand1ID.clear();
10807 Cand2ID.clear();
10808
10809 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10810 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10811 if (Cand1ID != Cand2ID)
10812 return Comparison::Worse;
10813 }
10814
10815 return Comparison::Equal;
10816}
10817
10818static Comparison
10820 const OverloadCandidate &Cand2) {
10821 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10822 !Cand2.Function->isMultiVersion())
10823 return Comparison::Equal;
10824
10825 // If both are invalid, they are equal. If one of them is invalid, the other
10826 // is better.
10827 if (Cand1.Function->isInvalidDecl()) {
10828 if (Cand2.Function->isInvalidDecl())
10829 return Comparison::Equal;
10830 return Comparison::Worse;
10831 }
10832 if (Cand2.Function->isInvalidDecl())
10833 return Comparison::Better;
10834
10835 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10836 // cpu_dispatch, else arbitrarily based on the identifiers.
10837 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10838 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10839 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10840 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10841
10842 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10843 return Comparison::Equal;
10844
10845 if (Cand1CPUDisp && !Cand2CPUDisp)
10846 return Comparison::Better;
10847 if (Cand2CPUDisp && !Cand1CPUDisp)
10848 return Comparison::Worse;
10849
10850 if (Cand1CPUSpec && Cand2CPUSpec) {
10851 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10852 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10853 ? Comparison::Better
10854 : Comparison::Worse;
10855
10856 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10857 FirstDiff = std::mismatch(
10858 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10859 Cand2CPUSpec->cpus_begin(),
10860 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10861 return LHS->getName() == RHS->getName();
10862 });
10863
10864 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10865 "Two different cpu-specific versions should not have the same "
10866 "identifier list, otherwise they'd be the same decl!");
10867 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10868 ? Comparison::Better
10869 : Comparison::Worse;
10870 }
10871 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10872}
10873
10874/// Compute the type of the implicit object parameter for the given function,
10875/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10876/// null QualType if there is a 'matches anything' implicit object parameter.
10877static std::optional<QualType>
10880 return std::nullopt;
10881
10882 auto *M = cast<CXXMethodDecl>(F);
10883 // Static member functions' object parameters match all types.
10884 if (M->isStatic())
10885 return QualType();
10886 return M->getFunctionObjectParameterReferenceType();
10887}
10888
10889// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10890// represent the same entity.
10891static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10892 const FunctionDecl *F2) {
10893 if (declaresSameEntity(F1, F2))
10894 return true;
10895 auto PT1 = F1->getPrimaryTemplate();
10896 auto PT2 = F2->getPrimaryTemplate();
10897 if (PT1 && PT2) {
10898 if (declaresSameEntity(PT1, PT2) ||
10899 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10900 PT2->getInstantiatedFromMemberTemplate()))
10901 return true;
10902 }
10903 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10904 // different functions with same params). Consider removing this (as no test
10905 // fail w/o it).
10906 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10907 if (First) {
10908 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10909 return *T;
10910 }
10911 assert(I < F->getNumParams());
10912 return F->getParamDecl(I++)->getType();
10913 };
10914
10915 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10916 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10917
10918 if (F1NumParams != F2NumParams)
10919 return false;
10920
10921 unsigned I1 = 0, I2 = 0;
10922 for (unsigned I = 0; I != F1NumParams; ++I) {
10923 QualType T1 = NextParam(F1, I1, I == 0);
10924 QualType T2 = NextParam(F2, I2, I == 0);
10925 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10926 if (!Context.hasSameUnqualifiedType(T1, T2))
10927 return false;
10928 }
10929 return true;
10930}
10931
10932/// We're allowed to use constraints partial ordering only if the candidates
10933/// have the same parameter types:
10934/// [over.match.best.general]p2.6
10935/// F1 and F2 are non-template functions with the same
10936/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10938 FunctionDecl *Fn2,
10939 bool IsFn1Reversed,
10940 bool IsFn2Reversed) {
10941 assert(Fn1 && Fn2);
10942 if (Fn1->isVariadic() != Fn2->isVariadic())
10943 return false;
10944
10945 if (!S.FunctionNonObjectParamTypesAreEqual(Fn1, Fn2, nullptr,
10946 IsFn1Reversed ^ IsFn2Reversed))
10947 return false;
10948
10949 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10950 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10951 if (Mem1 && Mem2) {
10952 // if they are member functions, both are direct members of the same class,
10953 // and
10954 if (Mem1->getParent() != Mem2->getParent())
10955 return false;
10956 // if both are non-static member functions, they have the same types for
10957 // their object parameters
10958 if (Mem1->isInstance() && Mem2->isInstance() &&
10960 Mem1->getFunctionObjectParameterReferenceType(),
10961 Mem1->getFunctionObjectParameterReferenceType()))
10962 return false;
10963 }
10964 return true;
10965}
10966
10967static FunctionDecl *
10969 bool IsFn1Reversed, bool IsFn2Reversed) {
10970 if (!Fn1 || !Fn2)
10971 return nullptr;
10972
10973 // C++ [temp.constr.order]:
10974 // A non-template function F1 is more partial-ordering-constrained than a
10975 // non-template function F2 if:
10976 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10977 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10978
10979 if (Cand1IsSpecialization || Cand2IsSpecialization)
10980 return nullptr;
10981
10982 // - they have the same non-object-parameter-type-lists, and [...]
10983 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10984 IsFn2Reversed))
10985 return nullptr;
10986
10987 // - the declaration of F1 is more constrained than the declaration of F2.
10988 return S.getMoreConstrainedFunction(Fn1, Fn2);
10989}
10990
10991/// isBetterOverloadCandidate - Determines whether the first overload
10992/// candidate is a better candidate than the second (C++ 13.3.3p1).
10994 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10996 bool PartialOverloading) {
10997 // Define viable functions to be better candidates than non-viable
10998 // functions.
10999 if (!Cand2.Viable)
11000 return Cand1.Viable;
11001 else if (!Cand1.Viable)
11002 return false;
11003
11004 // [CUDA] A function with 'never' preference is marked not viable, therefore
11005 // is never shown up here. The worst preference shown up here is 'wrong side',
11006 // e.g. an H function called by a HD function in device compilation. This is
11007 // valid AST as long as the HD function is not emitted, e.g. it is an inline
11008 // function which is called only by an H function. A deferred diagnostic will
11009 // be triggered if it is emitted. However a wrong-sided function is still
11010 // a viable candidate here.
11011 //
11012 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
11013 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
11014 // can be emitted, Cand1 is not better than Cand2. This rule should have
11015 // precedence over other rules.
11016 //
11017 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
11018 // other rules should be used to determine which is better. This is because
11019 // host/device based overloading resolution is mostly for determining
11020 // viability of a function. If two functions are both viable, other factors
11021 // should take precedence in preference, e.g. the standard-defined preferences
11022 // like argument conversion ranks or enable_if partial-ordering. The
11023 // preference for pass-object-size parameters is probably most similar to a
11024 // type-based-overloading decision and so should take priority.
11025 //
11026 // If other rules cannot determine which is better, CUDA preference will be
11027 // used again to determine which is better.
11028 //
11029 // TODO: Currently IdentifyPreference does not return correct values
11030 // for functions called in global variable initializers due to missing
11031 // correct context about device/host. Therefore we can only enforce this
11032 // rule when there is a caller. We should enforce this rule for functions
11033 // in global variable initializers once proper context is added.
11034 //
11035 // TODO: We can only enable the hostness based overloading resolution when
11036 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
11037 // overloading resolution diagnostics.
11038 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
11039 S.getLangOpts().GPUExcludeWrongSideOverloads) {
11040 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
11041 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
11042 bool IsCand1ImplicitHD =
11044 bool IsCand2ImplicitHD =
11046 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
11047 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11048 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
11049 // The implicit HD function may be a function in a system header which
11050 // is forced by pragma. In device compilation, if we prefer HD candidates
11051 // over wrong-sided candidates, overloading resolution may change, which
11052 // may result in non-deferrable diagnostics. As a workaround, we let
11053 // implicit HD candidates take equal preference as wrong-sided candidates.
11054 // This will preserve the overloading resolution.
11055 // TODO: We still need special handling of implicit HD functions since
11056 // they may incur other diagnostics to be deferred. We should make all
11057 // host/device related diagnostics deferrable and remove special handling
11058 // of implicit HD functions.
11059 auto EmitThreshold =
11060 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
11061 (IsCand1ImplicitHD || IsCand2ImplicitHD))
11064 auto Cand1Emittable = P1 > EmitThreshold;
11065 auto Cand2Emittable = P2 > EmitThreshold;
11066 if (Cand1Emittable && !Cand2Emittable)
11067 return true;
11068 if (!Cand1Emittable && Cand2Emittable)
11069 return false;
11070 }
11071 }
11072
11073 // C++ [over.match.best]p1: (Changed in C++23)
11074 //
11075 // -- if F is a static member function, ICS1(F) is defined such
11076 // that ICS1(F) is neither better nor worse than ICS1(G) for
11077 // any function G, and, symmetrically, ICS1(G) is neither
11078 // better nor worse than ICS1(F).
11079 unsigned StartArg = 0;
11080 if (!Cand1.TookAddressOfOverload &&
11082 StartArg = 1;
11083
11084 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
11085 // We don't allow incompatible pointer conversions in C++.
11086 if (!S.getLangOpts().CPlusPlus)
11087 return ICS.isStandard() &&
11088 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
11089
11090 // The only ill-formed conversion we allow in C++ is the string literal to
11091 // char* conversion, which is only considered ill-formed after C++11.
11092 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
11094 };
11095
11096 // Define functions that don't require ill-formed conversions for a given
11097 // argument to be better candidates than functions that do.
11098 unsigned NumArgs = Cand1.Conversions.size();
11099 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
11100 bool HasBetterConversion = false;
11101 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11102 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
11103 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
11104 if (Cand1Bad != Cand2Bad) {
11105 if (Cand1Bad)
11106 return false;
11107 HasBetterConversion = true;
11108 }
11109 }
11110
11111 if (HasBetterConversion)
11112 return true;
11113
11114 // C++ [over.match.best]p1:
11115 // A viable function F1 is defined to be a better function than another
11116 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
11117 // conversion sequence than ICSi(F2), and then...
11118 bool HasWorseConversion = false;
11119 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11121 Cand1.Conversions[ArgIdx],
11122 Cand2.Conversions[ArgIdx])) {
11124 // Cand1 has a better conversion sequence.
11125 HasBetterConversion = true;
11126 break;
11127
11129 if (Cand1.Function && Cand2.Function &&
11130 Cand1.isReversed() != Cand2.isReversed() &&
11131 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
11132 // Work around large-scale breakage caused by considering reversed
11133 // forms of operator== in C++20:
11134 //
11135 // When comparing a function against a reversed function, if we have a
11136 // better conversion for one argument and a worse conversion for the
11137 // other, the implicit conversion sequences are treated as being equally
11138 // good.
11139 //
11140 // This prevents a comparison function from being considered ambiguous
11141 // with a reversed form that is written in the same way.
11142 //
11143 // We diagnose this as an extension from CreateOverloadedBinOp.
11144 HasWorseConversion = true;
11145 break;
11146 }
11147
11148 // Cand1 can't be better than Cand2.
11149 return false;
11150
11152 // Do nothing.
11153 break;
11154 }
11155 }
11156
11157 // -- for some argument j, ICSj(F1) is a better conversion sequence than
11158 // ICSj(F2), or, if not that,
11159 if (HasBetterConversion && !HasWorseConversion)
11160 return true;
11161
11162 // -- the context is an initialization by user-defined conversion
11163 // (see 8.5, 13.3.1.5) and the standard conversion sequence
11164 // from the return type of F1 to the destination type (i.e.,
11165 // the type of the entity being initialized) is a better
11166 // conversion sequence than the standard conversion sequence
11167 // from the return type of F2 to the destination type.
11169 Cand1.Function && Cand2.Function &&
11172
11173 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
11174 // First check whether we prefer one of the conversion functions over the
11175 // other. This only distinguishes the results in non-standard, extension
11176 // cases such as the conversion from a lambda closure type to a function
11177 // pointer or block.
11182 Cand1.FinalConversion,
11183 Cand2.FinalConversion);
11184
11187
11188 // FIXME: Compare kind of reference binding if conversion functions
11189 // convert to a reference type used in direct reference binding, per
11190 // C++14 [over.match.best]p1 section 2 bullet 3.
11191 }
11192
11193 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
11194 // as combined with the resolution to CWG issue 243.
11195 //
11196 // When the context is initialization by constructor ([over.match.ctor] or
11197 // either phase of [over.match.list]), a constructor is preferred over
11198 // a conversion function.
11199 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
11200 Cand1.Function && Cand2.Function &&
11203 return isa<CXXConstructorDecl>(Cand1.Function);
11204
11205 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
11206 return Cand2.StrictPackMatch;
11207
11208 // -- F1 is a non-template function and F2 is a function template
11209 // specialization, or, if not that,
11210 bool Cand1IsSpecialization = Cand1.Function &&
11212 bool Cand2IsSpecialization = Cand2.Function &&
11214 if (Cand1IsSpecialization != Cand2IsSpecialization)
11215 return Cand2IsSpecialization;
11216
11217 // -- F1 and F2 are function template specializations, and the function
11218 // template for F1 is more specialized than the template for F2
11219 // according to the partial ordering rules described in 14.5.5.2, or,
11220 // if not that,
11221 if (Cand1IsSpecialization && Cand2IsSpecialization) {
11222 const auto *Obj1Context =
11223 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
11224 const auto *Obj2Context =
11225 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
11226 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
11228 Cand2.Function->getPrimaryTemplate(), Loc,
11230 : TPOC_Call,
11232 Obj1Context ? S.Context.getCanonicalTagType(Obj1Context)
11233 : QualType{},
11234 Obj2Context ? S.Context.getCanonicalTagType(Obj2Context)
11235 : QualType{},
11236 Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
11237 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
11238 }
11239 }
11240
11241 // -— F1 and F2 are non-template functions and F1 is more
11242 // partial-ordering-constrained than F2 [...],
11244 S, Cand1.Function, Cand2.Function, Cand1.isReversed(),
11245 Cand2.isReversed());
11246 F && F == Cand1.Function)
11247 return true;
11248
11249 // -- F1 is a constructor for a class D, F2 is a constructor for a base
11250 // class B of D, and for all arguments the corresponding parameters of
11251 // F1 and F2 have the same type.
11252 // FIXME: Implement the "all parameters have the same type" check.
11253 bool Cand1IsInherited =
11254 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
11255 bool Cand2IsInherited =
11256 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
11257 if (Cand1IsInherited != Cand2IsInherited)
11258 return Cand2IsInherited;
11259 else if (Cand1IsInherited) {
11260 assert(Cand2IsInherited);
11261 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
11262 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
11263 if (Cand1Class->isDerivedFrom(Cand2Class))
11264 return true;
11265 if (Cand2Class->isDerivedFrom(Cand1Class))
11266 return false;
11267 // Inherited from sibling base classes: still ambiguous.
11268 }
11269
11270 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11271 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11272 // with reversed order of parameters and F1 is not
11273 //
11274 // We rank reversed + different operator as worse than just reversed, but
11275 // that comparison can never happen, because we only consider reversing for
11276 // the maximally-rewritten operator (== or <=>).
11277 if (Cand1.RewriteKind != Cand2.RewriteKind)
11278 return Cand1.RewriteKind < Cand2.RewriteKind;
11279
11280 // Check C++17 tie-breakers for deduction guides.
11281 {
11282 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
11283 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
11284 if (Guide1 && Guide2) {
11285 // -- F1 is generated from a deduction-guide and F2 is not
11286 if (Guide1->isImplicit() != Guide2->isImplicit())
11287 return Guide2->isImplicit();
11288
11289 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11290 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11291 return true;
11292 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11293 return false;
11294
11295 // --F1 is generated from a non-template constructor and F2 is generated
11296 // from a constructor template
11297 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11298 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11299 if (Constructor1 && Constructor2) {
11300 bool isC1Templated = Constructor1->getTemplatedKind() !=
11302 bool isC2Templated = Constructor2->getTemplatedKind() !=
11304 if (isC1Templated != isC2Templated)
11305 return isC2Templated;
11306 }
11307 }
11308 }
11309
11310 // Check for enable_if value-based overload resolution.
11311 if (Cand1.Function && Cand2.Function) {
11313 if (Cmp != Comparison::Equal)
11314 return Cmp == Comparison::Better;
11315 }
11316
11317 bool HasPS1 = Cand1.Function != nullptr &&
11319 bool HasPS2 = Cand2.Function != nullptr &&
11321 if (HasPS1 != HasPS2 && HasPS1)
11322 return true;
11323
11324 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11325 if (MV == Comparison::Better)
11326 return true;
11327 if (MV == Comparison::Worse)
11328 return false;
11329
11330 // If other rules cannot determine which is better, CUDA preference is used
11331 // to determine which is better.
11332 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11333 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11334 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
11335 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11336 }
11337
11338 // General member function overloading is handled above, so this only handles
11339 // constructors with address spaces.
11340 // This only handles address spaces since C++ has no other
11341 // qualifier that can be used with constructors.
11342 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
11343 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
11344 if (CD1 && CD2) {
11345 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11346 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11347 if (AS1 != AS2) {
11349 return true;
11351 return false;
11352 }
11353 }
11354
11355 return false;
11356}
11357
11358/// Determine whether two declarations are "equivalent" for the purposes of
11359/// name lookup and overload resolution. This applies when the same internal/no
11360/// linkage entity is defined by two modules (probably by textually including
11361/// the same header). In such a case, we don't consider the declarations to
11362/// declare the same entity, but we also don't want lookups with both
11363/// declarations visible to be ambiguous in some cases (this happens when using
11364/// a modularized libstdc++).
11366 const NamedDecl *B) {
11367 auto *VA = dyn_cast_or_null<ValueDecl>(A);
11368 auto *VB = dyn_cast_or_null<ValueDecl>(B);
11369 if (!VA || !VB)
11370 return false;
11371
11372 // The declarations must be declaring the same name as an internal linkage
11373 // entity in different modules.
11374 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11375 VB->getDeclContext()->getRedeclContext()) ||
11376 getOwningModule(VA) == getOwningModule(VB) ||
11377 VA->isExternallyVisible() || VB->isExternallyVisible())
11378 return false;
11379
11380 // Check that the declarations appear to be equivalent.
11381 //
11382 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11383 // For constants and functions, we should check the initializer or body is
11384 // the same. For non-constant variables, we shouldn't allow it at all.
11385 if (Context.hasSameType(VA->getType(), VB->getType()))
11386 return true;
11387
11388 // Enum constants within unnamed enumerations will have different types, but
11389 // may still be similar enough to be interchangeable for our purposes.
11390 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
11391 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
11392 // Only handle anonymous enums. If the enumerations were named and
11393 // equivalent, they would have been merged to the same type.
11394 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
11395 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
11396 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11397 !Context.hasSameType(EnumA->getIntegerType(),
11398 EnumB->getIntegerType()))
11399 return false;
11400 // Allow this only if the value is the same for both enumerators.
11401 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
11402 }
11403 }
11404
11405 // Nothing else is sufficiently similar.
11406 return false;
11407}
11408
11411 assert(D && "Unknown declaration");
11412 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11413
11414 Module *M = getOwningModule(D);
11415 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
11416 << !M << (M ? M->getFullModuleName() : "");
11417
11418 for (auto *E : Equiv) {
11419 Module *M = getOwningModule(E);
11420 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
11421 << !M << (M ? M->getFullModuleName() : "");
11422 }
11423}
11424
11427 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11429 static_cast<CNSInfo *>(DeductionFailure.Data)
11430 ->Satisfaction.ContainsErrors;
11431}
11432
11435 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11436 bool PartialOverloading, bool AllowExplicit,
11438 bool AggregateCandidateDeduction) {
11439
11440 auto *C =
11441 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11442
11445 /*AllowObjCConversionOnExplicit=*/false,
11446 /*AllowResultConversion=*/false, AllowExplicit, SuppressUserConversions,
11447 PartialOverloading, AggregateCandidateDeduction},
11449 FoundDecl,
11450 Args,
11451 IsADLCandidate,
11452 PO};
11453
11454 HasDeferredTemplateConstructors |=
11455 isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl());
11456}
11457
11459 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11460 CXXRecordDecl *ActingContext, QualType ObjectType,
11461 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11462 bool SuppressUserConversions, bool PartialOverloading,
11464
11465 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11466
11467 auto *C =
11468 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11469
11472 /*AllowObjCConversionOnExplicit=*/false,
11473 /*AllowResultConversion=*/false,
11474 /*AllowExplicit=*/false, SuppressUserConversions, PartialOverloading,
11475 /*AggregateCandidateDeduction=*/false},
11476 MethodTmpl,
11477 FoundDecl,
11478 Args,
11479 ActingContext,
11480 ObjectClassification,
11481 ObjectType,
11482 PO};
11483}
11484
11487 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11488 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11489 bool AllowResultConversion) {
11490
11491 auto *C =
11492 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11493
11496 AllowObjCConversionOnExplicit, AllowResultConversion,
11497 /*AllowExplicit=*/false,
11498 /*SuppressUserConversions=*/false,
11499 /*PartialOverloading*/ false,
11500 /*AggregateCandidateDeduction=*/false},
11502 FoundDecl,
11503 ActingContext,
11504 From,
11505 ToType};
11506}
11507
11508static void
11511
11513 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext,
11514 /*ExplicitTemplateArgs=*/nullptr, C.ObjectType, C.ObjectClassification,
11515 C.Args, C.SuppressUserConversions, C.PartialOverloading, C.PO);
11516}
11517
11518static void
11522 S, CandidateSet, C.FunctionTemplate, C.FoundDecl,
11523 /*ExplicitTemplateArgs=*/nullptr, C.Args, C.SuppressUserConversions,
11524 C.PartialOverloading, C.AllowExplicit, C.IsADLCandidate, C.PO,
11525 C.AggregateCandidateDeduction);
11526}
11527
11528static void
11532 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From,
11533 C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit,
11534 C.AllowResultConversion);
11535}
11536
11538 Candidates.reserve(Candidates.size() + DeferredCandidatesCount);
11539 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11540 while (Cand) {
11541 switch (Cand->Kind) {
11544 S, *this,
11545 *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11546 break;
11549 S, *this,
11550 *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11551 break;
11554 S, *this,
11555 *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11556 break;
11557 }
11558 Cand = Cand->Next;
11559 }
11560 FirstDeferredCandidate = nullptr;
11561 DeferredCandidatesCount = 0;
11562}
11563
11565OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11566 Best->Best = true;
11567 if (Best->Function && Best->Function->isDeleted())
11568 return OR_Deleted;
11569 return OR_Success;
11570}
11571
11572void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11574 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11575 // are accepted by both clang and NVCC. However, during a particular
11576 // compilation mode only one call variant is viable. We need to
11577 // exclude non-viable overload candidates from consideration based
11578 // only on their host/device attributes. Specifically, if one
11579 // candidate call is WrongSide and the other is SameSide, we ignore
11580 // the WrongSide candidate.
11581 // We only need to remove wrong-sided candidates here if
11582 // -fgpu-exclude-wrong-side-overloads is off. When
11583 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11584 // uniformly in isBetterOverloadCandidate.
11585 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11586 return;
11587 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11588
11589 bool ContainsSameSideCandidate =
11590 llvm::any_of(Candidates, [&](const OverloadCandidate *Cand) {
11591 // Check viable function only.
11592 return Cand->Viable && Cand->Function &&
11593 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11595 });
11596
11597 if (!ContainsSameSideCandidate)
11598 return;
11599
11600 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11601 // Check viable function only to avoid unnecessary data copying/moving.
11602 return Cand->Viable && Cand->Function &&
11603 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11605 };
11606 llvm::erase_if(Candidates, IsWrongSideCandidate);
11607}
11608
11609/// Computes the best viable function (C++ 13.3.3)
11610/// within an overload candidate set.
11611///
11612/// \param Loc The location of the function name (or operator symbol) for
11613/// which overload resolution occurs.
11614///
11615/// \param Best If overload resolution was successful or found a deleted
11616/// function, \p Best points to the candidate function found.
11617///
11618/// \returns The result of overload resolution.
11620 SourceLocation Loc,
11621 iterator &Best) {
11622
11624 DeferredCandidatesCount == 0) &&
11625 "Unexpected deferred template candidates");
11626
11627 bool TwoPhaseResolution =
11628 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11629
11630 if (TwoPhaseResolution) {
11631 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11632 if (Best != end() && Best->isPerfectMatch(S.Context)) {
11633 if (!(HasDeferredTemplateConstructors &&
11634 isa_and_nonnull<CXXConversionDecl>(Best->Function)))
11635 return Res;
11636 }
11637 }
11638
11640 return BestViableFunctionImpl(S, Loc, Best);
11641}
11642
11643OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11645
11647 Candidates.reserve(this->Candidates.size());
11648 std::transform(this->Candidates.begin(), this->Candidates.end(),
11649 std::back_inserter(Candidates),
11650 [](OverloadCandidate &Cand) { return &Cand; });
11651
11652 if (S.getLangOpts().CUDA)
11653 CudaExcludeWrongSideCandidates(S, Candidates);
11654
11655 Best = end();
11656 for (auto *Cand : Candidates) {
11657 Cand->Best = false;
11658 if (Cand->Viable) {
11659 if (Best == end() ||
11660 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
11661 Best = Cand;
11662 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11663 // This candidate has constraint that we were unable to evaluate because
11664 // it referenced an expression that contained an error. Rather than fall
11665 // back onto a potentially unintended candidate (made worse by
11666 // subsuming constraints), treat this as 'no viable candidate'.
11667 Best = end();
11668 return OR_No_Viable_Function;
11669 }
11670 }
11671
11672 // If we didn't find any viable functions, abort.
11673 if (Best == end())
11674 return OR_No_Viable_Function;
11675
11676 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11677 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11678 PendingBest.push_back(&*Best);
11679 Best->Best = true;
11680
11681 // Make sure that this function is better than every other viable
11682 // function. If not, we have an ambiguity.
11683 while (!PendingBest.empty()) {
11684 auto *Curr = PendingBest.pop_back_val();
11685 for (auto *Cand : Candidates) {
11686 if (Cand->Viable && !Cand->Best &&
11687 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
11688 PendingBest.push_back(Cand);
11689 Cand->Best = true;
11690
11692 Curr->Function))
11693 EquivalentCands.push_back(Cand->Function);
11694 else
11695 Best = end();
11696 }
11697 }
11698 }
11699
11700 if (Best == end())
11701 return OR_Ambiguous;
11702
11703 OverloadingResult R = ResultForBestCandidate(Best);
11704
11705 if (!EquivalentCands.empty())
11707 EquivalentCands);
11708 return R;
11709}
11710
11711namespace {
11712
11713enum OverloadCandidateKind {
11714 oc_function,
11715 oc_method,
11716 oc_reversed_binary_operator,
11717 oc_constructor,
11718 oc_implicit_default_constructor,
11719 oc_implicit_copy_constructor,
11720 oc_implicit_move_constructor,
11721 oc_implicit_copy_assignment,
11722 oc_implicit_move_assignment,
11723 oc_implicit_equality_comparison,
11724 oc_inherited_constructor
11725};
11726
11727enum OverloadCandidateSelect {
11728 ocs_non_template,
11729 ocs_template,
11730 ocs_described_template,
11731};
11732
11733static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11734ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11735 const FunctionDecl *Fn,
11737 std::string &Description) {
11738
11739 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11740 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11741 isTemplate = true;
11742 Description = S.getTemplateArgumentBindingsText(
11743 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11744 }
11745
11746 OverloadCandidateSelect Select = [&]() {
11747 if (!Description.empty())
11748 return ocs_described_template;
11749 return isTemplate ? ocs_template : ocs_non_template;
11750 }();
11751
11752 OverloadCandidateKind Kind = [&]() {
11753 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11754 return oc_implicit_equality_comparison;
11755
11756 if (CRK & CRK_Reversed)
11757 return oc_reversed_binary_operator;
11758
11759 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
11760 if (!Ctor->isImplicit()) {
11762 return oc_inherited_constructor;
11763 else
11764 return oc_constructor;
11765 }
11766
11767 if (Ctor->isDefaultConstructor())
11768 return oc_implicit_default_constructor;
11769
11770 if (Ctor->isMoveConstructor())
11771 return oc_implicit_move_constructor;
11772
11773 assert(Ctor->isCopyConstructor() &&
11774 "unexpected sort of implicit constructor");
11775 return oc_implicit_copy_constructor;
11776 }
11777
11778 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11779 // This actually gets spelled 'candidate function' for now, but
11780 // it doesn't hurt to split it out.
11781 if (!Meth->isImplicit())
11782 return oc_method;
11783
11784 if (Meth->isMoveAssignmentOperator())
11785 return oc_implicit_move_assignment;
11786
11787 if (Meth->isCopyAssignmentOperator())
11788 return oc_implicit_copy_assignment;
11789
11790 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11791 return oc_method;
11792 }
11793
11794 return oc_function;
11795 }();
11796
11797 return std::make_pair(Kind, Select);
11798}
11799
11800void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11801 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11802 // set.
11803 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11804 S.Diag(FoundDecl->getLocation(),
11805 diag::note_ovl_candidate_inherited_constructor)
11806 << Shadow->getNominatedBaseClass();
11807}
11808
11809} // end anonymous namespace
11810
11812 const FunctionDecl *FD) {
11813 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11814 bool AlwaysTrue;
11815 if (EnableIf->getCond()->isValueDependent() ||
11816 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11817 return false;
11818 if (!AlwaysTrue)
11819 return false;
11820 }
11821 return true;
11822}
11823
11824/// Returns true if we can take the address of the function.
11825///
11826/// \param Complain - If true, we'll emit a diagnostic
11827/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11828/// we in overload resolution?
11829/// \param Loc - The location of the statement we're complaining about. Ignored
11830/// if we're not complaining, or if we're in overload resolution.
11832 bool Complain,
11833 bool InOverloadResolution,
11834 SourceLocation Loc) {
11835 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11836 if (Complain) {
11837 if (InOverloadResolution)
11838 S.Diag(FD->getBeginLoc(),
11839 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11840 else
11841 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11842 }
11843 return false;
11844 }
11845
11846 if (FD->getTrailingRequiresClause()) {
11847 ConstraintSatisfaction Satisfaction;
11848 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11849 return false;
11850 if (!Satisfaction.IsSatisfied) {
11851 if (Complain) {
11852 if (InOverloadResolution) {
11853 SmallString<128> TemplateArgString;
11854 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11855 TemplateArgString += " ";
11856 TemplateArgString += S.getTemplateArgumentBindingsText(
11857 FunTmpl->getTemplateParameters(),
11859 }
11860
11861 S.Diag(FD->getBeginLoc(),
11862 diag::note_ovl_candidate_unsatisfied_constraints)
11863 << TemplateArgString;
11864 } else
11865 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11866 << FD;
11867 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11868 }
11869 return false;
11870 }
11871 }
11872
11873 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11874 return P->hasAttr<PassObjectSizeAttr>();
11875 });
11876 if (I == FD->param_end())
11877 return true;
11878
11879 if (Complain) {
11880 // Add one to ParamNo because it's user-facing
11881 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11882 if (InOverloadResolution)
11883 S.Diag(FD->getLocation(),
11884 diag::note_ovl_candidate_has_pass_object_size_params)
11885 << ParamNo;
11886 else
11887 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11888 << FD << ParamNo;
11889 }
11890 return false;
11891}
11892
11894 const FunctionDecl *FD) {
11895 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11896 /*InOverloadResolution=*/true,
11897 /*Loc=*/SourceLocation());
11898}
11899
11901 bool Complain,
11902 SourceLocation Loc) {
11903 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11904 /*InOverloadResolution=*/false,
11905 Loc);
11906}
11907
11908// Don't print candidates other than the one that matches the calling
11909// convention of the call operator, since that is guaranteed to exist.
11911 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11912
11913 if (!ConvD)
11914 return false;
11915 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11916 if (!RD->isLambda())
11917 return false;
11918
11919 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11920 CallingConv CallOpCC =
11921 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11922 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11923 CallingConv ConvToCC =
11924 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11925
11926 return ConvToCC != CallOpCC;
11927}
11928
11929// Notes the location of an overload candidate.
11931 OverloadCandidateRewriteKind RewriteKind,
11932 QualType DestType, bool TakingAddress) {
11933 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11934 return;
11935 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11936 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11937 return;
11938 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11939 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11940 return;
11942 return;
11943
11944 std::string FnDesc;
11945 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11946 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11947 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11948 << (unsigned)KSPair.first << (unsigned)KSPair.second
11949 << Fn << FnDesc;
11950
11951 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11952 Diag(Fn->getLocation(), PD);
11953 MaybeEmitInheritedConstructorNote(*this, Found);
11954}
11955
11956static void
11958 // Perhaps the ambiguity was caused by two atomic constraints that are
11959 // 'identical' but not equivalent:
11960 //
11961 // void foo() requires (sizeof(T) > 4) { } // #1
11962 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11963 //
11964 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11965 // #2 to subsume #1, but these constraint are not considered equivalent
11966 // according to the subsumption rules because they are not the same
11967 // source-level construct. This behavior is quite confusing and we should try
11968 // to help the user figure out what happened.
11969
11970 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11971 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11972 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11973 if (!I->Function)
11974 continue;
11976 if (auto *Template = I->Function->getPrimaryTemplate())
11977 Template->getAssociatedConstraints(AC);
11978 else
11979 I->Function->getAssociatedConstraints(AC);
11980 if (AC.empty())
11981 continue;
11982 if (FirstCand == nullptr) {
11983 FirstCand = I->Function;
11984 FirstAC = AC;
11985 } else if (SecondCand == nullptr) {
11986 SecondCand = I->Function;
11987 SecondAC = AC;
11988 } else {
11989 // We have more than one pair of constrained functions - this check is
11990 // expensive and we'd rather not try to diagnose it.
11991 return;
11992 }
11993 }
11994 if (!SecondCand)
11995 return;
11996 // The diagnostic can only happen if there are associated constraints on
11997 // both sides (there needs to be some identical atomic constraint).
11998 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11999 SecondCand, SecondAC))
12000 // Just show the user one diagnostic, they'll probably figure it out
12001 // from here.
12002 return;
12003}
12004
12005// Notes the location of all overload candidates designated through
12006// OverloadedExpr
12007void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
12008 bool TakingAddress) {
12009 assert(OverloadedExpr->getType() == Context.OverloadTy);
12010
12011 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
12012 OverloadExpr *OvlExpr = Ovl.Expression;
12013
12014 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
12015 IEnd = OvlExpr->decls_end();
12016 I != IEnd; ++I) {
12017 if (FunctionTemplateDecl *FunTmpl =
12018 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
12019 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
12020 TakingAddress);
12021 } else if (FunctionDecl *Fun
12022 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
12023 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
12024 }
12025 }
12026}
12027
12028/// Diagnoses an ambiguous conversion. The partial diagnostic is the
12029/// "lead" diagnostic; it will be given two arguments, the source and
12030/// target types of the conversion.
12032 Sema &S,
12033 SourceLocation CaretLoc,
12034 const PartialDiagnostic &PDiag) const {
12035 S.Diag(CaretLoc, PDiag)
12036 << Ambiguous.getFromType() << Ambiguous.getToType();
12037 unsigned CandsShown = 0;
12039 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
12040 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
12041 break;
12042 ++CandsShown;
12043 S.NoteOverloadCandidate(I->first, I->second);
12044 }
12045 S.Diags.overloadCandidatesShown(CandsShown);
12046 if (I != E)
12047 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
12048}
12049
12051 unsigned I, bool TakingCandidateAddress) {
12052 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
12053 assert(Conv.isBad());
12054 assert(Cand->Function && "for now, candidate must be a function");
12055 FunctionDecl *Fn = Cand->Function;
12056
12057 // There's a conversion slot for the object argument if this is a
12058 // non-constructor method. Note that 'I' corresponds the
12059 // conversion-slot index.
12060 bool isObjectArgument = false;
12061 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Fn) &&
12063 if (I == 0)
12064 isObjectArgument = true;
12065 else if (!cast<CXXMethodDecl>(Fn)->isExplicitObjectMemberFunction())
12066 I--;
12067 }
12068
12069 std::string FnDesc;
12070 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12071 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
12072 FnDesc);
12073
12074 Expr *FromExpr = Conv.Bad.FromExpr;
12075 QualType FromTy = Conv.Bad.getFromType();
12076 QualType ToTy = Conv.Bad.getToType();
12077 SourceRange ToParamRange;
12078
12079 // FIXME: In presence of parameter packs we can't determine parameter range
12080 // reliably, as we don't have access to instantiation.
12081 bool HasParamPack =
12082 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
12083 return Parm->isParameterPack();
12084 });
12085 if (!isObjectArgument && !HasParamPack && I < Fn->getNumParams())
12086 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
12087
12088 if (FromTy == S.Context.OverloadTy) {
12089 assert(FromExpr && "overload set argument came from implicit argument?");
12090 Expr *E = FromExpr->IgnoreParens();
12091 if (isa<UnaryOperator>(E))
12092 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12093 DeclarationName Name = cast<OverloadExpr>(E)->getName();
12094
12095 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
12096 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12097 << ToParamRange << ToTy << Name << I + 1;
12098 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12099 return;
12100 }
12101
12102 // Do some hand-waving analysis to see if the non-viability is due
12103 // to a qualifier mismatch.
12104 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
12105 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
12106 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
12107 CToTy = RT->getPointeeType();
12108 else {
12109 // TODO: detect and diagnose the full richness of const mismatches.
12110 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
12111 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
12112 CFromTy = FromPT->getPointeeType();
12113 CToTy = ToPT->getPointeeType();
12114 }
12115 }
12116
12117 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
12118 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
12119 Qualifiers FromQs = CFromTy.getQualifiers();
12120 Qualifiers ToQs = CToTy.getQualifiers();
12121
12122 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
12123 if (isObjectArgument)
12124 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
12125 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12126 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
12127 else
12128 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
12129 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12130 << FnDesc << ToParamRange << FromQs.getAddressSpace()
12131 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
12132 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12133 return;
12134 }
12135
12136 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12137 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
12138 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12139 << ToParamRange << FromTy << FromQs.getObjCLifetime()
12140 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
12141 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12142 return;
12143 }
12144
12145 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
12146 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
12147 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12148 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
12149 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
12150 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12151 return;
12152 }
12153
12154 if (!FromQs.getPointerAuth().isEquivalent(ToQs.getPointerAuth())) {
12155 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ptrauth)
12156 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12157 << FromTy << !!FromQs.getPointerAuth()
12158 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
12159 << ToQs.getPointerAuth().getAsString() << I + 1
12160 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
12161 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12162 return;
12163 }
12164
12165 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
12166 assert(CVR && "expected qualifiers mismatch");
12167
12168 if (isObjectArgument) {
12169 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
12170 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12171 << FromTy << (CVR - 1);
12172 } else {
12173 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
12174 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12175 << ToParamRange << FromTy << (CVR - 1) << I + 1;
12176 }
12177 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12178 return;
12179 }
12180
12183 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
12184 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12185 << (unsigned)isObjectArgument << I + 1
12187 << ToParamRange;
12188 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12189 return;
12190 }
12191
12192 // Special diagnostic for failure to convert an initializer list, since
12193 // telling the user that it has type void is not useful.
12194 if (FromExpr && isa<InitListExpr>(FromExpr)) {
12195 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
12196 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12197 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12200 ? 2
12201 : 0);
12202 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12203 return;
12204 }
12205
12206 // Diagnose references or pointers to incomplete types differently,
12207 // since it's far from impossible that the incompleteness triggered
12208 // the failure.
12209 QualType TempFromTy = FromTy.getNonReferenceType();
12210 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
12211 TempFromTy = PTy->getPointeeType();
12212 if (TempFromTy->isIncompleteType()) {
12213 // Emit the generic diagnostic and, optionally, add the hints to it.
12214 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
12215 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12216 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12217 << (unsigned)(Cand->Fix.Kind);
12218
12219 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12220 return;
12221 }
12222
12223 // Diagnose base -> derived pointer conversions.
12224 unsigned BaseToDerivedConversion = 0;
12225 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
12226 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
12227 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12228 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12229 !FromPtrTy->getPointeeType()->isIncompleteType() &&
12230 !ToPtrTy->getPointeeType()->isIncompleteType() &&
12231 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
12232 FromPtrTy->getPointeeType()))
12233 BaseToDerivedConversion = 1;
12234 }
12235 } else if (const ObjCObjectPointerType *FromPtrTy
12236 = FromTy->getAs<ObjCObjectPointerType>()) {
12237 if (const ObjCObjectPointerType *ToPtrTy
12238 = ToTy->getAs<ObjCObjectPointerType>())
12239 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
12240 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
12241 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12242 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12243 FromIface->isSuperClassOf(ToIface))
12244 BaseToDerivedConversion = 2;
12245 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
12246 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
12247 S.getASTContext()) &&
12248 !FromTy->isIncompleteType() &&
12249 !ToRefTy->getPointeeType()->isIncompleteType() &&
12250 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
12251 BaseToDerivedConversion = 3;
12252 }
12253 }
12254
12255 if (BaseToDerivedConversion) {
12256 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
12257 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12258 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
12259 << I + 1;
12260 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12261 return;
12262 }
12263
12264 if (isa<ObjCObjectPointerType>(CFromTy) &&
12265 isa<PointerType>(CToTy)) {
12266 Qualifiers FromQs = CFromTy.getQualifiers();
12267 Qualifiers ToQs = CToTy.getQualifiers();
12268 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12269 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
12270 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12271 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12272 << I + 1;
12273 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12274 return;
12275 }
12276 }
12277
12278 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
12279 return;
12280
12281 // __amdgpu_feature_predicate_t can be explicitly cast to the logical op type,
12282 // although this is almost always an error and we advise against it.
12283 if (FromTy == S.Context.AMDGPUFeaturePredicateTy &&
12284 ToTy == S.Context.getLogicalOperationType()) {
12285 S.Diag(Conv.Bad.FromExpr->getExprLoc(),
12286 diag::err_amdgcn_predicate_type_needs_explicit_bool_cast)
12287 << Conv.Bad.FromExpr << ToTy;
12288 return;
12289 }
12290
12291 // Emit the generic diagnostic and, optionally, add the hints to it.
12292 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
12293 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12294 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12295 << (unsigned)(Cand->Fix.Kind);
12296
12297 // Check that location of Fn is not in system header.
12298 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
12299 // If we can fix the conversion, suggest the FixIts.
12300 for (const FixItHint &HI : Cand->Fix.Hints)
12301 FDiag << HI;
12302 }
12303
12304 S.Diag(Fn->getLocation(), FDiag);
12305
12306 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12307}
12308
12309/// Additional arity mismatch diagnosis specific to a function overload
12310/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12311/// over a candidate in any candidate set.
12313 unsigned NumArgs, bool IsAddressOf = false) {
12314 assert(Cand->Function && "Candidate is required to be a function.");
12315 FunctionDecl *Fn = Cand->Function;
12316 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12317 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12318
12319 // With invalid overloaded operators, it's possible that we think we
12320 // have an arity mismatch when in fact it looks like we have the
12321 // right number of arguments, because only overloaded operators have
12322 // the weird behavior of overloading member and non-member functions.
12323 // Just don't report anything.
12324 if (Fn->isInvalidDecl() &&
12325 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12326 return true;
12327
12328 if (NumArgs < MinParams) {
12329 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12331 Cand->DeductionFailure.getResult() ==
12333 } else {
12334 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12336 Cand->DeductionFailure.getResult() ==
12338 }
12339
12340 return false;
12341}
12342
12343/// General arity mismatch diagnosis over a candidate in a candidate set.
12345 unsigned NumFormalArgs,
12346 bool IsAddressOf = false) {
12347 assert(isa<FunctionDecl>(D) &&
12348 "The templated declaration should at least be a function"
12349 " when diagnosing bad template argument deduction due to too many"
12350 " or too few arguments");
12351
12353
12354 // TODO: treat calls to a missing default constructor as a special case
12355 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12356 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12357 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12358
12359 // at least / at most / exactly
12360 bool HasExplicitObjectParam =
12361 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12362
12363 unsigned ParamCount =
12364 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12365 unsigned mode, modeCount;
12366
12367 if (NumFormalArgs < MinParams) {
12368 if (MinParams != ParamCount || FnTy->isVariadic() ||
12369 FnTy->isTemplateVariadic())
12370 mode = 0; // "at least"
12371 else
12372 mode = 2; // "exactly"
12373 modeCount = MinParams;
12374 } else {
12375 if (MinParams != ParamCount)
12376 mode = 1; // "at most"
12377 else
12378 mode = 2; // "exactly"
12379 modeCount = ParamCount;
12380 }
12381
12382 std::string Description;
12383 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12384 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
12385
12386 unsigned FirstNonObjectParamIdx = HasExplicitObjectParam ? 1 : 0;
12387 if (modeCount == 1 && !IsAddressOf &&
12388 FirstNonObjectParamIdx < Fn->getNumParams() &&
12389 Fn->getParamDecl(FirstNonObjectParamIdx)->getDeclName())
12390 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
12391 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12392 << Description << mode << Fn->getParamDecl(FirstNonObjectParamIdx)
12393 << NumFormalArgs << HasExplicitObjectParam
12394 << Fn->getParametersSourceRange();
12395 else
12396 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
12397 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12398 << Description << mode << modeCount << NumFormalArgs
12399 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12400
12401 MaybeEmitInheritedConstructorNote(S, Found);
12402}
12403
12404/// Arity mismatch diagnosis specific to a function overload candidate.
12406 unsigned NumFormalArgs) {
12407 assert(Cand->Function && "Candidate must be a function");
12408 FunctionDecl *Fn = Cand->Function;
12409 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
12410 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
12411 Cand->TookAddressOfOverload);
12412}
12413
12415 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12416 return TD;
12417 llvm_unreachable("Unsupported: Getting the described template declaration"
12418 " for bad deduction diagnosis");
12419}
12420
12421/// Diagnose a failed template-argument deduction.
12422static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12423 DeductionFailureInfo &DeductionFailure,
12424 unsigned NumArgs, bool TakingCandidateAddress,
12425 TemplateSpecCandidateSetKind CandidateSetKind =
12427 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12428 NamedDecl *ParamD;
12429 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12430 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12431 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12432 switch (DeductionFailure.getResult()) {
12434 llvm_unreachable(
12435 "TemplateDeductionResult::Success while diagnosing bad deduction");
12437 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12438 "while diagnosing bad deduction");
12441 return;
12442
12444 assert(ParamD && "no parameter found for incomplete deduction result");
12445 S.Diag(Templated->getLocation(),
12446 diag::note_ovl_candidate_incomplete_deduction)
12447 << ParamD->getDeclName();
12448 MaybeEmitInheritedConstructorNote(S, Found);
12449 return;
12450 }
12451
12453 assert(ParamD && "no parameter found for incomplete deduction result");
12454 S.Diag(Templated->getLocation(),
12455 diag::note_ovl_candidate_incomplete_deduction_pack)
12456 << ParamD->getDeclName()
12457 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12458 << *DeductionFailure.getFirstArg();
12459 MaybeEmitInheritedConstructorNote(S, Found);
12460 return;
12461 }
12462
12464 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12466
12467 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12468
12469 // Param will have been canonicalized, but it should just be a
12470 // qualified version of ParamD, so move the qualifiers to that.
12472 Qs.strip(Param);
12473 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
12474 assert(S.Context.hasSameType(Param, NonCanonParam));
12475
12476 // Arg has also been canonicalized, but there's nothing we can do
12477 // about that. It also doesn't matter as much, because it won't
12478 // have any template parameters in it (because deduction isn't
12479 // done on dependent types).
12480 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12481
12482 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
12483 << ParamD->getDeclName() << Arg << NonCanonParam;
12484 MaybeEmitInheritedConstructorNote(S, Found);
12485 return;
12486 }
12487
12489 assert(ParamD && "no parameter found for inconsistent deduction result");
12490 int which = 0;
12491 if (isa<TemplateTypeParmDecl>(ParamD))
12492 which = 0;
12493 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
12494 // Deduction might have failed because we deduced arguments of two
12495 // different types for a non-type template parameter.
12496 // FIXME: Use a different TDK value for this.
12497 QualType T1 =
12498 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12499 QualType T2 =
12500 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12501 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12502 S.Diag(Templated->getLocation(),
12503 diag::note_ovl_candidate_inconsistent_deduction_types)
12504 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12505 << *DeductionFailure.getSecondArg() << T2;
12506 MaybeEmitInheritedConstructorNote(S, Found);
12507 return;
12508 }
12509
12510 which = 1;
12511 } else {
12512 which = 2;
12513 }
12514
12515 // Tweak the diagnostic if the problem is that we deduced packs of
12516 // different arities. We'll print the actual packs anyway in case that
12517 // includes additional useful information.
12518 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12519 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12520 DeductionFailure.getFirstArg()->pack_size() !=
12521 DeductionFailure.getSecondArg()->pack_size()) {
12522 which = 3;
12523 }
12524
12525 S.Diag(Templated->getLocation(),
12526 diag::note_ovl_candidate_inconsistent_deduction)
12527 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12528 << *DeductionFailure.getSecondArg();
12529 MaybeEmitInheritedConstructorNote(S, Found);
12530 return;
12531 }
12532
12534 assert(ParamD && "no parameter found for invalid explicit arguments");
12535
12536 auto Diag = S.Diag(Templated->getLocation(),
12537 diag::note_ovl_candidate_explicit_arg_mismatch);
12538 if (ParamD->getDeclName())
12539 Diag << diag::ExplicitArgMismatchNameKind::Named << ParamD->getDeclName();
12540 else
12541 Diag << diag::ExplicitArgMismatchNameKind::Unnamed
12542 << (getDepthAndIndex(ParamD).second + 1);
12543 if (PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic()) {
12544 SmallString<128> DiagContent;
12545 PDiag->second.EmitToString(S.getDiagnostics(), DiagContent);
12546 Diag << diag::ExplicitArgMismatchReasonKind::Detailed << DiagContent;
12547 } else {
12548 Diag << diag::ExplicitArgMismatchReasonKind::Vague;
12549 }
12550
12551 MaybeEmitInheritedConstructorNote(S, Found);
12552 return;
12553 }
12555 // Format the template argument list into the argument string.
12556 SmallString<128> TemplateArgString;
12557 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12558 TemplateArgString = " ";
12559 TemplateArgString += S.getTemplateArgumentBindingsText(
12560 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12561 if (TemplateArgString.size() == 1)
12562 TemplateArgString.clear();
12563 S.Diag(Templated->getLocation(),
12564 diag::note_ovl_candidate_unsatisfied_constraints)
12565 << TemplateArgString;
12566
12568 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12569 return;
12570 }
12573 DiagnoseArityMismatch(S, Found, Templated, NumArgs, TakingCandidateAddress);
12574 return;
12575
12577 S.Diag(Templated->getLocation(),
12578 diag::note_ovl_candidate_instantiation_depth);
12579 MaybeEmitInheritedConstructorNote(S, Found);
12580 return;
12581
12583 // Format the template argument list into the argument string.
12584 SmallString<128> TemplateArgString;
12585 if (TemplateArgumentList *Args =
12586 DeductionFailure.getTemplateArgumentList()) {
12587 TemplateArgString = " ";
12588 TemplateArgString += S.getTemplateArgumentBindingsText(
12589 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12590 if (TemplateArgString.size() == 1)
12591 TemplateArgString.clear();
12592 }
12593
12594 // If this candidate was disabled by enable_if, say so.
12595 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12596 if (PDiag && PDiag->second.getDiagID() ==
12597 diag::err_typename_nested_not_found_enable_if) {
12598 // FIXME: Use the source range of the condition, and the fully-qualified
12599 // name of the enable_if template. These are both present in PDiag.
12600 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
12601 << "'enable_if'" << TemplateArgString;
12602 return;
12603 }
12604
12605 // We found a specific requirement that disabled the enable_if.
12606 if (PDiag && PDiag->second.getDiagID() ==
12607 diag::err_typename_nested_not_found_requirement) {
12608 S.Diag(Templated->getLocation(),
12609 diag::note_ovl_candidate_disabled_by_requirement)
12610 << PDiag->second.getStringArg(0) << TemplateArgString;
12611 return;
12612 }
12613
12614 // Format the SFINAE diagnostic into the argument string.
12615 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12616 // formatted message in another diagnostic.
12617 SmallString<128> SFINAEArgString;
12618 SourceRange R;
12619 if (PDiag) {
12620 SFINAEArgString = ": ";
12621 R = SourceRange(PDiag->first, PDiag->first);
12622 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
12623 }
12624
12625 S.Diag(Templated->getLocation(),
12626 diag::note_ovl_candidate_substitution_failure)
12627 << TemplateArgString << SFINAEArgString << R;
12628 MaybeEmitInheritedConstructorNote(S, Found);
12629 return;
12630 }
12631
12634 // Format the template argument list into the argument string.
12635 SmallString<128> TemplateArgString;
12636 if (TemplateArgumentList *Args =
12637 DeductionFailure.getTemplateArgumentList()) {
12638 TemplateArgString = " ";
12639 TemplateArgString += S.getTemplateArgumentBindingsText(
12640 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12641 if (TemplateArgString.size() == 1)
12642 TemplateArgString.clear();
12643 }
12644
12645 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
12646 << (*DeductionFailure.getCallArgIndex() + 1)
12647 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12648 << TemplateArgString
12649 << (DeductionFailure.getResult() ==
12651 break;
12652 }
12653
12655 // FIXME: Provide a source location to indicate what we couldn't match.
12656 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12657 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12658 if (FirstTA.getKind() == TemplateArgument::Template &&
12659 SecondTA.getKind() == TemplateArgument::Template) {
12660 TemplateName FirstTN = FirstTA.getAsTemplate();
12661 TemplateName SecondTN = SecondTA.getAsTemplate();
12662 if (FirstTN.getKind() == TemplateName::Template &&
12663 SecondTN.getKind() == TemplateName::Template) {
12664 if (FirstTN.getAsTemplateDecl()->getName() ==
12665 SecondTN.getAsTemplateDecl()->getName()) {
12666 // FIXME: This fixes a bad diagnostic where both templates are named
12667 // the same. This particular case is a bit difficult since:
12668 // 1) It is passed as a string to the diagnostic printer.
12669 // 2) The diagnostic printer only attempts to find a better
12670 // name for types, not decls.
12671 // Ideally, this should folded into the diagnostic printer.
12672 S.Diag(Templated->getLocation(),
12673 CandidateSetKind ==
12675 ? diag::note_friend_template_non_deduced_mismatch_qualified
12676 : diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12677 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12678 return;
12679 }
12680 }
12681 }
12682
12683 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
12685 return;
12686
12687 // FIXME: For generic lambda parameters, check if the function is a lambda
12688 // call operator, and if so, emit a prettier and more informative
12689 // diagnostic that mentions 'auto' and lambda in addition to
12690 // (or instead of?) the canonical template type parameters.
12691 S.Diag(Templated->getLocation(),
12693 ? diag::note_friend_template_non_deduced_mismatch
12694 : diag::note_ovl_candidate_non_deduced_mismatch)
12695 << FirstTA << SecondTA;
12696 return;
12697 }
12698 // TODO: diagnose these individually, then kill off
12699 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12701 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
12702 MaybeEmitInheritedConstructorNote(S, Found);
12703 return;
12705 S.Diag(Templated->getLocation(),
12706 diag::note_cuda_ovl_candidate_target_mismatch);
12707 return;
12708 }
12709}
12710
12711/// Diagnose a failed template-argument deduction, for function calls.
12713 unsigned NumArgs,
12714 bool TakingCandidateAddress) {
12715 assert(Cand->Function && "Candidate must be a function");
12716 FunctionDecl *Fn = Cand->Function;
12720 if (CheckArityMismatch(S, Cand, NumArgs))
12721 return;
12722 }
12723 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
12724 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12725}
12726
12727/// CUDA: diagnose an invalid call across targets.
12729 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12730 assert(Cand->Function && "Candidate must be a Function.");
12731 FunctionDecl *Callee = Cand->Function;
12732
12733 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
12734 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
12735
12736 std::string FnDesc;
12737 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12738 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
12739 Cand->getRewriteKind(), FnDesc);
12740
12741 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
12742 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12743 << FnDesc /* Ignored */
12744 << CalleeTarget << CallerTarget;
12745
12746 // This could be an implicit constructor for which we could not infer the
12747 // target due to a collsion. Diagnose that case.
12748 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
12749 if (Meth != nullptr && Meth->isImplicit()) {
12750 CXXRecordDecl *ParentClass = Meth->getParent();
12752
12753 switch (FnKindPair.first) {
12754 default:
12755 return;
12756 case oc_implicit_default_constructor:
12758 break;
12759 case oc_implicit_copy_constructor:
12761 break;
12762 case oc_implicit_move_constructor:
12764 break;
12765 case oc_implicit_copy_assignment:
12767 break;
12768 case oc_implicit_move_assignment:
12770 break;
12771 };
12772
12773 bool ConstRHS = false;
12774 if (Meth->getNumParams()) {
12775 if (const ReferenceType *RT =
12776 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
12777 ConstRHS = RT->getPointeeType().isConstQualified();
12778 }
12779 }
12780
12781 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
12782 /* ConstRHS */ ConstRHS,
12783 /* Diagnose */ true);
12784 }
12785}
12786
12788 assert(Cand->Function && "Candidate must be a function");
12789 FunctionDecl *Callee = Cand->Function;
12790 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12791
12792 S.Diag(Callee->getLocation(),
12793 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12794 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12795}
12796
12798 assert(Cand->Function && "Candidate must be a function");
12799 FunctionDecl *Fn = Cand->Function;
12801 assert(ES.isExplicit() && "not an explicit candidate");
12802
12803 unsigned Kind;
12804 switch (Fn->getDeclKind()) {
12805 case Decl::Kind::CXXConstructor:
12806 Kind = 0;
12807 break;
12808 case Decl::Kind::CXXConversion:
12809 Kind = 1;
12810 break;
12811 case Decl::Kind::CXXDeductionGuide:
12812 Kind = Fn->isImplicit() ? 0 : 2;
12813 break;
12814 default:
12815 llvm_unreachable("invalid Decl");
12816 }
12817
12818 // Note the location of the first (in-class) declaration; a redeclaration
12819 // (particularly an out-of-class definition) will typically lack the
12820 // 'explicit' specifier.
12821 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12822 FunctionDecl *First = Fn->getFirstDecl();
12823 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12824 First = Pattern->getFirstDecl();
12825
12826 S.Diag(First->getLocation(),
12827 diag::note_ovl_candidate_explicit)
12828 << Kind << (ES.getExpr() ? 1 : 0)
12829 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12830}
12831
12833 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
12834 if (!DG)
12835 return;
12836 TemplateDecl *OriginTemplate =
12838 // We want to always print synthesized deduction guides for type aliases.
12839 // They would retain the explicit bit of the corresponding constructor.
12840 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12841 return;
12842 std::string FunctionProto;
12843 llvm::raw_string_ostream OS(FunctionProto);
12844 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12845 if (!Template) {
12846 // This also could be an instantiation. Find out the primary template.
12847 FunctionDecl *Pattern =
12848 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12849 if (!Pattern) {
12850 // The implicit deduction guide is built on an explicit non-template
12851 // deduction guide. Currently, this might be the case only for type
12852 // aliases.
12853 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12854 // gets merged.
12855 assert(OriginTemplate->isTypeAlias() &&
12856 "Non-template implicit deduction guides are only possible for "
12857 "type aliases");
12858 DG->print(OS);
12859 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12860 << FunctionProto;
12861 return;
12862 }
12864 assert(Template && "Cannot find the associated function template of "
12865 "CXXDeductionGuideDecl?");
12866 }
12867 Template->print(OS);
12868 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12869 << FunctionProto;
12870}
12871
12872/// Generates a 'note' diagnostic for an overload candidate. We've
12873/// already generated a primary error at the call site.
12874///
12875/// It really does need to be a single diagnostic with its caret
12876/// pointed at the candidate declaration. Yes, this creates some
12877/// major challenges of technical writing. Yes, this makes pointing
12878/// out problems with specific arguments quite awkward. It's still
12879/// better than generating twenty screens of text for every failed
12880/// overload.
12881///
12882/// It would be great to be able to express per-candidate problems
12883/// more richly for those diagnostic clients that cared, but we'd
12884/// still have to be just as careful with the default diagnostics.
12885/// \param CtorDestAS Addr space of object being constructed (for ctor
12886/// candidates only).
12888 unsigned NumArgs,
12889 bool TakingCandidateAddress,
12890 LangAS CtorDestAS = LangAS::Default) {
12891 assert(Cand->Function && "Candidate must be a function");
12892 FunctionDecl *Fn = Cand->Function;
12894 return;
12895
12896 // There is no physical candidate declaration to point to for OpenCL builtins.
12897 // Except for failed conversions, the notes are identical for each candidate,
12898 // so do not generate such notes.
12899 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12901 return;
12902
12903 // Skip implicit member functions when trying to resolve
12904 // the address of a an overload set for a function pointer.
12905 if (Cand->TookAddressOfOverload &&
12906 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12907 return;
12908
12909 // Note deleted candidates, but only if they're viable.
12910 if (Cand->Viable) {
12911 if (Fn->isDeleted()) {
12912 std::string FnDesc;
12913 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12914 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12915 Cand->getRewriteKind(), FnDesc);
12916
12917 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12918 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12919 << (Fn->isDeleted()
12920 ? (Fn->getCanonicalDecl()->isDeletedAsWritten() ? 1 : 2)
12921 : 0);
12922 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12923 return;
12924 }
12925
12926 // We don't really have anything else to say about viable candidates.
12927 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12928 return;
12929 }
12930
12931 // If this is a synthesized deduction guide we're deducing against, add a note
12932 // for it. These deduction guides are not explicitly spelled in the source
12933 // code, so simply printing a deduction failure note mentioning synthesized
12934 // template parameters or pointing to the header of the surrounding RecordDecl
12935 // would be confusing.
12936 //
12937 // We prefer adding such notes at the end of the deduction failure because
12938 // duplicate code snippets appearing in the diagnostic would likely become
12939 // noisy.
12940 llvm::scope_exit _([&] { NoteImplicitDeductionGuide(S, Fn); });
12941
12942 switch (Cand->FailureKind) {
12945 return DiagnoseArityMismatch(S, Cand, NumArgs);
12946
12948 return DiagnoseBadDeduction(S, Cand, NumArgs,
12949 TakingCandidateAddress);
12950
12952 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12953 << (Fn->getPrimaryTemplate() ? 1 : 0);
12954 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12955 return;
12956 }
12957
12959 Qualifiers QualsForPrinting;
12960 QualsForPrinting.setAddressSpace(CtorDestAS);
12961 S.Diag(Fn->getLocation(),
12962 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12963 << QualsForPrinting;
12964 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12965 return;
12966 }
12967
12971 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12972
12974 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12975 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12976 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12977 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12978
12979 // FIXME: this currently happens when we're called from SemaInit
12980 // when user-conversion overload fails. Figure out how to handle
12981 // those conditions and diagnose them well.
12982 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12983 }
12984
12986 return DiagnoseBadTarget(S, Cand);
12987
12988 case ovl_fail_enable_if:
12989 return DiagnoseFailedEnableIfAttr(S, Cand);
12990
12991 case ovl_fail_explicit:
12992 return DiagnoseFailedExplicitSpec(S, Cand);
12993
12995 // It's generally not interesting to note copy/move constructors here.
12996 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12997 return;
12998 S.Diag(Fn->getLocation(),
12999 diag::note_ovl_candidate_inherited_constructor_slice)
13000 << (Fn->getPrimaryTemplate() ? 1 : 0)
13001 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
13002 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
13003 return;
13004
13006 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
13007 (void)Available;
13008 assert(!Available);
13009 break;
13010 }
13012 // Do nothing, these should simply be ignored.
13013 break;
13014
13016 std::string FnDesc;
13017 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
13018 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
13019 Cand->getRewriteKind(), FnDesc);
13020
13021 S.Diag(Fn->getLocation(),
13022 diag::note_ovl_candidate_constraints_not_satisfied)
13023 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
13024 << FnDesc /* Ignored */;
13025 ConstraintSatisfaction Satisfaction;
13026 if (S.CheckFunctionConstraints(Fn, Satisfaction, SourceLocation(),
13027 /*ForOverloadResolution=*/true))
13028 break;
13029 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13030 }
13031 }
13032}
13033
13036 return;
13037
13038 // Desugar the type of the surrogate down to a function type,
13039 // retaining as many typedefs as possible while still showing
13040 // the function type (and, therefore, its parameter types).
13041 QualType FnType = Cand->Surrogate->getConversionType();
13042 bool isLValueReference = false;
13043 bool isRValueReference = false;
13044 bool isPointer = false;
13045 if (const LValueReferenceType *FnTypeRef =
13046 FnType->getAs<LValueReferenceType>()) {
13047 FnType = FnTypeRef->getPointeeType();
13048 isLValueReference = true;
13049 } else if (const RValueReferenceType *FnTypeRef =
13050 FnType->getAs<RValueReferenceType>()) {
13051 FnType = FnTypeRef->getPointeeType();
13052 isRValueReference = true;
13053 }
13054 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
13055 FnType = FnTypePtr->getPointeeType();
13056 isPointer = true;
13057 }
13058 // Desugar down to a function type.
13059 FnType = QualType(FnType->getAs<FunctionType>(), 0);
13060 // Reconstruct the pointer/reference as appropriate.
13061 if (isPointer) FnType = S.Context.getPointerType(FnType);
13062 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
13063 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
13064
13065 if (!Cand->Viable &&
13067 S.Diag(Cand->Surrogate->getLocation(),
13068 diag::note_ovl_surrogate_constraints_not_satisfied)
13069 << Cand->Surrogate;
13070 ConstraintSatisfaction Satisfaction;
13071 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
13072 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13073 } else {
13074 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
13075 << FnType;
13076 }
13077}
13078
13079static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
13080 SourceLocation OpLoc,
13081 OverloadCandidate *Cand) {
13082 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
13083 std::string TypeStr("operator");
13084 TypeStr += Opc;
13085 TypeStr += "(";
13086 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
13087 if (Cand->Conversions.size() == 1) {
13088 TypeStr += ")";
13089 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
13090 } else {
13091 TypeStr += ", ";
13092 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
13093 TypeStr += ")";
13094 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
13095 }
13096}
13097
13099 OverloadCandidate *Cand) {
13100 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
13101 if (ICS.isBad()) break; // all meaningless after first invalid
13102 if (!ICS.isAmbiguous()) continue;
13103
13105 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
13106 }
13107}
13108
13110 if (Cand->Function)
13111 return Cand->Function->getLocation();
13112 if (Cand->IsSurrogate)
13113 return Cand->Surrogate->getLocation();
13114 return SourceLocation();
13115}
13116
13117static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
13118 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
13122 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
13123
13127 return 1;
13128
13131 return 2;
13132
13140 return 3;
13141
13143 return 4;
13144
13146 return 5;
13147
13150 return 6;
13151 }
13152 llvm_unreachable("Unhandled deduction result");
13153}
13154
13155namespace {
13156
13157struct CompareOverloadCandidatesForDisplay {
13158 Sema &S;
13159 SourceLocation Loc;
13160 size_t NumArgs;
13162
13163 CompareOverloadCandidatesForDisplay(
13164 Sema &S, SourceLocation Loc, size_t NArgs,
13166 : S(S), NumArgs(NArgs), CSK(CSK) {}
13167
13168 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
13169 // If there are too many or too few arguments, that's the high-order bit we
13170 // want to sort by, even if the immediate failure kind was something else.
13171 if (C->FailureKind == ovl_fail_too_many_arguments ||
13172 C->FailureKind == ovl_fail_too_few_arguments)
13173 return static_cast<OverloadFailureKind>(C->FailureKind);
13174
13175 if (C->Function) {
13176 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
13178 if (NumArgs < C->Function->getMinRequiredArguments())
13180 }
13181
13182 return static_cast<OverloadFailureKind>(C->FailureKind);
13183 }
13184
13185 bool operator()(const OverloadCandidate *L,
13186 const OverloadCandidate *R) {
13187 // Fast-path this check.
13188 if (L == R) return false;
13189
13190 // Order first by viability.
13191 if (L->Viable) {
13192 if (!R->Viable) return true;
13193
13194 if (int Ord = CompareConversions(*L, *R))
13195 return Ord < 0;
13196 // Use other tie breakers.
13197 } else if (R->Viable)
13198 return false;
13199
13200 assert(L->Viable == R->Viable);
13201
13202 // Criteria by which we can sort non-viable candidates:
13203 if (!L->Viable) {
13204 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
13205 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
13206
13207 // 1. Arity mismatches come after other candidates.
13208 if (LFailureKind == ovl_fail_too_many_arguments ||
13209 LFailureKind == ovl_fail_too_few_arguments) {
13210 if (RFailureKind == ovl_fail_too_many_arguments ||
13211 RFailureKind == ovl_fail_too_few_arguments) {
13212 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
13213 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
13214 if (LDist == RDist) {
13215 if (LFailureKind == RFailureKind)
13216 // Sort non-surrogates before surrogates.
13217 return !L->IsSurrogate && R->IsSurrogate;
13218 // Sort candidates requiring fewer parameters than there were
13219 // arguments given after candidates requiring more parameters
13220 // than there were arguments given.
13221 return LFailureKind == ovl_fail_too_many_arguments;
13222 }
13223 return LDist < RDist;
13224 }
13225 return false;
13226 }
13227 if (RFailureKind == ovl_fail_too_many_arguments ||
13228 RFailureKind == ovl_fail_too_few_arguments)
13229 return true;
13230
13231 // 2. Bad conversions come first and are ordered by the number
13232 // of bad conversions and quality of good conversions.
13233 if (LFailureKind == ovl_fail_bad_conversion) {
13234 if (RFailureKind != ovl_fail_bad_conversion)
13235 return true;
13236
13237 // The conversion that can be fixed with a smaller number of changes,
13238 // comes first.
13239 unsigned numLFixes = L->Fix.NumConversionsFixed;
13240 unsigned numRFixes = R->Fix.NumConversionsFixed;
13241 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
13242 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
13243 if (numLFixes != numRFixes) {
13244 return numLFixes < numRFixes;
13245 }
13246
13247 // If there's any ordering between the defined conversions...
13248 if (int Ord = CompareConversions(*L, *R))
13249 return Ord < 0;
13250 } else if (RFailureKind == ovl_fail_bad_conversion)
13251 return false;
13252
13253 if (LFailureKind == ovl_fail_bad_deduction) {
13254 if (RFailureKind != ovl_fail_bad_deduction)
13255 return true;
13256
13257 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
13258 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
13259 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
13260 if (LRank != RRank)
13261 return LRank < RRank;
13262 }
13263 } else if (RFailureKind == ovl_fail_bad_deduction)
13264 return false;
13265
13266 // TODO: others?
13267 }
13268
13269 // Sort everything else by location.
13270 SourceLocation LLoc = GetLocationForCandidate(L);
13271 SourceLocation RLoc = GetLocationForCandidate(R);
13272
13273 // Put candidates without locations (e.g. builtins) at the end.
13274 if (LLoc.isValid() && RLoc.isValid())
13275 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13276 if (LLoc.isValid() && !RLoc.isValid())
13277 return true;
13278 if (RLoc.isValid() && !LLoc.isValid())
13279 return false;
13280 assert(!LLoc.isValid() && !RLoc.isValid());
13281 // For builtins and other functions without locations, fallback to the order
13282 // in which they were added into the candidate set.
13283 return L < R;
13284 }
13285
13286private:
13287 struct ConversionSignals {
13288 unsigned KindRank = 0;
13290
13291 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13292 ConversionSignals Sig;
13293 Sig.KindRank = Seq.getKindRank();
13294 if (Seq.isStandard())
13295 Sig.Rank = Seq.Standard.getRank();
13296 else if (Seq.isUserDefined())
13297 Sig.Rank = Seq.UserDefined.After.getRank();
13298 // We intend StaticObjectArgumentConversion to compare the same as
13299 // StandardConversion with ICR_ExactMatch rank.
13300 return Sig;
13301 }
13302
13303 static ConversionSignals ForObjectArgument() {
13304 // We intend StaticObjectArgumentConversion to compare the same as
13305 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13306 return {};
13307 }
13308 };
13309
13310 // Returns -1 if conversions in L are considered better.
13311 // 0 if they are considered indistinguishable.
13312 // 1 if conversions in R are better.
13313 int CompareConversions(const OverloadCandidate &L,
13314 const OverloadCandidate &R) {
13315 // We cannot use `isBetterOverloadCandidate` because it is defined
13316 // according to the C++ standard and provides a partial order, but we need
13317 // a total order as this function is used in sort.
13318 assert(L.Conversions.size() == R.Conversions.size());
13319 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13320 auto LS = L.IgnoreObjectArgument && I == 0
13321 ? ConversionSignals::ForObjectArgument()
13322 : ConversionSignals::ForSequence(L.Conversions[I]);
13323 auto RS = R.IgnoreObjectArgument
13324 ? ConversionSignals::ForObjectArgument()
13325 : ConversionSignals::ForSequence(R.Conversions[I]);
13326 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
13327 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
13328 ? -1
13329 : 1;
13330 }
13331 // FIXME: find a way to compare templates for being more or less
13332 // specialized that provides a strict weak ordering.
13333 return 0;
13334 }
13335};
13336}
13337
13338/// CompleteNonViableCandidate - Normally, overload resolution only
13339/// computes up to the first bad conversion. Produces the FixIt set if
13340/// possible.
13341static void
13343 ArrayRef<Expr *> Args,
13345 assert(!Cand->Viable);
13346
13347 // Don't do anything on failures other than bad conversion.
13349 return;
13350
13351 // We only want the FixIts if all the arguments can be corrected.
13352 bool Unfixable = false;
13353 // Use a implicit copy initialization to check conversion fixes.
13355
13356 // Attempt to fix the bad conversion.
13357 unsigned ConvCount = Cand->Conversions.size();
13358 for (unsigned ConvIdx =
13359 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13360 : 0);
13361 /**/; ++ConvIdx) {
13362 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13363 if (Cand->Conversions[ConvIdx].isInitialized() &&
13364 Cand->Conversions[ConvIdx].isBad()) {
13365 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13366 break;
13367 }
13368 }
13369
13370 // FIXME: this should probably be preserved from the overload
13371 // operation somehow.
13372 bool SuppressUserConversions = false;
13373
13374 unsigned ConvIdx = 0;
13375 unsigned ArgIdx = 0;
13376 ArrayRef<QualType> ParamTypes;
13377 bool Reversed = Cand->isReversed();
13378
13379 if (Cand->IsSurrogate) {
13380 QualType ConvType
13382 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13383 ConvType = ConvPtrType->getPointeeType();
13384 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13385 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13386 ConvIdx = 1;
13387 } else if (Cand->Function) {
13388 ParamTypes =
13389 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13390 if (isa<CXXMethodDecl>(Cand->Function) &&
13393 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13394 ConvIdx = 1;
13396 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13398 OO_Subscript)
13399 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13400 ArgIdx = 1;
13401 }
13402 } else {
13403 // Builtin operator.
13404 assert(ConvCount <= 3);
13405 ParamTypes = Cand->BuiltinParamTypes;
13406 }
13407
13408 // Fill in the rest of the conversions.
13409 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13410 ConvIdx != ConvCount && ArgIdx < Args.size();
13411 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13412 if (Cand->Conversions[ConvIdx].isInitialized()) {
13413 // We've already checked this conversion.
13414 } else if (ParamIdx < ParamTypes.size()) {
13415 if (ParamTypes[ParamIdx]->isDependentType())
13416 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13417 Args[ArgIdx]->getType());
13418 else {
13419 Cand->Conversions[ConvIdx] =
13420 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
13421 SuppressUserConversions,
13422 /*InOverloadResolution=*/true,
13423 /*AllowObjCWritebackConversion=*/
13424 S.getLangOpts().ObjCAutoRefCount);
13425 // Store the FixIt in the candidate if it exists.
13426 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13427 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13428 }
13429 } else
13430 Cand->Conversions[ConvIdx].setEllipsis();
13431 }
13432}
13433
13436 SourceLocation OpLoc,
13437 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13438
13440
13441 // Sort the candidates by viability and position. Sorting directly would
13442 // be prohibitive, so we make a set of pointers and sort those.
13444 if (OCD == OCD_AllCandidates) Cands.reserve(size());
13445 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13446 Cand != LastCand; ++Cand) {
13447 if (!Filter(*Cand))
13448 continue;
13449 switch (OCD) {
13450 case OCD_AllCandidates:
13451 if (!Cand->Viable) {
13452 if (!Cand->Function && !Cand->IsSurrogate) {
13453 // This a non-viable builtin candidate. We do not, in general,
13454 // want to list every possible builtin candidate.
13455 continue;
13456 }
13457 CompleteNonViableCandidate(S, Cand, Args, Kind);
13458 }
13459 break;
13460
13462 if (!Cand->Viable)
13463 continue;
13464 break;
13465
13467 if (!Cand->Best)
13468 continue;
13469 break;
13470 }
13471
13472 Cands.push_back(Cand);
13473 }
13474
13475 llvm::stable_sort(
13476 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13477
13478 return Cands;
13479}
13480
13482 SourceLocation OpLoc) {
13483 bool DeferHint = false;
13484 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13485 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13486 // host device candidates.
13487 auto WrongSidedCands =
13488 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
13489 return (Cand.Viable == false &&
13491 (Cand.Function &&
13492 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13493 Cand.Function->template hasAttr<CUDADeviceAttr>());
13494 });
13495 DeferHint = !WrongSidedCands.empty();
13496 }
13497 return DeferHint;
13498}
13499
13500/// When overload resolution fails, prints diagnostic messages containing the
13501/// candidates in the candidate set.
13504 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13505 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13506
13507 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13508
13509 {
13510 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13511 S.Diag(PD.first, PD.second);
13512 }
13513
13514 // In WebAssembly we don't want to emit further diagnostics if a table is
13515 // passed as an argument to a function.
13516 bool NoteCands = true;
13517 for (const Expr *Arg : Args) {
13518 if (Arg->getType()->isWebAssemblyTableType())
13519 NoteCands = false;
13520 }
13521
13522 if (NoteCands)
13523 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13524
13525 if (OCD == OCD_AmbiguousCandidates)
13527 {Candidates.begin(), Candidates.end()});
13528}
13529
13532 StringRef Opc, SourceLocation OpLoc) {
13533 bool ReportedAmbiguousConversions = false;
13534
13535 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13536 unsigned CandsShown = 0;
13537 auto I = Cands.begin(), E = Cands.end();
13538 for (; I != E; ++I) {
13539 OverloadCandidate *Cand = *I;
13540
13541 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13542 ShowOverloads == Ovl_Best) {
13543 break;
13544 }
13545 ++CandsShown;
13546
13547 if (Cand->Function)
13548 NoteFunctionCandidate(S, Cand, Args.size(),
13549 Kind == CSK_AddressOfOverloadSet, DestAS);
13550 else if (Cand->IsSurrogate)
13551 NoteSurrogateCandidate(S, Cand);
13552 else {
13553 assert(Cand->Viable &&
13554 "Non-viable built-in candidates are not added to Cands.");
13555 // Generally we only see ambiguities including viable builtin
13556 // operators if overload resolution got screwed up by an
13557 // ambiguous user-defined conversion.
13558 //
13559 // FIXME: It's quite possible for different conversions to see
13560 // different ambiguities, though.
13561 if (!ReportedAmbiguousConversions) {
13562 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13563 ReportedAmbiguousConversions = true;
13564 }
13565
13566 // If this is a viable builtin, print it.
13567 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13568 }
13569 }
13570
13571 // Inform S.Diags that we've shown an overload set with N elements. This may
13572 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13573 S.Diags.overloadCandidatesShown(CandsShown);
13574
13575 if (I != E) {
13576 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13577 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
13578 }
13579}
13580
13582 const Sema &S) const {
13583 if (S.getLangOpts().CUDA) {
13584 auto *Caller = S.getCurFunctionDecl(true);
13585 // Overloading based on __host__ and __device__ attributes takes
13586 // higher priority, HD functions may favor template candidates even when a
13587 // non-template candidate would be a perfect match.
13588 if (Caller && Caller->hasAttr<CUDAHostAttr>() &&
13589 Caller->hasAttr<CUDADeviceAttr>())
13590 return false;
13591 }
13592
13593 return
13594 // For user defined conversion we need to check against different
13595 // combination of CV qualifiers and look at any explicit specifier, so
13596 // always deduce template candidates.
13598 // When doing code completion, we want to see all the
13599 // viable candidates.
13600 && Kind != CSK_CodeCompletion;
13601}
13602
13603static SourceLocation
13605 return Cand->Specialization ? Cand->Specialization->getLocation()
13606 : SourceLocation();
13607}
13608
13609namespace {
13610struct CompareTemplateSpecCandidatesForDisplay {
13611 Sema &S;
13612 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13613
13614 bool operator()(const TemplateSpecCandidate *L,
13615 const TemplateSpecCandidate *R) {
13616 // Fast-path this check.
13617 if (L == R)
13618 return false;
13619
13620 // Assuming that both candidates are not matches...
13621
13622 // Sort by the ranking of deduction failures.
13623 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
13625 RankDeductionFailure(R->DeductionFailure);
13626
13627 // Sort everything else by location.
13628 SourceLocation LLoc = GetLocationForCandidate(L);
13629 SourceLocation RLoc = GetLocationForCandidate(R);
13630
13631 // Put candidates without locations (e.g. builtins) at the end.
13632 if (LLoc.isInvalid())
13633 return false;
13634 if (RLoc.isInvalid())
13635 return true;
13636
13637 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13638 }
13639};
13640}
13641
13642/// Diagnose a template argument deduction failure.
13643/// We are treating these failures as overload failures due to bad
13644/// deductions.
13646 Sema &S, bool ForTakingAddress,
13647 TemplateSpecCandidateSetKind CandidateSetKind) {
13649 DeductionFailure, /*NumArgs=*/0, ForTakingAddress,
13650 CandidateSetKind);
13651}
13652
13653void TemplateSpecCandidateSet::destroyCandidates() {
13654 for (iterator i = begin(), e = end(); i != e; ++i) {
13655 i->DeductionFailure.Destroy();
13656 }
13657}
13658
13660 destroyCandidates();
13661 Candidates.clear();
13662}
13663
13664/// NoteCandidates - When no template specialization match is found, prints
13665/// diagnostic messages containing the non-matching specializations that form
13666/// the candidate set.
13667/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13668/// OCD == OCD_AllCandidates and Cand->Viable == false.
13670 // Sort the candidates by position (assuming no candidate is a match).
13671 // Sorting directly would be prohibitive, so we make a set of pointers
13672 // and sort those.
13674 Cands.reserve(size());
13675 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13676 if (Cand->Specialization)
13677 Cands.push_back(Cand);
13678 // Otherwise, this is a non-matching builtin candidate. We do not,
13679 // in general, want to list every possible builtin candidate.
13680 }
13681
13682 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
13683
13684 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13685 // for generalization purposes (?).
13686 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13687
13689 unsigned CandsShown = 0;
13690 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13691 TemplateSpecCandidate *Cand = *I;
13692
13693 // Set an arbitrary limit on the number of candidates we'll spam
13694 // the user with. FIXME: This limit should depend on details of the
13695 // candidate list.
13696 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13697 break;
13698 ++CandsShown;
13699
13700 assert(Cand->Specialization &&
13701 "Non-matching built-in candidates are not added to Cands.");
13702 Cand->NoteDeductionFailure(S, ForTakingAddress, CandidateSetKind);
13703 }
13704
13705 if (I != E)
13706 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
13707}
13708
13709// [PossiblyAFunctionType] --> [Return]
13710// NonFunctionType --> NonFunctionType
13711// R (A) --> R(A)
13712// R (*)(A) --> R (A)
13713// R (&)(A) --> R (A)
13714// R (S::*)(A) --> R (A)
13716 QualType Ret = PossiblyAFunctionType;
13717 if (const PointerType *ToTypePtr =
13718 PossiblyAFunctionType->getAs<PointerType>())
13719 Ret = ToTypePtr->getPointeeType();
13720 else if (const ReferenceType *ToTypeRef =
13721 PossiblyAFunctionType->getAs<ReferenceType>())
13722 Ret = ToTypeRef->getPointeeType();
13723 else if (const MemberPointerType *MemTypePtr =
13724 PossiblyAFunctionType->getAs<MemberPointerType>())
13725 Ret = MemTypePtr->getPointeeType();
13726 Ret =
13727 Context.getCanonicalType(Ret).getUnqualifiedType();
13728 return Ret;
13729}
13730
13732 bool Complain = true) {
13733 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13734 S.DeduceReturnType(FD, Loc, Complain))
13735 return true;
13736
13737 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13738 if (S.getLangOpts().CPlusPlus17 &&
13739 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
13740 !S.ResolveExceptionSpec(Loc, FPT))
13741 return true;
13742
13743 return false;
13744}
13745
13746namespace {
13747// A helper class to help with address of function resolution
13748// - allows us to avoid passing around all those ugly parameters
13749class AddressOfFunctionResolver {
13750 Sema& S;
13751 Expr* SourceExpr;
13752 const QualType& TargetType;
13753 QualType TargetFunctionType; // Extracted function type from target type
13754
13755 bool Complain;
13756 //DeclAccessPair& ResultFunctionAccessPair;
13757 ASTContext& Context;
13758
13759 bool TargetTypeIsNonStaticMemberFunction;
13760 bool FoundNonTemplateFunction;
13761 bool StaticMemberFunctionFromBoundPointer;
13762 bool HasComplained;
13763
13764 OverloadExpr::FindResult OvlExprInfo;
13765 OverloadExpr *OvlExpr;
13766 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13767 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13768 TemplateSpecCandidateSet FailedCandidates;
13769
13770public:
13771 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13772 const QualType &TargetType, bool Complain)
13773 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13774 Complain(Complain), Context(S.getASTContext()),
13775 TargetTypeIsNonStaticMemberFunction(
13776 !!TargetType->getAs<MemberPointerType>()),
13777 FoundNonTemplateFunction(false),
13778 StaticMemberFunctionFromBoundPointer(false),
13779 HasComplained(false),
13780 OvlExprInfo(OverloadExpr::find(SourceExpr)),
13781 OvlExpr(OvlExprInfo.Expression),
13782 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13783 ExtractUnqualifiedFunctionTypeFromTargetType();
13784
13785 if (TargetFunctionType->isFunctionType()) {
13786 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
13787 if (!UME->isImplicitAccess() &&
13789 StaticMemberFunctionFromBoundPointer = true;
13790 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13791 DeclAccessPair dap;
13792 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13793 OvlExpr, false, &dap)) {
13794 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
13795 if (!Method->isStatic()) {
13796 // If the target type is a non-function type and the function found
13797 // is a non-static member function, pretend as if that was the
13798 // target, it's the only possible type to end up with.
13799 TargetTypeIsNonStaticMemberFunction = true;
13800
13801 // And skip adding the function if its not in the proper form.
13802 // We'll diagnose this due to an empty set of functions.
13803 if (!OvlExprInfo.HasFormOfMemberPointer)
13804 return;
13805 }
13806
13807 Matches.push_back(std::make_pair(dap, Fn));
13808 }
13809 return;
13810 }
13811
13812 if (OvlExpr->hasExplicitTemplateArgs())
13813 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
13814
13815 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13816 if (Matches.size() > 1 && S.getLangOpts().CUDA)
13817 EliminateSuboptimalCudaMatches();
13818
13819 // C++ [over.over]p4:
13820 // If more than one function is selected, [...]
13821 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13822 if (FoundNonTemplateFunction) {
13823 EliminateAllTemplateMatches();
13824 EliminateLessPartialOrderingConstrainedMatches();
13825 } else
13826 EliminateAllExceptMostSpecializedTemplate();
13827 }
13828 }
13829 }
13830
13831 bool hasComplained() const { return HasComplained; }
13832
13833private:
13834 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13835 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
13836 S.IsFunctionConversion(FD->getType(), TargetFunctionType);
13837 }
13838
13839 /// \return true if A is considered a better overload candidate for the
13840 /// desired type than B.
13841 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13842 // If A doesn't have exactly the correct type, we don't want to classify it
13843 // as "better" than anything else. This way, the user is required to
13844 // disambiguate for us if there are multiple candidates and no exact match.
13845 return candidateHasExactlyCorrectType(A) &&
13846 (!candidateHasExactlyCorrectType(B) ||
13847 compareEnableIfAttrs(S, A, B) == Comparison::Better);
13848 }
13849
13850 /// \return true if we were able to eliminate all but one overload candidate,
13851 /// false otherwise.
13852 bool eliminiateSuboptimalOverloadCandidates() {
13853 // Same algorithm as overload resolution -- one pass to pick the "best",
13854 // another pass to be sure that nothing is better than the best.
13855 auto Best = Matches.begin();
13856 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13857 if (isBetterCandidate(I->second, Best->second))
13858 Best = I;
13859
13860 const FunctionDecl *BestFn = Best->second;
13861 auto IsBestOrInferiorToBest = [this, BestFn](
13862 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13863 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
13864 };
13865
13866 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13867 // option, so we can potentially give the user a better error
13868 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
13869 return false;
13870 Matches[0] = *Best;
13871 Matches.resize(1);
13872 return true;
13873 }
13874
13875 bool isTargetTypeAFunction() const {
13876 return TargetFunctionType->isFunctionType();
13877 }
13878
13879 // [ToType] [Return]
13880
13881 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13882 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13883 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13884 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13885 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13886 }
13887
13888 // return true if any matching specializations were found
13889 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13890 const DeclAccessPair& CurAccessFunPair) {
13891 if (CXXMethodDecl *Method
13892 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13893 // Skip non-static function templates when converting to pointer, and
13894 // static when converting to member pointer.
13895 bool CanConvertToFunctionPointer =
13896 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13897 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13898 return false;
13899 }
13900 else if (TargetTypeIsNonStaticMemberFunction)
13901 return false;
13902
13903 // C++ [over.over]p2:
13904 // If the name is a function template, template argument deduction is
13905 // done (14.8.2.2), and if the argument deduction succeeds, the
13906 // resulting template argument list is used to generate a single
13907 // function template specialization, which is added to the set of
13908 // overloaded functions considered.
13909 FunctionDecl *Specialization = nullptr;
13910 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13912 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13913 Specialization, Info, /*IsAddressOfFunction*/ true);
13914 Result != TemplateDeductionResult::Success) {
13915 // Make a note of the failed deduction for diagnostics.
13916 FailedCandidates.addCandidate()
13917 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13918 MakeDeductionFailureInfo(Context, Result, Info));
13919 return false;
13920 }
13921
13922 // Template argument deduction ensures that we have an exact match or
13923 // compatible pointer-to-function arguments that would be adjusted by ICS.
13924 // This function template specicalization works.
13926 Context.getCanonicalType(Specialization->getType()),
13927 Context.getCanonicalType(TargetFunctionType)));
13928
13930 return false;
13931
13932 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13933 return true;
13934 }
13935
13936 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13937 const DeclAccessPair& CurAccessFunPair) {
13938 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13939 // Skip non-static functions when converting to pointer, and static
13940 // when converting to member pointer.
13941 bool CanConvertToFunctionPointer =
13942 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13943 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13944 return false;
13945 }
13946 else if (TargetTypeIsNonStaticMemberFunction)
13947 return false;
13948
13949 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13950 if (S.getLangOpts().CUDA) {
13951 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13952 if (!(Caller && Caller->isImplicit()) &&
13953 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13954 return false;
13955 }
13956 if (FunDecl->isMultiVersion()) {
13957 const auto *TA = FunDecl->getAttr<TargetAttr>();
13958 if (TA && !TA->isDefaultVersion())
13959 return false;
13960 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13961 if (TVA && !TVA->isDefaultVersion())
13962 return false;
13963 }
13964
13965 // If any candidate has a placeholder return type, trigger its deduction
13966 // now.
13967 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13968 Complain)) {
13969 HasComplained |= Complain;
13970 return false;
13971 }
13972
13973 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13974 return false;
13975
13976 // If we're in C, we need to support types that aren't exactly identical.
13977 if (!S.getLangOpts().CPlusPlus ||
13978 candidateHasExactlyCorrectType(FunDecl)) {
13979 Matches.push_back(std::make_pair(
13980 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13981 FoundNonTemplateFunction = true;
13982 return true;
13983 }
13984 }
13985
13986 return false;
13987 }
13988
13989 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13990 bool Ret = false;
13991
13992 // If the overload expression doesn't have the form of a pointer to
13993 // member, don't try to convert it to a pointer-to-member type.
13994 if (IsInvalidFormOfPointerToMemberFunction())
13995 return false;
13996
13997 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13998 E = OvlExpr->decls_end();
13999 I != E; ++I) {
14000 // Look through any using declarations to find the underlying function.
14001 NamedDecl *Fn = (*I)->getUnderlyingDecl();
14002
14003 // C++ [over.over]p3:
14004 // Non-member functions and static member functions match
14005 // targets of type "pointer-to-function" or "reference-to-function."
14006 // Nonstatic member functions match targets of
14007 // type "pointer-to-member-function."
14008 // Note that according to DR 247, the containing class does not matter.
14009 if (FunctionTemplateDecl *FunctionTemplate
14010 = dyn_cast<FunctionTemplateDecl>(Fn)) {
14011 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
14012 Ret = true;
14013 }
14014 // If we have explicit template arguments supplied, skip non-templates.
14015 else if (!OvlExpr->hasExplicitTemplateArgs() &&
14016 AddMatchingNonTemplateFunction(Fn, I.getPair()))
14017 Ret = true;
14018 }
14019 assert(Ret || Matches.empty());
14020 return Ret;
14021 }
14022
14023 void EliminateAllExceptMostSpecializedTemplate() {
14024 // [...] and any given function template specialization F1 is
14025 // eliminated if the set contains a second function template
14026 // specialization whose function template is more specialized
14027 // than the function template of F1 according to the partial
14028 // ordering rules of 14.5.5.2.
14029
14030 // The algorithm specified above is quadratic. We instead use a
14031 // two-pass algorithm (similar to the one used to identify the
14032 // best viable function in an overload set) that identifies the
14033 // best function template (if it exists).
14034
14035 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
14036 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
14037 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
14038
14039 // TODO: It looks like FailedCandidates does not serve much purpose
14040 // here, since the no_viable diagnostic has index 0.
14041 UnresolvedSetIterator Result = S.getMostSpecialized(
14042 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
14043 SourceExpr->getBeginLoc(), S.PDiag(),
14044 S.PDiag(diag::err_addr_ovl_ambiguous)
14045 << Matches[0].second->getDeclName(),
14046 S.PDiag(diag::note_ovl_candidate)
14047 << (unsigned)oc_function << (unsigned)ocs_described_template,
14048 Complain, TargetFunctionType);
14049
14050 if (Result != MatchesCopy.end()) {
14051 // Make it the first and only element
14052 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
14053 Matches[0].second = cast<FunctionDecl>(*Result);
14054 Matches.resize(1);
14055 } else
14056 HasComplained |= Complain;
14057 }
14058
14059 void EliminateAllTemplateMatches() {
14060 // [...] any function template specializations in the set are
14061 // eliminated if the set also contains a non-template function, [...]
14062 for (unsigned I = 0, N = Matches.size(); I != N; ) {
14063 if (Matches[I].second->getPrimaryTemplate() == nullptr)
14064 ++I;
14065 else {
14066 Matches[I] = Matches[--N];
14067 Matches.resize(N);
14068 }
14069 }
14070 }
14071
14072 void EliminateLessPartialOrderingConstrainedMatches() {
14073 // C++ [over.over]p5:
14074 // [...] Any given non-template function F0 is eliminated if the set
14075 // contains a second non-template function that is more
14076 // partial-ordering-constrained than F0. [...]
14077 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
14078 "Call EliminateAllTemplateMatches() first");
14079 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
14080 Results.push_back(Matches[0]);
14081 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
14082 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
14083 FunctionDecl *F = getMorePartialOrderingConstrained(
14084 S, Matches[I].second, Results[0].second,
14085 /*IsFn1Reversed=*/false,
14086 /*IsFn2Reversed=*/false);
14087 if (!F) {
14088 Results.push_back(Matches[I]);
14089 continue;
14090 }
14091 if (F == Matches[I].second) {
14092 Results.clear();
14093 Results.push_back(Matches[I]);
14094 }
14095 }
14096 std::swap(Matches, Results);
14097 }
14098
14099 void EliminateSuboptimalCudaMatches() {
14100 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
14101 Matches);
14102 }
14103
14104public:
14105 void ComplainNoMatchesFound() const {
14106 assert(Matches.empty());
14107 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
14108 << OvlExpr->getName() << TargetFunctionType
14109 << OvlExpr->getSourceRange();
14110 if (FailedCandidates.empty())
14111 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
14112 /*TakingAddress=*/true);
14113 else {
14114 // We have some deduction failure messages. Use them to diagnose
14115 // the function templates, and diagnose the non-template candidates
14116 // normally.
14117 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
14118 IEnd = OvlExpr->decls_end();
14119 I != IEnd; ++I)
14120 if (FunctionDecl *Fun =
14121 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
14123 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
14124 /*TakingAddress=*/true);
14125 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
14126 }
14127 }
14128
14129 bool IsInvalidFormOfPointerToMemberFunction() const {
14130 return TargetTypeIsNonStaticMemberFunction &&
14131 !OvlExprInfo.HasFormOfMemberPointer;
14132 }
14133
14134 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
14135 // TODO: Should we condition this on whether any functions might
14136 // have matched, or is it more appropriate to do that in callers?
14137 // TODO: a fixit wouldn't hurt.
14138 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
14139 << TargetType << OvlExpr->getSourceRange();
14140 }
14141
14142 bool IsStaticMemberFunctionFromBoundPointer() const {
14143 return StaticMemberFunctionFromBoundPointer;
14144 }
14145
14146 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
14147 S.Diag(OvlExpr->getBeginLoc(),
14148 diag::err_invalid_form_pointer_member_function)
14149 << OvlExpr->getSourceRange();
14150 }
14151
14152 void ComplainOfInvalidConversion() const {
14153 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
14154 << OvlExpr->getName() << TargetType;
14155 }
14156
14157 void ComplainMultipleMatchesFound() const {
14158 assert(Matches.size() > 1);
14159 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
14160 << OvlExpr->getName() << OvlExpr->getSourceRange();
14161 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
14162 /*TakingAddress=*/true);
14163 }
14164
14165 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
14166
14167 int getNumMatches() const { return Matches.size(); }
14168
14169 FunctionDecl* getMatchingFunctionDecl() const {
14170 if (Matches.size() != 1) return nullptr;
14171 return Matches[0].second;
14172 }
14173
14174 const DeclAccessPair* getMatchingFunctionAccessPair() const {
14175 if (Matches.size() != 1) return nullptr;
14176 return &Matches[0].first;
14177 }
14178};
14179}
14180
14181FunctionDecl *
14183 QualType TargetType,
14184 bool Complain,
14185 DeclAccessPair &FoundResult,
14186 bool *pHadMultipleCandidates) {
14187 assert(AddressOfExpr->getType() == Context.OverloadTy);
14188
14189 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
14190 Complain);
14191 int NumMatches = Resolver.getNumMatches();
14192 FunctionDecl *Fn = nullptr;
14193 bool ShouldComplain = Complain && !Resolver.hasComplained();
14194 if (NumMatches == 0 && ShouldComplain) {
14195 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
14196 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
14197 else
14198 Resolver.ComplainNoMatchesFound();
14199 }
14200 else if (NumMatches > 1 && ShouldComplain)
14201 Resolver.ComplainMultipleMatchesFound();
14202 else if (NumMatches == 1) {
14203 Fn = Resolver.getMatchingFunctionDecl();
14204 assert(Fn);
14205 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
14206 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
14207 FoundResult = *Resolver.getMatchingFunctionAccessPair();
14208 if (Complain) {
14209 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
14210 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
14211 else
14212 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
14213 }
14214 }
14215
14216 if (pHadMultipleCandidates)
14217 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
14218 return Fn;
14219}
14220
14224 OverloadExpr *Ovl = R.Expression;
14225 bool IsResultAmbiguous = false;
14226 FunctionDecl *Result = nullptr;
14227 DeclAccessPair DAP;
14228 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
14229
14230 // Return positive for better, negative for worse, 0 for equal preference.
14231 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
14232 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
14233 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
14234 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
14235 };
14236
14237 // Don't use the AddressOfResolver because we're specifically looking for
14238 // cases where we have one overload candidate that lacks
14239 // enable_if/pass_object_size/...
14240 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
14241 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
14242 if (!FD)
14243 return nullptr;
14244
14246 continue;
14247
14248 // If we found a better result, update Result.
14249 auto FoundBetter = [&]() {
14250 IsResultAmbiguous = false;
14251 DAP = I.getPair();
14252 Result = FD;
14253 };
14254
14255 // We have more than one result - see if it is more
14256 // partial-ordering-constrained than the previous one.
14257 if (Result) {
14258 // Check CUDA preference first. If the candidates have differennt CUDA
14259 // preference, choose the one with higher CUDA preference. Otherwise,
14260 // choose the one with more constraints.
14261 if (getLangOpts().CUDA) {
14262 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
14263 // FD has different preference than Result.
14264 if (PreferenceByCUDA != 0) {
14265 // FD is more preferable than Result.
14266 if (PreferenceByCUDA > 0)
14267 FoundBetter();
14268 continue;
14269 }
14270 }
14271 // FD has the same CUDA preference than Result. Continue to check
14272 // constraints.
14273
14274 // C++ [over.over]p5:
14275 // [...] Any given non-template function F0 is eliminated if the set
14276 // contains a second non-template function that is more
14277 // partial-ordering-constrained than F0 [...]
14278 FunctionDecl *MoreConstrained =
14280 /*IsFn1Reversed=*/false,
14281 /*IsFn2Reversed=*/false);
14282 if (MoreConstrained != FD) {
14283 if (!MoreConstrained) {
14284 IsResultAmbiguous = true;
14285 AmbiguousDecls.push_back(FD);
14286 }
14287 continue;
14288 }
14289 // FD is more constrained - replace Result with it.
14290 }
14291 FoundBetter();
14292 }
14293
14294 if (IsResultAmbiguous)
14295 return nullptr;
14296
14297 if (Result) {
14298 // We skipped over some ambiguous declarations which might be ambiguous with
14299 // the selected result.
14300 for (FunctionDecl *Skipped : AmbiguousDecls) {
14301 // If skipped candidate has different CUDA preference than the result,
14302 // there is no ambiguity. Otherwise check whether they have different
14303 // constraints.
14304 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
14305 continue;
14306 if (!getMoreConstrainedFunction(Skipped, Result))
14307 return nullptr;
14308 }
14309 Pair = DAP;
14310 }
14311 return Result;
14312}
14313
14315 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14316 Expr *E = SrcExpr.get();
14317 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14318
14319 DeclAccessPair DAP;
14321 if (!Found || Found->isCPUDispatchMultiVersion() ||
14322 Found->isCPUSpecificMultiVersion())
14323 return false;
14324
14325 // Emitting multiple diagnostics for a function that is both inaccessible and
14326 // unavailable is consistent with our behavior elsewhere. So, always check
14327 // for both.
14331 if (Res.isInvalid())
14332 return false;
14333 Expr *Fixed = Res.get();
14334 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14335 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
14336 else
14337 SrcExpr = Fixed;
14338 return true;
14339}
14340
14342 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14343 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14344 // C++ [over.over]p1:
14345 // [...] [Note: any redundant set of parentheses surrounding the
14346 // overloaded function name is ignored (5.1). ]
14347 // C++ [over.over]p1:
14348 // [...] The overloaded function name can be preceded by the &
14349 // operator.
14350
14351 // If we didn't actually find any template-ids, we're done.
14352 if (!ovl->hasExplicitTemplateArgs())
14353 return nullptr;
14354
14355 TemplateArgumentListInfo ExplicitTemplateArgs;
14356 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
14357
14358 // Look through all of the overloaded functions, searching for one
14359 // whose type matches exactly.
14360 FunctionDecl *Matched = nullptr;
14361 for (UnresolvedSetIterator I = ovl->decls_begin(),
14362 E = ovl->decls_end(); I != E; ++I) {
14363 // C++0x [temp.arg.explicit]p3:
14364 // [...] In contexts where deduction is done and fails, or in contexts
14365 // where deduction is not done, if a template argument list is
14366 // specified and it, along with any default template arguments,
14367 // identifies a single function template specialization, then the
14368 // template-id is an lvalue for the function template specialization.
14370 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
14371 if (!FunctionTemplate)
14372 continue;
14373
14374 // C++ [over.over]p2:
14375 // If the name is a function template, template argument deduction is
14376 // done (14.8.2.2), and if the argument deduction succeeds, the
14377 // resulting template argument list is used to generate a single
14378 // function template specialization, which is added to the set of
14379 // overloaded functions considered.
14380 FunctionDecl *Specialization = nullptr;
14381 TemplateDeductionInfo Info(ovl->getNameLoc());
14383 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
14384 /*IsAddressOfFunction*/ true);
14386 // Make a note of the failed deduction for diagnostics.
14387 if (FailedTSC)
14388 FailedTSC->addCandidate().set(
14389 I.getPair(), FunctionTemplate->getTemplatedDecl(),
14391 continue;
14392 }
14393
14394 assert(Specialization && "no specialization and no error?");
14395
14396 // C++ [temp.deduct.call]p6:
14397 // [...] If all successful deductions yield the same deduced A, that
14398 // deduced A is the result of deduction; otherwise, the parameter is
14399 // treated as a non-deduced context.
14400 if (Matched) {
14401 if (ForTypeDeduction &&
14403 Specialization->getType()))
14404 continue;
14405 // Multiple matches; we can't resolve to a single declaration.
14406 if (Complain) {
14407 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
14408 << ovl->getName();
14410 }
14411 return nullptr;
14412 }
14413
14414 Matched = Specialization;
14415 if (FoundResult) *FoundResult = I.getPair();
14416 }
14417
14418 if (Matched &&
14419 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
14420 return nullptr;
14421
14422 return Matched;
14423}
14424
14426 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14427 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14428 unsigned DiagIDForComplaining) {
14429 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14430
14432
14433 DeclAccessPair found;
14434 ExprResult SingleFunctionExpression;
14436 ovl.Expression, /*complain*/ false, &found)) {
14437 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
14438 SrcExpr = ExprError();
14439 return true;
14440 }
14441
14442 // It is only correct to resolve to an instance method if we're
14443 // resolving a form that's permitted to be a pointer to member.
14444 // Otherwise we'll end up making a bound member expression, which
14445 // is illegal in all the contexts we resolve like this.
14446 if (!ovl.HasFormOfMemberPointer &&
14447 isa<CXXMethodDecl>(fn) &&
14448 cast<CXXMethodDecl>(fn)->isInstance()) {
14449 if (!complain) return false;
14450
14451 Diag(ovl.Expression->getExprLoc(),
14452 diag::err_bound_member_function)
14453 << 0 << ovl.Expression->getSourceRange();
14454
14455 // TODO: I believe we only end up here if there's a mix of
14456 // static and non-static candidates (otherwise the expression
14457 // would have 'bound member' type, not 'overload' type).
14458 // Ideally we would note which candidate was chosen and why
14459 // the static candidates were rejected.
14460 SrcExpr = ExprError();
14461 return true;
14462 }
14463
14464 // Fix the expression to refer to 'fn'.
14465 SingleFunctionExpression =
14466 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
14467
14468 // If desired, do function-to-pointer decay.
14469 if (doFunctionPointerConversion) {
14470 SingleFunctionExpression =
14471 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
14472 if (SingleFunctionExpression.isInvalid()) {
14473 SrcExpr = ExprError();
14474 return true;
14475 }
14476 }
14477 }
14478
14479 if (!SingleFunctionExpression.isUsable()) {
14480 if (complain) {
14481 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
14482 << ovl.Expression->getName()
14483 << DestTypeForComplaining
14484 << OpRangeForComplaining
14486 NoteAllOverloadCandidates(SrcExpr.get());
14487
14488 SrcExpr = ExprError();
14489 return true;
14490 }
14491
14492 return false;
14493 }
14494
14495 SrcExpr = SingleFunctionExpression;
14496 return true;
14497}
14498
14499/// Add a single candidate to the overload set.
14501 DeclAccessPair FoundDecl,
14502 TemplateArgumentListInfo *ExplicitTemplateArgs,
14503 ArrayRef<Expr *> Args,
14504 OverloadCandidateSet &CandidateSet,
14505 bool PartialOverloading,
14506 bool KnownValid) {
14507 NamedDecl *Callee = FoundDecl.getDecl();
14508 if (isa<UsingShadowDecl>(Callee))
14509 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
14510
14511 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
14512 if (ExplicitTemplateArgs) {
14513 assert(!KnownValid && "Explicit template arguments?");
14514 return;
14515 }
14516 // Prevent ill-formed function decls to be added as overload candidates.
14517 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
14518 return;
14519
14520 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
14521 /*SuppressUserConversions=*/false,
14522 PartialOverloading);
14523 return;
14524 }
14525
14526 if (FunctionTemplateDecl *FuncTemplate
14527 = dyn_cast<FunctionTemplateDecl>(Callee)) {
14528 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
14529 ExplicitTemplateArgs, Args, CandidateSet,
14530 /*SuppressUserConversions=*/false,
14531 PartialOverloading);
14532 return;
14533 }
14534
14535 assert(!KnownValid && "unhandled case in overloaded call candidate");
14536}
14537
14539 ArrayRef<Expr *> Args,
14540 OverloadCandidateSet &CandidateSet,
14541 bool PartialOverloading) {
14542
14543#ifndef NDEBUG
14544 // Verify that ArgumentDependentLookup is consistent with the rules
14545 // in C++0x [basic.lookup.argdep]p3:
14546 //
14547 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14548 // and let Y be the lookup set produced by argument dependent
14549 // lookup (defined as follows). If X contains
14550 //
14551 // -- a declaration of a class member, or
14552 //
14553 // -- a block-scope function declaration that is not a
14554 // using-declaration, or
14555 //
14556 // -- a declaration that is neither a function or a function
14557 // template
14558 //
14559 // then Y is empty.
14560
14561 if (ULE->requiresADL()) {
14563 E = ULE->decls_end(); I != E; ++I) {
14564 assert(!(*I)->getDeclContext()->isRecord());
14565 assert(isa<UsingShadowDecl>(*I) ||
14566 !(*I)->getDeclContext()->isFunctionOrMethod());
14567 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14568 }
14569 }
14570#endif
14571
14572 // It would be nice to avoid this copy.
14573 TemplateArgumentListInfo TABuffer;
14574 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14575 if (ULE->hasExplicitTemplateArgs()) {
14576 ULE->copyTemplateArgumentsInto(TABuffer);
14577 ExplicitTemplateArgs = &TABuffer;
14578 }
14579
14581 E = ULE->decls_end(); I != E; ++I)
14582 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14583 CandidateSet, PartialOverloading,
14584 /*KnownValid*/ true);
14585
14586 if (ULE->requiresADL())
14588 Args, ExplicitTemplateArgs,
14589 CandidateSet, PartialOverloading);
14590}
14591
14593 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14594 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14595 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14596 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14597 CandidateSet, false, /*KnownValid*/ false);
14598}
14599
14600/// Determine whether a declaration with the specified name could be moved into
14601/// a different namespace.
14603 switch (Name.getCXXOverloadedOperator()) {
14604 case OO_New: case OO_Array_New:
14605 case OO_Delete: case OO_Array_Delete:
14606 return false;
14607
14608 default:
14609 return true;
14610 }
14611}
14612
14613/// Attempt to recover from an ill-formed use of a non-dependent name in a
14614/// template, where the non-dependent name was declared after the template
14615/// was defined. This is common in code written for a compilers which do not
14616/// correctly implement two-stage name lookup.
14617///
14618/// Returns true if a viable candidate was found and a diagnostic was issued.
14620 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14622 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14623 CXXRecordDecl **FoundInClass = nullptr) {
14624 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14625 return false;
14626
14627 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14628 if (DC->isTransparentContext())
14629 continue;
14630
14631 SemaRef.LookupQualifiedName(R, DC);
14632
14633 if (!R.empty()) {
14634 R.suppressDiagnostics();
14635
14636 OverloadCandidateSet Candidates(FnLoc, CSK);
14637 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14638 Candidates);
14639
14642 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
14643
14644 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
14645 // We either found non-function declarations or a best viable function
14646 // at class scope. A class-scope lookup result disables ADL. Don't
14647 // look past this, but let the caller know that we found something that
14648 // either is, or might be, usable in this class.
14649 if (FoundInClass) {
14650 *FoundInClass = RD;
14651 if (OR == OR_Success) {
14652 R.clear();
14653 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
14654 R.resolveKind();
14655 }
14656 }
14657 return false;
14658 }
14659
14660 if (OR != OR_Success) {
14661 // There wasn't a unique best function or function template.
14662 return false;
14663 }
14664
14665 // Find the namespaces where ADL would have looked, and suggest
14666 // declaring the function there instead.
14667 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14668 Sema::AssociatedClassSet AssociatedClasses;
14669 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
14670 AssociatedNamespaces,
14671 AssociatedClasses);
14672 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14673 if (canBeDeclaredInNamespace(R.getLookupName())) {
14674 DeclContext *Std = SemaRef.getStdNamespace();
14675 for (Sema::AssociatedNamespaceSet::iterator
14676 it = AssociatedNamespaces.begin(),
14677 end = AssociatedNamespaces.end(); it != end; ++it) {
14678 // Never suggest declaring a function within namespace 'std'.
14679 if (Std && Std->Encloses(*it))
14680 continue;
14681
14682 // Never suggest declaring a function within a namespace with a
14683 // reserved name, like __gnu_cxx.
14684 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
14685 if (NS &&
14686 NS->getQualifiedNameAsString().find("__") != std::string::npos)
14687 continue;
14688
14689 SuggestedNamespaces.insert(*it);
14690 }
14691 }
14692
14693 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
14694 << R.getLookupName();
14695 if (SuggestedNamespaces.empty()) {
14696 SemaRef.Diag(Best->Function->getLocation(),
14697 diag::note_not_found_by_two_phase_lookup)
14698 << R.getLookupName() << 0;
14699 } else if (SuggestedNamespaces.size() == 1) {
14700 SemaRef.Diag(Best->Function->getLocation(),
14701 diag::note_not_found_by_two_phase_lookup)
14702 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14703 } else {
14704 // FIXME: It would be useful to list the associated namespaces here,
14705 // but the diagnostics infrastructure doesn't provide a way to produce
14706 // a localized representation of a list of items.
14707 SemaRef.Diag(Best->Function->getLocation(),
14708 diag::note_not_found_by_two_phase_lookup)
14709 << R.getLookupName() << 2;
14710 }
14711
14712 // Try to recover by calling this function.
14713 return true;
14714 }
14715
14716 R.clear();
14717 }
14718
14719 return false;
14720}
14721
14722/// Attempt to recover from ill-formed use of a non-dependent operator in a
14723/// template, where the non-dependent operator was declared after the template
14724/// was defined.
14725///
14726/// Returns true if a viable candidate was found and a diagnostic was issued.
14727static bool
14729 SourceLocation OpLoc,
14730 ArrayRef<Expr *> Args) {
14731 DeclarationName OpName =
14733 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14734 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
14736 /*ExplicitTemplateArgs=*/nullptr, Args);
14737}
14738
14739namespace {
14740class BuildRecoveryCallExprRAII {
14741 Sema &SemaRef;
14742 Sema::SatisfactionStackResetRAII SatStack;
14743
14744public:
14745 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14746 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14747 SemaRef.IsBuildingRecoveryCallExpr = true;
14748 }
14749
14750 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14751};
14752}
14753
14754/// Attempts to recover from a call where no functions were found.
14755///
14756/// This function will do one of three things:
14757/// * Diagnose, recover, and return a recovery expression.
14758/// * Diagnose, fail to recover, and return ExprError().
14759/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14760/// expected to diagnose as appropriate.
14761static ExprResult
14764 SourceLocation LParenLoc,
14766 SourceLocation RParenLoc,
14767 bool EmptyLookup, bool AllowTypoCorrection) {
14768 // Do not try to recover if it is already building a recovery call.
14769 // This stops infinite loops for template instantiations like
14770 //
14771 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14772 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14773 if (SemaRef.IsBuildingRecoveryCallExpr)
14774 return ExprResult();
14775 BuildRecoveryCallExprRAII RCE(SemaRef);
14776
14777 CXXScopeSpec SS;
14778 SS.Adopt(ULE->getQualifierLoc());
14779 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14780
14781 TemplateArgumentListInfo TABuffer;
14782 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14783 if (ULE->hasExplicitTemplateArgs()) {
14784 ULE->copyTemplateArgumentsInto(TABuffer);
14785 ExplicitTemplateArgs = &TABuffer;
14786 }
14787
14788 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14790 CXXRecordDecl *FoundInClass = nullptr;
14791 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
14793 ExplicitTemplateArgs, Args, &FoundInClass)) {
14794 // OK, diagnosed a two-phase lookup issue.
14795 } else if (EmptyLookup) {
14796 // Try to recover from an empty lookup with typo correction.
14797 R.clear();
14798 NoTypoCorrectionCCC NoTypoValidator{};
14799 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14800 ExplicitTemplateArgs != nullptr,
14801 dyn_cast<MemberExpr>(Fn));
14802 CorrectionCandidateCallback &Validator =
14803 AllowTypoCorrection
14804 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14805 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14806 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
14807 Args))
14808 return ExprError();
14809 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14810 // We found a usable declaration of the name in a dependent base of some
14811 // enclosing class.
14812 // FIXME: We should also explain why the candidates found by name lookup
14813 // were not viable.
14814 if (SemaRef.DiagnoseDependentMemberLookup(R))
14815 return ExprError();
14816 } else {
14817 // We had viable candidates and couldn't recover; let the caller diagnose
14818 // this.
14819 return ExprResult();
14820 }
14821
14822 // If we get here, we should have issued a diagnostic and formed a recovery
14823 // lookup result.
14824 assert(!R.empty() && "lookup results empty despite recovery");
14825
14826 // If recovery created an ambiguity, just bail out.
14827 if (R.isAmbiguous()) {
14828 R.suppressDiagnostics();
14829 return ExprError();
14830 }
14831
14832 // Build an implicit member call if appropriate. Just drop the
14833 // casts and such from the call, we don't really care.
14834 ExprResult NewFn = ExprError();
14835 if ((*R.begin())->isCXXClassMember())
14836 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14837 ExplicitTemplateArgs, S);
14838 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14839 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
14840 ExplicitTemplateArgs);
14841 else
14842 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
14843
14844 if (NewFn.isInvalid())
14845 return ExprError();
14846
14847 // This shouldn't cause an infinite loop because we're giving it
14848 // an expression with viable lookup results, which should never
14849 // end up here.
14850 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
14851 MultiExprArg(Args.data(), Args.size()),
14852 RParenLoc);
14853}
14854
14857 MultiExprArg Args,
14858 SourceLocation RParenLoc,
14859 OverloadCandidateSet *CandidateSet,
14860 ExprResult *Result) {
14861#ifndef NDEBUG
14862 if (ULE->requiresADL()) {
14863 // To do ADL, we must have found an unqualified name.
14864 assert(!ULE->getQualifier() && "qualified name with ADL");
14865
14866 // We don't perform ADL for implicit declarations of builtins.
14867 // Verify that this was correctly set up.
14868 FunctionDecl *F;
14869 if (ULE->decls_begin() != ULE->decls_end() &&
14870 ULE->decls_begin() + 1 == ULE->decls_end() &&
14871 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14872 F->getBuiltinID() && F->isImplicit())
14873 llvm_unreachable("performing ADL for builtin");
14874
14875 // We don't perform ADL in C.
14876 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14877 }
14878#endif
14879
14880 UnbridgedCastsSet UnbridgedCasts;
14881 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14882 *Result = ExprError();
14883 return true;
14884 }
14885
14886 // Add the functions denoted by the callee to the set of candidate
14887 // functions, including those from argument-dependent lookup.
14888 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
14889
14890 if (getLangOpts().MSVCCompat &&
14891 CurContext->isDependentContext() && !isSFINAEContext() &&
14893
14895 if (CandidateSet->empty() ||
14896 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
14898 // In Microsoft mode, if we are inside a template class member function
14899 // then create a type dependent CallExpr. The goal is to postpone name
14900 // lookup to instantiation time to be able to search into type dependent
14901 // base classes.
14902 CallExpr *CE =
14903 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
14904 RParenLoc, CurFPFeatureOverrides());
14906 *Result = CE;
14907 return true;
14908 }
14909 }
14910
14911 if (CandidateSet->empty())
14912 return false;
14913
14914 UnbridgedCasts.restore();
14915 return false;
14916}
14917
14918// Guess at what the return type for an unresolvable overload should be.
14921 std::optional<QualType> Result;
14922 // Adjust Type after seeing a candidate.
14923 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14924 if (!Candidate.Function)
14925 return;
14926 if (Candidate.Function->isInvalidDecl())
14927 return;
14928 QualType T = Candidate.Function->getReturnType();
14929 if (T.isNull())
14930 return;
14931 if (!Result)
14932 Result = T;
14933 else if (Result != T)
14934 Result = QualType();
14935 };
14936
14937 // Look for an unambiguous type from a progressively larger subset.
14938 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14939 //
14940 // First, consider only the best candidate.
14941 if (Best && *Best != CS.end())
14942 ConsiderCandidate(**Best);
14943 // Next, consider only viable candidates.
14944 if (!Result)
14945 for (const auto &C : CS)
14946 if (C.Viable)
14947 ConsiderCandidate(C);
14948 // Finally, consider all candidates.
14949 if (!Result)
14950 for (const auto &C : CS)
14951 ConsiderCandidate(C);
14952
14953 if (!Result)
14954 return QualType();
14955 auto Value = *Result;
14956 if (Value.isNull() || Value->isUndeducedType())
14957 return QualType();
14958 return Value;
14959}
14960
14961/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14962/// the completed call expression. If overload resolution fails, emits
14963/// diagnostics and returns ExprError()
14966 SourceLocation LParenLoc,
14967 MultiExprArg Args,
14968 SourceLocation RParenLoc,
14969 Expr *ExecConfig,
14970 OverloadCandidateSet *CandidateSet,
14972 OverloadingResult OverloadResult,
14973 bool AllowTypoCorrection) {
14974 switch (OverloadResult) {
14975 case OR_Success: {
14976 FunctionDecl *FDecl = (*Best)->Function;
14977 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14978 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14979 return ExprError();
14980 ExprResult Res =
14981 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14982 if (Res.isInvalid())
14983 return ExprError();
14984 return SemaRef.BuildResolvedCallExpr(
14985 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14986 /*IsExecConfig=*/false,
14987 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14988 }
14989
14990 case OR_No_Viable_Function: {
14991 if (*Best != CandidateSet->end() &&
14992 CandidateSet->getKind() ==
14994 if (CXXMethodDecl *M =
14995 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
14997 CandidateSet->NoteCandidates(
14999 Fn->getBeginLoc(),
15000 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
15001 SemaRef, OCD_AmbiguousCandidates, Args);
15002 return ExprError();
15003 }
15004 }
15005
15006 // Try to recover by looking for viable functions which the user might
15007 // have meant to call.
15008 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
15009 Args, RParenLoc,
15010 CandidateSet->empty(),
15011 AllowTypoCorrection);
15012 if (Recovery.isInvalid() || Recovery.isUsable())
15013 return Recovery;
15014
15015 // If the user passes in a function that we can't take the address of, we
15016 // generally end up emitting really bad error messages. Here, we attempt to
15017 // emit better ones.
15018 for (const Expr *Arg : Args) {
15019 if (!Arg->getType()->isFunctionType())
15020 continue;
15021 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
15022 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15023 if (FD &&
15024 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
15025 Arg->getExprLoc()))
15026 return ExprError();
15027 }
15028 }
15029
15030 CandidateSet->NoteCandidates(
15032 Fn->getBeginLoc(),
15033 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
15034 << ULE->getName() << Fn->getSourceRange()),
15035 SemaRef, OCD_AllCandidates, Args);
15036 break;
15037 }
15038
15039 case OR_Ambiguous:
15040 CandidateSet->NoteCandidates(
15041 PartialDiagnosticAt(Fn->getBeginLoc(),
15042 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
15043 << ULE->getName() << Fn->getSourceRange()),
15044 SemaRef, OCD_AmbiguousCandidates, Args);
15045 break;
15046
15047 case OR_Deleted: {
15048 FunctionDecl *FDecl = (*Best)->Function;
15049 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
15050 Fn->getSourceRange(), ULE->getName(),
15051 *CandidateSet, FDecl, Args);
15052
15053 // We emitted an error for the unavailable/deleted function call but keep
15054 // the call in the AST.
15055 ExprResult Res =
15056 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
15057 if (Res.isInvalid())
15058 return ExprError();
15059 return SemaRef.BuildResolvedCallExpr(
15060 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
15061 /*IsExecConfig=*/false,
15062 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
15063 }
15064 }
15065
15066 // Overload resolution failed, try to recover.
15067 SmallVector<Expr *, 8> SubExprs = {Fn};
15068 SubExprs.append(Args.begin(), Args.end());
15069 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
15070 chooseRecoveryType(*CandidateSet, Best));
15071}
15072
15075 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
15076 if (I->Viable &&
15077 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
15078 I->Viable = false;
15079 I->FailureKind = ovl_fail_addr_not_available;
15080 }
15081 }
15082}
15083
15086 SourceLocation LParenLoc,
15087 MultiExprArg Args,
15088 SourceLocation RParenLoc,
15089 Expr *ExecConfig,
15090 bool AllowTypoCorrection,
15091 bool CalleesAddressIsTaken) {
15092
15096
15097 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
15098 ExprResult result;
15099
15100 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
15101 &result))
15102 return result;
15103
15104 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
15105 // functions that aren't addressible are considered unviable.
15106 if (CalleesAddressIsTaken)
15107 markUnaddressableCandidatesUnviable(*this, CandidateSet);
15108
15110 OverloadingResult OverloadResult =
15111 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
15112
15113 // [C++23][over.call.func]
15114 // if overload resolution selects a non-static member function,
15115 // the call is ill-formed;
15117 Best != CandidateSet.end()) {
15118 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
15119 M && M->isImplicitObjectMemberFunction()) {
15120 OverloadResult = OR_No_Viable_Function;
15121 }
15122 }
15123
15124 // Model the case with a call to a templated function whose definition
15125 // encloses the call and whose return type contains a placeholder type as if
15126 // the UnresolvedLookupExpr was type-dependent.
15127 if (OverloadResult == OR_Success) {
15128 const FunctionDecl *FDecl = Best->Function;
15129 if (LangOpts.CUDA)
15130 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
15131 if (FDecl && FDecl->isTemplateInstantiation() &&
15132 FDecl->getReturnType()->isUndeducedType()) {
15133
15134 // Creating dependent CallExpr is not okay if the enclosing context itself
15135 // is not dependent. This situation notably arises if a non-dependent
15136 // member function calls the later-defined overloaded static function.
15137 //
15138 // For example, in
15139 // class A {
15140 // void c() { callee(1); }
15141 // static auto callee(auto x) { }
15142 // };
15143 //
15144 // Here callee(1) is unresolved at the call site, but is not inside a
15145 // dependent context. There will be no further attempt to resolve this
15146 // call if it is made dependent.
15147
15148 if (const auto *TP =
15149 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
15150 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
15151 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
15152 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
15153 }
15154 }
15155 }
15156
15157 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15158 ExecConfig, &CandidateSet, &Best,
15159 OverloadResult, AllowTypoCorrection);
15160}
15161
15165 const UnresolvedSetImpl &Fns,
15166 bool PerformADL) {
15168 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
15169 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
15170}
15171
15174 bool HadMultipleCandidates) {
15175 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
15176 // the FoundDecl as it impedes TransformMemberExpr.
15177 // We go a bit further here: if there's no difference in UnderlyingDecl,
15178 // then using FoundDecl vs Method shouldn't make a difference either.
15179 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
15180 FoundDecl = Method;
15181 // Convert the expression to match the conversion function's implicit object
15182 // parameter.
15183 ExprResult Exp;
15184 if (Method->isExplicitObjectMemberFunction())
15186 else
15188 E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
15189 if (Exp.isInvalid())
15190 return true;
15191
15192 if (Method->getParent()->isLambda() &&
15193 Method->getConversionType()->isBlockPointerType()) {
15194 // This is a lambda conversion to block pointer; check if the argument
15195 // was a LambdaExpr.
15196 Expr *SubE = E;
15197 auto *CE = dyn_cast<CastExpr>(SubE);
15198 if (CE && CE->getCastKind() == CK_NoOp)
15199 SubE = CE->getSubExpr();
15200 SubE = SubE->IgnoreParens();
15201 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
15202 SubE = BE->getSubExpr();
15203 if (isa<LambdaExpr>(SubE)) {
15204 // For the conversion to block pointer on a lambda expression, we
15205 // construct a special BlockLiteral instead; this doesn't really make
15206 // a difference in ARC, but outside of ARC the resulting block literal
15207 // follows the normal lifetime rules for block literals instead of being
15208 // autoreleased.
15212 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
15214
15215 // FIXME: This note should be produced by a CodeSynthesisContext.
15216 if (BlockExp.isInvalid())
15217 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
15218 return BlockExp;
15219 }
15220 }
15221 CallExpr *CE;
15222 QualType ResultType = Method->getReturnType();
15224 ResultType = ResultType.getNonLValueExprType(Context);
15225 if (Method->isExplicitObjectMemberFunction()) {
15226 ExprResult FnExpr =
15227 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
15228 HadMultipleCandidates, E->getBeginLoc());
15229 if (FnExpr.isInvalid())
15230 return ExprError();
15231 Expr *ObjectParam = Exp.get();
15232 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
15233 ResultType, VK, Exp.get()->getEndLoc(),
15235 CE->setUsesMemberSyntax(true);
15236 } else {
15237 MemberExpr *ME =
15238 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
15240 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
15241 HadMultipleCandidates, DeclarationNameInfo(),
15242 Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
15243
15244 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
15245 Exp.get()->getEndLoc(),
15247 }
15248
15249 if (CheckFunctionCall(Method, CE,
15250 Method->getType()->castAs<FunctionProtoType>()))
15251 return ExprError();
15252
15254}
15255
15258 const UnresolvedSetImpl &Fns,
15259 ArrayRef<Expr *> Args, bool PerformADL) {
15260 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15261
15262 SourceLocation OpLoc = CandidateSet.getLocation();
15263 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15264
15265 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15266 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15267 if (PerformADL)
15268 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15269 /*ExplicitTemplateArgs*/ nullptr,
15270 CandidateSet);
15271 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15272}
15273
15276 const UnresolvedSetImpl &Fns,
15277 Expr *Input, bool PerformADL) {
15279 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15280 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15281 // TODO: provide better source location info.
15282 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15283
15284 if (checkPlaceholderForOverload(*this, Input))
15285 return ExprError();
15286
15287 Expr *Args[2] = { Input, nullptr };
15288 unsigned NumArgs = 1;
15289
15290 // For post-increment and post-decrement, add the implicit '0' as
15291 // the second argument, so that we know this is a post-increment or
15292 // post-decrement.
15293 if (Opc == UO_PostInc || Opc == UO_PostDec) {
15294 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15295 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
15296 SourceLocation());
15297 NumArgs = 2;
15298 }
15299
15300 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
15301
15302 if (Input->isTypeDependent()) {
15304 // [C++26][expr.unary.op][expr.pre.incr]
15305 // The * operator yields an lvalue of type
15306 // The pre/post increment operators yied an lvalue.
15307 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
15308 VK = VK_LValue;
15309
15310 if (Fns.empty())
15311 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
15312 OK_Ordinary, OpLoc, false,
15314
15315 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15317 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
15318 if (Fn.isInvalid())
15319 return ExprError();
15320 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
15321 Context.DependentTy, VK_PRValue, OpLoc,
15323 }
15324
15325 // Build an empty overload set.
15327 LookupOverloadedUnaryOp(CandidateSet, Op, Fns, ArgsArray, PerformADL);
15328
15329 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15330
15331 // Perform overload resolution.
15333 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15334 case OR_Success: {
15335 // We found a built-in operator or an overloaded operator.
15336 FunctionDecl *FnDecl = Best->Function;
15337
15338 if (FnDecl) {
15339 Expr *Base = nullptr;
15340 // We matched an overloaded operator. Build a call to that
15341 // operator.
15342
15343 // Convert the arguments.
15344 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15345 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
15346
15347 ExprResult InputInit;
15348 if (Method->isExplicitObjectMemberFunction())
15349 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
15350 else
15352 Input, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15353 if (InputInit.isInvalid())
15354 return ExprError();
15355 Base = Input = InputInit.get();
15356 } else {
15357 // Convert the arguments.
15358 ExprResult InputInit
15360 Context,
15361 FnDecl->getParamDecl(0)),
15363 Input);
15364 if (InputInit.isInvalid())
15365 return ExprError();
15366 Input = InputInit.get();
15367 }
15368
15369 // Build the actual expression node.
15370 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
15371 Base, HadMultipleCandidates,
15372 OpLoc);
15373 if (FnExpr.isInvalid())
15374 return ExprError();
15375
15376 // Determine the result type.
15377 QualType ResultTy = FnDecl->getReturnType();
15379 ResultTy = ResultTy.getNonLValueExprType(Context);
15380
15381 Args[0] = Input;
15383 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
15385 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15386
15387 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
15388 return ExprError();
15389
15390 if (CheckFunctionCall(FnDecl, TheCall,
15391 FnDecl->getType()->castAs<FunctionProtoType>()))
15392 return ExprError();
15393 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
15394 } else {
15395 // We matched a built-in operator. Convert the arguments, then
15396 // break out so that we will build the appropriate built-in
15397 // operator node.
15399 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
15402 if (InputRes.isInvalid())
15403 return ExprError();
15404 Input = InputRes.get();
15405 break;
15406 }
15407 }
15408
15410 // This is an erroneous use of an operator which can be overloaded by
15411 // a non-member function. Check for non-member operators which were
15412 // defined too late to be candidates.
15413 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
15414 // FIXME: Recover by calling the found function.
15415 return ExprError();
15416
15417 // No viable function; fall through to handling this as a
15418 // built-in operator, which will produce an error message for us.
15419 break;
15420
15421 case OR_Ambiguous:
15422 CandidateSet.NoteCandidates(
15423 PartialDiagnosticAt(OpLoc,
15424 PDiag(diag::err_ovl_ambiguous_oper_unary)
15426 << Input->getType() << Input->getSourceRange()),
15427 *this, OCD_AmbiguousCandidates, ArgsArray,
15428 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15429 return ExprError();
15430
15431 case OR_Deleted: {
15432 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15433 // object whose method was called. Later in NoteCandidates size of ArgsArray
15434 // is passed further and it eventually ends up compared to number of
15435 // function candidate parameters which never includes the object parameter,
15436 // so slice ArgsArray to make sure apples are compared to apples.
15437 StringLiteral *Msg = Best->Function->getDeletedMessage();
15438 CandidateSet.NoteCandidates(
15439 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15441 << (Msg != nullptr)
15442 << (Msg ? Msg->getString() : StringRef())
15443 << Input->getSourceRange()),
15444 *this, OCD_AllCandidates, ArgsArray.drop_front(),
15445 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15446 return ExprError();
15447 }
15448 }
15449
15450 // Either we found no viable overloaded operator or we matched a
15451 // built-in operator. In either case, fall through to trying to
15452 // build a built-in operation.
15453 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15454}
15455
15458 const UnresolvedSetImpl &Fns,
15459 ArrayRef<Expr *> Args, bool PerformADL) {
15460 SourceLocation OpLoc = CandidateSet.getLocation();
15461
15462 OverloadedOperatorKind ExtraOp =
15465 : OO_None;
15466
15467 // Add the candidates from the given function set. This also adds the
15468 // rewritten candidates using these functions if necessary.
15469 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15470
15471 // As template candidates are not deduced immediately,
15472 // persist the array in the overload set.
15473 ArrayRef<Expr *> ReversedArgs;
15474 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15475 CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15476 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
15477
15478 // Add operator candidates that are member functions.
15479 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15480 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15481 AddMemberOperatorCandidates(Op, OpLoc, ReversedArgs, CandidateSet,
15483
15484 // In C++20, also add any rewritten member candidates.
15485 if (ExtraOp) {
15486 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
15487 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15488 AddMemberOperatorCandidates(ExtraOp, OpLoc, ReversedArgs, CandidateSet,
15490 }
15491
15492 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15493 // performed for an assignment operator (nor for operator[] nor operator->,
15494 // which don't get here).
15495 if (Op != OO_Equal && PerformADL) {
15496 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15497 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15498 /*ExplicitTemplateArgs*/ nullptr,
15499 CandidateSet);
15500 if (ExtraOp) {
15501 DeclarationName ExtraOpName =
15502 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
15503 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
15504 /*ExplicitTemplateArgs*/ nullptr,
15505 CandidateSet);
15506 }
15507 }
15508
15509 // Add builtin operator candidates.
15510 //
15511 // FIXME: We don't add any rewritten candidates here. This is strictly
15512 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15513 // resulting in our selecting a rewritten builtin candidate. For example:
15514 //
15515 // enum class E { e };
15516 // bool operator!=(E, E) requires false;
15517 // bool k = E::e != E::e;
15518 //
15519 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15520 // it seems unreasonable to consider rewritten builtin candidates. A core
15521 // issue has been filed proposing to removed this requirement.
15522 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15523}
15524
15527 const UnresolvedSetImpl &Fns, Expr *LHS,
15528 Expr *RHS, bool PerformADL,
15529 bool AllowRewrittenCandidates,
15530 FunctionDecl *DefaultedFn) {
15531 Expr *Args[2] = { LHS, RHS };
15532 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15533
15534 if (!getLangOpts().CPlusPlus20)
15535 AllowRewrittenCandidates = false;
15536
15538
15539 // If either side is type-dependent, create an appropriate dependent
15540 // expression.
15541 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15542 if (Fns.empty()) {
15543 // If there are no functions to store, just build a dependent
15544 // BinaryOperator or CompoundAssignment.
15547 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
15548 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
15549 Context.DependentTy);
15551 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
15553 }
15554
15555 // FIXME: save results of ADL from here?
15556 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15557 // TODO: provide better source location info in DNLoc component.
15558 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15559 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15561 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
15562 if (Fn.isInvalid())
15563 return ExprError();
15564 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
15565 Context.DependentTy, VK_PRValue, OpLoc,
15567 }
15568
15569 // If this is the .* operator, which is not overloadable, just
15570 // create a built-in binary operator.
15571 if (Opc == BO_PtrMemD) {
15572 auto CheckPlaceholder = [&](Expr *&Arg) {
15574 if (Res.isUsable())
15575 Arg = Res.get();
15576 return !Res.isUsable();
15577 };
15578
15579 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15580 // expression that contains placeholders (in either the LHS or RHS).
15581 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15582 return ExprError();
15583 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15584 }
15585
15586 // Always do placeholder-like conversions on the RHS.
15587 if (checkPlaceholderForOverload(*this, Args[1]))
15588 return ExprError();
15589
15590 // Do placeholder-like conversion on the LHS; note that we should
15591 // not get here with a PseudoObject LHS.
15592 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15593 if (checkPlaceholderForOverload(*this, Args[0]))
15594 return ExprError();
15595
15596 // If this is the assignment operator, we only perform overload resolution
15597 // if the left-hand side is a class or enumeration type. This is actually
15598 // a hack. The standard requires that we do overload resolution between the
15599 // various built-in candidates, but as DR507 points out, this can lead to
15600 // problems. So we do it this way, which pretty much follows what GCC does.
15601 // Note that we go the traditional code path for compound assignment forms.
15602 // In HLSL, user-defined structs/classes do not have constructors or
15603 // overloadable assignment operators, so we can take this shortcut too.
15604 const Type *LHSTy = Args[0]->getType().getTypePtr();
15605 if (Opc == BO_Assign &&
15606 (!LHSTy->isOverloadableType() ||
15607 (getLangOpts().HLSL && LHSTy->isRecordType() &&
15609 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15610
15611 // Build the overload set.
15614 Op, OpLoc, AllowRewrittenCandidates));
15615 if (DefaultedFn)
15616 CandidateSet.exclude(DefaultedFn);
15617 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15618
15619 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15620
15621 // Perform overload resolution.
15623 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15624 case OR_Success: {
15625 // We found a built-in operator or an overloaded operator.
15626 FunctionDecl *FnDecl = Best->Function;
15627
15628 bool IsReversed = Best->isReversed();
15629 if (IsReversed)
15630 std::swap(Args[0], Args[1]);
15631
15632 if (FnDecl) {
15633
15634 if (FnDecl->isInvalidDecl())
15635 return ExprError();
15636
15637 Expr *Base = nullptr;
15638 // We matched an overloaded operator. Build a call to that
15639 // operator.
15640
15641 OverloadedOperatorKind ChosenOp =
15643
15644 // C++2a [over.match.oper]p9:
15645 // If a rewritten operator== candidate is selected by overload
15646 // resolution for an operator@, its return type shall be cv bool
15647 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15648 !FnDecl->getReturnType()->isBooleanType()) {
15649 bool IsExtension =
15651 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15652 : diag::err_ovl_rewrite_equalequal_not_bool)
15653 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
15654 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15655 Diag(FnDecl->getLocation(), diag::note_declared_at);
15656 if (!IsExtension)
15657 return ExprError();
15658 }
15659
15660 if (AllowRewrittenCandidates && !IsReversed &&
15661 CandidateSet.getRewriteInfo().isReversible()) {
15662 // We could have reversed this operator, but didn't. Check if some
15663 // reversed form was a viable candidate, and if so, if it had a
15664 // better conversion for either parameter. If so, this call is
15665 // formally ambiguous, and allowing it is an extension.
15667 for (OverloadCandidate &Cand : CandidateSet) {
15668 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15669 allowAmbiguity(Context, Cand.Function, FnDecl)) {
15670 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15672 *this, OpLoc, Cand.Conversions[ArgIdx],
15673 Best->Conversions[ArgIdx]) ==
15675 AmbiguousWith.push_back(Cand.Function);
15676 break;
15677 }
15678 }
15679 }
15680 }
15681
15682 if (!AmbiguousWith.empty()) {
15683 bool AmbiguousWithSelf =
15684 AmbiguousWith.size() == 1 &&
15685 declaresSameEntity(AmbiguousWith.front(), FnDecl);
15686 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
15688 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15689 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15690 if (AmbiguousWithSelf) {
15691 Diag(FnDecl->getLocation(),
15692 diag::note_ovl_ambiguous_oper_binary_reversed_self);
15693 // Mark member== const or provide matching != to disallow reversed
15694 // args. Eg.
15695 // struct S { bool operator==(const S&); };
15696 // S()==S();
15697 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
15698 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15699 !MD->isConst() &&
15700 !MD->hasCXXExplicitFunctionObjectParameter() &&
15701 Context.hasSameUnqualifiedType(
15702 MD->getFunctionObjectParameterType(),
15703 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
15704 Context.hasSameUnqualifiedType(
15705 MD->getFunctionObjectParameterType(),
15706 Args[0]->getType()) &&
15707 Context.hasSameUnqualifiedType(
15708 MD->getFunctionObjectParameterType(),
15709 Args[1]->getType()))
15710 Diag(FnDecl->getLocation(),
15711 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15712 } else {
15713 Diag(FnDecl->getLocation(),
15714 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15715 for (auto *F : AmbiguousWith)
15716 Diag(F->getLocation(),
15717 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15718 }
15719 }
15720 }
15721
15722 // Check for nonnull = nullable.
15723 // This won't be caught in the arg's initialization: the parameter to
15724 // the assignment operator is not marked nonnull.
15725 if (Op == OO_Equal)
15727 Args[1]->getType(), OpLoc);
15728
15729 // Convert the arguments.
15730 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15731 // Best->Access is only meaningful for class members.
15732 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
15733
15734 ExprResult Arg0, Arg1;
15735 unsigned ParamIdx = 0;
15736 if (Method->isExplicitObjectMemberFunction()) {
15737 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
15738 ParamIdx = 1;
15739 } else {
15741 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15742 }
15745 Context, FnDecl->getParamDecl(ParamIdx)),
15746 SourceLocation(), Args[1]);
15747 if (Arg0.isInvalid() || Arg1.isInvalid())
15748 return ExprError();
15749
15750 Base = Args[0] = Arg0.getAs<Expr>();
15751 Args[1] = RHS = Arg1.getAs<Expr>();
15752 } else {
15753 // Convert the arguments.
15756 FnDecl->getParamDecl(0)),
15757 SourceLocation(), Args[0]);
15758 if (Arg0.isInvalid())
15759 return ExprError();
15760
15761 ExprResult Arg1 =
15764 FnDecl->getParamDecl(1)),
15765 SourceLocation(), Args[1]);
15766 if (Arg1.isInvalid())
15767 return ExprError();
15768 Args[0] = LHS = Arg0.getAs<Expr>();
15769 Args[1] = RHS = Arg1.getAs<Expr>();
15770 }
15771
15772 // Build the actual expression node.
15773 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
15774 Best->FoundDecl, Base,
15775 HadMultipleCandidates, OpLoc);
15776 if (FnExpr.isInvalid())
15777 return ExprError();
15778
15779 // Determine the result type.
15780 QualType ResultTy = FnDecl->getReturnType();
15782 ResultTy = ResultTy.getNonLValueExprType(Context);
15783
15784 CallExpr *TheCall;
15785 ArrayRef<const Expr *> ArgsArray(Args, 2);
15786 const Expr *ImplicitThis = nullptr;
15787
15788 // We always create a CXXOperatorCallExpr, even for explicit object
15789 // members; CodeGen should take care not to emit the this pointer.
15791 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
15793 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate),
15794 IsReversed);
15795
15796 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
15797 Method && Method->isImplicitObjectMemberFunction()) {
15798 // Cut off the implicit 'this'.
15799 ImplicitThis = ArgsArray[0];
15800 ArgsArray = ArgsArray.slice(1);
15801 }
15802
15803 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
15804 FnDecl))
15805 return ExprError();
15806
15807 if (Op == OO_Equal) {
15808 // Check for a self move.
15809 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
15810 // lifetime check.
15812 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
15813 Args[1]);
15814 }
15815 if (ImplicitThis) {
15816 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
15817 QualType ThisTypeFromDecl = Context.getPointerType(
15818 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
15819
15820 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
15821 ThisTypeFromDecl);
15822 }
15823
15824 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
15825 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
15827
15828 ExprResult R = MaybeBindToTemporary(TheCall);
15829 if (R.isInvalid())
15830 return ExprError();
15831
15832 R = CheckForImmediateInvocation(R, FnDecl);
15833 if (R.isInvalid())
15834 return ExprError();
15835
15836 // For a rewritten candidate, we've already reversed the arguments
15837 // if needed. Perform the rest of the rewrite now.
15838 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15839 (Op == OO_Spaceship && IsReversed)) {
15840 if (Op == OO_ExclaimEqual) {
15841 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15842 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
15843 } else {
15844 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15845 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15846 Expr *ZeroLiteral =
15848
15851 Ctx.Entity = FnDecl;
15853
15855 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
15856 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15857 /*AllowRewrittenCandidates=*/false);
15858
15860 }
15861 if (R.isInvalid())
15862 return ExprError();
15863 } else {
15864 assert(ChosenOp == Op && "unexpected operator name");
15865 }
15866
15867 // Make a note in the AST if we did any rewriting.
15868 if (Best->RewriteKind != CRK_None)
15869 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15870
15871 return R;
15872 } else {
15873 // We matched a built-in operator. Convert the arguments, then
15874 // break out so that we will build the appropriate built-in
15875 // operator node.
15877 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15880 if (ArgsRes0.isInvalid())
15881 return ExprError();
15882 Args[0] = ArgsRes0.get();
15883
15885 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15888 if (ArgsRes1.isInvalid())
15889 return ExprError();
15890 Args[1] = ArgsRes1.get();
15891 break;
15892 }
15893 }
15894
15895 case OR_No_Viable_Function: {
15896 // C++ [over.match.oper]p9:
15897 // If the operator is the operator , [...] and there are no
15898 // viable functions, then the operator is assumed to be the
15899 // built-in operator and interpreted according to clause 5.
15900 if (Opc == BO_Comma)
15901 break;
15902
15903 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15904 // compare result using '==' and '<'.
15905 if (DefaultedFn && Opc == BO_Cmp) {
15906 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
15907 Args[1], DefaultedFn);
15908 if (E.isInvalid() || E.isUsable())
15909 return E;
15910 }
15911
15912 // For class as left operand for assignment or compound assignment
15913 // operator do not fall through to handling in built-in, but report that
15914 // no overloaded assignment operator found
15916 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
15917 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
15918 Args, OpLoc);
15919 DeferDiagsRAII DDR(*this,
15920 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
15921 if (Args[0]->getType()->isRecordType() &&
15922 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15923 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15925 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15926 if (Args[0]->getType()->isIncompleteType()) {
15927 Diag(OpLoc, diag::note_assign_lhs_incomplete)
15928 << Args[0]->getType()
15929 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15930 }
15931 } else {
15932 // This is an erroneous use of an operator which can be overloaded by
15933 // a non-member function. Check for non-member operators which were
15934 // defined too late to be candidates.
15935 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
15936 // FIXME: Recover by calling the found function.
15937 return ExprError();
15938
15939 // No viable function; try to create a built-in operation, which will
15940 // produce an error. Then, show the non-viable candidates.
15941 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15942 }
15943 assert(Result.isInvalid() &&
15944 "C++ binary operator overloading is missing candidates!");
15945 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
15946 return Result;
15947 }
15948
15949 case OR_Ambiguous:
15950 CandidateSet.NoteCandidates(
15951 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15953 << Args[0]->getType()
15954 << Args[1]->getType()
15955 << Args[0]->getSourceRange()
15956 << Args[1]->getSourceRange()),
15958 OpLoc);
15959 return ExprError();
15960
15961 case OR_Deleted: {
15962 if (isImplicitlyDeleted(Best->Function)) {
15963 FunctionDecl *DeletedFD = Best->Function;
15965 DeletedFD->getDefaultedFunctionKind();
15966 if (DFK.isSpecialMember()) {
15967 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15968 << Args[0]->getType() << DFK.asSpecialMember();
15969 } else {
15970 assert(DFK.isComparison());
15971 Diag(OpLoc, diag::err_ovl_deleted_comparison)
15972 << Args[0]->getType() << DeletedFD;
15973 }
15974
15975 // The user probably meant to call this special member. Just
15976 // explain why it's deleted.
15977 NoteDeletedFunction(DeletedFD);
15978 return ExprError();
15979 }
15980
15981 StringLiteral *Msg = Best->Function->getDeletedMessage();
15982 CandidateSet.NoteCandidates(
15984 OpLoc,
15985 PDiag(diag::err_ovl_deleted_oper)
15986 << getOperatorSpelling(Best->Function->getDeclName()
15987 .getCXXOverloadedOperator())
15988 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15989 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15991 OpLoc);
15992 return ExprError();
15993 }
15994 }
15995
15996 // We matched a built-in operator; build it.
15997 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15998}
15999
16001 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
16002 FunctionDecl *DefaultedFn) {
16003 const ComparisonCategoryInfo *Info =
16004 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
16005 // If we're not producing a known comparison category type, we can't
16006 // synthesize a three-way comparison. Let the caller diagnose this.
16007 if (!Info)
16008 return ExprResult((Expr*)nullptr);
16009
16010 // If we ever want to perform this synthesis more generally, we will need to
16011 // apply the temporary materialization conversion to the operands.
16012 assert(LHS->isGLValue() && RHS->isGLValue() &&
16013 "cannot use prvalue expressions more than once");
16014 Expr *OrigLHS = LHS;
16015 Expr *OrigRHS = RHS;
16016
16017 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
16018 // each of them multiple times below.
16019 LHS = new (Context)
16020 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
16021 LHS->getObjectKind(), LHS);
16022 RHS = new (Context)
16023 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
16024 RHS->getObjectKind(), RHS);
16025
16026 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
16027 DefaultedFn);
16028 if (Eq.isInvalid())
16029 return ExprError();
16030
16031 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
16032 true, DefaultedFn);
16033 if (Less.isInvalid())
16034 return ExprError();
16035
16037 if (Info->isPartial()) {
16038 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
16039 DefaultedFn);
16040 if (Greater.isInvalid())
16041 return ExprError();
16042 }
16043
16044 // Form the list of comparisons we're going to perform.
16045 struct Comparison {
16048 } Comparisons[4] =
16054 };
16055
16056 int I = Info->isPartial() ? 3 : 2;
16057
16058 // Combine the comparisons with suitable conditional expressions.
16060 for (; I >= 0; --I) {
16061 // Build a reference to the comparison category constant.
16062 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
16063 // FIXME: Missing a constant for a comparison category. Diagnose this?
16064 if (!VI)
16065 return ExprResult((Expr*)nullptr);
16066 ExprResult ThisResult =
16068 if (ThisResult.isInvalid())
16069 return ExprError();
16070
16071 // Build a conditional unless this is the final case.
16072 if (Result.get()) {
16073 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
16074 ThisResult.get(), Result.get());
16075 if (Result.isInvalid())
16076 return ExprError();
16077 } else {
16078 Result = ThisResult;
16079 }
16080 }
16081
16082 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
16083 // bind the OpaqueValueExprs before they're (repeatedly) used.
16084 Expr *SyntacticForm = BinaryOperator::Create(
16085 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
16086 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
16088 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
16089 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
16090}
16091
16093 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
16094 MultiExprArg Args, SourceLocation LParenLoc) {
16095
16096 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16097 unsigned NumParams = Proto->getNumParams();
16098 unsigned NumArgsSlots =
16099 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
16100 // Build the full argument list for the method call (the implicit object
16101 // parameter is placed at the beginning of the list).
16102 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
16103 bool IsError = false;
16104 // Initialize the implicit object parameter.
16105 // Check the argument types.
16106 for (unsigned i = 0; i != NumParams; i++) {
16107 Expr *Arg;
16108 if (i < Args.size()) {
16109 Arg = Args[i];
16110 ExprResult InputInit =
16112 S.Context, Method->getParamDecl(i)),
16113 SourceLocation(), Arg);
16114 IsError |= InputInit.isInvalid();
16115 Arg = InputInit.getAs<Expr>();
16116 } else {
16117 ExprResult DefArg =
16118 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
16119 if (DefArg.isInvalid()) {
16120 IsError = true;
16121 break;
16122 }
16123 Arg = DefArg.getAs<Expr>();
16124 }
16125
16126 MethodArgs.push_back(Arg);
16127 }
16128 return IsError;
16129}
16130
16132 SourceLocation RLoc,
16133 Expr *Base,
16134 MultiExprArg ArgExpr) {
16136 Args.push_back(Base);
16137 for (auto *e : ArgExpr) {
16138 Args.push_back(e);
16139 }
16140 DeclarationName OpName =
16141 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
16142
16143 SourceRange Range = ArgExpr.empty()
16144 ? SourceRange{}
16145 : SourceRange(ArgExpr.front()->getBeginLoc(),
16146 ArgExpr.back()->getEndLoc());
16147
16148 // If either side is type-dependent, create an appropriate dependent
16149 // expression.
16151
16152 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
16153 // CHECKME: no 'operator' keyword?
16154 DeclarationNameInfo OpNameInfo(OpName, LLoc);
16155 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16157 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
16158 if (Fn.isInvalid())
16159 return ExprError();
16160 // Can't add any actual overloads yet
16161
16162 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
16163 Context.DependentTy, VK_PRValue, RLoc,
16165 }
16166
16167 // Handle placeholders
16168 UnbridgedCastsSet UnbridgedCasts;
16169 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
16170 return ExprError();
16171 }
16172 // Build an empty overload set.
16174
16175 // Subscript can only be overloaded as a member function.
16176
16177 // Add operator candidates that are member functions.
16178 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
16179
16180 // Add builtin operator candidates.
16181 if (Args.size() == 2)
16182 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
16183
16184 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16185
16186 // Perform overload resolution.
16188 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
16189 case OR_Success: {
16190 // We found a built-in operator or an overloaded operator.
16191 FunctionDecl *FnDecl = Best->Function;
16192
16193 if (FnDecl) {
16194 // We matched an overloaded operator. Build a call to that
16195 // operator.
16196
16197 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
16198
16199 // Convert the arguments.
16201 SmallVector<Expr *, 2> MethodArgs;
16202
16203 // Initialize the object parameter.
16204 if (Method->isExplicitObjectMemberFunction()) {
16205 ExprResult Res =
16207 if (Res.isInvalid())
16208 return ExprError();
16209 Args[0] = Res.get();
16210 ArgExpr = Args;
16211 } else {
16213 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16214 if (Arg0.isInvalid())
16215 return ExprError();
16216
16217 MethodArgs.push_back(Arg0.get());
16218 }
16219
16221 *this, MethodArgs, Method, ArgExpr, LLoc);
16222 if (IsError)
16223 return ExprError();
16224
16225 // Build the actual expression node.
16226 DeclarationNameInfo OpLocInfo(OpName, LLoc);
16227 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16229 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
16230 OpLocInfo.getLoc(), OpLocInfo.getInfo());
16231 if (FnExpr.isInvalid())
16232 return ExprError();
16233
16234 // Determine the result type
16235 QualType ResultTy = FnDecl->getReturnType();
16237 ResultTy = ResultTy.getNonLValueExprType(Context);
16238
16240 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
16242
16243 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
16244 return ExprError();
16245
16246 if (CheckFunctionCall(Method, TheCall,
16247 Method->getType()->castAs<FunctionProtoType>()))
16248 return ExprError();
16249
16251 FnDecl);
16252 } else {
16253 // We matched a built-in operator. Convert the arguments, then
16254 // break out so that we will build the appropriate built-in
16255 // operator node.
16257 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
16260 if (ArgsRes0.isInvalid())
16261 return ExprError();
16262 Args[0] = ArgsRes0.get();
16263
16265 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
16268 if (ArgsRes1.isInvalid())
16269 return ExprError();
16270 Args[1] = ArgsRes1.get();
16271
16272 break;
16273 }
16274 }
16275
16276 case OR_No_Viable_Function: {
16278 CandidateSet.empty()
16279 ? (PDiag(diag::err_ovl_no_oper)
16280 << Args[0]->getType() << /*subscript*/ 0
16281 << Args[0]->getSourceRange() << Range)
16282 : (PDiag(diag::err_ovl_no_viable_subscript)
16283 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
16284 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
16285 OCD_AllCandidates, ArgExpr, "[]", LLoc);
16286 return ExprError();
16287 }
16288
16289 case OR_Ambiguous:
16290 if (Args.size() == 2) {
16291 CandidateSet.NoteCandidates(
16293 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
16294 << "[]" << Args[0]->getType() << Args[1]->getType()
16295 << Args[0]->getSourceRange() << Range),
16296 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16297 } else {
16298 CandidateSet.NoteCandidates(
16300 PDiag(diag::err_ovl_ambiguous_subscript_call)
16301 << Args[0]->getType()
16302 << Args[0]->getSourceRange() << Range),
16303 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16304 }
16305 return ExprError();
16306
16307 case OR_Deleted: {
16308 StringLiteral *Msg = Best->Function->getDeletedMessage();
16309 CandidateSet.NoteCandidates(
16311 PDiag(diag::err_ovl_deleted_oper)
16312 << "[]" << (Msg != nullptr)
16313 << (Msg ? Msg->getString() : StringRef())
16314 << Args[0]->getSourceRange() << Range),
16315 *this, OCD_AllCandidates, Args, "[]", LLoc);
16316 return ExprError();
16317 }
16318 }
16319
16320 // We matched a built-in operator; build it.
16321 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
16322}
16323
16325 SourceLocation LParenLoc,
16326 MultiExprArg Args,
16327 SourceLocation RParenLoc,
16328 Expr *ExecConfig, bool IsExecConfig,
16329 bool AllowRecovery) {
16330 assert(MemExprE->getType() == Context.BoundMemberTy ||
16331 MemExprE->getType() == Context.OverloadTy);
16332
16333 // Dig out the member expression. This holds both the object
16334 // argument and the member function we're referring to.
16335 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16336
16337 // Determine whether this is a call to a pointer-to-member function.
16338 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
16339 assert(op->getType() == Context.BoundMemberTy);
16340 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16341
16342 QualType fnType =
16343 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16344
16345 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16346 QualType resultType = proto->getCallResultType(Context);
16348
16349 // Check that the object type isn't more qualified than the
16350 // member function we're calling.
16351 Qualifiers funcQuals = proto->getMethodQuals();
16352
16353 QualType objectType = op->getLHS()->getType();
16354 if (op->getOpcode() == BO_PtrMemI)
16355 objectType = objectType->castAs<PointerType>()->getPointeeType();
16356 Qualifiers objectQuals = objectType.getQualifiers();
16357
16358 Qualifiers difference = objectQuals - funcQuals;
16359 difference.removeObjCGCAttr();
16360 difference.removeAddressSpace();
16361 if (difference) {
16362 std::string qualsString = difference.getAsString();
16363 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
16364 << fnType.getUnqualifiedType()
16365 << qualsString
16366 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
16367 }
16368
16370 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
16372
16373 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
16374 call, nullptr))
16375 return ExprError();
16376
16377 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
16378 return ExprError();
16379
16380 if (CheckOtherCall(call, proto))
16381 return ExprError();
16382
16383 return MaybeBindToTemporary(call);
16384 }
16385
16386 // We only try to build a recovery expr at this level if we can preserve
16387 // the return type, otherwise we return ExprError() and let the caller
16388 // recover.
16389 auto BuildRecoveryExpr = [&](QualType Type) {
16390 if (!AllowRecovery)
16391 return ExprError();
16392 std::vector<Expr *> SubExprs = {MemExprE};
16393 llvm::append_range(SubExprs, Args);
16394 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
16395 Type);
16396 };
16397 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
16398 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
16399 RParenLoc, CurFPFeatureOverrides());
16400
16401 UnbridgedCastsSet UnbridgedCasts;
16402 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16403 return ExprError();
16404
16405 MemberExpr *MemExpr;
16406 CXXMethodDecl *Method = nullptr;
16407 bool HadMultipleCandidates = false;
16408 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
16409 NestedNameSpecifier Qualifier = std::nullopt;
16410 if (isa<MemberExpr>(NakedMemExpr)) {
16411 MemExpr = cast<MemberExpr>(NakedMemExpr);
16413 FoundDecl = MemExpr->getFoundDecl();
16414 Qualifier = MemExpr->getQualifier();
16415 UnbridgedCasts.restore();
16416 } else {
16417 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
16418 Qualifier = UnresExpr->getQualifier();
16419
16420 QualType ObjectType = UnresExpr->getBaseType();
16421 Expr::Classification ObjectClassification
16423 : UnresExpr->getBase()->Classify(Context);
16424
16425 // Add overload candidates
16426 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16428
16429 // FIXME: avoid copy.
16430 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16431 if (UnresExpr->hasExplicitTemplateArgs()) {
16432 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16433 TemplateArgs = &TemplateArgsBuffer;
16434 }
16435
16437 E = UnresExpr->decls_end(); I != E; ++I) {
16438
16439 QualType ExplicitObjectType = ObjectType;
16440
16441 NamedDecl *Func = *I;
16442 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
16444 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
16445
16446 bool HasExplicitParameter = false;
16447 if (const auto *M = dyn_cast<FunctionDecl>(Func);
16448 M && M->hasCXXExplicitFunctionObjectParameter())
16449 HasExplicitParameter = true;
16450 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
16451 M &&
16452 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16453 HasExplicitParameter = true;
16454
16455 if (HasExplicitParameter)
16456 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
16457
16458 // Microsoft supports direct constructor calls.
16459 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
16461 CandidateSet,
16462 /*SuppressUserConversions*/ false);
16463 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
16464 // If explicit template arguments were provided, we can't call a
16465 // non-template member function.
16466 if (TemplateArgs)
16467 continue;
16468
16469 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
16470 ObjectClassification, Args, CandidateSet,
16471 /*SuppressUserConversions=*/false);
16472 } else {
16474 I.getPair(), ActingDC, TemplateArgs,
16475 ExplicitObjectType, ObjectClassification,
16476 Args, CandidateSet,
16477 /*SuppressUserConversions=*/false);
16478 }
16479 }
16480
16481 HadMultipleCandidates = (CandidateSet.size() > 1);
16482
16483 DeclarationName DeclName = UnresExpr->getMemberName();
16484
16485 UnbridgedCasts.restore();
16486
16488 bool Succeeded = false;
16489 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
16490 Best)) {
16491 case OR_Success:
16492 Method = cast<CXXMethodDecl>(Best->Function);
16493 FoundDecl = Best->FoundDecl;
16494 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
16495 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
16496 break;
16497 // If FoundDecl is different from Method (such as if one is a template
16498 // and the other a specialization), make sure DiagnoseUseOfDecl is
16499 // called on both.
16500 // FIXME: This would be more comprehensively addressed by modifying
16501 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16502 // being used.
16503 if (Method != FoundDecl.getDecl() &&
16505 break;
16506 Succeeded = true;
16507 break;
16508
16510 CandidateSet.NoteCandidates(
16512 UnresExpr->getMemberLoc(),
16513 PDiag(diag::err_ovl_no_viable_member_function_in_call)
16514 << DeclName << MemExprE->getSourceRange()),
16515 *this, OCD_AllCandidates, Args);
16516 break;
16517 case OR_Ambiguous:
16518 CandidateSet.NoteCandidates(
16519 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16520 PDiag(diag::err_ovl_ambiguous_member_call)
16521 << DeclName << MemExprE->getSourceRange()),
16522 *this, OCD_AmbiguousCandidates, Args);
16523 break;
16524 case OR_Deleted:
16526 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
16527 CandidateSet, Best->Function, Args, /*IsMember=*/true);
16528 break;
16529 }
16530 // Overload resolution fails, try to recover.
16531 if (!Succeeded)
16532 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
16533
16534 ExprResult Res =
16535 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
16536 if (Res.isInvalid())
16537 return ExprError();
16538 MemExprE = Res.get();
16539
16540 // If overload resolution picked a static member
16541 // build a non-member call based on that function.
16542 if (Method->isStatic()) {
16543 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
16544 ExecConfig, IsExecConfig);
16545 }
16546
16547 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
16548 }
16549
16550 QualType ResultType = Method->getReturnType();
16552 ResultType = ResultType.getNonLValueExprType(Context);
16553
16554 assert(Method && "Member call to something that isn't a method?");
16555 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16556
16557 CallExpr *TheCall = nullptr;
16559 if (Method->isExplicitObjectMemberFunction()) {
16560 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
16561 NewArgs))
16562 return ExprError();
16563
16564 // Build the actual expression node.
16565 ExprResult FnExpr =
16566 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
16567 HadMultipleCandidates, MemExpr->getExprLoc());
16568 if (FnExpr.isInvalid())
16569 return ExprError();
16570
16571 TheCall =
16572 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
16573 CurFPFeatureOverrides(), Proto->getNumParams());
16574 TheCall->setUsesMemberSyntax(true);
16575 } else {
16576 // Convert the object argument (for a non-static member function call).
16578 MemExpr->getBase(), Qualifier, FoundDecl, Method);
16579 if (ObjectArg.isInvalid())
16580 return ExprError();
16581 MemExpr->setBase(ObjectArg.get());
16582 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
16583 RParenLoc, CurFPFeatureOverrides(),
16584 Proto->getNumParams());
16585 }
16586
16587 // Check for a valid return type.
16588 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
16589 TheCall, Method))
16590 return BuildRecoveryExpr(ResultType);
16591
16592 // Convert the rest of the arguments
16593 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
16594 RParenLoc))
16595 return BuildRecoveryExpr(ResultType);
16596
16597 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16598
16599 if (CheckFunctionCall(Method, TheCall, Proto))
16600 return ExprError();
16601
16602 // In the case the method to call was not selected by the overloading
16603 // resolution process, we still need to handle the enable_if attribute. Do
16604 // that here, so it will not hide previous -- and more relevant -- errors.
16605 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
16606 if (const EnableIfAttr *Attr =
16607 CheckEnableIf(Method, LParenLoc, Args, true)) {
16608 Diag(MemE->getMemberLoc(),
16609 diag::err_ovl_no_viable_member_function_in_call)
16610 << Method << Method->getSourceRange();
16611 Diag(Method->getLocation(),
16612 diag::note_ovl_candidate_disabled_by_function_cond_attr)
16613 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16614 return ExprError();
16615 }
16616 }
16617
16619 TheCall->getDirectCallee()->isPureVirtual()) {
16620 const FunctionDecl *MD = TheCall->getDirectCallee();
16621
16622 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
16624 Diag(MemExpr->getBeginLoc(),
16625 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16627 << MD->getParent();
16628
16629 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
16630 if (getLangOpts().AppleKext)
16631 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
16632 << MD->getParent() << MD->getDeclName();
16633 }
16634 }
16635
16636 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
16637 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16638 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16639 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
16640 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16641 MemExpr->getMemberLoc());
16642 }
16643
16645 TheCall->getDirectCallee());
16646}
16647
16650 SourceLocation LParenLoc,
16651 MultiExprArg Args,
16652 SourceLocation RParenLoc) {
16653 if (checkPlaceholderForOverload(*this, Obj))
16654 return ExprError();
16655 ExprResult Object = Obj;
16656
16657 UnbridgedCastsSet UnbridgedCasts;
16658 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16659 return ExprError();
16660
16661 assert(Object.get()->getType()->isRecordType() &&
16662 "Requires object type argument");
16663
16664 // C++ [over.call.object]p1:
16665 // If the primary-expression E in the function call syntax
16666 // evaluates to a class object of type "cv T", then the set of
16667 // candidate functions includes at least the function call
16668 // operators of T. The function call operators of T are obtained by
16669 // ordinary lookup of the name operator() in the context of
16670 // (E).operator().
16671 OverloadCandidateSet CandidateSet(LParenLoc,
16673 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
16674
16675 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
16676 diag::err_incomplete_object_call, Object.get()))
16677 return true;
16678
16679 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16680 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16682 R.suppressAccessDiagnostics();
16683
16684 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16685 Oper != OperEnd; ++Oper) {
16686 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
16687 Object.get()->Classify(Context), Args, CandidateSet,
16688 /*SuppressUserConversion=*/false);
16689 }
16690
16691 // When calling a lambda, both the call operator, and
16692 // the conversion operator to function pointer
16693 // are considered. But when constraint checking
16694 // on the call operator fails, it will also fail on the
16695 // conversion operator as the constraints are always the same.
16696 // As the user probably does not intend to perform a surrogate call,
16697 // we filter them out to produce better error diagnostics, ie to avoid
16698 // showing 2 failed overloads instead of one.
16699 bool IgnoreSurrogateFunctions = false;
16700 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16701 const OverloadCandidate &Candidate = *CandidateSet.begin();
16702 if (!Candidate.Viable &&
16704 IgnoreSurrogateFunctions = true;
16705 }
16706
16707 // C++ [over.call.object]p2:
16708 // In addition, for each (non-explicit in C++0x) conversion function
16709 // declared in T of the form
16710 //
16711 // operator conversion-type-id () cv-qualifier;
16712 //
16713 // where cv-qualifier is the same cv-qualification as, or a
16714 // greater cv-qualification than, cv, and where conversion-type-id
16715 // denotes the type "pointer to function of (P1,...,Pn) returning
16716 // R", or the type "reference to pointer to function of
16717 // (P1,...,Pn) returning R", or the type "reference to function
16718 // of (P1,...,Pn) returning R", a surrogate call function [...]
16719 // is also considered as a candidate function. Similarly,
16720 // surrogate call functions are added to the set of candidate
16721 // functions for each conversion function declared in an
16722 // accessible base class provided the function is not hidden
16723 // within T by another intervening declaration.
16724 const auto &Conversions = Record->getVisibleConversionFunctions();
16725 for (auto I = Conversions.begin(), E = Conversions.end();
16726 !IgnoreSurrogateFunctions && I != E; ++I) {
16727 NamedDecl *D = *I;
16728 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
16729 if (isa<UsingShadowDecl>(D))
16730 D = cast<UsingShadowDecl>(D)->getTargetDecl();
16731
16732 // Skip over templated conversion functions; they aren't
16733 // surrogates.
16735 continue;
16736
16738 if (!Conv->isExplicit()) {
16739 // Strip the reference type (if any) and then the pointer type (if
16740 // any) to get down to what might be a function type.
16741 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16742 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16743 ConvType = ConvPtrType->getPointeeType();
16744
16745 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16746 {
16747 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
16748 Object.get(), Args, CandidateSet);
16749 }
16750 }
16751 }
16752
16753 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16754
16755 // Perform overload resolution.
16757 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
16758 Best)) {
16759 case OR_Success:
16760 // Overload resolution succeeded; we'll build the appropriate call
16761 // below.
16762 break;
16763
16764 case OR_No_Viable_Function: {
16766 CandidateSet.empty()
16767 ? (PDiag(diag::err_ovl_no_oper)
16768 << Object.get()->getType() << /*call*/ 1
16769 << Object.get()->getSourceRange())
16770 : (PDiag(diag::err_ovl_no_viable_object_call)
16771 << Object.get()->getType() << Object.get()->getSourceRange());
16772 CandidateSet.NoteCandidates(
16773 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
16774 OCD_AllCandidates, Args);
16775 break;
16776 }
16777 case OR_Ambiguous:
16778 if (!R.isAmbiguous())
16779 CandidateSet.NoteCandidates(
16780 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16781 PDiag(diag::err_ovl_ambiguous_object_call)
16782 << Object.get()->getType()
16783 << Object.get()->getSourceRange()),
16784 *this, OCD_AmbiguousCandidates, Args);
16785 break;
16786
16787 case OR_Deleted: {
16788 // FIXME: Is this diagnostic here really necessary? It seems that
16789 // 1. we don't have any tests for this diagnostic, and
16790 // 2. we already issue err_deleted_function_use for this later on anyway.
16791 StringLiteral *Msg = Best->Function->getDeletedMessage();
16792 CandidateSet.NoteCandidates(
16793 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16794 PDiag(diag::err_ovl_deleted_object_call)
16795 << Object.get()->getType() << (Msg != nullptr)
16796 << (Msg ? Msg->getString() : StringRef())
16797 << Object.get()->getSourceRange()),
16798 *this, OCD_AllCandidates, Args);
16799 break;
16800 }
16801 }
16802
16803 if (Best == CandidateSet.end())
16804 return true;
16805
16806 UnbridgedCasts.restore();
16807
16808 if (Best->Function == nullptr) {
16809 // Since there is no function declaration, this is one of the
16810 // surrogate candidates. Dig out the conversion function.
16811 CXXConversionDecl *Conv
16813 Best->Conversions[0].UserDefined.ConversionFunction);
16814
16815 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
16816 Best->FoundDecl);
16817 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
16818 return ExprError();
16819 assert(Conv == Best->FoundDecl.getDecl() &&
16820 "Found Decl & conversion-to-functionptr should be same, right?!");
16821 // We selected one of the surrogate functions that converts the
16822 // object parameter to a function pointer. Perform the conversion
16823 // on the object argument, then let BuildCallExpr finish the job.
16824
16825 // Create an implicit member expr to refer to the conversion operator.
16826 // and then call it.
16827 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
16828 Conv, HadMultipleCandidates);
16829 if (Call.isInvalid())
16830 return ExprError();
16831 // Record usage of conversion in an implicit cast.
16833 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
16834 nullptr, VK_PRValue, CurFPFeatureOverrides());
16835
16836 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
16837 }
16838
16839 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
16840
16841 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16842 // that calls this method, using Object for the implicit object
16843 // parameter and passing along the remaining arguments.
16844 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16845
16846 // An error diagnostic has already been printed when parsing the declaration.
16847 if (Method->isInvalidDecl())
16848 return ExprError();
16849
16850 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16851 unsigned NumParams = Proto->getNumParams();
16852
16853 DeclarationNameInfo OpLocInfo(
16854 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
16855 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16856 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16857 Obj, HadMultipleCandidates,
16858 OpLocInfo.getLoc(),
16859 OpLocInfo.getInfo());
16860 if (NewFn.isInvalid())
16861 return true;
16862
16863 SmallVector<Expr *, 8> MethodArgs;
16864 MethodArgs.reserve(NumParams + 1);
16865
16866 bool IsError = false;
16867
16868 // Initialize the object parameter.
16870 if (Method->isExplicitObjectMemberFunction()) {
16871 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
16872 } else {
16874 Object.get(), /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16875 if (ObjRes.isInvalid())
16876 IsError = true;
16877 else
16878 Object = ObjRes;
16879 MethodArgs.push_back(Object.get());
16880 }
16881
16883 *this, MethodArgs, Method, Args, LParenLoc);
16884
16885 // If this is a variadic call, handle args passed through "...".
16886 if (Proto->isVariadic()) {
16887 // Promote the arguments (C99 6.5.2.2p7).
16888 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16890 Args[i], VariadicCallType::Method, nullptr);
16891 IsError |= Arg.isInvalid();
16892 MethodArgs.push_back(Arg.get());
16893 }
16894 }
16895
16896 if (IsError)
16897 return true;
16898
16899 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16900
16901 // Once we've built TheCall, all of the expressions are properly owned.
16902 QualType ResultTy = Method->getReturnType();
16904 ResultTy = ResultTy.getNonLValueExprType(Context);
16905
16907 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
16909
16910 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
16911 return true;
16912
16913 if (CheckFunctionCall(Method, TheCall, Proto))
16914 return true;
16915
16917}
16918
16920 SourceLocation OpLoc,
16921 bool *NoArrowOperatorFound) {
16922 assert(Base->getType()->isRecordType() &&
16923 "left-hand side must have class type");
16924
16926 return ExprError();
16927
16928 SourceLocation Loc = Base->getExprLoc();
16929
16930 // C++ [over.ref]p1:
16931 //
16932 // [...] An expression x->m is interpreted as (x.operator->())->m
16933 // for a class object x of type T if T::operator->() exists and if
16934 // the operator is selected as the best match function by the
16935 // overload resolution mechanism (13.3).
16936 DeclarationName OpName =
16937 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
16939
16940 if (RequireCompleteType(Loc, Base->getType(),
16941 diag::err_typecheck_incomplete_tag, Base))
16942 return ExprError();
16943
16944 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16945 LookupQualifiedName(R, Base->getType()->castAsRecordDecl());
16946 R.suppressAccessDiagnostics();
16947
16948 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16949 Oper != OperEnd; ++Oper) {
16950 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
16951 {}, CandidateSet,
16952 /*SuppressUserConversion=*/false);
16953 }
16954
16955 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16956
16957 // Perform overload resolution.
16959 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
16960 case OR_Success:
16961 // Overload resolution succeeded; we'll build the call below.
16962 break;
16963
16964 case OR_No_Viable_Function: {
16965 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
16966 if (CandidateSet.empty()) {
16967 QualType BaseType = Base->getType();
16968 if (NoArrowOperatorFound) {
16969 // Report this specific error to the caller instead of emitting a
16970 // diagnostic, as requested.
16971 *NoArrowOperatorFound = true;
16972 return ExprError();
16973 }
16974 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16975 << BaseType << Base->getSourceRange();
16976 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16977 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16978 << FixItHint::CreateReplacement(OpLoc, ".");
16979 }
16980 } else
16981 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16982 << "operator->" << Base->getSourceRange();
16983 CandidateSet.NoteCandidates(*this, Base, Cands);
16984 return ExprError();
16985 }
16986 case OR_Ambiguous:
16987 if (!R.isAmbiguous())
16988 CandidateSet.NoteCandidates(
16989 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16990 << "->" << Base->getType()
16991 << Base->getSourceRange()),
16993 return ExprError();
16994
16995 case OR_Deleted: {
16996 StringLiteral *Msg = Best->Function->getDeletedMessage();
16997 CandidateSet.NoteCandidates(
16998 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16999 << "->" << (Msg != nullptr)
17000 << (Msg ? Msg->getString() : StringRef())
17001 << Base->getSourceRange()),
17002 *this, OCD_AllCandidates, Base);
17003 return ExprError();
17004 }
17005 }
17006
17007 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
17008
17009 // Convert the object parameter.
17010 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
17011
17012 if (Method->isExplicitObjectMemberFunction()) {
17014 if (R.isInvalid())
17015 return ExprError();
17016 Base = R.get();
17017 } else {
17019 Base, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
17020 if (BaseResult.isInvalid())
17021 return ExprError();
17022 Base = BaseResult.get();
17023 }
17024
17025 // Build the operator call.
17026 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
17027 Base, HadMultipleCandidates, OpLoc);
17028 if (FnExpr.isInvalid())
17029 return ExprError();
17030
17031 QualType ResultTy = Method->getReturnType();
17033 ResultTy = ResultTy.getNonLValueExprType(Context);
17034
17035 CallExpr *TheCall =
17036 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
17037 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
17038
17039 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
17040 return ExprError();
17041
17042 if (CheckFunctionCall(Method, TheCall,
17043 Method->getType()->castAs<FunctionProtoType>()))
17044 return ExprError();
17045
17047}
17048
17050 DeclarationNameInfo &SuffixInfo,
17051 ArrayRef<Expr*> Args,
17052 SourceLocation LitEndLoc,
17053 TemplateArgumentListInfo *TemplateArgs) {
17054 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
17055
17056 OverloadCandidateSet CandidateSet(UDSuffixLoc,
17058 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
17059 TemplateArgs);
17060
17061 bool HadMultipleCandidates = (CandidateSet.size() > 1);
17062
17063 // Perform overload resolution. This will usually be trivial, but might need
17064 // to perform substitutions for a literal operator template.
17066 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
17067 case OR_Success:
17068 case OR_Deleted:
17069 break;
17070
17072 CandidateSet.NoteCandidates(
17073 PartialDiagnosticAt(UDSuffixLoc,
17074 PDiag(diag::err_ovl_no_viable_function_in_call)
17075 << R.getLookupName()),
17076 *this, OCD_AllCandidates, Args);
17077 return ExprError();
17078
17079 case OR_Ambiguous:
17080 CandidateSet.NoteCandidates(
17081 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
17082 << R.getLookupName()),
17083 *this, OCD_AmbiguousCandidates, Args);
17084 return ExprError();
17085 }
17086
17087 FunctionDecl *FD = Best->Function;
17088 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
17089 nullptr, HadMultipleCandidates,
17090 SuffixInfo.getLoc(),
17091 SuffixInfo.getInfo());
17092 if (Fn.isInvalid())
17093 return true;
17094
17095 // Check the argument types. This should almost always be a no-op, except
17096 // that array-to-pointer decay is applied to string literals.
17097 Expr *ConvArgs[2];
17098 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
17101 SourceLocation(), Args[ArgIdx]);
17102 if (InputInit.isInvalid())
17103 return true;
17104 ConvArgs[ArgIdx] = InputInit.get();
17105 }
17106
17107 QualType ResultTy = FD->getReturnType();
17109 ResultTy = ResultTy.getNonLValueExprType(Context);
17110
17112 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
17113 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
17114
17115 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
17116 return ExprError();
17117
17118 if (CheckFunctionCall(FD, UDL, nullptr))
17119 return ExprError();
17120
17122}
17123
17126 SourceLocation RangeLoc,
17127 const DeclarationNameInfo &NameInfo,
17128 LookupResult &MemberLookup,
17129 OverloadCandidateSet *CandidateSet,
17130 Expr *Range, ExprResult *CallExpr) {
17131 Scope *S = nullptr;
17132
17134 if (!MemberLookup.empty()) {
17135 ExprResult MemberRef =
17136 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
17137 /*IsPtr=*/false, CXXScopeSpec(),
17138 /*TemplateKWLoc=*/SourceLocation(),
17139 /*FirstQualifierInScope=*/nullptr,
17140 MemberLookup,
17141 /*TemplateArgs=*/nullptr, S);
17142 if (MemberRef.isInvalid()) {
17143 *CallExpr = ExprError();
17144 return FRS_DiagnosticIssued;
17145 }
17146 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
17147 if (CallExpr->isInvalid()) {
17148 *CallExpr = ExprError();
17149 return FRS_DiagnosticIssued;
17150 }
17151 } else {
17152 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
17154 NameInfo, UnresolvedSet<0>());
17155 if (FnR.isInvalid())
17156 return FRS_DiagnosticIssued;
17158
17159 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
17160 CandidateSet, CallExpr);
17161 if (CandidateSet->empty() || CandidateSetError) {
17162 *CallExpr = ExprError();
17163 return FRS_NoViableFunction;
17164 }
17166 OverloadingResult OverloadResult =
17167 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
17168
17169 if (OverloadResult == OR_No_Viable_Function) {
17170 *CallExpr = ExprError();
17171 return FRS_NoViableFunction;
17172 }
17173 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
17174 Loc, nullptr, CandidateSet, &Best,
17175 OverloadResult,
17176 /*AllowTypoCorrection=*/false);
17177 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
17178 *CallExpr = ExprError();
17179 return FRS_DiagnosticIssued;
17180 }
17181 }
17182 return FRS_Success;
17183}
17184
17186 FunctionDecl *Fn) {
17187 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
17188 ExprResult SubExpr =
17189 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
17190 if (SubExpr.isInvalid())
17191 return ExprError();
17192 if (SubExpr.get() == PE->getSubExpr())
17193 return PE;
17194
17195 return new (Context)
17196 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
17197 }
17198
17199 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
17200 ExprResult SubExpr =
17201 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
17202 if (SubExpr.isInvalid())
17203 return ExprError();
17204 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
17205 SubExpr.get()->getType()) &&
17206 "Implicit cast type cannot be determined from overload");
17207 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
17208 if (SubExpr.get() == ICE->getSubExpr())
17209 return ICE;
17210
17211 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
17212 SubExpr.get(), nullptr, ICE->getValueKind(),
17214 }
17215
17216 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
17217 if (!GSE->isResultDependent()) {
17218 ExprResult SubExpr =
17219 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
17220 if (SubExpr.isInvalid())
17221 return ExprError();
17222 if (SubExpr.get() == GSE->getResultExpr())
17223 return GSE;
17224
17225 // Replace the resulting type information before rebuilding the generic
17226 // selection expression.
17227 ArrayRef<Expr *> A = GSE->getAssocExprs();
17228 SmallVector<Expr *, 4> AssocExprs(A);
17229 unsigned ResultIdx = GSE->getResultIndex();
17230 AssocExprs[ResultIdx] = SubExpr.get();
17231
17232 if (GSE->isExprPredicate())
17234 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
17235 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
17236 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
17237 ResultIdx);
17239 Context, GSE->getGenericLoc(), GSE->getControllingType(),
17240 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
17241 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
17242 ResultIdx);
17243 }
17244 // Rather than fall through to the unreachable, return the original generic
17245 // selection expression.
17246 return GSE;
17247 }
17248
17249 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
17250 assert(UnOp->getOpcode() == UO_AddrOf &&
17251 "Can only take the address of an overloaded function");
17252 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
17253 if (!Method->isImplicitObjectMemberFunction()) {
17254 // Do nothing: the address of static and
17255 // explicit object member functions is a (non-member) function pointer.
17256 } else {
17257 // Fix the subexpression, which really has to be an
17258 // UnresolvedLookupExpr holding an overloaded member function
17259 // or template.
17260 ExprResult SubExpr =
17261 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17262 if (SubExpr.isInvalid())
17263 return ExprError();
17264 if (SubExpr.get() == UnOp->getSubExpr())
17265 return UnOp;
17266
17267 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
17268 SubExpr.get(), Method))
17269 return ExprError();
17270
17271 assert(isa<DeclRefExpr>(SubExpr.get()) &&
17272 "fixed to something other than a decl ref");
17273 NestedNameSpecifier Qualifier =
17274 cast<DeclRefExpr>(SubExpr.get())->getQualifier();
17275 assert(Qualifier &&
17276 "fixed to a member ref with no nested name qualifier");
17277
17278 // We have taken the address of a pointer to member
17279 // function. Perform the computation here so that we get the
17280 // appropriate pointer to member type.
17281 QualType MemPtrType = Context.getMemberPointerType(
17282 Fn->getType(), Qualifier,
17283 cast<CXXRecordDecl>(Method->getDeclContext()));
17284 // Under the MS ABI, lock down the inheritance model now.
17285 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
17286 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
17287
17288 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
17289 MemPtrType, VK_PRValue, OK_Ordinary,
17290 UnOp->getOperatorLoc(), false,
17292 }
17293 }
17294 ExprResult SubExpr =
17295 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17296 if (SubExpr.isInvalid())
17297 return ExprError();
17298 if (SubExpr.get() == UnOp->getSubExpr())
17299 return UnOp;
17300
17301 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
17302 SubExpr.get());
17303 }
17304
17305 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
17306 if (Found.getAccess() == AS_none) {
17308 }
17309 // FIXME: avoid copy.
17310 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17311 if (ULE->hasExplicitTemplateArgs()) {
17312 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
17313 TemplateArgs = &TemplateArgsBuffer;
17314 }
17315
17316 QualType Type = Fn->getType();
17317 ExprValueKind ValueKind =
17318 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
17319 ? VK_LValue
17320 : VK_PRValue;
17321
17322 // FIXME: Duplicated from BuildDeclarationNameExpr.
17323 if (unsigned BID = Fn->getBuiltinID()) {
17324 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
17325 Type = Context.BuiltinFnTy;
17326 ValueKind = VK_PRValue;
17327 }
17328 }
17329
17331 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
17332 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
17333 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17334 return DRE;
17335 }
17336
17337 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
17338 // FIXME: avoid copy.
17339 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17340 if (MemExpr->hasExplicitTemplateArgs()) {
17341 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
17342 TemplateArgs = &TemplateArgsBuffer;
17343 }
17344
17345 Expr *Base;
17346
17347 // If we're filling in a static method where we used to have an
17348 // implicit member access, rewrite to a simple decl ref.
17349 if (MemExpr->isImplicitAccess()) {
17350 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17352 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
17353 MemExpr->getQualifierLoc(), Found.getDecl(),
17354 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17355 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17356 return DRE;
17357 } else {
17358 SourceLocation Loc = MemExpr->getMemberLoc();
17359 if (MemExpr->getQualifier())
17360 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17361 Base =
17362 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
17363 }
17364 } else
17365 Base = MemExpr->getBase();
17366
17367 ExprValueKind valueKind;
17368 QualType type;
17369 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17370 valueKind = VK_LValue;
17371 type = Fn->getType();
17372 } else {
17373 valueKind = VK_PRValue;
17374 type = Context.BoundMemberTy;
17375 }
17376
17377 return BuildMemberExpr(
17378 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
17379 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
17380 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
17381 type, valueKind, OK_Ordinary, TemplateArgs);
17382 }
17383
17384 llvm_unreachable("Invalid reference to overloaded function");
17385}
17386
17392
17393bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17395 if (!PartialOverloading || !Function)
17396 return true;
17397 if (Function->isVariadic())
17398 return false;
17399 if (const auto *Proto =
17400 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
17401 if (Proto->isTemplateVariadic())
17402 return false;
17403 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17404 if (const auto *Proto =
17405 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
17406 if (Proto->isTemplateVariadic())
17407 return false;
17408 return true;
17409}
17410
17412 DeclarationName Name,
17413 OverloadCandidateSet &CandidateSet,
17414 FunctionDecl *Fn, MultiExprArg Args,
17415 bool IsMember) {
17416 StringLiteral *Msg = Fn->getDeletedMessage();
17417 CandidateSet.NoteCandidates(
17418 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
17419 << IsMember << Name << (Msg != nullptr)
17420 << (Msg ? Msg->getString() : StringRef())
17421 << Range),
17422 *this, OCD_AllCandidates, Args);
17423}
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.
Result
Implement __builtin_bit_cast and related operations.
#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.
llvm::json::Object Object
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
static AccessResult DeduceTemplateArguments(Sema &S, FriendTemplateDecl *FTD, DeclContext *DC, const TemplateSpecializationType *TST, ArrayRef< TemplateParameterList * > TPLs, TemplateSpecCandidateSet *FailedTSC, MultiLevelTemplateArgumentList &DeducedArgs)
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:186
static bool hasExplicitAttr(const VarDecl *D)
Definition SemaCUDA.cpp:32
This file declares semantic analysis for CUDA constructs.
CastType
Definition SemaCast.cpp:50
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 void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, DeductionFailureInfo &DeductionFailure, unsigned NumArgs, bool TakingCandidateAddress, TemplateSpecCandidateSetKind CandidateSetKind=TemplateSpecCandidateSetKind::Normal)
Diagnose a failed template-argument deduction.
static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn)
static const FunctionType * getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv)
static bool functionHasPassObjectSizeParams(const FunctionDecl *FD)
static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, const FunctionDecl *Cand2)
Compares the enable_if attributes of two FunctionDecls, for the purposes of overload resolution.
static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr *ArgExpr)
CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, if any, found in visible typ...
FixedEnumPromotion
static void AddOverloadedCallCandidate(Sema &S, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading, bool KnownValid)
Add a single candidate to the overload set.
static void AddTemplateOverloadCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit, Sema::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction)
static bool IsVectorOrMatrixElementConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, Expr *From)
static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, OverloadCandidateSet *CandidateSet, OverloadCandidateSet::iterator *Best, OverloadingResult OverloadResult, bool AllowTypoCorrection)
FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns the completed call expre...
static bool isQualificationConversionStep(QualType FromType, QualType ToType, bool CStyle, bool IsTopLevel, bool &PreviousToQualsIncludeConst, bool &ObjCLifetimeConversion, const ASTContext &Ctx)
Perform a single iteration of the loop for checking if a qualification conversion is valid.
static ImplicitConversionSequence::CompareKind CompareQualificationConversions(Sema &S, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareQualificationConversions - Compares two standard conversion sequences to determine whether the...
static void dropPointerConversion(StandardConversionSequence &SCS)
dropPointerConversions - If the given standard conversion sequence involves any pointer conversions,...
static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand)
static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, unsigned NumFormalArgs, bool IsAddressOf=false)
General arity mismatch diagnosis over a candidate in a candidate set.
static const Expr * IgnoreNarrowingConversion(ASTContext &Ctx, const Expr *Converted)
Skip any implicit casts which could be either part of a narrowing conversion or after one in an impli...
static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1, const FunctionDecl *F2)
static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI)
static QualType BuildSimilarlyQualifiedPointerType(const Type *FromPtr, QualType ToPointee, QualType ToType, ASTContext &Context, bool StripObjCLifetime=false)
BuildSimilarlyQualifiedPointerType - In a pointer conversion from the pointer type FromPtr to a point...
static void forAllQualifierCombinations(QualifiersAndAtomic Quals, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static bool FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, QualType DeclType, SourceLocation DeclLoc, Expr *Init, QualType T2, bool AllowRvalues, bool AllowExplicit)
Look for a user-defined conversion to a value reference-compatible with DeclType.
static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static Expr * GetExplicitObjectExpr(Sema &S, Expr *Obj, const FunctionDecl *Fun)
static bool hasDeprecatedStringLiteralToCharPtrConversion(const ImplicitConversionSequence &ICS)
static void AddBuiltinAssignmentOperatorCandidates(Sema &S, QualType T, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
Helper function for AddBuiltinOperatorCandidates() that adds the volatile- and non-volatile-qualified...
static bool CheckConvertedConstantConversions(Sema &S, StandardConversionSequence &SCS)
Check that the specified conversion is permitted in a converted constant expression,...
static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, SourceLocation OpLoc, OverloadCandidate *Cand)
static ImplicitConversionSequence::CompareKind compareConversionFunctions(Sema &S, FunctionDecl *Function1, FunctionDecl *Function2)
Compare the user-defined conversion functions or constructors of two user-defined conversion sequence...
static void forAllQualifierCombinationsImpl(QualifiersAndAtomic Available, QualifiersAndAtomic Applied, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static const char * GetImplicitConversionName(ImplicitConversionKind Kind)
GetImplicitConversionName - Return the name of this kind of implicit conversion.
static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, bool Complain, bool InOverloadResolution, SourceLocation Loc)
Returns true if we can take the address of the function.
static ImplicitConversionSequence::CompareKind CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareDerivedToBaseConversions - Compares two standard conversion sequences to determine whether the...
static bool convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, ArrayRef< Expr * > Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, Expr *&ConvertedThis, SmallVectorImpl< Expr * > &ConvertedArgs)
static TemplateDecl * getDescribedTemplate(Decl *Templated)
static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, ArrayRef< Expr * > Args, OverloadCandidateSet::CandidateSetKind CSK)
CompleteNonViableCandidate - Normally, overload resolution only computes up to the first bad conversi...
static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs)
Adopt the given qualifiers for the given type.
static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, OverloadCandidate *Cand)
static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, unsigned NumArgs, bool IsAddressOf=false)
Additional arity mismatch diagnosis specific to a function overload candidates.
static ImplicitConversionSequence::CompareKind compareStandardConversionSubsets(ASTContext &Context, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
static bool hasDependentExplicit(FunctionTemplateDecl *FTD)
static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, ImplicitConversionKind &ElConv, Expr *From, bool InOverloadResolution, bool CStyle)
Determine whether the conversion from FromType to ToType is a valid vector conversion.
static ImplicitConversionSequence TryContextuallyConvertToObjCPointer(Sema &S, Expr *From)
TryContextuallyConvertToObjCPointer - Attempt to contextually convert the expression From to an Objec...
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static ExprResult CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base, bool HadMultipleCandidates, SourceLocation Loc=SourceLocation(), const DeclarationNameLoc &LocInfo=DeclarationNameLoc())
A convenience routine for creating a decayed reference to a function.
static std::optional< QualType > getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F)
Compute the type of the implicit object parameter for the given function, if any.
static bool checkPlaceholderForOverload(Sema &S, Expr *&E, UnbridgedCastsSet *unbridgedCasts=nullptr)
checkPlaceholderForOverload - Do any interesting placeholder-like preprocessing on the given expressi...
static FixedEnumPromotion getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS)
Returns kind of fixed enum promotion the SCS uses.
static bool isAllowableExplicitConversion(Sema &S, QualType ConvType, QualType ToType, bool AllowObjCPointerConversion)
Determine whether this is an allowable conversion from the result of an explicit conversion operator ...
@ ft_different_class
@ ft_parameter_mismatch
@ ft_noexcept
@ ft_return_type
@ ft_parameter_arity
@ ft_default
@ ft_qualifer_mismatch
static bool isNonViableMultiVersionOverload(FunctionDecl *FD)
static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X, const FunctionDecl *Y)
static ImplicitConversionSequence TryImplicitConversion(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion, bool AllowObjCConversionOnExplicit)
TryImplicitConversion - Attempt to perform an implicit conversion from the given expression (Expr) to...
static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest, APValue &PreNarrowingValue)
BuildConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static ImplicitConversionSequence TryListConversion(Sema &S, InitListExpr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion)
TryListConversion - Try to copy-initialize a value of type ToType from the initializer list From.
static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, bool UseOverrideRules=false)
static QualType withoutUnaligned(ASTContext &Ctx, QualType T)
static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand)
CUDA: diagnose an invalid call across targets.
static void MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef< OverloadCandidate > Cands)
static bool diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, UnresolvedSetImpl &ExplicitConversions)
static void AddMethodTemplateCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, OverloadCandidateParamOrder PO)
static void AddTemplateConversionCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion)
static ImplicitConversionSequence TryContextuallyConvertToBool(Sema &S, Expr *From)
TryContextuallyConvertToBool - Attempt to contextually convert the expression From to bool (C++0x [co...
static ImplicitConversionSequence TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, Expr::Classification FromClassification, CXXMethodDecl *Method, const CXXRecordDecl *ActingContext, bool InOverloadResolution=false, QualType ExplicitParameterType=QualType(), bool SuppressUserConversion=false)
TryObjectArgumentInitialization - Try to initialize the object parameter of the given member function...
static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, DeclAccessPair &Found)
static ImplicitConversionSequence::CompareKind CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, const ImplicitConversionSequence &ICS1, const ImplicitConversionSequence &ICS2)
CompareImplicitConversionSequences - Compare two implicit conversion sequences to determine whether o...
static ImplicitConversionSequence::CompareKind CompareOverflowBehaviorConversions(Sema &S, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareOverflowBehaviorConversions - Compares two standard conversion sequences to determine whether ...
static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, unsigned NumArgs, bool TakingCandidateAddress, LangAS CtorDestAS=LangAS::Default)
Generates a 'note' diagnostic for an overload candidate.
static ImplicitConversionSequence TryCopyInitialization(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion, bool AllowExplicit=false)
TryCopyInitialization - Try to copy-initialize a value of type ToType from the expression From.
static ExprResult diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter, QualType T, UnresolvedSetImpl &ViableConversions)
static void markUnaddressableCandidatesUnviable(Sema &S, OverloadCandidateSet &CS)
static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE)
Sema::AllowedExplicit AllowedExplicit
static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, Expr *Arg)
Helper function for adjusting address spaces for the pointer or reference operands of builtin operato...
static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand)
static bool DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, CXXRecordDecl **FoundInClass=nullptr)
Attempt to recover from an ill-formed use of a non-dependent name in a template, where the non-depend...
static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
Determine whether one of the given reference bindings is better than the other based on what kind of ...
static bool canBeDeclaredInNamespace(const DeclarationName &Name)
Determine whether a declaration with the specified name could be moved into a different namespace.
static ExprResult finishContextualImplicitConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter)
static bool IsStandardConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle, bool AllowObjCWritebackConversion)
IsStandardConversion - Determines whether there is a standard conversion sequence (C++ [conv],...
static bool DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args)
Attempt to recover from ill-formed use of a non-dependent operator in a template, where the non-depen...
static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, Qualifiers ToQuals)
Determine whether the lifetime conversion between the two given qualifiers sets is nontrivial.
static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I, bool TakingCandidateAddress)
static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, bool Complain=true)
static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc, Expr *FirstOperand, FunctionDecl *EqFD)
static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, const FunctionDecl *FD)
static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method, Expr *Object, MultiExprArg &Args, SmallVectorImpl< Expr * > &NewArgs)
static OverloadingResult IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, CXXRecordDecl *To, UserDefinedConversionSequence &User, OverloadCandidateSet &CandidateSet, bool AllowExplicit)
static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, ImplicitConversionKind &ElConv, Expr *From, bool InOverloadResolution, bool CStyle)
Determine whether the conversion from FromType to ToType is a valid matrix conversion.
static bool checkAddressOfCandidateIsAvailable(Sema &S, const FunctionDecl *FD)
static bool IsFloatingPointConversion(Sema &S, QualType FromType, QualType ToType)
Determine whether the conversion from FromType to ToType is a valid floating point conversion.
static bool isFirstArgumentCompatibleWithType(ASTContext &Context, CXXConstructorDecl *Constructor, QualType Type)
static Comparison isBetterMultiversionCandidate(const OverloadCandidate &Cand1, const OverloadCandidate &Cand2)
static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn)
static void collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, UnresolvedSetImpl &ViableConversions, OverloadCandidateSet &CandidateSet)
static ImplicitConversionSequence TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, SourceLocation DeclLoc, bool SuppressUserConversions, bool AllowExplicit)
Compute an implicit conversion sequence for reference initialization.
static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD)
Determine whether a given function template has a simple explicit specifier or a non-value-dependent ...
static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args, UnbridgedCastsSet &unbridged)
checkArgPlaceholdersForOverload - Check a set of call operands for placeholders.
static QualType makeQualifiedLValueReferenceType(QualType Base, QualifiersAndAtomic Quals, Sema &S)
static QualType chooseRecoveryType(OverloadCandidateSet &CS, OverloadCandidateSet::iterator *Best)
static void AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet, DeferredMethodTemplateOverloadCandidate &C)
static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand)
static ExprResult BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MutableArrayRef< Expr * > Args, SourceLocation RParenLoc, bool EmptyLookup, bool AllowTypoCorrection)
Attempts to recover from a call where no functions were found.
static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand)
static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, bool ArgDependent, SourceLocation Loc, CheckFn &&IsSuccessful)
static OverloadingResult IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, UserDefinedConversionSequence &User, OverloadCandidateSet &Conversions, AllowedExplicit AllowExplicit, bool AllowObjCConversionOnExplicit)
Determines whether there is a user-defined conversion sequence (C++ [over.ics.user]) that converts ex...
static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, FunctionDecl *Fn, ArrayRef< Expr * > Args)
IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is an acceptable non-member overloaded ...
static FunctionDecl * getMorePartialOrderingConstrained(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2, bool IsFn1Reversed, bool IsFn2Reversed)
static 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)
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
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:484
bool isFloat() const
Definition APValue.h:489
bool isInt() const
Definition APValue.h:488
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:991
APFloat & getFloat()
Definition APValue.h:525
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
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:832
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:985
CanQualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
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:948
CanQualType Float128Ty
CanQualType UnsignedLongTy
QualType getRestrictType(QualType T) const
Return the uniqued reference to the type for a restrict qualified type.
CanQualType CharTy
CanQualType IntTy
bool areCompatibleOverflowBehaviorTypes(QualType LHS, QualType RHS)
Return true if two OverflowBehaviorTypes are compatible for assignment.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
CanQualType SignedCharTy
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
QualType getObjCIdType() const
Represents the Objective-CC id type.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
bool isSameTemplateParameterList(const TemplateParameterList *X, const TemplateParameterList *Y) const
Determine whether two template parameter lists are similar enough that they may be used in declaratio...
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType UnsignedInt128Ty
CanQualType VoidTy
CanQualType UnsignedCharTy
CanQualType UnsignedIntTy
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
CanQualType UnsignedLongLongTy
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
CanQualType UnsignedShortTy
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
CanQualType ShortTy
CanQualType Char32Ty
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getCVRQualifiedType(QualType T, unsigned CVR) const
Return a type with additional const, volatile, or restrict qualifiers.
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:947
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:4006
QualType getConstantArrayType(const ASTContext &Ctx) const
Definition Type.cpp:316
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3836
QualType getElementType() const
Definition TypeBase.h:3848
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8300
Attr - This represents one attribute.
Definition Attr.h:46
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4082
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2211
StringRef getOpcodeStr() const
Definition Expr.h:4148
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2164
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:5131
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4223
Pointer to a block type.
Definition TypeBase.h:3656
This class is used for builtin types like 'int'.
Definition TypeBase.h:3241
Kind getKind() const
Definition TypeBase.h:3292
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:2641
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3069
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:3106
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2976
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition DeclCXX.h:3008
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:3012
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:183
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:725
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2149
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:2719
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:2726
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2870
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2292
static CXXOperatorCallExpr * Create(const ASTContext &Ctx, OverloadedOperatorKind OpKind, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation OperatorLoc, FPOptionsOverride FPFeatures, ADLCallKind UsesADL=NotADL, bool IsReversed=false)
Definition ExprCXX.cpp:655
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:1027
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition DeclCXX.cpp:1989
bool isHLSLBuiltinRecord() const
Returns true if the class is a built-in HLSL record.
Definition DeclCXX.h:1568
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:1744
A rewritten comparison expression that was originally written using operator syntax.
Definition ExprCXX.h:290
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:181
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:2987
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:1545
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3170
void setUsesMemberSyntax(bool V=true)
Definition Expr.h:3151
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition Expr.h:3369
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:3355
QualType getElementType() const
Definition TypeBase.h:3365
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:5153
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3874
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:356
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4501
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4520
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4517
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:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
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:1290
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:1483
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:581
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
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:596
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
SourceLocation getLocation() const
Definition DeclBase.h:447
DeclContext * getDeclContext()
Definition DeclBase.h:456
AccessSpecifier getAccess() const
Definition DeclBase.h:515
specific_attr_iterator< T > specific_attr_end() const
Definition DeclBase.h:577
specific_attr_iterator< T > specific_attr_begin() const
Definition DeclBase.h:572
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:935
bool hasAttr() const
Definition DeclBase.h:585
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:832
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:856
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition Diagnostic.h:798
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition Diagnostic.h:783
OverloadsShown getShowOverloads() const
Definition Diagnostic.h:774
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:610
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4146
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4364
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4262
Store information needed for an explicit specifier.
Definition DeclCXX.h:1948
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition DeclCXX.h:1972
ExplicitSpecKind getKind() const
Definition DeclCXX.h:1956
const Expr * getExpr() const
Definition DeclCXX.h:1957
static ExplicitSpecifier getFromDecl(const FunctionDecl *Function)
Definition DeclCXX.cpp:2370
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition ExprCXX.cpp:1497
The return type of classify().
Definition Expr.h:340
bool isLValue() const
Definition Expr.h:391
bool isPRValue() const
Definition Expr.h:394
bool isXValue() const
Definition Expr.h:392
static Classification makeSimpleLValue()
Create a simple, modifiable lvalue.
Definition Expr.h:399
bool isRValue() const
Definition Expr.h:395
This represents one expression.
Definition Expr.h:113
bool isIntegerConstantExpr(const ASTContext &Ctx) const
bool isGLValue() const
Definition Expr.h:288
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3128
void setType(QualType t)
Definition Expr.h:146
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:178
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:448
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:195
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:247
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3119
bool isPRValue() const
Definition Expr.h:286
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition Expr.cpp:3372
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4265
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:851
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:855
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:455
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:831
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:4104
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:480
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition Expr.h:416
QualType getType() const
Definition Expr.h:145
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:527
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:438
ExtVectorType - Extended vector type.
Definition TypeBase.h:4381
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3295
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:81
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:142
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:105
For a defaulted function, the kind of defaulted function that it is.
Definition Decl.h:2123
CXXSpecialMemberKind asSpecialMember() const
Definition Decl.h:2152
Represents a function declaration or definition.
Definition Decl.h:2059
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2820
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2928
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4234
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3806
param_iterator param_end()
Definition Decl.h:2918
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition Decl.cpp:3710
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3909
QualType getReturnType() const
Definition Decl.h:2976
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2905
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:4305
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4354
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3791
param_iterator param_begin()
Definition Decl.h:2917
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3121
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4370
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4298
unsigned getNumNonObjectParams() const
Definition Decl.cpp:3913
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2597
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4171
bool isConsteval() const
Definition Decl.h:2609
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition Decl.cpp:3754
DefaultedFunctionKind getDefaultedFunctionKind() const
Determine the kind of defaulting that would be done for a given function.
Definition Decl.cpp:3288
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:2993
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:3759
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3870
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2816
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5421
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5925
unsigned getNumParams() const
Definition TypeBase.h:5699
Qualifiers getMethodQuals() const
Definition TypeBase.h:5847
QualType getParamType(unsigned i) const
Definition TypeBase.h:5701
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5825
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5861
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:4728
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4799
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4656
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4617
ExtInfo getExtInfo() const
Definition TypeBase.h:4973
CallingConv getCallConv() const
Definition TypeBase.h:4972
QualType getReturnType() const
Definition TypeBase.h:4957
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4985
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:4752
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:3897
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2103
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:623
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:674
void setBad(BadConversionSequence::FailureKind Failure, Expr *FromExpr, QualType ToType)
Sets this sequence as a bad conversion for an explicit argument.
Definition Overload.h:771
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition Overload.h:678
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:828
AmbiguousConversionSequence Ambiguous
When ConversionKind == AmbiguousConversion, provides the details of the ambiguous conversion.
Definition Overload.h:682
bool hasInitializerListContainerType() const
Definition Overload.h:810
unsigned getKindRank() const
Return a ranking of the implicit conversion sequence kind, where smaller ranks represent better conve...
Definition Overload.h:735
bool isInitializerListOfIncompleteArray() const
Definition Overload.h:817
BadConversionSequence Bad
When ConversionKind == BadConversion, provides the details of the bad conversion.
Definition Overload.h:686
QualType getInitializerListContainerType() const
Definition Overload.h:820
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition Expr.h:5352
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition Expr.h:5468
unsigned getNumInits() const
Definition Expr.h:5385
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:2529
const Expr * getInit(unsigned Init) const
Definition Expr.h:5407
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:2547
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:981
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3731
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
DeclClass * getAsSingle() const
Definition Lookup.h:558
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
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
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
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:4465
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3408
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3597
NestedNameSpecifier getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition Expr.h:3519
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3491
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition Expr.h:3505
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition Expr.h:3626
Expr * getBase() const
Definition Expr.h:3485
void setBase(Expr *E)
Definition Expr.h:3484
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1824
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3603
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition Expr.h:3495
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3767
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3799
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5704
QualType getPointeeType() const
Definition TypeBase.h:3785
Describes a module or submodule.
Definition Module.h:340
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:240
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition Module.h:940
This represents a decl that may have a name.
Definition Decl.h:275
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:488
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:302
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:341
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1684
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1208
Represent a C++ namespace.
Definition Decl.h:593
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:1160
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:8063
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition TypeBase.h:8119
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition TypeBase.h:8208
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:8177
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8131
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8171
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1915
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:8183
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1198
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1161
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:1361
bool shouldDeferTemplateArgumentDeduction(const Sema &S) const
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:1459
ConversionSequenceList allocateConversionSequences(unsigned NumConversions)
Allocate storage for conversion sequences for NumConversions conversions.
Definition Overload.h:1393
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:1409
OperatorRewriteInfo getRewriteInfo() const
Definition Overload.h:1351
@ CSK_AddressOfOverloadSet
C++ [over.match.call.general] Resolve a call through the address of an overload set.
Definition Overload.h:1186
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition Overload.h:1182
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition Overload.h:1177
@ CSK_Normal
Normal lookup.
Definition Overload.h:1165
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition Overload.h:1172
@ CSK_CodeCompletion
When doing overload resolution during code completion, we want to show all viable candidates,...
Definition Overload.h:1191
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1377
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:1369
SourceLocation getLocation() const
Definition Overload.h:1349
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions={})
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition Overload.h:1424
void InjectNonDeducedTemplateCandidates(Sema &S)
CandidateSetKind getKind() const
Definition Overload.h:1350
size_t nonDeferredCandidatesCount() const
Definition Overload.h:1384
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:3142
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition ExprCXX.h:3294
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3203
NestedNameSpecifier getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition ExprCXX.h:3258
SourceLocation getNameLoc() const
Gets the location of the name.
Definition ExprCXX.h:3255
UnresolvedSetImpl::iterator decls_iterator
Definition ExprCXX.h:3233
decls_iterator decls_begin() const
Definition ExprCXX.h:3235
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition ExprCXX.h:3246
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition ExprCXX.h:3268
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition ExprCXX.h:3264
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition ExprCXX.h:3324
decls_iterator decls_end() const
Definition ExprCXX.h:3238
DeclarationName getName() const
Gets the name looked up.
Definition ExprCXX.h:3252
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:279
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2226
Represents a parameter to a function.
Definition Decl.h:1820
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3046
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:302
std::string getAsString() const
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3408
QualType getPointeeType() const
Definition TypeBase.h:3418
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5225
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8585
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8579
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8590
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3718
QualType withConst() const
Definition TypeBase.h:1175
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition TypeBase.h:1241
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8501
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8627
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8541
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:8686
QualType getCanonicalType() const
Definition TypeBase.h:8553
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8595
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition TypeBase.h:1090
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:8655
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8574
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8622
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8547
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1348
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:8666
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8533
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8441
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8448
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4828
QualifiersAndAtomic withVolatile()
Definition TypeBase.h:854
QualifiersAndAtomic withAtomic()
Definition TypeBase.h:861
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
unsigned getCVRQualifiers() const
Definition TypeBase.h:489
GC getObjCGCAttr() const
Definition TypeBase.h:520
bool hasOnlyConst() const
Definition TypeBase.h:459
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:355
void removeObjCLifetime()
Definition TypeBase.h:552
bool hasConst() const
Definition TypeBase.h:458
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition TypeBase.h:728
bool hasRestrict() const
Definition TypeBase.h:478
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:709
void removeObjCGCAttr()
Definition TypeBase.h:524
void removeUnaligned()
Definition TypeBase.h:516
void removeAddressSpace()
Definition TypeBase.h:597
void setAddressSpace(LangAS space)
Definition TypeBase.h:592
bool hasVolatile() const
Definition TypeBase.h:468
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:604
bool hasObjCGCAttr() const
Definition TypeBase.h:519
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:546
void removeVolatile()
Definition TypeBase.h:470
std::string getAsString() const
LangAS getAddressSpace() const
Definition TypeBase.h:572
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition TypeBase.h:751
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3749
Represents a struct/union/class.
Definition Decl.h:4460
field_range fields() const
Definition Decl.h:4663
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4648
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3687
QualType getPointeeType() const
Definition TypeBase.h:3705
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:1539
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
Definition SemaARM.cpp:1584
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:187
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:211
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:462
static bool isImplicitHostDeviceFunction(const FunctionDecl *D)
Definition SemaCUDA.cpp:399
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:409
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:311
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:10361
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.
RAII class to control scope of DeferDiags.
Definition Sema.h:10084
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1384
DelayedDiagnosticsState pushUndelayed()
Enter a new scope where access and deprecation diagnostics are not delayed.
Definition Sema.h:1419
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:12549
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12583
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
bool TryFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy) const
Same as IsFunctionConversion, but if this would return true, it sets ResultTy to ToType.
SemaAMDGPU & AMDGPU()
Definition Sema.h:1446
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:10102
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:9370
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9397
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition Sema.h:9382
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9378
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:418
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:169
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:1471
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:10444
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10447
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10453
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10451
@ AR_dependent
Definition Sema.h:1690
@ AR_accessible
Definition Sema.h:1688
@ AR_inaccessible
Definition Sema.h:1689
@ AR_delayed
Definition Sema.h:1691
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:2079
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:1768
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:1304
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:701
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:228
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:932
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:1516
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:764
ASTContext & getASTContext() const
Definition Sema.h:935
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:777
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....
void LookupOverloadedUnaryOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef< Expr * > Args, bool RequiresADL=true)
Perform lookup for an overloaded unary operator.
@ FRS_Success
Definition Sema.h:10832
@ FRS_DiagnosticIssued
Definition Sema.h:10834
@ FRS_NoViableFunction
Definition Sema.h:10833
llvm::SmallSetVector< CXXRecordDecl *, 16 > AssociatedClassSet
Definition Sema.h:9363
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:10153
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:1208
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:3649
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:12247
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:277
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
const LangOptions & getLangOpts() const
Definition Sema.h:928
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:1302
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:1481
llvm::SmallSetVector< DeclContext *, 16 > AssociatedNamespaceSet
Definition Sema.h:9362
MemberPointerConversionDirection
Definition Sema.h:10285
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:10472
MemberPointerConversionResult CheckMemberPointerConversion(QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind, CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange, bool IgnoreBaseAccess, MemberPointerConversionDirection Direction)
CheckMemberPointerConversion - Check the member pointer conversion from the expression From to the ty...
Expr * BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit)
Build a CXXThisExpr and mark it referenced in the current context.
bool IsOverflowBehaviorTypeConversion(QualType FromType, QualType ToType)
IsOverflowBehaviorTypeConversion - Determines whether the conversion from FromType to ToType necessar...
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add the overload candidates named by callee and/or found by argument dependent lookup to the given ov...
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:648
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:15639
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:9898
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:7013
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:1444
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
bool IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType)
IsOverflowBehaviorTypePromotion - Determines whether the conversion from FromType to ToType involves ...
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, SourceLocation Loc={}, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8209
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:14055
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:7510
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:13798
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:15594
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:127
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:6776
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6745
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:10277
SourceManager & SourceMgr
Definition Sema.h:1307
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
DiagnosticsEngine & Diags
Definition Sema.h:1306
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:524
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:6453
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:1451
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:8689
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
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false, bool AllowRelaxedEval=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
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
unsigned IsLvalueReference
Whether this is an lvalue reference binding (otherwise, it's an rvalue reference binding).
Definition Overload.h:349
ImplicitConversionKind Dimension
Dimension - Between the second and third conversion a vector or matrix dimension conversion may occur...
Definition Overload.h:314
unsigned BindsToFunctionLvalue
Whether we're binding to a function lvalue.
Definition Overload.h:353
unsigned DirectBinding
DirectBinding - True when this is a reference binding that is a direct binding (C++ [dcl....
Definition Overload.h:344
ImplicitConversionRank getRank() const
getRank - Retrieve the rank of this standard conversion sequence (C++ 13.3.3.1.1p3).
bool isPointerConversionToVoidPointer(ASTContext &Context) const
isPointerConversionToVoidPointer - Determines whether this conversion is a conversion of a pointer to...
unsigned FromBracedInitList
Whether the source expression was originally a single element braced-init-list.
Definition Overload.h:374
QualType getToType(unsigned Idx) const
Definition Overload.h:411
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1819
StringRef getString() const
Definition Expr.h:1887
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:684
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition TargetInfo.h:726
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition TargetInfo.h:711
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:3673
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2549
bool isBlockPointerType() const
Definition TypeBase.h:8758
bool isVoidType() const
Definition TypeBase.h:9110
bool isBooleanType() const
Definition TypeBase.h:9247
bool isObjCBuiltinType() const
Definition TypeBase.h:8968
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2319
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:2026
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:824
bool isIncompleteArrayType() const
Definition TypeBase.h:8845
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2296
bool isFloat16Type() const
Definition TypeBase.h:9119
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:761
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2203
bool isRValueReferenceType() const
Definition TypeBase.h:8770
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:8841
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9277
bool isArrayType() const
Definition TypeBase.h:8837
bool isCharType() const
Definition Type.cpp:2223
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition TypeBase.h:9182
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isArithmeticType() const
Definition Type.cpp:2454
bool isPointerType() const
Definition TypeBase.h:8738
bool isArrayParameterType() const
Definition TypeBase.h:8853
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9154
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2699
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9404
bool isReferenceType() const
Definition TypeBase.h:8762
bool isEnumeralType() const
Definition TypeBase.h:8869
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2186
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8938
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9232
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2259
bool isExtVectorBoolType() const
Definition TypeBase.h:8885
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8925
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2867
bool isLValueReferenceType() const
Definition TypeBase.h:8766
bool isBitIntType() const
Definition TypeBase.h:9013
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2859
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2535
bool isAnyComplexType() const
Definition TypeBase.h:8873
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9170
bool isHalfType() const
Definition TypeBase.h:9114
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:9092
bool isQueueT() const
Definition TypeBase.h:8994
bool isMemberPointerType() const
Definition TypeBase.h:8819
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition TypeBase.h:9260
bool isObjCIdType() const
Definition TypeBase.h:8950
bool isMatrixType() const
Definition TypeBase.h:8901
bool isOverflowBehaviorType() const
Definition TypeBase.h:8909
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9253
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2574
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isEventT() const
Definition TypeBase.h:8986
bool isBFloat16Type() const
Definition TypeBase.h:9131
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2559
bool isFunctionType() const
Definition TypeBase.h:8734
bool isObjCObjectPointerType() const
Definition TypeBase.h:8917
bool isVectorType() const
Definition TypeBase.h:8877
bool isObjCClassType() const
Definition TypeBase.h:8956
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2437
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2720
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2998
bool isHLSLAttributedResourceType() const
Definition TypeBase.h:9067
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:2364
bool isAnyPointerType() const
Definition TypeBase.h:8746
TypeClass getTypeClass() const
Definition TypeBase.h:2449
bool isSamplerT() const
Definition TypeBase.h:8982
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9337
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:690
bool isNullPtrType() const
Definition TypeBase.h:9147
bool isRecordType() const
Definition TypeBase.h:8865
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2288
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition Expr.cpp:1458
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:5188
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:1434
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3372
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition ExprCXX.h:3441
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:463
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4179
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition ExprCXX.h:4287
QualType getBaseType() const
Definition ExprCXX.h:4261
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition ExprCXX.h:4271
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition ExprCXX.h:4252
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:4297
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition ExprCXX.h:4291
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:644
static UserDefinedLiteral * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation LitEndLoc, SourceLocation SuffixLoc, FPOptionsOverride FPFeatures)
Definition ExprCXX.cpp:999
QualType getType() const
Definition Decl.h:724
unsigned getNumElements() const
Definition TypeBase.h:4304
QualType getElementType() const
Definition TypeBase.h:4303
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.
PRESERVE_NONE bool Ret(InterpState &S)
Definition Interp.h:288
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...
Top level wrappers for InstallAPI frontend operations.
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:817
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:828
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:824
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:820
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:65
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
Stmt Stmt * Callback
Definition StmtOpenMP.h:919
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:860
@ ovl_fail_final_conversion_not_exact
This conversion function template specialization candidate is not viable because the final conversion...
Definition Overload.h:888
@ ovl_fail_enable_if
This candidate function was not viable because an enable_if attribute disabled it.
Definition Overload.h:897
@ ovl_fail_illegal_constructor
This conversion candidate was not considered because it is an illegal instantiation of a constructor ...
Definition Overload.h:880
@ ovl_fail_bad_final_conversion
This conversion candidate is not viable because its result type is not implicitly convertible to the ...
Definition Overload.h:884
@ 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:925
@ ovl_fail_too_few_arguments
Definition Overload.h:862
@ ovl_fail_addr_not_available
This candidate was not viable because its address could not be taken.
Definition Overload.h:904
@ ovl_fail_too_many_arguments
Definition Overload.h:861
@ ovl_non_default_multiversion_function
This candidate was not viable because it is a non-default multiversioned function.
Definition Overload.h:912
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition Overload.h:921
@ ovl_fail_bad_conversion
Definition Overload.h:863
@ ovl_fail_bad_target
(CUDA) This candidate was not viable because the callee was not accessible from the caller's target (...
Definition Overload.h:893
@ ovl_fail_bad_deduction
Definition Overload.h:864
@ ovl_fail_inhctor_slice
This inherited constructor is not viable because it would slice the argument.
Definition Overload.h:908
@ ovl_fail_object_addrspace_mismatch
This constructor/conversion candidate fail due to an address space mismatch between the object being ...
Definition Overload.h:917
@ ovl_fail_explicit
This candidate constructor or conversion function is explicit but the context doesn't permit explicit...
Definition Overload.h:901
@ ovl_fail_trivial_conversion
This conversion candidate was not considered because it duplicates the work of a trivial or derived-t...
Definition Overload.h:869
@ Comparison
A comparison.
Definition Sema.h:661
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1801
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition TypeBase.h:1804
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1807
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:162
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:152
Expr::ConstantExprKind ConstantExprKind
Definition Expr.h:1062
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:125
@ AS_none
Definition Specifiers.h:128
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:930
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:906
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
OptionalUnsigned< unsigned > UnsignedOrNone
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
TemplateSpecCandidateSetKind
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:683
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:706
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:727
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:685
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:723
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:581
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:217
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Decl.h:2019
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:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:145
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
bool shouldEnforceArgLimit(bool PartialOverloading, FunctionDecl *Function)
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:147
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:316
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition Template.h:312
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1305
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:374
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:424
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:419
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:422
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:395
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:381
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:417
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:426
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:414
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:384
@ Invalid
The declaration was invalid; do nothing.
Definition Sema.h:378
@ Success
Template argument deduction was successful.
Definition Sema.h:376
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:398
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:387
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:401
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:390
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:411
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:428
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:405
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:408
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:199
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
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:1520
@ None
The alignment was not explicit in code.
Definition ASTContext.h:176
CCEKind
Contexts in which a converted constant expression is required.
Definition Sema.h:832
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:835
@ Noexcept
Condition in a noexcept(bool) specifier.
Definition Sema.h:840
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:838
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:836
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:845
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:839
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:6033
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:442
__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:523
ConversionSet::const_iterator const_iterator
Definition Overload.h:559
SmallVector< std::pair< NamedDecl *, FunctionDecl * >, 4 > ConversionSet
Definition Overload.h:524
void addConversion(NamedDecl *Found, FunctionDecl *D)
Definition Overload.h:550
void copyFrom(const AmbiguousConversionSequence &)
const Expr * ConstraintExpr
Definition Decl.h:89
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:90
QualType getToType() const
Definition Overload.h:608
QualType getFromType() const
Definition Overload.h:607
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:1103
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:666
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:668
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:650
SmallVectorImpl< PartialDiagnosticAt > * ExtendedDiag
Location where we spot ptr to int cast or null subobject while evaluating constant expression in MS c...
Definition Expr.h:654
Extra information about a function prototype.
Definition TypeBase.h:5506
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5511
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition Overload.h:1196
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:1218
bool isReversible() const
Determines whether this operator could be implemented by a function with reversed parameter order.
Definition Overload.h:1245
SourceLocation OpLoc
The source location of the operator.
Definition Overload.h:1207
bool AllowRewrittenCandidates
Whether we should include rewritten candidates in the overload set.
Definition Overload.h:1209
OverloadCandidateRewriteKind getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO)
Determine the kind of rewrite that should be performed for this candidate.
Definition Overload.h:1235
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:934
unsigned StrictPackMatch
Have we matched any packs on the parameter side, versus any non-packs on the argument side,...
Definition Overload.h:999
unsigned IgnoreObjectArgument
IgnoreObjectArgument - True to indicate that the first argument's conversion, which for this function...
Definition Overload.h:990
bool TryToFixBadConversion(unsigned Idx, Sema &S)
Definition Overload.h:1064
bool NotValidBecauseConstraintExprHasError() const
bool isReversed() const
Definition Overload.h:1038
unsigned IsADLCandidate
True if the candidate was found using ADL.
Definition Overload.h:1003
unsigned IsSurrogate
IsSurrogate - True to indicate that this candidate is a surrogate for a conversion to a function poin...
Definition Overload.h:980
QualType BuiltinParamTypes[3]
BuiltinParamTypes - Provides the parameter types of a built-in overload candidate.
Definition Overload.h:948
DeclAccessPair FoundDecl
FoundDecl - The original declaration that was looked up / invented / otherwise found,...
Definition Overload.h:944
FunctionDecl * Function
Function - The actual function that this candidate represents.
Definition Overload.h:939
unsigned RewriteKind
Whether this is a rewritten candidate, and if so, of what kind?
Definition Overload.h:1011
ConversionFixItGenerator Fix
The FixIt hints which can be used to fix the Bad candidate.
Definition Overload.h:960
unsigned Best
Whether this candidate is the best viable function, or tied for being the best viable function.
Definition Overload.h:974
StandardConversionSequence FinalConversion
FinalConversion - For a conversion function (where Function is a CXXConversionDecl),...
Definition Overload.h:1029
unsigned getNumParams() const
Definition Overload.h:1077
unsigned HasFinalConversion
Whether FinalConversion has been set.
Definition Overload.h:1007
unsigned TookAddressOfOverload
Definition Overload.h:993
unsigned FailureKind
FailureKind - The reason why this candidate is not viable.
Definition Overload.h:1016
unsigned ExplicitCallArguments
The number of call arguments that were explicitly provided, to be used while performing partial order...
Definition Overload.h:1020
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition Overload.h:957
DeductionFailureInfo DeductionFailure
Definition Overload.h:1023
unsigned Viable
Viable - True to indicate that this overload candidate is viable.
Definition Overload.h:964
CXXConversionDecl * Surrogate
Surrogate - The conversion function for which this candidate is a surrogate, but only if IsSurrogate ...
Definition Overload.h:952
OverloadCandidateRewriteKind getRewriteKind() const
Get RewriteKind value in OverloadCandidateRewriteKind type (This function is to workaround the spurio...
Definition Overload.h:1034
bool SuppressUserConversions
Do not consider any user-defined conversions when constructing the initializing sequence.
Definition Sema.h:10564
bool OnlyInitializeNonUserDefinedConversions
Before constructing the initializing sequence, we check whether the parameter type and argument type ...
Definition Sema.h:10571
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13209
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13294
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13343
Abstract class used to diagnose incomplete types.
Definition Sema.h:8286
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition TypeBase.h:871
const Type * Ty
The locally-unqualified type.
Definition TypeBase.h:873
Qualifiers Quals
The local qualifiers.
Definition TypeBase.h:876
TemplateSpecCandidate - This is a generalization of OverloadCandidate which keeps track of template a...
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)
void NoteDeductionFailure(Sema &S, bool ForTakingAddress, TemplateSpecCandidateSetKind CandidateSetKind)
Diagnose a template argument deduction failure.
UserDefinedConversionSequence - Represents a user-defined conversion sequence (C++ 13....
Definition Overload.h:478
StandardConversionSequence Before
Represents the standard conversion that occurs before the actual user-defined conversion.
Definition Overload.h:490
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition Overload.h:512
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition Overload.h:503
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition Overload.h:507
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition Overload.h:498
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition Overload.h:517
void dump() const
dump - Print this user-defined conversion sequence to standard error.
Describes an entity that is being assigned.