clang 22.0.0git
SemaOverload.cpp
Go to the documentation of this file.
1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Sema routines for C++ overloading.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
22#include "clang/AST/Type.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Overload.h"
33#include "clang/Sema/SemaARM.h"
34#include "clang/Sema/SemaCUDA.h"
35#include "clang/Sema/SemaObjC.h"
36#include "clang/Sema/Template.h"
38#include "llvm/ADT/DenseSet.h"
39#include "llvm/ADT/STLExtras.h"
40#include "llvm/ADT/STLForwardCompat.h"
41#include "llvm/ADT/ScopeExit.h"
42#include "llvm/ADT/SmallPtrSet.h"
43#include "llvm/ADT/SmallVector.h"
44#include <algorithm>
45#include <cassert>
46#include <cstddef>
47#include <cstdlib>
48#include <optional>
49
50using namespace clang;
51using namespace sema;
52
54
56 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
57 return P->hasAttr<PassObjectSizeAttr>();
58 });
59}
60
61/// A convenience routine for creating a decayed reference to a function.
63 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
64 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
65 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
66 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
67 return ExprError();
68 // If FoundDecl is different from Fn (such as if one is a template
69 // and the other a specialization), make sure DiagnoseUseOfDecl is
70 // called on both.
71 // FIXME: This would be more comprehensively addressed by modifying
72 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
73 // being used.
74 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
75 return ExprError();
76 DeclRefExpr *DRE = new (S.Context)
77 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
78 if (HadMultipleCandidates)
79 DRE->setHadMultipleCandidates(true);
80
82 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
83 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
85 DRE->setType(Fn->getType());
86 }
87 }
88 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
89 CK_FunctionToPointerDecay);
90}
91
92static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
93 bool InOverloadResolution,
95 bool CStyle,
96 bool AllowObjCWritebackConversion);
97
99 QualType &ToType,
100 bool InOverloadResolution,
102 bool CStyle);
104IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
106 OverloadCandidateSet& Conversions,
107 AllowedExplicit AllowExplicit,
108 bool AllowObjCConversionOnExplicit);
109
112 const StandardConversionSequence& SCS1,
113 const StandardConversionSequence& SCS2);
114
117 const StandardConversionSequence& SCS1,
118 const StandardConversionSequence& SCS2);
119
122 const StandardConversionSequence& SCS1,
123 const StandardConversionSequence& SCS2);
124
125/// GetConversionRank - Retrieve the implicit conversion rank
126/// corresponding to the given implicit conversion kind.
128 static const ImplicitConversionRank Rank[] = {
155 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
156 // it was omitted by the patch that added
157 // ICK_Zero_Event_Conversion
158 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
159 // it was omitted by the patch that added
160 // ICK_Zero_Queue_Conversion
167 };
168 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
169 return Rank[(int)Kind];
170}
171
174 ImplicitConversionKind Dimension) {
176 if (Rank == ICR_HLSL_Scalar_Widening) {
177 if (Base == ICR_Promotion)
179 if (Base == ICR_Conversion)
181 }
182 if (Rank == ICR_HLSL_Dimension_Reduction) {
183 if (Base == ICR_Promotion)
185 if (Base == ICR_Conversion)
187 }
188 return Rank;
189}
190
191/// GetImplicitConversionName - Return the name of this kind of
192/// implicit conversion.
194 static const char *const Name[] = {
195 "No conversion",
196 "Lvalue-to-rvalue",
197 "Array-to-pointer",
198 "Function-to-pointer",
199 "Function pointer conversion",
200 "Qualification",
201 "Integral promotion",
202 "Floating point promotion",
203 "Complex promotion",
204 "Integral conversion",
205 "Floating conversion",
206 "Complex conversion",
207 "Floating-integral conversion",
208 "Pointer conversion",
209 "Pointer-to-member conversion",
210 "Boolean conversion",
211 "Compatible-types conversion",
212 "Derived-to-base conversion",
213 "Vector conversion",
214 "SVE Vector conversion",
215 "RVV Vector conversion",
216 "Vector splat",
217 "Complex-real conversion",
218 "Block Pointer conversion",
219 "Transparent Union Conversion",
220 "Writeback conversion",
221 "OpenCL Zero Event Conversion",
222 "OpenCL Zero Queue Conversion",
223 "C specific type conversion",
224 "Incompatible pointer conversion",
225 "Fixed point conversion",
226 "HLSL vector truncation",
227 "Non-decaying array conversion",
228 "HLSL vector splat",
229 };
230 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
231 return Name[Kind];
232}
233
234/// StandardConversionSequence - Set the standard conversion
235/// sequence to the identity conversion.
243 ReferenceBinding = false;
244 DirectBinding = false;
245 IsLvalueReference = true;
246 BindsToFunctionLvalue = false;
247 BindsToRvalue = false;
250 FromBracedInitList = false;
251 CopyConstructor = nullptr;
252}
253
254/// getRank - Retrieve the rank of this standard conversion sequence
255/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
256/// implicit conversions.
259 if (GetConversionRank(First) > Rank)
260 Rank = GetConversionRank(First);
261 if (GetConversionRank(Second) > Rank)
263 if (GetDimensionConversionRank(Rank, Dimension) > Rank)
265 if (GetConversionRank(Third) > Rank)
266 Rank = GetConversionRank(Third);
267 return Rank;
268}
269
270/// isPointerConversionToBool - Determines whether this conversion is
271/// a conversion of a pointer or pointer-to-member to bool. This is
272/// used as part of the ranking of standard conversion sequences
273/// (C++ 13.3.3.2p4).
275 // Note that FromType has not necessarily been transformed by the
276 // array-to-pointer or function-to-pointer implicit conversions, so
277 // check for their presence as well as checking whether FromType is
278 // a pointer.
279 if (getToType(1)->isBooleanType() &&
280 (getFromType()->isPointerType() ||
281 getFromType()->isMemberPointerType() ||
282 getFromType()->isObjCObjectPointerType() ||
283 getFromType()->isBlockPointerType() ||
285 return true;
286
287 return false;
288}
289
290/// isPointerConversionToVoidPointer - Determines whether this
291/// conversion is a conversion of a pointer to a void pointer. This is
292/// used as part of the ranking of standard conversion sequences (C++
293/// 13.3.3.2p4).
294bool
297 QualType FromType = getFromType();
298 QualType ToType = getToType(1);
299
300 // Note that FromType has not necessarily been transformed by the
301 // array-to-pointer implicit conversion, so check for its presence
302 // and redo the conversion to get a pointer.
304 FromType = Context.getArrayDecayedType(FromType);
305
306 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
307 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
308 return ToPtrType->getPointeeType()->isVoidType();
309
310 return false;
311}
312
313/// Skip any implicit casts which could be either part of a narrowing conversion
314/// or after one in an implicit conversion.
316 const Expr *Converted) {
317 // We can have cleanups wrapping the converted expression; these need to be
318 // preserved so that destructors run if necessary.
319 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
320 Expr *Inner =
321 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
322 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
323 EWC->getObjects());
324 }
325
326 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
327 switch (ICE->getCastKind()) {
328 case CK_NoOp:
329 case CK_IntegralCast:
330 case CK_IntegralToBoolean:
331 case CK_IntegralToFloating:
332 case CK_BooleanToSignedIntegral:
333 case CK_FloatingToIntegral:
334 case CK_FloatingToBoolean:
335 case CK_FloatingCast:
336 Converted = ICE->getSubExpr();
337 continue;
338
339 default:
340 return Converted;
341 }
342 }
343
344 return Converted;
345}
346
347/// Check if this standard conversion sequence represents a narrowing
348/// conversion, according to C++11 [dcl.init.list]p7.
349///
350/// \param Ctx The AST context.
351/// \param Converted The result of applying this standard conversion sequence.
352/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
353/// value of the expression prior to the narrowing conversion.
354/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
355/// type of the expression prior to the narrowing conversion.
356/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
357/// from floating point types to integral types should be ignored.
359 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
360 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
361 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
362 "narrowing check outside C++");
363
364 // C++11 [dcl.init.list]p7:
365 // A narrowing conversion is an implicit conversion ...
366 QualType FromType = getToType(0);
367 QualType ToType = getToType(1);
368
369 // A conversion to an enumeration type is narrowing if the conversion to
370 // the underlying type is narrowing. This only arises for expressions of
371 // the form 'Enum{init}'.
372 if (const auto *ED = ToType->getAsEnumDecl())
373 ToType = ED->getIntegerType();
374
375 switch (Second) {
376 // 'bool' is an integral type; dispatch to the right place to handle it.
378 if (FromType->isRealFloatingType())
379 goto FloatingIntegralConversion;
381 goto IntegralConversion;
382 // -- from a pointer type or pointer-to-member type to bool, or
383 return NK_Type_Narrowing;
384
385 // -- from a floating-point type to an integer type, or
386 //
387 // -- from an integer type or unscoped enumeration type to a floating-point
388 // type, except where the source is a constant expression and the actual
389 // value after conversion will fit into the target type and will produce
390 // the original value when converted back to the original type, or
392 FloatingIntegralConversion:
393 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
394 return NK_Type_Narrowing;
395 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
396 ToType->isRealFloatingType()) {
397 if (IgnoreFloatToIntegralConversion)
398 return NK_Not_Narrowing;
399 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
400 assert(Initializer && "Unknown conversion expression");
401
402 // If it's value-dependent, we can't tell whether it's narrowing.
403 if (Initializer->isValueDependent())
405
406 if (std::optional<llvm::APSInt> IntConstantValue =
407 Initializer->getIntegerConstantExpr(Ctx)) {
408 // Convert the integer to the floating type.
409 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
410 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
411 llvm::APFloat::rmNearestTiesToEven);
412 // And back.
413 llvm::APSInt ConvertedValue = *IntConstantValue;
414 bool ignored;
415 Result.convertToInteger(ConvertedValue,
416 llvm::APFloat::rmTowardZero, &ignored);
417 // If the resulting value is different, this was a narrowing conversion.
418 if (*IntConstantValue != ConvertedValue) {
419 ConstantValue = APValue(*IntConstantValue);
420 ConstantType = Initializer->getType();
422 }
423 } else {
424 // Variables are always narrowings.
426 }
427 }
428 return NK_Not_Narrowing;
429
430 // -- from long double to double or float, or from double to float, except
431 // where the source is a constant expression and the actual value after
432 // conversion is within the range of values that can be represented (even
433 // if it cannot be represented exactly), or
435 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
436 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
437 // FromType is larger than ToType.
438 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
439
440 // If it's value-dependent, we can't tell whether it's narrowing.
441 if (Initializer->isValueDependent())
443
445 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
446 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
447 // Constant!
448 if (Ctx.getLangOpts().C23)
449 ConstantValue = R.Val;
450 assert(ConstantValue.isFloat());
451 llvm::APFloat FloatVal = ConstantValue.getFloat();
452 // Convert the source value into the target type.
453 bool ignored;
454 llvm::APFloat Converted = FloatVal;
455 llvm::APFloat::opStatus ConvertStatus =
456 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
457 llvm::APFloat::rmNearestTiesToEven, &ignored);
458 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
459 llvm::APFloat::rmNearestTiesToEven, &ignored);
460 if (Ctx.getLangOpts().C23) {
461 if (FloatVal.isNaN() && Converted.isNaN() &&
462 !FloatVal.isSignaling() && !Converted.isSignaling()) {
463 // Quiet NaNs are considered the same value, regardless of
464 // payloads.
465 return NK_Not_Narrowing;
466 }
467 // For normal values, check exact equality.
468 if (!Converted.bitwiseIsEqual(FloatVal)) {
469 ConstantType = Initializer->getType();
471 }
472 } else {
473 // If there was no overflow, the source value is within the range of
474 // values that can be represented.
475 if (ConvertStatus & llvm::APFloat::opOverflow) {
476 ConstantType = Initializer->getType();
478 }
479 }
480 } else {
482 }
483 }
484 return NK_Not_Narrowing;
485
486 // -- from an integer type or unscoped enumeration type to an integer type
487 // that cannot represent all the values of the original type, except where
488 // (CWG2627) -- the source is a bit-field whose width w is less than that
489 // of its type (or, for an enumeration type, its underlying type) and the
490 // target type can represent all the values of a hypothetical extended
491 // integer type with width w and with the same signedness as the original
492 // type or
493 // -- the source is a constant expression and the actual value after
494 // conversion will fit into the target type and will produce the original
495 // value when converted back to the original type.
497 IntegralConversion: {
498 assert(FromType->isIntegralOrUnscopedEnumerationType());
499 assert(ToType->isIntegralOrUnscopedEnumerationType());
500 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
501 unsigned FromWidth = Ctx.getIntWidth(FromType);
502 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
503 const unsigned ToWidth = Ctx.getIntWidth(ToType);
504
505 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
506 bool ToSigned, unsigned ToWidth) {
507 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
508 !(FromSigned && !ToSigned);
509 };
510
511 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
512 return NK_Not_Narrowing;
513
514 // Not all values of FromType can be represented in ToType.
515 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
516
517 bool DependentBitField = false;
518 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
519 if (BitField->getBitWidth()->isValueDependent())
520 DependentBitField = true;
521 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
522 BitFieldWidth < FromWidth) {
523 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
524 return NK_Not_Narrowing;
525
526 // The initializer will be truncated to the bit-field width
527 FromWidth = BitFieldWidth;
528 }
529 }
530
531 // If it's value-dependent, we can't tell whether it's narrowing.
532 if (Initializer->isValueDependent())
534
535 std::optional<llvm::APSInt> OptInitializerValue =
536 Initializer->getIntegerConstantExpr(Ctx);
537 if (!OptInitializerValue) {
538 // If the bit-field width was dependent, it might end up being small
539 // enough to fit in the target type (unless the target type is unsigned
540 // and the source type is signed, in which case it will never fit)
541 if (DependentBitField && !(FromSigned && !ToSigned))
543
544 // Otherwise, such a conversion is always narrowing
546 }
547 llvm::APSInt &InitializerValue = *OptInitializerValue;
548 bool Narrowing = false;
549 if (FromWidth < ToWidth) {
550 // Negative -> unsigned is narrowing. Otherwise, more bits is never
551 // narrowing.
552 if (InitializerValue.isSigned() && InitializerValue.isNegative())
553 Narrowing = true;
554 } else {
555 // Add a bit to the InitializerValue so we don't have to worry about
556 // signed vs. unsigned comparisons.
557 InitializerValue =
558 InitializerValue.extend(InitializerValue.getBitWidth() + 1);
559 // Convert the initializer to and from the target width and signed-ness.
560 llvm::APSInt ConvertedValue = InitializerValue;
561 ConvertedValue = ConvertedValue.trunc(ToWidth);
562 ConvertedValue.setIsSigned(ToSigned);
563 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
564 ConvertedValue.setIsSigned(InitializerValue.isSigned());
565 // If the result is different, this was a narrowing conversion.
566 if (ConvertedValue != InitializerValue)
567 Narrowing = true;
568 }
569 if (Narrowing) {
570 ConstantType = Initializer->getType();
571 ConstantValue = APValue(InitializerValue);
573 }
574
575 return NK_Not_Narrowing;
576 }
577 case ICK_Complex_Real:
578 if (FromType->isComplexType() && !ToType->isComplexType())
579 return NK_Type_Narrowing;
580 return NK_Not_Narrowing;
581
583 if (Ctx.getLangOpts().C23) {
584 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
586 if (Initializer->EvaluateAsRValue(R, Ctx)) {
587 ConstantValue = R.Val;
588 assert(ConstantValue.isFloat());
589 llvm::APFloat FloatVal = ConstantValue.getFloat();
590 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
591 // value, the unqualified versions of the type of the initializer and
592 // the corresponding real type of the object declared shall be
593 // compatible.
594 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
595 ConstantType = Initializer->getType();
597 }
598 }
599 }
600 return NK_Not_Narrowing;
601 default:
602 // Other kinds of conversions are not narrowings.
603 return NK_Not_Narrowing;
604 }
605}
606
607/// dump - Print this standard conversion sequence to standard
608/// error. Useful for debugging overloading issues.
609LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
610 raw_ostream &OS = llvm::errs();
611 bool PrintedSomething = false;
612 if (First != ICK_Identity) {
614 PrintedSomething = true;
615 }
616
617 if (Second != ICK_Identity) {
618 if (PrintedSomething) {
619 OS << " -> ";
620 }
622
623 if (CopyConstructor) {
624 OS << " (by copy constructor)";
625 } else if (DirectBinding) {
626 OS << " (direct reference binding)";
627 } else if (ReferenceBinding) {
628 OS << " (reference binding)";
629 }
630 PrintedSomething = true;
631 }
632
633 if (Third != ICK_Identity) {
634 if (PrintedSomething) {
635 OS << " -> ";
636 }
638 PrintedSomething = true;
639 }
640
641 if (!PrintedSomething) {
642 OS << "No conversions required";
643 }
644}
645
646/// dump - Print this user-defined conversion sequence to standard
647/// error. Useful for debugging overloading issues.
649 raw_ostream &OS = llvm::errs();
650 if (Before.First || Before.Second || Before.Third) {
651 Before.dump();
652 OS << " -> ";
653 }
655 OS << '\'' << *ConversionFunction << '\'';
656 else
657 OS << "aggregate initialization";
658 if (After.First || After.Second || After.Third) {
659 OS << " -> ";
660 After.dump();
661 }
662}
663
664/// dump - Print this implicit conversion sequence to standard
665/// error. Useful for debugging overloading issues.
667 raw_ostream &OS = llvm::errs();
669 OS << "Worst list element conversion: ";
670 switch (ConversionKind) {
672 OS << "Standard conversion: ";
673 Standard.dump();
674 break;
676 OS << "User-defined conversion: ";
678 break;
680 OS << "Ellipsis conversion";
681 break;
683 OS << "Ambiguous conversion";
684 break;
685 case BadConversion:
686 OS << "Bad conversion";
687 break;
688 }
689
690 OS << "\n";
691}
692
694 new (&conversions()) ConversionSet();
695}
696
698 conversions().~ConversionSet();
699}
700
701void
706}
707
708namespace {
709 // Structure used by DeductionFailureInfo to store
710 // template argument information.
711 struct DFIArguments {
712 TemplateArgument FirstArg;
713 TemplateArgument SecondArg;
714 };
715 // Structure used by DeductionFailureInfo to store
716 // template parameter and template argument information.
717 struct DFIParamWithArguments : DFIArguments {
718 TemplateParameter Param;
719 };
720 // Structure used by DeductionFailureInfo to store template argument
721 // information and the index of the problematic call argument.
722 struct DFIDeducedMismatchArgs : DFIArguments {
723 TemplateArgumentList *TemplateArgs;
724 unsigned CallArgIndex;
725 };
726 // Structure used by DeductionFailureInfo to store information about
727 // unsatisfied constraints.
728 struct CNSInfo {
729 TemplateArgumentList *TemplateArgs;
730 ConstraintSatisfaction Satisfaction;
731 };
732}
733
734/// Convert from Sema's representation of template deduction information
735/// to the form used in overload-candidate information.
739 TemplateDeductionInfo &Info) {
741 Result.Result = static_cast<unsigned>(TDK);
742 Result.HasDiagnostic = false;
743 switch (TDK) {
750 Result.Data = nullptr;
751 break;
752
755 Result.Data = Info.Param.getOpaqueValue();
756 break;
757
760 // FIXME: Should allocate from normal heap so that we can free this later.
761 auto *Saved = new (Context) DFIDeducedMismatchArgs;
762 Saved->FirstArg = Info.FirstArg;
763 Saved->SecondArg = Info.SecondArg;
764 Saved->TemplateArgs = Info.takeSugared();
765 Saved->CallArgIndex = Info.CallArgIndex;
766 Result.Data = Saved;
767 break;
768 }
769
771 // FIXME: Should allocate from normal heap so that we can free this later.
772 DFIArguments *Saved = new (Context) DFIArguments;
773 Saved->FirstArg = Info.FirstArg;
774 Saved->SecondArg = Info.SecondArg;
775 Result.Data = Saved;
776 break;
777 }
778
780 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
783 // FIXME: Should allocate from normal heap so that we can free this later.
784 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
785 Saved->Param = Info.Param;
786 Saved->FirstArg = Info.FirstArg;
787 Saved->SecondArg = Info.SecondArg;
788 Result.Data = Saved;
789 break;
790 }
791
793 Result.Data = Info.takeSugared();
794 if (Info.hasSFINAEDiagnostic()) {
798 Result.HasDiagnostic = true;
799 }
800 break;
801
803 CNSInfo *Saved = new (Context) CNSInfo;
804 Saved->TemplateArgs = Info.takeSugared();
805 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
806 Result.Data = Saved;
807 break;
808 }
809
813 llvm_unreachable("not a deduction failure");
814 }
815
816 return Result;
817}
818
820 switch (static_cast<TemplateDeductionResult>(Result)) {
830 break;
831
838 // FIXME: Destroy the data?
839 Data = nullptr;
840 break;
841
843 // FIXME: Destroy the template argument list?
844 Data = nullptr;
846 Diag->~PartialDiagnosticAt();
847 HasDiagnostic = false;
848 }
849 break;
850
852 // FIXME: Destroy the template argument list?
853 Data = nullptr;
855 Diag->~PartialDiagnosticAt();
856 HasDiagnostic = false;
857 }
858 break;
859
860 // Unhandled
863 break;
864 }
865}
866
868 if (HasDiagnostic)
869 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
870 return nullptr;
871}
872
874 switch (static_cast<TemplateDeductionResult>(Result)) {
887 return TemplateParameter();
888
891 return TemplateParameter::getFromOpaqueValue(Data);
892
896 return static_cast<DFIParamWithArguments*>(Data)->Param;
897
898 // Unhandled
901 break;
902 }
903
904 return TemplateParameter();
905}
906
908 switch (static_cast<TemplateDeductionResult>(Result)) {
922 return nullptr;
923
926 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
927
929 return static_cast<TemplateArgumentList*>(Data);
930
932 return static_cast<CNSInfo*>(Data)->TemplateArgs;
933
934 // Unhandled
937 break;
938 }
939
940 return nullptr;
941}
942
944 switch (static_cast<TemplateDeductionResult>(Result)) {
956 return nullptr;
957
964 return &static_cast<DFIArguments*>(Data)->FirstArg;
965
966 // Unhandled
969 break;
970 }
971
972 return nullptr;
973}
974
976 switch (static_cast<TemplateDeductionResult>(Result)) {
989 return nullptr;
990
996 return &static_cast<DFIArguments*>(Data)->SecondArg;
997
998 // Unhandled
1001 break;
1002 }
1003
1004 return nullptr;
1005}
1006
1008 switch (static_cast<TemplateDeductionResult>(Result)) {
1011 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1012
1013 default:
1014 return std::nullopt;
1015 }
1016}
1017
1019 const FunctionDecl *Y) {
1020 if (!X || !Y)
1021 return false;
1022 if (X->getNumParams() != Y->getNumParams())
1023 return false;
1024 // FIXME: when do rewritten comparison operators
1025 // with explicit object parameters correspond?
1026 // https://cplusplus.github.io/CWG/issues/2797.html
1027 for (unsigned I = 0; I < X->getNumParams(); ++I)
1028 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1029 Y->getParamDecl(I)->getType()))
1030 return false;
1031 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1032 auto *FTY = Y->getDescribedFunctionTemplate();
1033 if (!FTY)
1034 return false;
1035 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1036 FTY->getTemplateParameters()))
1037 return false;
1038 }
1039 return true;
1040}
1041
1043 Expr *FirstOperand, FunctionDecl *EqFD) {
1044 assert(EqFD->getOverloadedOperator() ==
1045 OverloadedOperatorKind::OO_EqualEqual);
1046 // C++2a [over.match.oper]p4:
1047 // A non-template function or function template F named operator== is a
1048 // rewrite target with first operand o unless a search for the name operator!=
1049 // in the scope S from the instantiation context of the operator expression
1050 // finds a function or function template that would correspond
1051 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1052 // scope of the class type of o if F is a class member, and the namespace
1053 // scope of which F is a member otherwise. A function template specialization
1054 // named operator== is a rewrite target if its function template is a rewrite
1055 // target.
1057 OverloadedOperatorKind::OO_ExclaimEqual);
1058 if (isa<CXXMethodDecl>(EqFD)) {
1059 // If F is a class member, search scope is class type of first operand.
1060 QualType RHS = FirstOperand->getType();
1061 auto *RHSRec = RHS->getAsCXXRecordDecl();
1062 if (!RHSRec)
1063 return true;
1064 LookupResult Members(S, NotEqOp, OpLoc,
1066 S.LookupQualifiedName(Members, RHSRec);
1067 Members.suppressAccessDiagnostics();
1068 for (NamedDecl *Op : Members)
1069 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1070 return false;
1071 return true;
1072 }
1073 // Otherwise the search scope is the namespace scope of which F is a member.
1074 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1075 auto *NotEqFD = Op->getAsFunction();
1076 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1077 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1078 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1080 cast<Decl>(Op->getLexicalDeclContext())))
1081 return false;
1082 }
1083 return true;
1084}
1085
1089 return false;
1090 return Op == OO_EqualEqual || Op == OO_Spaceship;
1091}
1092
1094 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
1095 auto Op = FD->getOverloadedOperator();
1096 if (!allowsReversed(Op))
1097 return false;
1098 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1099 assert(OriginalArgs.size() == 2);
1101 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1102 return false;
1103 }
1104 // Don't bother adding a reversed candidate that can never be a better
1105 // match than the non-reversed version.
1106 return FD->getNumNonObjectParams() != 2 ||
1108 FD->getParamDecl(1)->getType()) ||
1109 FD->hasAttr<EnableIfAttr>();
1110}
1111
1112void OverloadCandidateSet::destroyCandidates() {
1113 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1114 for (auto &C : i->Conversions)
1115 C.~ImplicitConversionSequence();
1116 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1117 i->DeductionFailure.Destroy();
1118 }
1119}
1120
1122 destroyCandidates();
1123 SlabAllocator.Reset();
1124 NumInlineBytesUsed = 0;
1125 Candidates.clear();
1126 Functions.clear();
1127 Kind = CSK;
1128 FirstDeferredCandidate = nullptr;
1129 DeferredCandidatesCount = 0;
1130 HasDeferredTemplateConstructors = false;
1131 ResolutionByPerfectCandidateIsDisabled = false;
1132}
1133
1134namespace {
1135 class UnbridgedCastsSet {
1136 struct Entry {
1137 Expr **Addr;
1138 Expr *Saved;
1139 };
1140 SmallVector<Entry, 2> Entries;
1141
1142 public:
1143 void save(Sema &S, Expr *&E) {
1144 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1145 Entry entry = { &E, E };
1146 Entries.push_back(entry);
1148 }
1149
1150 void restore() {
1152 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1153 *i->Addr = i->Saved;
1154 }
1155 };
1156}
1157
1158/// checkPlaceholderForOverload - Do any interesting placeholder-like
1159/// preprocessing on the given expression.
1160///
1161/// \param unbridgedCasts a collection to which to add unbridged casts;
1162/// without this, they will be immediately diagnosed as errors
1163///
1164/// Return true on unrecoverable error.
1165static bool
1167 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1168 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1169 // We can't handle overloaded expressions here because overload
1170 // resolution might reasonably tweak them.
1171 if (placeholder->getKind() == BuiltinType::Overload) return false;
1172
1173 // If the context potentially accepts unbridged ARC casts, strip
1174 // the unbridged cast and add it to the collection for later restoration.
1175 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1176 unbridgedCasts) {
1177 unbridgedCasts->save(S, E);
1178 return false;
1179 }
1180
1181 // Go ahead and check everything else.
1182 ExprResult result = S.CheckPlaceholderExpr(E);
1183 if (result.isInvalid())
1184 return true;
1185
1186 E = result.get();
1187 return false;
1188 }
1189
1190 // Nothing to do.
1191 return false;
1192}
1193
1194/// checkArgPlaceholdersForOverload - Check a set of call operands for
1195/// placeholders.
1197 UnbridgedCastsSet &unbridged) {
1198 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1199 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1200 return true;
1201
1202 return false;
1203}
1204
1206 const LookupResult &Old, NamedDecl *&Match,
1207 bool NewIsUsingDecl) {
1208 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1209 I != E; ++I) {
1210 NamedDecl *OldD = *I;
1211
1212 bool OldIsUsingDecl = false;
1213 if (isa<UsingShadowDecl>(OldD)) {
1214 OldIsUsingDecl = true;
1215
1216 // We can always introduce two using declarations into the same
1217 // context, even if they have identical signatures.
1218 if (NewIsUsingDecl) continue;
1219
1220 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1221 }
1222
1223 // A using-declaration does not conflict with another declaration
1224 // if one of them is hidden.
1225 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1226 continue;
1227
1228 // If either declaration was introduced by a using declaration,
1229 // we'll need to use slightly different rules for matching.
1230 // Essentially, these rules are the normal rules, except that
1231 // function templates hide function templates with different
1232 // return types or template parameter lists.
1233 bool UseMemberUsingDeclRules =
1234 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1235 !New->getFriendObjectKind();
1236
1237 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1238 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1239 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1240 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1241 continue;
1242 }
1243
1244 if (!isa<FunctionTemplateDecl>(OldD) &&
1245 !shouldLinkPossiblyHiddenDecl(*I, New))
1246 continue;
1247
1248 Match = *I;
1249 return OverloadKind::Match;
1250 }
1251
1252 // Builtins that have custom typechecking or have a reference should
1253 // not be overloadable or redeclarable.
1254 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1255 Match = *I;
1257 }
1258 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1259 // We can overload with these, which can show up when doing
1260 // redeclaration checks for UsingDecls.
1261 assert(Old.getLookupKind() == LookupUsingDeclName);
1262 } else if (isa<TagDecl>(OldD)) {
1263 // We can always overload with tags by hiding them.
1264 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1265 // Optimistically assume that an unresolved using decl will
1266 // overload; if it doesn't, we'll have to diagnose during
1267 // template instantiation.
1268 //
1269 // Exception: if the scope is dependent and this is not a class
1270 // member, the using declaration can only introduce an enumerator.
1271 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1272 Match = *I;
1274 }
1275 } else {
1276 // (C++ 13p1):
1277 // Only function declarations can be overloaded; object and type
1278 // declarations cannot be overloaded.
1279 Match = *I;
1281 }
1282 }
1283
1284 // C++ [temp.friend]p1:
1285 // For a friend function declaration that is not a template declaration:
1286 // -- if the name of the friend is a qualified or unqualified template-id,
1287 // [...], otherwise
1288 // -- if the name of the friend is a qualified-id and a matching
1289 // non-template function is found in the specified class or namespace,
1290 // the friend declaration refers to that function, otherwise,
1291 // -- if the name of the friend is a qualified-id and a matching function
1292 // template is found in the specified class or namespace, the friend
1293 // declaration refers to the deduced specialization of that function
1294 // template, otherwise
1295 // -- the name shall be an unqualified-id [...]
1296 // If we get here for a qualified friend declaration, we've just reached the
1297 // third bullet. If the type of the friend is dependent, skip this lookup
1298 // until instantiation.
1299 if (New->getFriendObjectKind() && New->getQualifier() &&
1300 !New->getDescribedFunctionTemplate() &&
1301 !New->getDependentSpecializationInfo() &&
1302 !New->getType()->isDependentType()) {
1303 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1304 TemplateSpecResult.addAllDecls(Old);
1305 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1306 /*QualifiedFriend*/true)) {
1307 New->setInvalidDecl();
1309 }
1310
1311 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1312 return OverloadKind::Match;
1313 }
1314
1316}
1317
1318template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1319 assert(D && "function decl should not be null");
1320 if (auto *A = D->getAttr<AttrT>())
1321 return !A->isImplicit();
1322 return false;
1323}
1324
1326 FunctionDecl *Old,
1327 bool UseMemberUsingDeclRules,
1328 bool ConsiderCudaAttrs,
1329 bool UseOverrideRules = false) {
1330 // C++ [basic.start.main]p2: This function shall not be overloaded.
1331 if (New->isMain())
1332 return false;
1333
1334 // MSVCRT user defined entry points cannot be overloaded.
1335 if (New->isMSVCRTEntryPoint())
1336 return false;
1337
1338 NamedDecl *OldDecl = Old;
1339 NamedDecl *NewDecl = New;
1341 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1342
1343 // C++ [temp.fct]p2:
1344 // A function template can be overloaded with other function templates
1345 // and with normal (non-template) functions.
1346 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1347 return true;
1348
1349 // Is the function New an overload of the function Old?
1350 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1351 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1352
1353 // Compare the signatures (C++ 1.3.10) of the two functions to
1354 // determine whether they are overloads. If we find any mismatch
1355 // in the signature, they are overloads.
1356
1357 // If either of these functions is a K&R-style function (no
1358 // prototype), then we consider them to have matching signatures.
1359 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1360 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1361 return false;
1362
1363 const auto *OldType = cast<FunctionProtoType>(OldQType);
1364 const auto *NewType = cast<FunctionProtoType>(NewQType);
1365
1366 // The signature of a function includes the types of its
1367 // parameters (C++ 1.3.10), which includes the presence or absence
1368 // of the ellipsis; see C++ DR 357).
1369 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1370 return true;
1371
1372 // For member-like friends, the enclosing class is part of the signature.
1373 if ((New->isMemberLikeConstrainedFriend() ||
1375 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1376 return true;
1377
1378 // Compare the parameter lists.
1379 // This can only be done once we have establish that friend functions
1380 // inhabit the same context, otherwise we might tried to instantiate
1381 // references to non-instantiated entities during constraint substitution.
1382 // GH78101.
1383 if (NewTemplate) {
1384 OldDecl = OldTemplate;
1385 NewDecl = NewTemplate;
1386 // C++ [temp.over.link]p4:
1387 // The signature of a function template consists of its function
1388 // signature, its return type and its template parameter list. The names
1389 // of the template parameters are significant only for establishing the
1390 // relationship between the template parameters and the rest of the
1391 // signature.
1392 //
1393 // We check the return type and template parameter lists for function
1394 // templates first; the remaining checks follow.
1395 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1396 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1397 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1398 bool SameReturnType = SemaRef.Context.hasSameType(
1399 Old->getDeclaredReturnType(), New->getDeclaredReturnType());
1400 // FIXME(GH58571): Match template parameter list even for non-constrained
1401 // template heads. This currently ensures that the code prior to C++20 is
1402 // not newly broken.
1403 bool ConstraintsInTemplateHead =
1406 // C++ [namespace.udecl]p11:
1407 // The set of declarations named by a using-declarator that inhabits a
1408 // class C does not include member functions and member function
1409 // templates of a base class that "correspond" to (and thus would
1410 // conflict with) a declaration of a function or function template in
1411 // C.
1412 // Comparing return types is not required for the "correspond" check to
1413 // decide whether a member introduced by a shadow declaration is hidden.
1414 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1415 !SameTemplateParameterList)
1416 return true;
1417 if (!UseMemberUsingDeclRules &&
1418 (!SameTemplateParameterList || !SameReturnType))
1419 return true;
1420 }
1421
1422 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1423 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1424
1425 int OldParamsOffset = 0;
1426 int NewParamsOffset = 0;
1427
1428 // When determining if a method is an overload from a base class, act as if
1429 // the implicit object parameter are of the same type.
1430
1431 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1433 auto ThisType = M->getFunctionObjectParameterReferenceType();
1434 if (ThisType.isConstQualified())
1435 Q.removeConst();
1436 return Q;
1437 }
1438
1439 // We do not allow overloading based off of '__restrict'.
1440 Q.removeRestrict();
1441
1442 // We may not have applied the implicit const for a constexpr member
1443 // function yet (because we haven't yet resolved whether this is a static
1444 // or non-static member function). Add it now, on the assumption that this
1445 // is a redeclaration of OldMethod.
1446 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1447 (M->isConstexpr() || M->isConsteval()) &&
1448 !isa<CXXConstructorDecl>(NewMethod))
1449 Q.addConst();
1450 return Q;
1451 };
1452
1453 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1454 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1455 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1456
1457 if (OldMethod->isExplicitObjectMemberFunction()) {
1458 BS.Quals.removeVolatile();
1459 DS.Quals.removeVolatile();
1460 }
1461
1462 return BS.Quals == DS.Quals;
1463 };
1464
1465 auto CompareType = [&](QualType Base, QualType D) {
1466 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1467 auto DS = D.getNonReferenceType().getCanonicalType().split();
1468
1469 if (!AreQualifiersEqual(BS, DS))
1470 return false;
1471
1472 if (OldMethod->isImplicitObjectMemberFunction() &&
1473 OldMethod->getParent() != NewMethod->getParent()) {
1474 CanQualType ParentType =
1475 SemaRef.Context.getCanonicalTagType(OldMethod->getParent());
1476 if (ParentType.getTypePtr() != BS.Ty)
1477 return false;
1478 BS.Ty = DS.Ty;
1479 }
1480
1481 // FIXME: should we ignore some type attributes here?
1482 if (BS.Ty != DS.Ty)
1483 return false;
1484
1485 if (Base->isLValueReferenceType())
1486 return D->isLValueReferenceType();
1487 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1488 };
1489
1490 // If the function is a class member, its signature includes the
1491 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1492 auto DiagnoseInconsistentRefQualifiers = [&]() {
1493 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1494 return false;
1495 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1496 return false;
1497 if (OldMethod->isExplicitObjectMemberFunction() ||
1498 NewMethod->isExplicitObjectMemberFunction())
1499 return false;
1500 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1501 NewMethod->getRefQualifier() == RQ_None)) {
1502 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1503 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1504 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1505 return true;
1506 }
1507 return false;
1508 };
1509
1510 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1511 OldParamsOffset++;
1512 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1513 NewParamsOffset++;
1514
1515 if (OldType->getNumParams() - OldParamsOffset !=
1516 NewType->getNumParams() - NewParamsOffset ||
1518 {OldType->param_type_begin() + OldParamsOffset,
1519 OldType->param_type_end()},
1520 {NewType->param_type_begin() + NewParamsOffset,
1521 NewType->param_type_end()},
1522 nullptr)) {
1523 return true;
1524 }
1525
1526 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1527 !NewMethod->isStatic()) {
1528 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1529 const CXXMethodDecl *New) {
1530 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1531 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1532
1533 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1534 return F->getRefQualifier() == RQ_None &&
1535 !F->isExplicitObjectMemberFunction();
1536 };
1537
1538 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1539 CompareType(OldObjectType.getNonReferenceType(),
1540 NewObjectType.getNonReferenceType()))
1541 return true;
1542 return CompareType(OldObjectType, NewObjectType);
1543 }(OldMethod, NewMethod);
1544
1545 if (!HaveCorrespondingObjectParameters) {
1546 if (DiagnoseInconsistentRefQualifiers())
1547 return true;
1548 // CWG2554
1549 // and, if at least one is an explicit object member function, ignoring
1550 // object parameters
1551 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1552 !OldMethod->isExplicitObjectMemberFunction()))
1553 return true;
1554 }
1555 }
1556
1557 if (!UseOverrideRules &&
1558 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1559 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1560 OldRC = Old->getTrailingRequiresClause();
1561 if (!NewRC != !OldRC)
1562 return true;
1563 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1564 return true;
1565 if (NewRC &&
1566 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC.ConstraintExpr,
1567 NewDecl, NewRC.ConstraintExpr))
1568 return true;
1569 }
1570
1571 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1572 NewMethod->isImplicitObjectMemberFunction()) {
1573 if (DiagnoseInconsistentRefQualifiers())
1574 return true;
1575 }
1576
1577 // Though pass_object_size is placed on parameters and takes an argument, we
1578 // consider it to be a function-level modifier for the sake of function
1579 // identity. Either the function has one or more parameters with
1580 // pass_object_size or it doesn't.
1583 return true;
1584
1585 // enable_if attributes are an order-sensitive part of the signature.
1587 NewI = New->specific_attr_begin<EnableIfAttr>(),
1588 NewE = New->specific_attr_end<EnableIfAttr>(),
1589 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1590 OldE = Old->specific_attr_end<EnableIfAttr>();
1591 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1592 if (NewI == NewE || OldI == OldE)
1593 return true;
1594 llvm::FoldingSetNodeID NewID, OldID;
1595 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1596 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1597 if (NewID != OldID)
1598 return true;
1599 }
1600
1601 // At this point, it is known that the two functions have the same signature.
1602 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1603 // Don't allow overloading of destructors. (In theory we could, but it
1604 // would be a giant change to clang.)
1605 if (!isa<CXXDestructorDecl>(New)) {
1606 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1607 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1608 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1609 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1610 "Unexpected invalid target.");
1611
1612 // Allow overloading of functions with same signature and different CUDA
1613 // target attributes.
1614 if (NewTarget != OldTarget) {
1615 // Special case: non-constexpr function is allowed to override
1616 // constexpr virtual function
1617 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1618 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1619 !hasExplicitAttr<CUDAHostAttr>(Old) &&
1620 !hasExplicitAttr<CUDADeviceAttr>(Old) &&
1621 !hasExplicitAttr<CUDAHostAttr>(New) &&
1622 !hasExplicitAttr<CUDADeviceAttr>(New)) {
1623 return false;
1624 }
1625 return true;
1626 }
1627 }
1628 }
1629 }
1630
1631 // The signatures match; this is not an overload.
1632 return false;
1633}
1634
1636 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1637 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1638 ConsiderCudaAttrs);
1639}
1640
1642 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1643 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1644 /*UseMemberUsingDeclRules=*/false,
1645 /*ConsiderCudaAttrs=*/true,
1646 /*UseOverrideRules=*/true);
1647}
1648
1649/// Tries a user-defined conversion from From to ToType.
1650///
1651/// Produces an implicit conversion sequence for when a standard conversion
1652/// is not an option. See TryImplicitConversion for more information.
1655 bool SuppressUserConversions,
1656 AllowedExplicit AllowExplicit,
1657 bool InOverloadResolution,
1658 bool CStyle,
1659 bool AllowObjCWritebackConversion,
1660 bool AllowObjCConversionOnExplicit) {
1662
1663 if (SuppressUserConversions) {
1664 // We're not in the case above, so there is no conversion that
1665 // we can perform.
1667 return ICS;
1668 }
1669
1670 // Attempt user-defined conversion.
1671 OverloadCandidateSet Conversions(From->getExprLoc(),
1673 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1674 Conversions, AllowExplicit,
1675 AllowObjCConversionOnExplicit)) {
1676 case OR_Success:
1677 case OR_Deleted:
1678 ICS.setUserDefined();
1679 // C++ [over.ics.user]p4:
1680 // A conversion of an expression of class type to the same class
1681 // type is given Exact Match rank, and a conversion of an
1682 // expression of class type to a base class of that type is
1683 // given Conversion rank, in spite of the fact that a copy
1684 // constructor (i.e., a user-defined conversion function) is
1685 // called for those cases.
1687 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1688 QualType FromType;
1689 SourceLocation FromLoc;
1690 // C++11 [over.ics.list]p6, per DR2137:
1691 // C++17 [over.ics.list]p6:
1692 // If C is not an initializer-list constructor and the initializer list
1693 // has a single element of type cv U, where U is X or a class derived
1694 // from X, the implicit conversion sequence has Exact Match rank if U is
1695 // X, or Conversion rank if U is derived from X.
1696 bool FromListInit = false;
1697 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1698 InitList && InitList->getNumInits() == 1 &&
1700 const Expr *SingleInit = InitList->getInit(0);
1701 FromType = SingleInit->getType();
1702 FromLoc = SingleInit->getBeginLoc();
1703 FromListInit = true;
1704 } else {
1705 FromType = From->getType();
1706 FromLoc = From->getBeginLoc();
1707 }
1708 QualType FromCanon =
1710 QualType ToCanon
1712 if ((FromCanon == ToCanon ||
1713 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1714 // Turn this into a "standard" conversion sequence, so that it
1715 // gets ranked with standard conversion sequences.
1717 ICS.setStandard();
1719 ICS.Standard.setFromType(FromType);
1720 ICS.Standard.setAllToTypes(ToType);
1721 ICS.Standard.FromBracedInitList = FromListInit;
1724 if (ToCanon != FromCanon)
1726 }
1727 }
1728 break;
1729
1730 case OR_Ambiguous:
1731 ICS.setAmbiguous();
1732 ICS.Ambiguous.setFromType(From->getType());
1733 ICS.Ambiguous.setToType(ToType);
1734 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1735 Cand != Conversions.end(); ++Cand)
1736 if (Cand->Best)
1737 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1738 break;
1739
1740 // Fall through.
1743 break;
1744 }
1745
1746 return ICS;
1747}
1748
1749/// TryImplicitConversion - Attempt to perform an implicit conversion
1750/// from the given expression (Expr) to the given type (ToType). This
1751/// function returns an implicit conversion sequence that can be used
1752/// to perform the initialization. Given
1753///
1754/// void f(float f);
1755/// void g(int i) { f(i); }
1756///
1757/// this routine would produce an implicit conversion sequence to
1758/// describe the initialization of f from i, which will be a standard
1759/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1760/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1761//
1762/// Note that this routine only determines how the conversion can be
1763/// performed; it does not actually perform the conversion. As such,
1764/// it will not produce any diagnostics if no conversion is available,
1765/// but will instead return an implicit conversion sequence of kind
1766/// "BadConversion".
1767///
1768/// If @p SuppressUserConversions, then user-defined conversions are
1769/// not permitted.
1770/// If @p AllowExplicit, then explicit user-defined conversions are
1771/// permitted.
1772///
1773/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1774/// writeback conversion, which allows __autoreleasing id* parameters to
1775/// be initialized with __strong id* or __weak id* arguments.
1778 bool SuppressUserConversions,
1779 AllowedExplicit AllowExplicit,
1780 bool InOverloadResolution,
1781 bool CStyle,
1782 bool AllowObjCWritebackConversion,
1783 bool AllowObjCConversionOnExplicit) {
1785 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1786 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1787 ICS.setStandard();
1788 return ICS;
1789 }
1790
1791 if (!S.getLangOpts().CPlusPlus) {
1793 return ICS;
1794 }
1795
1796 // C++ [over.ics.user]p4:
1797 // A conversion of an expression of class type to the same class
1798 // type is given Exact Match rank, and a conversion of an
1799 // expression of class type to a base class of that type is
1800 // given Conversion rank, in spite of the fact that a copy/move
1801 // constructor (i.e., a user-defined conversion function) is
1802 // called for those cases.
1803 QualType FromType = From->getType();
1804 if (ToType->isRecordType() &&
1805 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1806 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1807 ICS.setStandard();
1809 ICS.Standard.setFromType(FromType);
1810 ICS.Standard.setAllToTypes(ToType);
1811
1812 // We don't actually check at this point whether there is a valid
1813 // copy/move constructor, since overloading just assumes that it
1814 // exists. When we actually perform initialization, we'll find the
1815 // appropriate constructor to copy the returned object, if needed.
1816 ICS.Standard.CopyConstructor = nullptr;
1817
1818 // Determine whether this is considered a derived-to-base conversion.
1819 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1821
1822 return ICS;
1823 }
1824
1825 if (S.getLangOpts().HLSL && ToType->isHLSLAttributedResourceType() &&
1826 FromType->isHLSLAttributedResourceType()) {
1827 auto *ToResType = cast<HLSLAttributedResourceType>(ToType);
1828 auto *FromResType = cast<HLSLAttributedResourceType>(FromType);
1829 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1830 FromResType->getWrappedType()) &&
1831 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1832 FromResType->getContainedType()) &&
1833 ToResType->getAttrs() == FromResType->getAttrs()) {
1834 ICS.setStandard();
1836 ICS.Standard.setFromType(FromType);
1837 ICS.Standard.setAllToTypes(ToType);
1838 return ICS;
1839 }
1840 }
1841
1842 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1843 AllowExplicit, InOverloadResolution, CStyle,
1844 AllowObjCWritebackConversion,
1845 AllowObjCConversionOnExplicit);
1846}
1847
1850 bool SuppressUserConversions,
1851 AllowedExplicit AllowExplicit,
1852 bool InOverloadResolution,
1853 bool CStyle,
1854 bool AllowObjCWritebackConversion) {
1855 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1856 AllowExplicit, InOverloadResolution, CStyle,
1857 AllowObjCWritebackConversion,
1858 /*AllowObjCConversionOnExplicit=*/false);
1859}
1860
1862 AssignmentAction Action,
1863 bool AllowExplicit) {
1864 if (checkPlaceholderForOverload(*this, From))
1865 return ExprError();
1866
1867 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1868 bool AllowObjCWritebackConversion =
1869 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1870 Action == AssignmentAction::Sending);
1871 if (getLangOpts().ObjC)
1872 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1873 From->getType(), From);
1875 *this, From, ToType,
1876 /*SuppressUserConversions=*/false,
1877 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1878 /*InOverloadResolution=*/false,
1879 /*CStyle=*/false, AllowObjCWritebackConversion,
1880 /*AllowObjCConversionOnExplicit=*/false);
1881 return PerformImplicitConversion(From, ToType, ICS, Action);
1882}
1883
1885 QualType &ResultTy) const {
1886 bool Changed = IsFunctionConversion(FromType, ToType);
1887 if (Changed)
1888 ResultTy = ToType;
1889 return Changed;
1890}
1891
1893 bool *DiscardingCFIUncheckedCallee,
1894 bool *AddingCFIUncheckedCallee) const {
1895 if (DiscardingCFIUncheckedCallee)
1896 *DiscardingCFIUncheckedCallee = false;
1897 if (AddingCFIUncheckedCallee)
1898 *AddingCFIUncheckedCallee = false;
1899
1900 if (Context.hasSameUnqualifiedType(FromType, ToType))
1901 return false;
1902
1903 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1904 // or F(t noexcept) -> F(t)
1905 // where F adds one of the following at most once:
1906 // - a pointer
1907 // - a member pointer
1908 // - a block pointer
1909 // Changes here need matching changes in FindCompositePointerType.
1910 CanQualType CanTo = Context.getCanonicalType(ToType);
1911 CanQualType CanFrom = Context.getCanonicalType(FromType);
1912 Type::TypeClass TyClass = CanTo->getTypeClass();
1913 if (TyClass != CanFrom->getTypeClass()) return false;
1914 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1915 if (TyClass == Type::Pointer) {
1916 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1917 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1918 } else if (TyClass == Type::BlockPointer) {
1919 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1920 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1921 } else if (TyClass == Type::MemberPointer) {
1922 auto ToMPT = CanTo.castAs<MemberPointerType>();
1923 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1924 // A function pointer conversion cannot change the class of the function.
1925 if (!declaresSameEntity(ToMPT->getMostRecentCXXRecordDecl(),
1926 FromMPT->getMostRecentCXXRecordDecl()))
1927 return false;
1928 CanTo = ToMPT->getPointeeType();
1929 CanFrom = FromMPT->getPointeeType();
1930 } else {
1931 return false;
1932 }
1933
1934 TyClass = CanTo->getTypeClass();
1935 if (TyClass != CanFrom->getTypeClass()) return false;
1936 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1937 return false;
1938 }
1939
1940 const auto *FromFn = cast<FunctionType>(CanFrom);
1941 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1942
1943 const auto *ToFn = cast<FunctionType>(CanTo);
1944 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1945
1946 bool Changed = false;
1947
1948 // Drop 'noreturn' if not present in target type.
1949 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1950 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1951 Changed = true;
1952 }
1953
1954 const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn);
1955 const auto *ToFPT = dyn_cast<FunctionProtoType>(ToFn);
1956
1957 if (FromFPT && ToFPT) {
1958 if (FromFPT->hasCFIUncheckedCallee() && !ToFPT->hasCFIUncheckedCallee()) {
1959 QualType NewTy = Context.getFunctionType(
1960 FromFPT->getReturnType(), FromFPT->getParamTypes(),
1961 FromFPT->getExtProtoInfo().withCFIUncheckedCallee(false));
1962 FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());
1963 FromFn = FromFPT;
1964 Changed = true;
1965 if (DiscardingCFIUncheckedCallee)
1966 *DiscardingCFIUncheckedCallee = true;
1967 } else if (!FromFPT->hasCFIUncheckedCallee() &&
1968 ToFPT->hasCFIUncheckedCallee()) {
1969 QualType NewTy = Context.getFunctionType(
1970 FromFPT->getReturnType(), FromFPT->getParamTypes(),
1971 FromFPT->getExtProtoInfo().withCFIUncheckedCallee(true));
1972 FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());
1973 FromFn = FromFPT;
1974 Changed = true;
1975 if (AddingCFIUncheckedCallee)
1976 *AddingCFIUncheckedCallee = true;
1977 }
1978 }
1979
1980 // Drop 'noexcept' if not present in target type.
1981 if (FromFPT && ToFPT) {
1982 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1983 FromFn = cast<FunctionType>(
1984 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1985 EST_None)
1986 .getTypePtr());
1987 Changed = true;
1988 }
1989
1990 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1991 // only if the ExtParameterInfo lists of the two function prototypes can be
1992 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1994 bool CanUseToFPT, CanUseFromFPT;
1995 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1996 CanUseFromFPT, NewParamInfos) &&
1997 CanUseToFPT && !CanUseFromFPT) {
1998 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1999 ExtInfo.ExtParameterInfos =
2000 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2001 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
2002 FromFPT->getParamTypes(), ExtInfo);
2003 FromFn = QT->getAs<FunctionType>();
2004 Changed = true;
2005 }
2006
2007 // For C, when called from checkPointerTypesForAssignment,
2008 // we need to not alter FromFn, or else even an innocuous cast
2009 // like dropping effects will fail. In C++ however we do want to
2010 // alter FromFn (because of the way PerformImplicitConversion works).
2011 if (Context.hasAnyFunctionEffects() && getLangOpts().CPlusPlus) {
2012 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
2013
2014 // Transparently add/drop effects; here we are concerned with
2015 // language rules/canonicalization. Adding/dropping effects is a warning.
2016 const auto FromFX = FromFPT->getFunctionEffects();
2017 const auto ToFX = ToFPT->getFunctionEffects();
2018 if (FromFX != ToFX) {
2019 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2020 ExtInfo.FunctionEffects = ToFX;
2021 QualType QT = Context.getFunctionType(
2022 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
2023 FromFn = QT->getAs<FunctionType>();
2024 Changed = true;
2025 }
2026 }
2027 }
2028
2029 if (!Changed)
2030 return false;
2031
2032 assert(QualType(FromFn, 0).isCanonical());
2033 if (QualType(FromFn, 0) != CanTo) return false;
2034
2035 return true;
2036}
2037
2038/// Determine whether the conversion from FromType to ToType is a valid
2039/// floating point conversion.
2040///
2041static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2042 QualType ToType) {
2043 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2044 return false;
2045 // FIXME: disable conversions between long double, __ibm128 and __float128
2046 // if their representation is different until there is back end support
2047 // We of course allow this conversion if long double is really double.
2048
2049 // Conversions between bfloat16 and float16 are currently not supported.
2050 if ((FromType->isBFloat16Type() &&
2051 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2052 (ToType->isBFloat16Type() &&
2053 (FromType->isFloat16Type() || FromType->isHalfType())))
2054 return false;
2055
2056 // Conversions between IEEE-quad and IBM-extended semantics are not
2057 // permitted.
2058 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
2059 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2060 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2061 &ToSem == &llvm::APFloat::IEEEquad()) ||
2062 (&FromSem == &llvm::APFloat::IEEEquad() &&
2063 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2064 return false;
2065 return true;
2066}
2067
2068static bool IsVectorElementConversion(Sema &S, QualType FromType,
2069 QualType ToType,
2070 ImplicitConversionKind &ICK, Expr *From) {
2071 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2072 return true;
2073
2074 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2076 return true;
2077 }
2078
2079 if (IsFloatingPointConversion(S, FromType, ToType)) {
2081 return true;
2082 }
2083
2084 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2086 return true;
2087 }
2088
2089 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2091 ToType->isRealFloatingType())) {
2093 return true;
2094 }
2095
2096 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2098 return true;
2099 }
2100
2101 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2102 ToType->isIntegralType(S.Context)) {
2104 return true;
2105 }
2106
2107 return false;
2108}
2109
2110/// Determine whether the conversion from FromType to ToType is a valid
2111/// vector conversion.
2112///
2113/// \param ICK Will be set to the vector conversion kind, if this is a vector
2114/// conversion.
2115static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2117 ImplicitConversionKind &ElConv, Expr *From,
2118 bool InOverloadResolution, bool CStyle) {
2119 // We need at least one of these types to be a vector type to have a vector
2120 // conversion.
2121 if (!ToType->isVectorType() && !FromType->isVectorType())
2122 return false;
2123
2124 // Identical types require no conversions.
2125 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2126 return false;
2127
2128 // HLSL allows implicit truncation of vector types.
2129 if (S.getLangOpts().HLSL) {
2130 auto *ToExtType = ToType->getAs<ExtVectorType>();
2131 auto *FromExtType = FromType->getAs<ExtVectorType>();
2132
2133 // If both arguments are vectors, handle possible vector truncation and
2134 // element conversion.
2135 if (ToExtType && FromExtType) {
2136 unsigned FromElts = FromExtType->getNumElements();
2137 unsigned ToElts = ToExtType->getNumElements();
2138 if (FromElts < ToElts)
2139 return false;
2140 if (FromElts == ToElts)
2141 ElConv = ICK_Identity;
2142 else
2144
2145 QualType FromElTy = FromExtType->getElementType();
2146 QualType ToElTy = ToExtType->getElementType();
2147 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2148 return true;
2149 return IsVectorElementConversion(S, FromElTy, ToElTy, ICK, From);
2150 }
2151 if (FromExtType && !ToExtType) {
2153 QualType FromElTy = FromExtType->getElementType();
2154 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2155 return true;
2156 return IsVectorElementConversion(S, FromElTy, ToType, ICK, From);
2157 }
2158 // Fallthrough for the case where ToType is a vector and FromType is not.
2159 }
2160
2161 // There are no conversions between extended vector types, only identity.
2162 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2163 if (FromType->getAs<ExtVectorType>()) {
2164 // There are no conversions between extended vector types other than the
2165 // identity conversion.
2166 return false;
2167 }
2168
2169 // Vector splat from any arithmetic type to a vector.
2170 if (FromType->isArithmeticType()) {
2171 if (S.getLangOpts().HLSL) {
2172 ElConv = ICK_HLSL_Vector_Splat;
2173 QualType ToElTy = ToExtType->getElementType();
2174 return IsVectorElementConversion(S, FromType, ToElTy, ICK, From);
2175 }
2176 ICK = ICK_Vector_Splat;
2177 return true;
2178 }
2179 }
2180
2181 if (ToType->isSVESizelessBuiltinType() ||
2182 FromType->isSVESizelessBuiltinType())
2183 if (S.ARM().areCompatibleSveTypes(FromType, ToType) ||
2184 S.ARM().areLaxCompatibleSveTypes(FromType, ToType)) {
2186 return true;
2187 }
2188
2189 if (ToType->isRVVSizelessBuiltinType() ||
2190 FromType->isRVVSizelessBuiltinType())
2191 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2192 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2194 return true;
2195 }
2196
2197 // We can perform the conversion between vector types in the following cases:
2198 // 1)vector types are equivalent AltiVec and GCC vector types
2199 // 2)lax vector conversions are permitted and the vector types are of the
2200 // same size
2201 // 3)the destination type does not have the ARM MVE strict-polymorphism
2202 // attribute, which inhibits lax vector conversion for overload resolution
2203 // only
2204 if (ToType->isVectorType() && FromType->isVectorType()) {
2205 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2206 (S.isLaxVectorConversion(FromType, ToType) &&
2207 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2208 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2209 S.isLaxVectorConversion(FromType, ToType) &&
2210 S.anyAltivecTypes(FromType, ToType) &&
2211 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2212 !InOverloadResolution && !CStyle) {
2213 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2214 << FromType << ToType;
2215 }
2217 return true;
2218 }
2219 }
2220
2221 return false;
2222}
2223
2224static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2225 bool InOverloadResolution,
2227 bool CStyle);
2228
2229/// IsStandardConversion - Determines whether there is a standard
2230/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2231/// expression From to the type ToType. Standard conversion sequences
2232/// only consider non-class types; for conversions that involve class
2233/// types, use TryImplicitConversion. If a conversion exists, SCS will
2234/// contain the standard conversion sequence required to perform this
2235/// conversion and this routine will return true. Otherwise, this
2236/// routine will return false and the value of SCS is unspecified.
2237static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2238 bool InOverloadResolution,
2240 bool CStyle,
2241 bool AllowObjCWritebackConversion) {
2242 QualType FromType = From->getType();
2243
2244 // Standard conversions (C++ [conv])
2246 SCS.IncompatibleObjC = false;
2247 SCS.setFromType(FromType);
2248 SCS.CopyConstructor = nullptr;
2249
2250 // There are no standard conversions for class types in C++, so
2251 // abort early. When overloading in C, however, we do permit them.
2252 if (S.getLangOpts().CPlusPlus &&
2253 (FromType->isRecordType() || ToType->isRecordType()))
2254 return false;
2255
2256 // The first conversion can be an lvalue-to-rvalue conversion,
2257 // array-to-pointer conversion, or function-to-pointer conversion
2258 // (C++ 4p1).
2259
2260 if (FromType == S.Context.OverloadTy) {
2261 DeclAccessPair AccessPair;
2262 if (FunctionDecl *Fn
2263 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2264 AccessPair)) {
2265 // We were able to resolve the address of the overloaded function,
2266 // so we can convert to the type of that function.
2267 FromType = Fn->getType();
2268 SCS.setFromType(FromType);
2269
2270 // we can sometimes resolve &foo<int> regardless of ToType, so check
2271 // if the type matches (identity) or we are converting to bool
2273 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2274 // if the function type matches except for [[noreturn]], it's ok
2275 if (!S.IsFunctionConversion(FromType,
2277 // otherwise, only a boolean conversion is standard
2278 if (!ToType->isBooleanType())
2279 return false;
2280 }
2281
2282 // Check if the "from" expression is taking the address of an overloaded
2283 // function and recompute the FromType accordingly. Take advantage of the
2284 // fact that non-static member functions *must* have such an address-of
2285 // expression.
2286 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2287 if (Method && !Method->isStatic() &&
2288 !Method->isExplicitObjectMemberFunction()) {
2289 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2290 "Non-unary operator on non-static member address");
2291 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2292 == UO_AddrOf &&
2293 "Non-address-of operator on non-static member address");
2294 FromType = S.Context.getMemberPointerType(
2295 FromType, /*Qualifier=*/std::nullopt, Method->getParent());
2296 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2297 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2298 UO_AddrOf &&
2299 "Non-address-of operator for overloaded function expression");
2300 FromType = S.Context.getPointerType(FromType);
2301 }
2302 } else {
2303 return false;
2304 }
2305 }
2306
2307 bool argIsLValue = From->isGLValue();
2308 // To handle conversion from ArrayParameterType to ConstantArrayType
2309 // this block must be above the one below because Array parameters
2310 // do not decay and when handling HLSLOutArgExprs and
2311 // the From expression is an LValue.
2312 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2313 ToType->isConstantArrayType()) {
2314 // HLSL constant array parameters do not decay, so if the argument is a
2315 // constant array and the parameter is an ArrayParameterType we have special
2316 // handling here.
2317 if (ToType->isArrayParameterType()) {
2318 FromType = S.Context.getArrayParameterType(FromType);
2319 } else if (FromType->isArrayParameterType()) {
2320 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2321 FromType = APT->getConstantArrayType(S.Context);
2322 }
2323
2325
2326 // Don't consider qualifiers, which include things like address spaces
2327 if (FromType.getCanonicalType().getUnqualifiedType() !=
2329 return false;
2330
2331 SCS.setAllToTypes(ToType);
2332 return true;
2333 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2334 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2335 // Lvalue-to-rvalue conversion (C++11 4.1):
2336 // A glvalue (3.10) of a non-function, non-array type T can
2337 // be converted to a prvalue.
2338
2340
2341 // C11 6.3.2.1p2:
2342 // ... if the lvalue has atomic type, the value has the non-atomic version
2343 // of the type of the lvalue ...
2344 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2345 FromType = Atomic->getValueType();
2346
2347 // If T is a non-class type, the type of the rvalue is the
2348 // cv-unqualified version of T. Otherwise, the type of the rvalue
2349 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2350 // just strip the qualifiers because they don't matter.
2351 FromType = FromType.getUnqualifiedType();
2352 } else if (FromType->isArrayType()) {
2353 // Array-to-pointer conversion (C++ 4.2)
2355
2356 // An lvalue or rvalue of type "array of N T" or "array of unknown
2357 // bound of T" can be converted to an rvalue of type "pointer to
2358 // T" (C++ 4.2p1).
2359 FromType = S.Context.getArrayDecayedType(FromType);
2360
2361 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2362 // This conversion is deprecated in C++03 (D.4)
2364
2365 // For the purpose of ranking in overload resolution
2366 // (13.3.3.1.1), this conversion is considered an
2367 // array-to-pointer conversion followed by a qualification
2368 // conversion (4.4). (C++ 4.2p2)
2369 SCS.Second = ICK_Identity;
2372 SCS.setAllToTypes(FromType);
2373 return true;
2374 }
2375 } else if (FromType->isFunctionType() && argIsLValue) {
2376 // Function-to-pointer conversion (C++ 4.3).
2378
2379 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2380 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2382 return false;
2383
2384 // An lvalue of function type T can be converted to an rvalue of
2385 // type "pointer to T." The result is a pointer to the
2386 // function. (C++ 4.3p1).
2387 FromType = S.Context.getPointerType(FromType);
2388 } else {
2389 // We don't require any conversions for the first step.
2390 SCS.First = ICK_Identity;
2391 }
2392 SCS.setToType(0, FromType);
2393
2394 // The second conversion can be an integral promotion, floating
2395 // point promotion, integral conversion, floating point conversion,
2396 // floating-integral conversion, pointer conversion,
2397 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2398 // For overloading in C, this can also be a "compatible-type"
2399 // conversion.
2400 bool IncompatibleObjC = false;
2402 ImplicitConversionKind DimensionICK = ICK_Identity;
2403 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2404 // The unqualified versions of the types are the same: there's no
2405 // conversion to do.
2406 SCS.Second = ICK_Identity;
2407 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2408 // Integral promotion (C++ 4.5).
2410 FromType = ToType.getUnqualifiedType();
2411 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2412 // Floating point promotion (C++ 4.6).
2414 FromType = ToType.getUnqualifiedType();
2415 } else if (S.IsComplexPromotion(FromType, ToType)) {
2416 // Complex promotion (Clang extension)
2418 FromType = ToType.getUnqualifiedType();
2419 } else if (ToType->isBooleanType() &&
2420 (FromType->isArithmeticType() ||
2421 FromType->isAnyPointerType() ||
2422 FromType->isBlockPointerType() ||
2423 FromType->isMemberPointerType())) {
2424 // Boolean conversions (C++ 4.12).
2426 FromType = S.Context.BoolTy;
2427 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2428 ToType->isIntegralType(S.Context)) {
2429 // Integral conversions (C++ 4.7).
2431 FromType = ToType.getUnqualifiedType();
2432 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2433 // Complex conversions (C99 6.3.1.6)
2435 FromType = ToType.getUnqualifiedType();
2436 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2437 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2438 // Complex-real conversions (C99 6.3.1.7)
2440 FromType = ToType.getUnqualifiedType();
2441 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2442 // Floating point conversions (C++ 4.8).
2444 FromType = ToType.getUnqualifiedType();
2445 } else if ((FromType->isRealFloatingType() &&
2446 ToType->isIntegralType(S.Context)) ||
2448 ToType->isRealFloatingType())) {
2449
2450 // Floating-integral conversions (C++ 4.9).
2452 FromType = ToType.getUnqualifiedType();
2453 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2455 } else if (AllowObjCWritebackConversion &&
2456 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2458 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2459 FromType, IncompatibleObjC)) {
2460 // Pointer conversions (C++ 4.10).
2462 SCS.IncompatibleObjC = IncompatibleObjC;
2463 FromType = FromType.getUnqualifiedType();
2464 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2465 InOverloadResolution, FromType)) {
2466 // Pointer to member conversions (4.11).
2468 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2469 From, InOverloadResolution, CStyle)) {
2470 SCS.Second = SecondICK;
2471 SCS.Dimension = DimensionICK;
2472 FromType = ToType.getUnqualifiedType();
2473 } else if (!S.getLangOpts().CPlusPlus &&
2474 S.Context.typesAreCompatible(ToType, FromType)) {
2475 // Compatible conversions (Clang extension for C function overloading)
2477 FromType = ToType.getUnqualifiedType();
2479 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2481 FromType = ToType;
2482 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2483 CStyle)) {
2484 // tryAtomicConversion has updated the standard conversion sequence
2485 // appropriately.
2486 return true;
2487 } else if (ToType->isEventT() &&
2489 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2491 FromType = ToType;
2492 } else if (ToType->isQueueT() &&
2494 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2496 FromType = ToType;
2497 } else if (ToType->isSamplerT() &&
2500 FromType = ToType;
2501 } else if ((ToType->isFixedPointType() &&
2502 FromType->isConvertibleToFixedPointType()) ||
2503 (FromType->isFixedPointType() &&
2504 ToType->isConvertibleToFixedPointType())) {
2506 FromType = ToType;
2507 } else {
2508 // No second conversion required.
2509 SCS.Second = ICK_Identity;
2510 }
2511 SCS.setToType(1, FromType);
2512
2513 // The third conversion can be a function pointer conversion or a
2514 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2515 bool ObjCLifetimeConversion;
2516 if (S.TryFunctionConversion(FromType, ToType, FromType)) {
2517 // Function pointer conversions (removing 'noexcept') including removal of
2518 // 'noreturn' (Clang extension).
2520 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2521 ObjCLifetimeConversion)) {
2523 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2524 FromType = ToType;
2525 } else {
2526 // No conversion required
2527 SCS.Third = ICK_Identity;
2528 }
2529
2530 // C++ [over.best.ics]p6:
2531 // [...] Any difference in top-level cv-qualification is
2532 // subsumed by the initialization itself and does not constitute
2533 // a conversion. [...]
2534 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2535 QualType CanonTo = S.Context.getCanonicalType(ToType);
2536 if (CanonFrom.getLocalUnqualifiedType()
2537 == CanonTo.getLocalUnqualifiedType() &&
2538 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2539 FromType = ToType;
2540 CanonFrom = CanonTo;
2541 }
2542
2543 SCS.setToType(2, FromType);
2544
2545 // If we have not converted the argument type to the parameter type,
2546 // this is a bad conversion sequence, unless we're resolving an overload in C.
2547 //
2548 // Permit conversions from a function without `cfi_unchecked_callee` to a
2549 // function with `cfi_unchecked_callee`.
2550 if (CanonFrom == CanonTo || S.AddingCFIUncheckedCallee(CanonFrom, CanonTo))
2551 return true;
2552
2553 if ((S.getLangOpts().CPlusPlus || !InOverloadResolution))
2554 return false;
2555
2556 ExprResult ER = ExprResult{From};
2557 AssignConvertType Conv =
2559 /*Diagnose=*/false,
2560 /*DiagnoseCFAudited=*/false,
2561 /*ConvertRHS=*/false);
2562 ImplicitConversionKind SecondConv;
2563 switch (Conv) {
2566 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2567 SecondConv = ICK_C_Only_Conversion;
2568 break;
2569 // For our purposes, discarding qualifiers is just as bad as using an
2570 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2571 // qualifiers, as well.
2576 break;
2577 default:
2578 return false;
2579 }
2580
2581 // First can only be an lvalue conversion, so we pretend that this was the
2582 // second conversion. First should already be valid from earlier in the
2583 // function.
2584 SCS.Second = SecondConv;
2585 SCS.setToType(1, ToType);
2586
2587 // Third is Identity, because Second should rank us worse than any other
2588 // conversion. This could also be ICK_Qualification, but it's simpler to just
2589 // lump everything in with the second conversion, and we don't gain anything
2590 // from making this ICK_Qualification.
2591 SCS.Third = ICK_Identity;
2592 SCS.setToType(2, ToType);
2593 return true;
2594}
2595
2596static bool
2598 QualType &ToType,
2599 bool InOverloadResolution,
2601 bool CStyle) {
2602
2603 const RecordType *UT = ToType->getAsUnionType();
2604 if (!UT)
2605 return false;
2606 // The field to initialize within the transparent union.
2607 const RecordDecl *UD = UT->getOriginalDecl()->getDefinitionOrSelf();
2608 if (!UD->hasAttr<TransparentUnionAttr>())
2609 return false;
2610 // It's compatible if the expression matches any of the fields.
2611 for (const auto *it : UD->fields()) {
2612 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2613 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2614 ToType = it->getType();
2615 return true;
2616 }
2617 }
2618 return false;
2619}
2620
2621bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2622 const BuiltinType *To = ToType->getAs<BuiltinType>();
2623 // All integers are built-in.
2624 if (!To) {
2625 return false;
2626 }
2627
2628 // An rvalue of type char, signed char, unsigned char, short int, or
2629 // unsigned short int can be converted to an rvalue of type int if
2630 // int can represent all the values of the source type; otherwise,
2631 // the source rvalue can be converted to an rvalue of type unsigned
2632 // int (C++ 4.5p1).
2633 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2634 !FromType->isEnumeralType()) {
2635 if ( // We can promote any signed, promotable integer type to an int
2636 (FromType->isSignedIntegerType() ||
2637 // We can promote any unsigned integer type whose size is
2638 // less than int to an int.
2639 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2640 return To->getKind() == BuiltinType::Int;
2641 }
2642
2643 return To->getKind() == BuiltinType::UInt;
2644 }
2645
2646 // C++11 [conv.prom]p3:
2647 // A prvalue of an unscoped enumeration type whose underlying type is not
2648 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2649 // following types that can represent all the values of the enumeration
2650 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2651 // unsigned int, long int, unsigned long int, long long int, or unsigned
2652 // long long int. If none of the types in that list can represent all the
2653 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2654 // type can be converted to an rvalue a prvalue of the extended integer type
2655 // with lowest integer conversion rank (4.13) greater than the rank of long
2656 // long in which all the values of the enumeration can be represented. If
2657 // there are two such extended types, the signed one is chosen.
2658 // C++11 [conv.prom]p4:
2659 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2660 // can be converted to a prvalue of its underlying type. Moreover, if
2661 // integral promotion can be applied to its underlying type, a prvalue of an
2662 // unscoped enumeration type whose underlying type is fixed can also be
2663 // converted to a prvalue of the promoted underlying type.
2664 if (const auto *FromED = FromType->getAsEnumDecl()) {
2665 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2666 // provided for a scoped enumeration.
2667 if (FromED->isScoped())
2668 return false;
2669
2670 // We can perform an integral promotion to the underlying type of the enum,
2671 // even if that's not the promoted type. Note that the check for promoting
2672 // the underlying type is based on the type alone, and does not consider
2673 // the bitfield-ness of the actual source expression.
2674 if (FromED->isFixed()) {
2675 QualType Underlying = FromED->getIntegerType();
2676 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2677 IsIntegralPromotion(nullptr, Underlying, ToType);
2678 }
2679
2680 // We have already pre-calculated the promotion type, so this is trivial.
2681 if (ToType->isIntegerType() &&
2682 isCompleteType(From->getBeginLoc(), FromType))
2683 return Context.hasSameUnqualifiedType(ToType, FromED->getPromotionType());
2684
2685 // C++ [conv.prom]p5:
2686 // If the bit-field has an enumerated type, it is treated as any other
2687 // value of that type for promotion purposes.
2688 //
2689 // ... so do not fall through into the bit-field checks below in C++.
2690 if (getLangOpts().CPlusPlus)
2691 return false;
2692 }
2693
2694 // C++0x [conv.prom]p2:
2695 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2696 // to an rvalue a prvalue of the first of the following types that can
2697 // represent all the values of its underlying type: int, unsigned int,
2698 // long int, unsigned long int, long long int, or unsigned long long int.
2699 // If none of the types in that list can represent all the values of its
2700 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2701 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2702 // type.
2703 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2704 ToType->isIntegerType()) {
2705 // Determine whether the type we're converting from is signed or
2706 // unsigned.
2707 bool FromIsSigned = FromType->isSignedIntegerType();
2708 uint64_t FromSize = Context.getTypeSize(FromType);
2709
2710 // The types we'll try to promote to, in the appropriate
2711 // order. Try each of these types.
2712 QualType PromoteTypes[6] = {
2713 Context.IntTy, Context.UnsignedIntTy,
2714 Context.LongTy, Context.UnsignedLongTy ,
2715 Context.LongLongTy, Context.UnsignedLongLongTy
2716 };
2717 for (int Idx = 0; Idx < 6; ++Idx) {
2718 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2719 if (FromSize < ToSize ||
2720 (FromSize == ToSize &&
2721 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2722 // We found the type that we can promote to. If this is the
2723 // type we wanted, we have a promotion. Otherwise, no
2724 // promotion.
2725 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2726 }
2727 }
2728 }
2729
2730 // An rvalue for an integral bit-field (9.6) can be converted to an
2731 // rvalue of type int if int can represent all the values of the
2732 // bit-field; otherwise, it can be converted to unsigned int if
2733 // unsigned int can represent all the values of the bit-field. If
2734 // the bit-field is larger yet, no integral promotion applies to
2735 // it. If the bit-field has an enumerated type, it is treated as any
2736 // other value of that type for promotion purposes (C++ 4.5p3).
2737 // FIXME: We should delay checking of bit-fields until we actually perform the
2738 // conversion.
2739 //
2740 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2741 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2742 // bit-fields and those whose underlying type is larger than int) for GCC
2743 // compatibility.
2744 if (From) {
2745 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2746 std::optional<llvm::APSInt> BitWidth;
2747 if (FromType->isIntegralType(Context) &&
2748 (BitWidth =
2749 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2750 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2751 ToSize = Context.getTypeSize(ToType);
2752
2753 // Are we promoting to an int from a bitfield that fits in an int?
2754 if (*BitWidth < ToSize ||
2755 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2756 return To->getKind() == BuiltinType::Int;
2757 }
2758
2759 // Are we promoting to an unsigned int from an unsigned bitfield
2760 // that fits into an unsigned int?
2761 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2762 return To->getKind() == BuiltinType::UInt;
2763 }
2764
2765 return false;
2766 }
2767 }
2768 }
2769
2770 // An rvalue of type bool can be converted to an rvalue of type int,
2771 // with false becoming zero and true becoming one (C++ 4.5p4).
2772 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2773 return true;
2774 }
2775
2776 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2777 // integral type.
2778 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2779 ToType->isIntegerType())
2780 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2781
2782 return false;
2783}
2784
2786 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2787 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2788 /// An rvalue of type float can be converted to an rvalue of type
2789 /// double. (C++ 4.6p1).
2790 if (FromBuiltin->getKind() == BuiltinType::Float &&
2791 ToBuiltin->getKind() == BuiltinType::Double)
2792 return true;
2793
2794 // C99 6.3.1.5p1:
2795 // When a float is promoted to double or long double, or a
2796 // double is promoted to long double [...].
2797 if (!getLangOpts().CPlusPlus &&
2798 (FromBuiltin->getKind() == BuiltinType::Float ||
2799 FromBuiltin->getKind() == BuiltinType::Double) &&
2800 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2801 ToBuiltin->getKind() == BuiltinType::Float128 ||
2802 ToBuiltin->getKind() == BuiltinType::Ibm128))
2803 return true;
2804
2805 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2806 // or not native half types are enabled.
2807 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2808 (ToBuiltin->getKind() == BuiltinType::Float ||
2809 ToBuiltin->getKind() == BuiltinType::Double))
2810 return true;
2811
2812 // Half can be promoted to float.
2813 if (!getLangOpts().NativeHalfType &&
2814 FromBuiltin->getKind() == BuiltinType::Half &&
2815 ToBuiltin->getKind() == BuiltinType::Float)
2816 return true;
2817 }
2818
2819 return false;
2820}
2821
2823 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2824 if (!FromComplex)
2825 return false;
2826
2827 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2828 if (!ToComplex)
2829 return false;
2830
2831 return IsFloatingPointPromotion(FromComplex->getElementType(),
2832 ToComplex->getElementType()) ||
2833 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2834 ToComplex->getElementType());
2835}
2836
2837/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2838/// the pointer type FromPtr to a pointer to type ToPointee, with the
2839/// same type qualifiers as FromPtr has on its pointee type. ToType,
2840/// if non-empty, will be a pointer to ToType that may or may not have
2841/// the right set of qualifiers on its pointee.
2842///
2843static QualType
2845 QualType ToPointee, QualType ToType,
2846 ASTContext &Context,
2847 bool StripObjCLifetime = false) {
2848 assert((FromPtr->getTypeClass() == Type::Pointer ||
2849 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2850 "Invalid similarly-qualified pointer type");
2851
2852 /// Conversions to 'id' subsume cv-qualifier conversions.
2853 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2854 return ToType.getUnqualifiedType();
2855
2856 QualType CanonFromPointee
2857 = Context.getCanonicalType(FromPtr->getPointeeType());
2858 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2859 Qualifiers Quals = CanonFromPointee.getQualifiers();
2860
2861 if (StripObjCLifetime)
2862 Quals.removeObjCLifetime();
2863
2864 // Exact qualifier match -> return the pointer type we're converting to.
2865 if (CanonToPointee.getLocalQualifiers() == Quals) {
2866 // ToType is exactly what we need. Return it.
2867 if (!ToType.isNull())
2868 return ToType.getUnqualifiedType();
2869
2870 // Build a pointer to ToPointee. It has the right qualifiers
2871 // already.
2872 if (isa<ObjCObjectPointerType>(ToType))
2873 return Context.getObjCObjectPointerType(ToPointee);
2874 return Context.getPointerType(ToPointee);
2875 }
2876
2877 // Just build a canonical type that has the right qualifiers.
2878 QualType QualifiedCanonToPointee
2879 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2880
2881 if (isa<ObjCObjectPointerType>(ToType))
2882 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2883 return Context.getPointerType(QualifiedCanonToPointee);
2884}
2885
2887 bool InOverloadResolution,
2888 ASTContext &Context) {
2889 // Handle value-dependent integral null pointer constants correctly.
2890 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2891 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2893 return !InOverloadResolution;
2894
2895 return Expr->isNullPointerConstant(Context,
2896 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2898}
2899
2901 bool InOverloadResolution,
2902 QualType& ConvertedType,
2903 bool &IncompatibleObjC) {
2904 IncompatibleObjC = false;
2905 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2906 IncompatibleObjC))
2907 return true;
2908
2909 // Conversion from a null pointer constant to any Objective-C pointer type.
2910 if (ToType->isObjCObjectPointerType() &&
2911 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2912 ConvertedType = ToType;
2913 return true;
2914 }
2915
2916 // Blocks: Block pointers can be converted to void*.
2917 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2918 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2919 ConvertedType = ToType;
2920 return true;
2921 }
2922 // Blocks: A null pointer constant can be converted to a block
2923 // pointer type.
2924 if (ToType->isBlockPointerType() &&
2925 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2926 ConvertedType = ToType;
2927 return true;
2928 }
2929
2930 // If the left-hand-side is nullptr_t, the right side can be a null
2931 // pointer constant.
2932 if (ToType->isNullPtrType() &&
2933 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2934 ConvertedType = ToType;
2935 return true;
2936 }
2937
2938 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2939 if (!ToTypePtr)
2940 return false;
2941
2942 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2943 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2944 ConvertedType = ToType;
2945 return true;
2946 }
2947
2948 // Beyond this point, both types need to be pointers
2949 // , including objective-c pointers.
2950 QualType ToPointeeType = ToTypePtr->getPointeeType();
2951 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2952 !getLangOpts().ObjCAutoRefCount) {
2953 ConvertedType = BuildSimilarlyQualifiedPointerType(
2954 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2955 Context);
2956 return true;
2957 }
2958 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2959 if (!FromTypePtr)
2960 return false;
2961
2962 QualType FromPointeeType = FromTypePtr->getPointeeType();
2963
2964 // If the unqualified pointee types are the same, this can't be a
2965 // pointer conversion, so don't do all of the work below.
2966 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2967 return false;
2968
2969 // An rvalue of type "pointer to cv T," where T is an object type,
2970 // can be converted to an rvalue of type "pointer to cv void" (C++
2971 // 4.10p2).
2972 if (FromPointeeType->isIncompleteOrObjectType() &&
2973 ToPointeeType->isVoidType()) {
2974 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2975 ToPointeeType,
2976 ToType, Context,
2977 /*StripObjCLifetime=*/true);
2978 return true;
2979 }
2980
2981 // MSVC allows implicit function to void* type conversion.
2982 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2983 ToPointeeType->isVoidType()) {
2984 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2985 ToPointeeType,
2986 ToType, Context);
2987 return true;
2988 }
2989
2990 // When we're overloading in C, we allow a special kind of pointer
2991 // conversion for compatible-but-not-identical pointee types.
2992 if (!getLangOpts().CPlusPlus &&
2993 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2994 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2995 ToPointeeType,
2996 ToType, Context);
2997 return true;
2998 }
2999
3000 // C++ [conv.ptr]p3:
3001 //
3002 // An rvalue of type "pointer to cv D," where D is a class type,
3003 // can be converted to an rvalue of type "pointer to cv B," where
3004 // B is a base class (clause 10) of D. If B is an inaccessible
3005 // (clause 11) or ambiguous (10.2) base class of D, a program that
3006 // necessitates this conversion is ill-formed. The result of the
3007 // conversion is a pointer to the base class sub-object of the
3008 // derived class object. The null pointer value is converted to
3009 // the null pointer value of the destination type.
3010 //
3011 // Note that we do not check for ambiguity or inaccessibility
3012 // here. That is handled by CheckPointerConversion.
3013 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3014 ToPointeeType->isRecordType() &&
3015 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
3016 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
3017 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3018 ToPointeeType,
3019 ToType, Context);
3020 return true;
3021 }
3022
3023 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3024 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
3025 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3026 ToPointeeType,
3027 ToType, Context);
3028 return true;
3029 }
3030
3031 return false;
3032}
3033
3034/// Adopt the given qualifiers for the given type.
3036 Qualifiers TQs = T.getQualifiers();
3037
3038 // Check whether qualifiers already match.
3039 if (TQs == Qs)
3040 return T;
3041
3042 if (Qs.compatiblyIncludes(TQs, Context))
3043 return Context.getQualifiedType(T, Qs);
3044
3045 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
3046}
3047
3049 QualType& ConvertedType,
3050 bool &IncompatibleObjC) {
3051 if (!getLangOpts().ObjC)
3052 return false;
3053
3054 // The set of qualifiers on the type we're converting from.
3055 Qualifiers FromQualifiers = FromType.getQualifiers();
3056
3057 // First, we handle all conversions on ObjC object pointer types.
3058 const ObjCObjectPointerType* ToObjCPtr =
3059 ToType->getAs<ObjCObjectPointerType>();
3060 const ObjCObjectPointerType *FromObjCPtr =
3061 FromType->getAs<ObjCObjectPointerType>();
3062
3063 if (ToObjCPtr && FromObjCPtr) {
3064 // If the pointee types are the same (ignoring qualifications),
3065 // then this is not a pointer conversion.
3066 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
3067 FromObjCPtr->getPointeeType()))
3068 return false;
3069
3070 // Conversion between Objective-C pointers.
3071 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3072 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3073 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3074 if (getLangOpts().CPlusPlus && LHS && RHS &&
3076 FromObjCPtr->getPointeeType(), getASTContext()))
3077 return false;
3078 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3079 ToObjCPtr->getPointeeType(),
3080 ToType, Context);
3081 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3082 return true;
3083 }
3084
3085 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3086 // Okay: this is some kind of implicit downcast of Objective-C
3087 // interfaces, which is permitted. However, we're going to
3088 // complain about it.
3089 IncompatibleObjC = true;
3090 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3091 ToObjCPtr->getPointeeType(),
3092 ToType, Context);
3093 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3094 return true;
3095 }
3096 }
3097 // Beyond this point, both types need to be C pointers or block pointers.
3098 QualType ToPointeeType;
3099 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3100 ToPointeeType = ToCPtr->getPointeeType();
3101 else if (const BlockPointerType *ToBlockPtr =
3102 ToType->getAs<BlockPointerType>()) {
3103 // Objective C++: We're able to convert from a pointer to any object
3104 // to a block pointer type.
3105 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3106 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3107 return true;
3108 }
3109 ToPointeeType = ToBlockPtr->getPointeeType();
3110 }
3111 else if (FromType->getAs<BlockPointerType>() &&
3112 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3113 // Objective C++: We're able to convert from a block pointer type to a
3114 // pointer to any object.
3115 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3116 return true;
3117 }
3118 else
3119 return false;
3120
3121 QualType FromPointeeType;
3122 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3123 FromPointeeType = FromCPtr->getPointeeType();
3124 else if (const BlockPointerType *FromBlockPtr =
3125 FromType->getAs<BlockPointerType>())
3126 FromPointeeType = FromBlockPtr->getPointeeType();
3127 else
3128 return false;
3129
3130 // If we have pointers to pointers, recursively check whether this
3131 // is an Objective-C conversion.
3132 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3133 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3134 IncompatibleObjC)) {
3135 // We always complain about this conversion.
3136 IncompatibleObjC = true;
3137 ConvertedType = Context.getPointerType(ConvertedType);
3138 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3139 return true;
3140 }
3141 // Allow conversion of pointee being objective-c pointer to another one;
3142 // as in I* to id.
3143 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3144 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3145 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3146 IncompatibleObjC)) {
3147
3148 ConvertedType = Context.getPointerType(ConvertedType);
3149 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3150 return true;
3151 }
3152
3153 // If we have pointers to functions or blocks, check whether the only
3154 // differences in the argument and result types are in Objective-C
3155 // pointer conversions. If so, we permit the conversion (but
3156 // complain about it).
3157 const FunctionProtoType *FromFunctionType
3158 = FromPointeeType->getAs<FunctionProtoType>();
3159 const FunctionProtoType *ToFunctionType
3160 = ToPointeeType->getAs<FunctionProtoType>();
3161 if (FromFunctionType && ToFunctionType) {
3162 // If the function types are exactly the same, this isn't an
3163 // Objective-C pointer conversion.
3164 if (Context.getCanonicalType(FromPointeeType)
3165 == Context.getCanonicalType(ToPointeeType))
3166 return false;
3167
3168 // Perform the quick checks that will tell us whether these
3169 // function types are obviously different.
3170 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3171 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3172 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3173 return false;
3174
3175 bool HasObjCConversion = false;
3176 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3177 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3178 // Okay, the types match exactly. Nothing to do.
3179 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3180 ToFunctionType->getReturnType(),
3181 ConvertedType, IncompatibleObjC)) {
3182 // Okay, we have an Objective-C pointer conversion.
3183 HasObjCConversion = true;
3184 } else {
3185 // Function types are too different. Abort.
3186 return false;
3187 }
3188
3189 // Check argument types.
3190 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3191 ArgIdx != NumArgs; ++ArgIdx) {
3192 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3193 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3194 if (Context.getCanonicalType(FromArgType)
3195 == Context.getCanonicalType(ToArgType)) {
3196 // Okay, the types match exactly. Nothing to do.
3197 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3198 ConvertedType, IncompatibleObjC)) {
3199 // Okay, we have an Objective-C pointer conversion.
3200 HasObjCConversion = true;
3201 } else {
3202 // Argument types are too different. Abort.
3203 return false;
3204 }
3205 }
3206
3207 if (HasObjCConversion) {
3208 // We had an Objective-C conversion. Allow this pointer
3209 // conversion, but complain about it.
3210 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3211 IncompatibleObjC = true;
3212 return true;
3213 }
3214 }
3215
3216 return false;
3217}
3218
3220 QualType& ConvertedType) {
3221 QualType ToPointeeType;
3222 if (const BlockPointerType *ToBlockPtr =
3223 ToType->getAs<BlockPointerType>())
3224 ToPointeeType = ToBlockPtr->getPointeeType();
3225 else
3226 return false;
3227
3228 QualType FromPointeeType;
3229 if (const BlockPointerType *FromBlockPtr =
3230 FromType->getAs<BlockPointerType>())
3231 FromPointeeType = FromBlockPtr->getPointeeType();
3232 else
3233 return false;
3234 // We have pointer to blocks, check whether the only
3235 // differences in the argument and result types are in Objective-C
3236 // pointer conversions. If so, we permit the conversion.
3237
3238 const FunctionProtoType *FromFunctionType
3239 = FromPointeeType->getAs<FunctionProtoType>();
3240 const FunctionProtoType *ToFunctionType
3241 = ToPointeeType->getAs<FunctionProtoType>();
3242
3243 if (!FromFunctionType || !ToFunctionType)
3244 return false;
3245
3246 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3247 return true;
3248
3249 // Perform the quick checks that will tell us whether these
3250 // function types are obviously different.
3251 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3252 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3253 return false;
3254
3255 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3256 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3257 if (FromEInfo != ToEInfo)
3258 return false;
3259
3260 bool IncompatibleObjC = false;
3261 if (Context.hasSameType(FromFunctionType->getReturnType(),
3262 ToFunctionType->getReturnType())) {
3263 // Okay, the types match exactly. Nothing to do.
3264 } else {
3265 QualType RHS = FromFunctionType->getReturnType();
3266 QualType LHS = ToFunctionType->getReturnType();
3267 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3268 !RHS.hasQualifiers() && LHS.hasQualifiers())
3269 LHS = LHS.getUnqualifiedType();
3270
3271 if (Context.hasSameType(RHS,LHS)) {
3272 // OK exact match.
3273 } else if (isObjCPointerConversion(RHS, LHS,
3274 ConvertedType, IncompatibleObjC)) {
3275 if (IncompatibleObjC)
3276 return false;
3277 // Okay, we have an Objective-C pointer conversion.
3278 }
3279 else
3280 return false;
3281 }
3282
3283 // Check argument types.
3284 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3285 ArgIdx != NumArgs; ++ArgIdx) {
3286 IncompatibleObjC = false;
3287 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3288 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3289 if (Context.hasSameType(FromArgType, ToArgType)) {
3290 // Okay, the types match exactly. Nothing to do.
3291 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3292 ConvertedType, IncompatibleObjC)) {
3293 if (IncompatibleObjC)
3294 return false;
3295 // Okay, we have an Objective-C pointer conversion.
3296 } else
3297 // Argument types are too different. Abort.
3298 return false;
3299 }
3300
3302 bool CanUseToFPT, CanUseFromFPT;
3303 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3304 CanUseToFPT, CanUseFromFPT,
3305 NewParamInfos))
3306 return false;
3307
3308 ConvertedType = ToType;
3309 return true;
3310}
3311
3312enum {
3321
3322/// Attempts to get the FunctionProtoType from a Type. Handles
3323/// MemberFunctionPointers properly.
3325 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3326 return FPT;
3327
3328 if (auto *MPT = FromType->getAs<MemberPointerType>())
3329 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3330
3331 return nullptr;
3332}
3333
3335 QualType FromType, QualType ToType) {
3336 // If either type is not valid, include no extra info.
3337 if (FromType.isNull() || ToType.isNull()) {
3338 PDiag << ft_default;
3339 return;
3340 }
3341
3342 // Get the function type from the pointers.
3343 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3344 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3345 *ToMember = ToType->castAs<MemberPointerType>();
3346 if (!declaresSameEntity(FromMember->getMostRecentCXXRecordDecl(),
3347 ToMember->getMostRecentCXXRecordDecl())) {
3348 PDiag << ft_different_class;
3349 if (ToMember->isSugared())
3350 PDiag << Context.getCanonicalTagType(
3351 ToMember->getMostRecentCXXRecordDecl());
3352 else
3353 PDiag << ToMember->getQualifier();
3354 if (FromMember->isSugared())
3355 PDiag << Context.getCanonicalTagType(
3356 FromMember->getMostRecentCXXRecordDecl());
3357 else
3358 PDiag << FromMember->getQualifier();
3359 return;
3360 }
3361 FromType = FromMember->getPointeeType();
3362 ToType = ToMember->getPointeeType();
3363 }
3364
3365 if (FromType->isPointerType())
3366 FromType = FromType->getPointeeType();
3367 if (ToType->isPointerType())
3368 ToType = ToType->getPointeeType();
3369
3370 // Remove references.
3371 FromType = FromType.getNonReferenceType();
3372 ToType = ToType.getNonReferenceType();
3373
3374 // Don't print extra info for non-specialized template functions.
3375 if (FromType->isInstantiationDependentType() &&
3376 !FromType->getAs<TemplateSpecializationType>()) {
3377 PDiag << ft_default;
3378 return;
3379 }
3380
3381 // No extra info for same types.
3382 if (Context.hasSameType(FromType, ToType)) {
3383 PDiag << ft_default;
3384 return;
3385 }
3386
3387 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3388 *ToFunction = tryGetFunctionProtoType(ToType);
3389
3390 // Both types need to be function types.
3391 if (!FromFunction || !ToFunction) {
3392 PDiag << ft_default;
3393 return;
3394 }
3395
3396 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3397 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3398 << FromFunction->getNumParams();
3399 return;
3400 }
3401
3402 // Handle different parameter types.
3403 unsigned ArgPos;
3404 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3405 PDiag << ft_parameter_mismatch << ArgPos + 1
3406 << ToFunction->getParamType(ArgPos)
3407 << FromFunction->getParamType(ArgPos);
3408 return;
3409 }
3410
3411 // Handle different return type.
3412 if (!Context.hasSameType(FromFunction->getReturnType(),
3413 ToFunction->getReturnType())) {
3414 PDiag << ft_return_type << ToFunction->getReturnType()
3415 << FromFunction->getReturnType();
3416 return;
3417 }
3418
3419 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3420 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3421 << FromFunction->getMethodQuals();
3422 return;
3423 }
3424
3425 // Handle exception specification differences on canonical type (in C++17
3426 // onwards).
3427 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
3428 ->isNothrow() !=
3429 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3430 ->isNothrow()) {
3431 PDiag << ft_noexcept;
3432 return;
3433 }
3434
3435 // Unable to find a difference, so add no extra info.
3436 PDiag << ft_default;
3437}
3438
3440 ArrayRef<QualType> New, unsigned *ArgPos,
3441 bool Reversed) {
3442 assert(llvm::size(Old) == llvm::size(New) &&
3443 "Can't compare parameters of functions with different number of "
3444 "parameters!");
3445
3446 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3447 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3448 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3449
3450 // Ignore address spaces in pointee type. This is to disallow overloading
3451 // on __ptr32/__ptr64 address spaces.
3452 QualType OldType =
3453 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3454 QualType NewType =
3455 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3456
3457 if (!Context.hasSameType(OldType, NewType)) {
3458 if (ArgPos)
3459 *ArgPos = Idx;
3460 return false;
3461 }
3462 }
3463 return true;
3464}
3465
3467 const FunctionProtoType *NewType,
3468 unsigned *ArgPos, bool Reversed) {
3469 return FunctionParamTypesAreEqual(OldType->param_types(),
3470 NewType->param_types(), ArgPos, Reversed);
3471}
3472
3474 const FunctionDecl *NewFunction,
3475 unsigned *ArgPos,
3476 bool Reversed) {
3477
3478 if (OldFunction->getNumNonObjectParams() !=
3479 NewFunction->getNumNonObjectParams())
3480 return false;
3481
3482 unsigned OldIgnore =
3484 unsigned NewIgnore =
3486
3487 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3488 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3489
3490 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3491 NewPT->param_types().slice(NewIgnore),
3492 ArgPos, Reversed);
3493}
3494
3496 CastKind &Kind,
3497 CXXCastPath& BasePath,
3498 bool IgnoreBaseAccess,
3499 bool Diagnose) {
3500 QualType FromType = From->getType();
3501 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3502
3503 Kind = CK_BitCast;
3504
3505 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3508 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3509 DiagRuntimeBehavior(From->getExprLoc(), From,
3510 PDiag(diag::warn_impcast_bool_to_null_pointer)
3511 << ToType << From->getSourceRange());
3512 else if (!isUnevaluatedContext())
3513 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3514 << ToType << From->getSourceRange();
3515 }
3516 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3517 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3518 QualType FromPointeeType = FromPtrType->getPointeeType(),
3519 ToPointeeType = ToPtrType->getPointeeType();
3520
3521 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3522 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3523 // We must have a derived-to-base conversion. Check an
3524 // ambiguous or inaccessible conversion.
3525 unsigned InaccessibleID = 0;
3526 unsigned AmbiguousID = 0;
3527 if (Diagnose) {
3528 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3529 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3530 }
3531 if (CheckDerivedToBaseConversion(
3532 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3533 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3534 &BasePath, IgnoreBaseAccess))
3535 return true;
3536
3537 // The conversion was successful.
3538 Kind = CK_DerivedToBase;
3539 }
3540
3541 if (Diagnose && !IsCStyleOrFunctionalCast &&
3542 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3543 assert(getLangOpts().MSVCCompat &&
3544 "this should only be possible with MSVCCompat!");
3545 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3546 << From->getSourceRange();
3547 }
3548 }
3549 } else if (const ObjCObjectPointerType *ToPtrType =
3550 ToType->getAs<ObjCObjectPointerType>()) {
3551 if (const ObjCObjectPointerType *FromPtrType =
3552 FromType->getAs<ObjCObjectPointerType>()) {
3553 // Objective-C++ conversions are always okay.
3554 // FIXME: We should have a different class of conversions for the
3555 // Objective-C++ implicit conversions.
3556 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3557 return false;
3558 } else if (FromType->isBlockPointerType()) {
3559 Kind = CK_BlockPointerToObjCPointerCast;
3560 } else {
3561 Kind = CK_CPointerToObjCPointerCast;
3562 }
3563 } else if (ToType->isBlockPointerType()) {
3564 if (!FromType->isBlockPointerType())
3565 Kind = CK_AnyPointerToBlockPointerCast;
3566 }
3567
3568 // We shouldn't fall into this case unless it's valid for other
3569 // reasons.
3571 Kind = CK_NullToPointer;
3572
3573 return false;
3574}
3575
3577 QualType ToType,
3578 bool InOverloadResolution,
3579 QualType &ConvertedType) {
3580 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3581 if (!ToTypePtr)
3582 return false;
3583
3584 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3585 if (From->isNullPointerConstant(Context,
3586 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3588 ConvertedType = ToType;
3589 return true;
3590 }
3591
3592 // Otherwise, both types have to be member pointers.
3593 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3594 if (!FromTypePtr)
3595 return false;
3596
3597 // A pointer to member of B can be converted to a pointer to member of D,
3598 // where D is derived from B (C++ 4.11p2).
3599 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3600 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3601
3602 if (!declaresSameEntity(FromClass, ToClass) &&
3603 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3604 ConvertedType = Context.getMemberPointerType(
3605 FromTypePtr->getPointeeType(), FromTypePtr->getQualifier(), ToClass);
3606 return true;
3607 }
3608
3609 return false;
3610}
3611
3613 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3614 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3615 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3616 // Lock down the inheritance model right now in MS ABI, whether or not the
3617 // pointee types are the same.
3618 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3619 (void)isCompleteType(CheckLoc, FromType);
3620 (void)isCompleteType(CheckLoc, QualType(ToPtrType, 0));
3621 }
3622
3623 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3624 if (!FromPtrType) {
3625 // This must be a null pointer to member pointer conversion
3626 Kind = CK_NullToMemberPointer;
3627 return MemberPointerConversionResult::Success;
3628 }
3629
3630 // T == T, modulo cv
3631 if (Direction == MemberPointerConversionDirection::Upcast &&
3632 !Context.hasSameUnqualifiedType(FromPtrType->getPointeeType(),
3633 ToPtrType->getPointeeType()))
3634 return MemberPointerConversionResult::DifferentPointee;
3635
3636 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3637 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3638
3639 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3640 const CXXRecordDecl *Cls) {
3641 if (declaresSameEntity(Qual.getAsRecordDecl(), Cls))
3642 PD << Qual;
3643 else
3644 PD << Context.getCanonicalTagType(Cls);
3645 };
3646 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3647 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3648 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3649 return PD;
3650 };
3651
3652 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3653 if (Direction == MemberPointerConversionDirection::Upcast)
3654 std::swap(Base, Derived);
3655
3656 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3657 /*DetectVirtual=*/true);
3658 if (!IsDerivedFrom(OpRange.getBegin(), Derived, Base, Paths))
3659 return MemberPointerConversionResult::NotDerived;
3660
3661 if (Paths.isAmbiguous(Context.getCanonicalTagType(Base))) {
3662 PartialDiagnostic PD = PDiag(diag::err_ambiguous_memptr_conv);
3663 PD << int(Direction);
3664 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3665 Diag(CheckLoc, PD);
3666 return MemberPointerConversionResult::Ambiguous;
3667 }
3668
3669 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3670 PartialDiagnostic PD = PDiag(diag::err_memptr_conv_via_virtual);
3671 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3672 Diag(CheckLoc, PD);
3673 return MemberPointerConversionResult::Virtual;
3674 }
3675
3676 // Must be a base to derived member conversion.
3677 BuildBasePathArray(Paths, BasePath);
3678 Kind = Direction == MemberPointerConversionDirection::Upcast
3679 ? CK_DerivedToBaseMemberPointer
3680 : CK_BaseToDerivedMemberPointer;
3681
3682 if (!IgnoreBaseAccess)
3683 switch (CheckBaseClassAccess(
3684 CheckLoc, Base, Derived, Paths.front(),
3685 Direction == MemberPointerConversionDirection::Upcast
3686 ? diag::err_upcast_to_inaccessible_base
3687 : diag::err_downcast_from_inaccessible_base,
3688 [&](PartialDiagnostic &PD) {
3689 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3690 DerivedQual = ToPtrType->getQualifier();
3691 if (Direction == MemberPointerConversionDirection::Upcast)
3692 std::swap(BaseQual, DerivedQual);
3693 DiagCls(PD, DerivedQual, Derived);
3694 DiagCls(PD, BaseQual, Base);
3695 })) {
3697 case Sema::AR_delayed:
3698 case Sema::AR_dependent:
3699 // Optimistically assume that the delayed and dependent cases
3700 // will work out.
3701 break;
3702
3704 return MemberPointerConversionResult::Inaccessible;
3705 }
3706
3707 return MemberPointerConversionResult::Success;
3708}
3709
3710/// Determine whether the lifetime conversion between the two given
3711/// qualifiers sets is nontrivial.
3713 Qualifiers ToQuals) {
3714 // Converting anything to const __unsafe_unretained is trivial.
3715 if (ToQuals.hasConst() &&
3717 return false;
3718
3719 return true;
3720}
3721
3722/// Perform a single iteration of the loop for checking if a qualification
3723/// conversion is valid.
3724///
3725/// Specifically, check whether any change between the qualifiers of \p
3726/// FromType and \p ToType is permissible, given knowledge about whether every
3727/// outer layer is const-qualified.
3729 bool CStyle, bool IsTopLevel,
3730 bool &PreviousToQualsIncludeConst,
3731 bool &ObjCLifetimeConversion,
3732 const ASTContext &Ctx) {
3733 Qualifiers FromQuals = FromType.getQualifiers();
3734 Qualifiers ToQuals = ToType.getQualifiers();
3735
3736 // Ignore __unaligned qualifier.
3737 FromQuals.removeUnaligned();
3738
3739 // Objective-C ARC:
3740 // Check Objective-C lifetime conversions.
3741 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3742 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3743 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3744 ObjCLifetimeConversion = true;
3745 FromQuals.removeObjCLifetime();
3746 ToQuals.removeObjCLifetime();
3747 } else {
3748 // Qualification conversions cannot cast between different
3749 // Objective-C lifetime qualifiers.
3750 return false;
3751 }
3752 }
3753
3754 // Allow addition/removal of GC attributes but not changing GC attributes.
3755 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3756 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3757 FromQuals.removeObjCGCAttr();
3758 ToQuals.removeObjCGCAttr();
3759 }
3760
3761 // __ptrauth qualifiers must match exactly.
3762 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3763 return false;
3764
3765 // -- for every j > 0, if const is in cv 1,j then const is in cv
3766 // 2,j, and similarly for volatile.
3767 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3768 return false;
3769
3770 // If address spaces mismatch:
3771 // - in top level it is only valid to convert to addr space that is a
3772 // superset in all cases apart from C-style casts where we allow
3773 // conversions between overlapping address spaces.
3774 // - in non-top levels it is not a valid conversion.
3775 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3776 (!IsTopLevel ||
3777 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
3778 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
3779 return false;
3780
3781 // -- if the cv 1,j and cv 2,j are different, then const is in
3782 // every cv for 0 < k < j.
3783 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3784 !PreviousToQualsIncludeConst)
3785 return false;
3786
3787 // The following wording is from C++20, where the result of the conversion
3788 // is T3, not T2.
3789 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3790 // "array of unknown bound of"
3791 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3792 return false;
3793
3794 // -- if the resulting P3,i is different from P1,i [...], then const is
3795 // added to every cv 3_k for 0 < k < i.
3796 if (!CStyle && FromType->isConstantArrayType() &&
3797 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3798 return false;
3799
3800 // Keep track of whether all prior cv-qualifiers in the "to" type
3801 // include const.
3802 PreviousToQualsIncludeConst =
3803 PreviousToQualsIncludeConst && ToQuals.hasConst();
3804 return true;
3805}
3806
3807bool
3809 bool CStyle, bool &ObjCLifetimeConversion) {
3810 FromType = Context.getCanonicalType(FromType);
3811 ToType = Context.getCanonicalType(ToType);
3812 ObjCLifetimeConversion = false;
3813
3814 // If FromType and ToType are the same type, this is not a
3815 // qualification conversion.
3816 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3817 return false;
3818
3819 // (C++ 4.4p4):
3820 // A conversion can add cv-qualifiers at levels other than the first
3821 // in multi-level pointers, subject to the following rules: [...]
3822 bool PreviousToQualsIncludeConst = true;
3823 bool UnwrappedAnyPointer = false;
3824 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3825 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3826 !UnwrappedAnyPointer,
3827 PreviousToQualsIncludeConst,
3828 ObjCLifetimeConversion, getASTContext()))
3829 return false;
3830 UnwrappedAnyPointer = true;
3831 }
3832
3833 // We are left with FromType and ToType being the pointee types
3834 // after unwrapping the original FromType and ToType the same number
3835 // of times. If we unwrapped any pointers, and if FromType and
3836 // ToType have the same unqualified type (since we checked
3837 // qualifiers above), then this is a qualification conversion.
3838 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3839}
3840
3841/// - Determine whether this is a conversion from a scalar type to an
3842/// atomic type.
3843///
3844/// If successful, updates \c SCS's second and third steps in the conversion
3845/// sequence to finish the conversion.
3846static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3847 bool InOverloadResolution,
3849 bool CStyle) {
3850 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3851 if (!ToAtomic)
3852 return false;
3853
3855 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3856 InOverloadResolution, InnerSCS,
3857 CStyle, /*AllowObjCWritebackConversion=*/false))
3858 return false;
3859
3860 SCS.Second = InnerSCS.Second;
3861 SCS.setToType(1, InnerSCS.getToType(1));
3862 SCS.Third = InnerSCS.Third;
3865 SCS.setToType(2, InnerSCS.getToType(2));
3866 return true;
3867}
3868
3871 QualType Type) {
3872 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3873 if (CtorType->getNumParams() > 0) {
3874 QualType FirstArg = CtorType->getParamType(0);
3875 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3876 return true;
3877 }
3878 return false;
3879}
3880
3881static OverloadingResult
3883 CXXRecordDecl *To,
3885 OverloadCandidateSet &CandidateSet,
3886 bool AllowExplicit) {
3888 for (auto *D : S.LookupConstructors(To)) {
3889 auto Info = getConstructorInfo(D);
3890 if (!Info)
3891 continue;
3892
3893 bool Usable = !Info.Constructor->isInvalidDecl() &&
3894 S.isInitListConstructor(Info.Constructor);
3895 if (Usable) {
3896 bool SuppressUserConversions = false;
3897 if (Info.ConstructorTmpl)
3898 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3899 /*ExplicitArgs*/ nullptr, From,
3900 CandidateSet, SuppressUserConversions,
3901 /*PartialOverloading*/ false,
3902 AllowExplicit);
3903 else
3904 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3905 CandidateSet, SuppressUserConversions,
3906 /*PartialOverloading*/ false, AllowExplicit);
3907 }
3908 }
3909
3910 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3911
3913 switch (auto Result =
3914 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3915 case OR_Deleted:
3916 case OR_Success: {
3917 // Record the standard conversion we used and the conversion function.
3918 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3919 QualType ThisType = Constructor->getFunctionObjectParameterType();
3920 // Initializer lists don't have conversions as such.
3922 User.HadMultipleCandidates = HadMultipleCandidates;
3924 User.FoundConversionFunction = Best->FoundDecl;
3926 User.After.setFromType(ThisType);
3927 User.After.setAllToTypes(ToType);
3928 return Result;
3929 }
3930
3932 return OR_No_Viable_Function;
3933 case OR_Ambiguous:
3934 return OR_Ambiguous;
3935 }
3936
3937 llvm_unreachable("Invalid OverloadResult!");
3938}
3939
3940/// Determines whether there is a user-defined conversion sequence
3941/// (C++ [over.ics.user]) that converts expression From to the type
3942/// ToType. If such a conversion exists, User will contain the
3943/// user-defined conversion sequence that performs such a conversion
3944/// and this routine will return true. Otherwise, this routine returns
3945/// false and User is unspecified.
3946///
3947/// \param AllowExplicit true if the conversion should consider C++0x
3948/// "explicit" conversion functions as well as non-explicit conversion
3949/// functions (C++0x [class.conv.fct]p2).
3950///
3951/// \param AllowObjCConversionOnExplicit true if the conversion should
3952/// allow an extra Objective-C pointer conversion on uses of explicit
3953/// constructors. Requires \c AllowExplicit to also be set.
3954static OverloadingResult
3957 OverloadCandidateSet &CandidateSet,
3958 AllowedExplicit AllowExplicit,
3959 bool AllowObjCConversionOnExplicit) {
3960 assert(AllowExplicit != AllowedExplicit::None ||
3961 !AllowObjCConversionOnExplicit);
3963
3964 // Whether we will only visit constructors.
3965 bool ConstructorsOnly = false;
3966
3967 // If the type we are conversion to is a class type, enumerate its
3968 // constructors.
3969 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
3970 // C++ [over.match.ctor]p1:
3971 // When objects of class type are direct-initialized (8.5), or
3972 // copy-initialized from an expression of the same or a
3973 // derived class type (8.5), overload resolution selects the
3974 // constructor. [...] For copy-initialization, the candidate
3975 // functions are all the converting constructors (12.3.1) of
3976 // that class. The argument list is the expression-list within
3977 // the parentheses of the initializer.
3978 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3979 (From->getType()->isRecordType() &&
3980 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3981 ConstructorsOnly = true;
3982
3983 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3984 // We're not going to find any constructors.
3985 } else if (auto *ToRecordDecl =
3986 dyn_cast<CXXRecordDecl>(ToRecordType->getOriginalDecl())) {
3987 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
3988
3989 Expr **Args = &From;
3990 unsigned NumArgs = 1;
3991 bool ListInitializing = false;
3992 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3993 // But first, see if there is an init-list-constructor that will work.
3995 S, From, ToType, ToRecordDecl, User, CandidateSet,
3996 AllowExplicit == AllowedExplicit::All);
3998 return Result;
3999 // Never mind.
4000 CandidateSet.clear(
4002
4003 // If we're list-initializing, we pass the individual elements as
4004 // arguments, not the entire list.
4005 Args = InitList->getInits();
4006 NumArgs = InitList->getNumInits();
4007 ListInitializing = true;
4008 }
4009
4010 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
4011 auto Info = getConstructorInfo(D);
4012 if (!Info)
4013 continue;
4014
4015 bool Usable = !Info.Constructor->isInvalidDecl();
4016 if (!ListInitializing)
4017 Usable = Usable && Info.Constructor->isConvertingConstructor(
4018 /*AllowExplicit*/ true);
4019 if (Usable) {
4020 bool SuppressUserConversions = !ConstructorsOnly;
4021 // C++20 [over.best.ics.general]/4.5:
4022 // if the target is the first parameter of a constructor [of class
4023 // X] and the constructor [...] is a candidate by [...] the second
4024 // phase of [over.match.list] when the initializer list has exactly
4025 // one element that is itself an initializer list, [...] and the
4026 // conversion is to X or reference to cv X, user-defined conversion
4027 // sequences are not considered.
4028 if (SuppressUserConversions && ListInitializing) {
4029 SuppressUserConversions =
4030 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
4031 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
4032 ToType);
4033 }
4034 if (Info.ConstructorTmpl)
4036 Info.ConstructorTmpl, Info.FoundDecl,
4037 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
4038 CandidateSet, SuppressUserConversions,
4039 /*PartialOverloading*/ false,
4040 AllowExplicit == AllowedExplicit::All);
4041 else
4042 // Allow one user-defined conversion when user specifies a
4043 // From->ToType conversion via an static cast (c-style, etc).
4044 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4045 llvm::ArrayRef(Args, NumArgs), CandidateSet,
4046 SuppressUserConversions,
4047 /*PartialOverloading*/ false,
4048 AllowExplicit == AllowedExplicit::All);
4049 }
4050 }
4051 }
4052 }
4053
4054 // Enumerate conversion functions, if we're allowed to.
4055 if (ConstructorsOnly || isa<InitListExpr>(From)) {
4056 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
4057 // No conversion functions from incomplete types.
4058 } else if (const RecordType *FromRecordType =
4059 From->getType()->getAsCanonical<RecordType>()) {
4060 if (auto *FromRecordDecl =
4061 dyn_cast<CXXRecordDecl>(FromRecordType->getOriginalDecl())) {
4062 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4063 // Add all of the conversion functions as candidates.
4064 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4065 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4066 DeclAccessPair FoundDecl = I.getPair();
4067 NamedDecl *D = FoundDecl.getDecl();
4068 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
4069 if (isa<UsingShadowDecl>(D))
4070 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4071
4072 CXXConversionDecl *Conv;
4073 FunctionTemplateDecl *ConvTemplate;
4074 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
4075 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4076 else
4077 Conv = cast<CXXConversionDecl>(D);
4078
4079 if (ConvTemplate)
4081 ConvTemplate, FoundDecl, ActingContext, From, ToType,
4082 CandidateSet, AllowObjCConversionOnExplicit,
4083 AllowExplicit != AllowedExplicit::None);
4084 else
4085 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
4086 CandidateSet, AllowObjCConversionOnExplicit,
4087 AllowExplicit != AllowedExplicit::None);
4088 }
4089 }
4090 }
4091
4092 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4093
4095 switch (auto Result =
4096 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4097 case OR_Success:
4098 case OR_Deleted:
4099 // Record the standard conversion we used and the conversion function.
4101 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
4102 // C++ [over.ics.user]p1:
4103 // If the user-defined conversion is specified by a
4104 // constructor (12.3.1), the initial standard conversion
4105 // sequence converts the source type to the type required by
4106 // the argument of the constructor.
4107 //
4108 if (isa<InitListExpr>(From)) {
4109 // Initializer lists don't have conversions as such.
4111 User.Before.FromBracedInitList = true;
4112 } else {
4113 if (Best->Conversions[0].isEllipsis())
4114 User.EllipsisConversion = true;
4115 else {
4116 User.Before = Best->Conversions[0].Standard;
4117 User.EllipsisConversion = false;
4118 }
4119 }
4120 User.HadMultipleCandidates = HadMultipleCandidates;
4122 User.FoundConversionFunction = Best->FoundDecl;
4124 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4125 User.After.setAllToTypes(ToType);
4126 return Result;
4127 }
4128 if (CXXConversionDecl *Conversion
4129 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4130
4131 assert(Best->HasFinalConversion);
4132
4133 // C++ [over.ics.user]p1:
4134 //
4135 // [...] If the user-defined conversion is specified by a
4136 // conversion function (12.3.2), the initial standard
4137 // conversion sequence converts the source type to the
4138 // implicit object parameter of the conversion function.
4139 User.Before = Best->Conversions[0].Standard;
4140 User.HadMultipleCandidates = HadMultipleCandidates;
4141 User.ConversionFunction = Conversion;
4142 User.FoundConversionFunction = Best->FoundDecl;
4143 User.EllipsisConversion = false;
4144
4145 // C++ [over.ics.user]p2:
4146 // The second standard conversion sequence converts the
4147 // result of the user-defined conversion to the target type
4148 // for the sequence. Since an implicit conversion sequence
4149 // is an initialization, the special rules for
4150 // initialization by user-defined conversion apply when
4151 // selecting the best user-defined conversion for a
4152 // user-defined conversion sequence (see 13.3.3 and
4153 // 13.3.3.1).
4154 User.After = Best->FinalConversion;
4155 return Result;
4156 }
4157 llvm_unreachable("Not a constructor or conversion function?");
4158
4160 return OR_No_Viable_Function;
4161
4162 case OR_Ambiguous:
4163 return OR_Ambiguous;
4164 }
4165
4166 llvm_unreachable("Invalid OverloadResult!");
4167}
4168
4169bool
4172 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4174 OverloadingResult OvResult =
4175 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4176 CandidateSet, AllowedExplicit::None, false);
4177
4178 if (!(OvResult == OR_Ambiguous ||
4179 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4180 return false;
4181
4182 auto Cands = CandidateSet.CompleteCandidates(
4183 *this,
4185 From);
4186 if (OvResult == OR_Ambiguous)
4187 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4188 << From->getType() << ToType << From->getSourceRange();
4189 else { // OR_No_Viable_Function && !CandidateSet.empty()
4190 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4191 diag::err_typecheck_nonviable_condition_incomplete,
4192 From->getType(), From->getSourceRange()))
4193 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4194 << false << From->getType() << From->getSourceRange() << ToType;
4195 }
4196
4197 CandidateSet.NoteCandidates(
4198 *this, From, Cands);
4199 return true;
4200}
4201
4202// Helper for compareConversionFunctions that gets the FunctionType that the
4203// conversion-operator return value 'points' to, or nullptr.
4204static const FunctionType *
4206 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4207 const PointerType *RetPtrTy =
4208 ConvFuncTy->getReturnType()->getAs<PointerType>();
4209
4210 if (!RetPtrTy)
4211 return nullptr;
4212
4213 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4214}
4215
4216/// Compare the user-defined conversion functions or constructors
4217/// of two user-defined conversion sequences to determine whether any ordering
4218/// is possible.
4221 FunctionDecl *Function2) {
4222 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4223 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4224 if (!Conv1 || !Conv2)
4226
4227 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4229
4230 // Objective-C++:
4231 // If both conversion functions are implicitly-declared conversions from
4232 // a lambda closure type to a function pointer and a block pointer,
4233 // respectively, always prefer the conversion to a function pointer,
4234 // because the function pointer is more lightweight and is more likely
4235 // to keep code working.
4236 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4237 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4238 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4239 if (Block1 != Block2)
4240 return Block1 ? ImplicitConversionSequence::Worse
4242 }
4243
4244 // In order to support multiple calling conventions for the lambda conversion
4245 // operator (such as when the free and member function calling convention is
4246 // different), prefer the 'free' mechanism, followed by the calling-convention
4247 // of operator(). The latter is in place to support the MSVC-like solution of
4248 // defining ALL of the possible conversions in regards to calling-convention.
4249 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4250 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4251
4252 if (Conv1FuncRet && Conv2FuncRet &&
4253 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4254 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4255 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4256
4257 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4258 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4259
4260 CallingConv CallOpCC =
4261 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4263 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4265 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4266
4267 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4268 for (CallingConv CC : PrefOrder) {
4269 if (Conv1CC == CC)
4271 if (Conv2CC == CC)
4273 }
4274 }
4275
4277}
4278
4280 const ImplicitConversionSequence &ICS) {
4282 (ICS.isUserDefined() &&
4284}
4285
4286/// CompareImplicitConversionSequences - Compare two implicit
4287/// conversion sequences to determine whether one is better than the
4288/// other or if they are indistinguishable (C++ 13.3.3.2).
4291 const ImplicitConversionSequence& ICS1,
4292 const ImplicitConversionSequence& ICS2)
4293{
4294 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4295 // conversion sequences (as defined in 13.3.3.1)
4296 // -- a standard conversion sequence (13.3.3.1.1) is a better
4297 // conversion sequence than a user-defined conversion sequence or
4298 // an ellipsis conversion sequence, and
4299 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4300 // conversion sequence than an ellipsis conversion sequence
4301 // (13.3.3.1.3).
4302 //
4303 // C++0x [over.best.ics]p10:
4304 // For the purpose of ranking implicit conversion sequences as
4305 // described in 13.3.3.2, the ambiguous conversion sequence is
4306 // treated as a user-defined sequence that is indistinguishable
4307 // from any other user-defined conversion sequence.
4308
4309 // String literal to 'char *' conversion has been deprecated in C++03. It has
4310 // been removed from C++11. We still accept this conversion, if it happens at
4311 // the best viable function. Otherwise, this conversion is considered worse
4312 // than ellipsis conversion. Consider this as an extension; this is not in the
4313 // standard. For example:
4314 //
4315 // int &f(...); // #1
4316 // void f(char*); // #2
4317 // void g() { int &r = f("foo"); }
4318 //
4319 // In C++03, we pick #2 as the best viable function.
4320 // In C++11, we pick #1 as the best viable function, because ellipsis
4321 // conversion is better than string-literal to char* conversion (since there
4322 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4323 // convert arguments, #2 would be the best viable function in C++11.
4324 // If the best viable function has this conversion, a warning will be issued
4325 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4326
4327 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4330 // Ill-formedness must not differ
4331 ICS1.isBad() == ICS2.isBad())
4335
4336 if (ICS1.getKindRank() < ICS2.getKindRank())
4338 if (ICS2.getKindRank() < ICS1.getKindRank())
4340
4341 // The following checks require both conversion sequences to be of
4342 // the same kind.
4343 if (ICS1.getKind() != ICS2.getKind())
4345
4348
4349 // Two implicit conversion sequences of the same form are
4350 // indistinguishable conversion sequences unless one of the
4351 // following rules apply: (C++ 13.3.3.2p3):
4352
4353 // List-initialization sequence L1 is a better conversion sequence than
4354 // list-initialization sequence L2 if:
4355 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4356 // if not that,
4357 // — L1 and L2 convert to arrays of the same element type, and either the
4358 // number of elements n_1 initialized by L1 is less than the number of
4359 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4360 // an array of unknown bound and L1 does not,
4361 // even if one of the other rules in this paragraph would otherwise apply.
4362 if (!ICS1.isBad()) {
4363 bool StdInit1 = false, StdInit2 = false;
4366 nullptr);
4369 nullptr);
4370 if (StdInit1 != StdInit2)
4371 return StdInit1 ? ImplicitConversionSequence::Better
4373
4376 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4378 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4380 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4381 CAT2->getElementType())) {
4382 // Both to arrays of the same element type
4383 if (CAT1->getSize() != CAT2->getSize())
4384 // Different sized, the smaller wins
4385 return CAT1->getSize().ult(CAT2->getSize())
4390 // One is incomplete, it loses
4394 }
4395 }
4396 }
4397
4398 if (ICS1.isStandard())
4399 // Standard conversion sequence S1 is a better conversion sequence than
4400 // standard conversion sequence S2 if [...]
4402 ICS1.Standard, ICS2.Standard);
4403 else if (ICS1.isUserDefined()) {
4404 // User-defined conversion sequence U1 is a better conversion
4405 // sequence than another user-defined conversion sequence U2 if
4406 // they contain the same user-defined conversion function or
4407 // constructor and if the second standard conversion sequence of
4408 // U1 is better than the second standard conversion sequence of
4409 // U2 (C++ 13.3.3.2p3).
4413 ICS1.UserDefined.After,
4414 ICS2.UserDefined.After);
4415 else
4419 }
4420
4421 return Result;
4422}
4423
4424// Per 13.3.3.2p3, compare the given standard conversion sequences to
4425// determine if one is a proper subset of the other.
4428 const StandardConversionSequence& SCS1,
4429 const StandardConversionSequence& SCS2) {
4432
4433 // the identity conversion sequence is considered to be a subsequence of
4434 // any non-identity conversion sequence
4435 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4437 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4439
4440 if (SCS1.Second != SCS2.Second) {
4441 if (SCS1.Second == ICK_Identity)
4443 else if (SCS2.Second == ICK_Identity)
4445 else
4447 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4449
4450 if (SCS1.Third == SCS2.Third) {
4451 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4453 }
4454
4455 if (SCS1.Third == ICK_Identity)
4459
4460 if (SCS2.Third == ICK_Identity)
4464
4466}
4467
4468/// Determine whether one of the given reference bindings is better
4469/// than the other based on what kind of bindings they are.
4470static bool
4472 const StandardConversionSequence &SCS2) {
4473 // C++0x [over.ics.rank]p3b4:
4474 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4475 // implicit object parameter of a non-static member function declared
4476 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4477 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4478 // lvalue reference to a function lvalue and S2 binds an rvalue
4479 // reference*.
4480 //
4481 // FIXME: Rvalue references. We're going rogue with the above edits,
4482 // because the semantics in the current C++0x working paper (N3225 at the
4483 // time of this writing) break the standard definition of std::forward
4484 // and std::reference_wrapper when dealing with references to functions.
4485 // Proposed wording changes submitted to CWG for consideration.
4488 return false;
4489
4490 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4491 SCS2.IsLvalueReference) ||
4494}
4495
4497 None,
4500};
4501
4502/// Returns kind of fixed enum promotion the \a SCS uses.
4503static FixedEnumPromotion
4505
4506 if (SCS.Second != ICK_Integral_Promotion)
4507 return FixedEnumPromotion::None;
4508
4509 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4510 if (!Enum)
4511 return FixedEnumPromotion::None;
4512
4513 if (!Enum->isFixed())
4514 return FixedEnumPromotion::None;
4515
4516 QualType UnderlyingType = Enum->getIntegerType();
4517 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4518 return FixedEnumPromotion::ToUnderlyingType;
4519
4520 return FixedEnumPromotion::ToPromotedUnderlyingType;
4521}
4522
4523/// CompareStandardConversionSequences - Compare two standard
4524/// conversion sequences to determine whether one is better than the
4525/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4528 const StandardConversionSequence& SCS1,
4529 const StandardConversionSequence& SCS2)
4530{
4531 // Standard conversion sequence S1 is a better conversion sequence
4532 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4533
4534 // -- S1 is a proper subsequence of S2 (comparing the conversion
4535 // sequences in the canonical form defined by 13.3.3.1.1,
4536 // excluding any Lvalue Transformation; the identity conversion
4537 // sequence is considered to be a subsequence of any
4538 // non-identity conversion sequence) or, if not that,
4541 return CK;
4542
4543 // -- the rank of S1 is better than the rank of S2 (by the rules
4544 // defined below), or, if not that,
4545 ImplicitConversionRank Rank1 = SCS1.getRank();
4546 ImplicitConversionRank Rank2 = SCS2.getRank();
4547 if (Rank1 < Rank2)
4549 else if (Rank2 < Rank1)
4551
4552 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4553 // are indistinguishable unless one of the following rules
4554 // applies:
4555
4556 // A conversion that is not a conversion of a pointer, or
4557 // pointer to member, to bool is better than another conversion
4558 // that is such a conversion.
4560 return SCS2.isPointerConversionToBool()
4563
4564 // C++14 [over.ics.rank]p4b2:
4565 // This is retroactively applied to C++11 by CWG 1601.
4566 //
4567 // A conversion that promotes an enumeration whose underlying type is fixed
4568 // to its underlying type is better than one that promotes to the promoted
4569 // underlying type, if the two are different.
4572 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4573 FEP1 != FEP2)
4574 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4577
4578 // C++ [over.ics.rank]p4b2:
4579 //
4580 // If class B is derived directly or indirectly from class A,
4581 // conversion of B* to A* is better than conversion of B* to
4582 // void*, and conversion of A* to void* is better than conversion
4583 // of B* to void*.
4584 bool SCS1ConvertsToVoid
4586 bool SCS2ConvertsToVoid
4588 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4589 // Exactly one of the conversion sequences is a conversion to
4590 // a void pointer; it's the worse conversion.
4591 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4593 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4594 // Neither conversion sequence converts to a void pointer; compare
4595 // their derived-to-base conversions.
4597 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4598 return DerivedCK;
4599 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4600 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4601 // Both conversion sequences are conversions to void
4602 // pointers. Compare the source types to determine if there's an
4603 // inheritance relationship in their sources.
4604 QualType FromType1 = SCS1.getFromType();
4605 QualType FromType2 = SCS2.getFromType();
4606
4607 // Adjust the types we're converting from via the array-to-pointer
4608 // conversion, if we need to.
4609 if (SCS1.First == ICK_Array_To_Pointer)
4610 FromType1 = S.Context.getArrayDecayedType(FromType1);
4611 if (SCS2.First == ICK_Array_To_Pointer)
4612 FromType2 = S.Context.getArrayDecayedType(FromType2);
4613
4614 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4615 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4616
4617 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4619 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4621
4622 // Objective-C++: If one interface is more specific than the
4623 // other, it is the better one.
4624 const ObjCObjectPointerType* FromObjCPtr1
4625 = FromType1->getAs<ObjCObjectPointerType>();
4626 const ObjCObjectPointerType* FromObjCPtr2
4627 = FromType2->getAs<ObjCObjectPointerType>();
4628 if (FromObjCPtr1 && FromObjCPtr2) {
4629 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4630 FromObjCPtr2);
4631 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4632 FromObjCPtr1);
4633 if (AssignLeft != AssignRight) {
4634 return AssignLeft? ImplicitConversionSequence::Better
4636 }
4637 }
4638 }
4639
4640 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4641 // Check for a better reference binding based on the kind of bindings.
4642 if (isBetterReferenceBindingKind(SCS1, SCS2))
4644 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4646 }
4647
4648 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4649 // bullet 3).
4651 = CompareQualificationConversions(S, SCS1, SCS2))
4652 return QualCK;
4653
4654 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4655 // C++ [over.ics.rank]p3b4:
4656 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4657 // which the references refer are the same type except for
4658 // top-level cv-qualifiers, and the type to which the reference
4659 // initialized by S2 refers is more cv-qualified than the type
4660 // to which the reference initialized by S1 refers.
4661 QualType T1 = SCS1.getToType(2);
4662 QualType T2 = SCS2.getToType(2);
4663 T1 = S.Context.getCanonicalType(T1);
4664 T2 = S.Context.getCanonicalType(T2);
4665 Qualifiers T1Quals, T2Quals;
4666 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4667 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4668 if (UnqualT1 == UnqualT2) {
4669 // Objective-C++ ARC: If the references refer to objects with different
4670 // lifetimes, prefer bindings that don't change lifetime.
4676 }
4677
4678 // If the type is an array type, promote the element qualifiers to the
4679 // type for comparison.
4680 if (isa<ArrayType>(T1) && T1Quals)
4681 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4682 if (isa<ArrayType>(T2) && T2Quals)
4683 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4684 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4686 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4688 }
4689 }
4690
4691 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4692 // floating-to-integral conversion if the integral conversion
4693 // is between types of the same size.
4694 // For example:
4695 // void f(float);
4696 // void f(int);
4697 // int main {
4698 // long a;
4699 // f(a);
4700 // }
4701 // Here, MSVC will call f(int) instead of generating a compile error
4702 // as clang will do in standard mode.
4703 if (S.getLangOpts().MSVCCompat &&
4706 SCS2.Second == ICK_Floating_Integral &&
4707 S.Context.getTypeSize(SCS1.getFromType()) ==
4708 S.Context.getTypeSize(SCS1.getToType(2)))
4710
4711 // Prefer a compatible vector conversion over a lax vector conversion
4712 // For example:
4713 //
4714 // typedef float __v4sf __attribute__((__vector_size__(16)));
4715 // void f(vector float);
4716 // void f(vector signed int);
4717 // int main() {
4718 // __v4sf a;
4719 // f(a);
4720 // }
4721 // Here, we'd like to choose f(vector float) and not
4722 // report an ambiguous call error
4723 if (SCS1.Second == ICK_Vector_Conversion &&
4724 SCS2.Second == ICK_Vector_Conversion) {
4725 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4726 SCS1.getFromType(), SCS1.getToType(2));
4727 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4728 SCS2.getFromType(), SCS2.getToType(2));
4729
4730 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4731 return SCS1IsCompatibleVectorConversion
4734 }
4735
4736 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4738 bool SCS1IsCompatibleSVEVectorConversion =
4739 S.ARM().areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4740 bool SCS2IsCompatibleSVEVectorConversion =
4741 S.ARM().areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4742
4743 if (SCS1IsCompatibleSVEVectorConversion !=
4744 SCS2IsCompatibleSVEVectorConversion)
4745 return SCS1IsCompatibleSVEVectorConversion
4748 }
4749
4750 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4752 bool SCS1IsCompatibleRVVVectorConversion =
4754 bool SCS2IsCompatibleRVVVectorConversion =
4756
4757 if (SCS1IsCompatibleRVVVectorConversion !=
4758 SCS2IsCompatibleRVVVectorConversion)
4759 return SCS1IsCompatibleRVVVectorConversion
4762 }
4764}
4765
4766/// CompareQualificationConversions - Compares two standard conversion
4767/// sequences to determine whether they can be ranked based on their
4768/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4771 const StandardConversionSequence& SCS1,
4772 const StandardConversionSequence& SCS2) {
4773 // C++ [over.ics.rank]p3:
4774 // -- S1 and S2 differ only in their qualification conversion and
4775 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4776 // [C++98]
4777 // [...] and the cv-qualification signature of type T1 is a proper subset
4778 // of the cv-qualification signature of type T2, and S1 is not the
4779 // deprecated string literal array-to-pointer conversion (4.2).
4780 // [C++2a]
4781 // [...] where T1 can be converted to T2 by a qualification conversion.
4782 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4783 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4785
4786 // FIXME: the example in the standard doesn't use a qualification
4787 // conversion (!)
4788 QualType T1 = SCS1.getToType(2);
4789 QualType T2 = SCS2.getToType(2);
4790 T1 = S.Context.getCanonicalType(T1);
4791 T2 = S.Context.getCanonicalType(T2);
4792 assert(!T1->isReferenceType() && !T2->isReferenceType());
4793 Qualifiers T1Quals, T2Quals;
4794 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4795 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4796
4797 // If the types are the same, we won't learn anything by unwrapping
4798 // them.
4799 if (UnqualT1 == UnqualT2)
4801
4802 // Don't ever prefer a standard conversion sequence that uses the deprecated
4803 // string literal array to pointer conversion.
4804 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4805 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4806
4807 // Objective-C++ ARC:
4808 // Prefer qualification conversions not involving a change in lifetime
4809 // to qualification conversions that do change lifetime.
4812 CanPick1 = false;
4815 CanPick2 = false;
4816
4817 bool ObjCLifetimeConversion;
4818 if (CanPick1 &&
4819 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4820 CanPick1 = false;
4821 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4822 // directions, so we can't short-cut this second check in general.
4823 if (CanPick2 &&
4824 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4825 CanPick2 = false;
4826
4827 if (CanPick1 != CanPick2)
4828 return CanPick1 ? ImplicitConversionSequence::Better
4831}
4832
4833/// CompareDerivedToBaseConversions - Compares two standard conversion
4834/// sequences to determine whether they can be ranked based on their
4835/// various kinds of derived-to-base conversions (C++
4836/// [over.ics.rank]p4b3). As part of these checks, we also look at
4837/// conversions between Objective-C interface types.
4840 const StandardConversionSequence& SCS1,
4841 const StandardConversionSequence& SCS2) {
4842 QualType FromType1 = SCS1.getFromType();
4843 QualType ToType1 = SCS1.getToType(1);
4844 QualType FromType2 = SCS2.getFromType();
4845 QualType ToType2 = SCS2.getToType(1);
4846
4847 // Adjust the types we're converting from via the array-to-pointer
4848 // conversion, if we need to.
4849 if (SCS1.First == ICK_Array_To_Pointer)
4850 FromType1 = S.Context.getArrayDecayedType(FromType1);
4851 if (SCS2.First == ICK_Array_To_Pointer)
4852 FromType2 = S.Context.getArrayDecayedType(FromType2);
4853
4854 // Canonicalize all of the types.
4855 FromType1 = S.Context.getCanonicalType(FromType1);
4856 ToType1 = S.Context.getCanonicalType(ToType1);
4857 FromType2 = S.Context.getCanonicalType(FromType2);
4858 ToType2 = S.Context.getCanonicalType(ToType2);
4859
4860 // C++ [over.ics.rank]p4b3:
4861 //
4862 // If class B is derived directly or indirectly from class A and
4863 // class C is derived directly or indirectly from B,
4864 //
4865 // Compare based on pointer conversions.
4866 if (SCS1.Second == ICK_Pointer_Conversion &&
4868 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4869 FromType1->isPointerType() && FromType2->isPointerType() &&
4870 ToType1->isPointerType() && ToType2->isPointerType()) {
4871 QualType FromPointee1 =
4873 QualType ToPointee1 =
4875 QualType FromPointee2 =
4877 QualType ToPointee2 =
4879
4880 // -- conversion of C* to B* is better than conversion of C* to A*,
4881 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4882 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4884 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4886 }
4887
4888 // -- conversion of B* to A* is better than conversion of C* to A*,
4889 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4890 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4892 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4894 }
4895 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4897 const ObjCObjectPointerType *FromPtr1
4898 = FromType1->getAs<ObjCObjectPointerType>();
4899 const ObjCObjectPointerType *FromPtr2
4900 = FromType2->getAs<ObjCObjectPointerType>();
4901 const ObjCObjectPointerType *ToPtr1
4902 = ToType1->getAs<ObjCObjectPointerType>();
4903 const ObjCObjectPointerType *ToPtr2
4904 = ToType2->getAs<ObjCObjectPointerType>();
4905
4906 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4907 // Apply the same conversion ranking rules for Objective-C pointer types
4908 // that we do for C++ pointers to class types. However, we employ the
4909 // Objective-C pseudo-subtyping relationship used for assignment of
4910 // Objective-C pointer types.
4911 bool FromAssignLeft
4912 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4913 bool FromAssignRight
4914 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4915 bool ToAssignLeft
4916 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4917 bool ToAssignRight
4918 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4919
4920 // A conversion to an a non-id object pointer type or qualified 'id'
4921 // type is better than a conversion to 'id'.
4922 if (ToPtr1->isObjCIdType() &&
4923 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4925 if (ToPtr2->isObjCIdType() &&
4926 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4928
4929 // A conversion to a non-id object pointer type is better than a
4930 // conversion to a qualified 'id' type
4931 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4933 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4935
4936 // A conversion to an a non-Class object pointer type or qualified 'Class'
4937 // type is better than a conversion to 'Class'.
4938 if (ToPtr1->isObjCClassType() &&
4939 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4941 if (ToPtr2->isObjCClassType() &&
4942 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4944
4945 // A conversion to a non-Class object pointer type is better than a
4946 // conversion to a qualified 'Class' type.
4947 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4949 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4951
4952 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4953 if (S.Context.hasSameType(FromType1, FromType2) &&
4954 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4955 (ToAssignLeft != ToAssignRight)) {
4956 if (FromPtr1->isSpecialized()) {
4957 // "conversion of B<A> * to B * is better than conversion of B * to
4958 // C *.
4959 bool IsFirstSame =
4960 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4961 bool IsSecondSame =
4962 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4963 if (IsFirstSame) {
4964 if (!IsSecondSame)
4966 } else if (IsSecondSame)
4968 }
4969 return ToAssignLeft? ImplicitConversionSequence::Worse
4971 }
4972
4973 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4974 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4975 (FromAssignLeft != FromAssignRight))
4976 return FromAssignLeft? ImplicitConversionSequence::Better
4978 }
4979 }
4980
4981 // Ranking of member-pointer types.
4982 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4983 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4984 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4985 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4986 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4987 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4988 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4989 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
4990 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
4991 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
4992 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
4993 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4994 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4995 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4997 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4999 }
5000 // conversion of B::* to C::* is better than conversion of A::* to C::*
5001 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5002 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5004 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5006 }
5007 }
5008
5009 if (SCS1.Second == ICK_Derived_To_Base) {
5010 // -- conversion of C to B is better than conversion of C to A,
5011 // -- binding of an expression of type C to a reference of type
5012 // B& is better than binding an expression of type C to a
5013 // reference of type A&,
5014 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5015 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5016 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
5018 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
5020 }
5021
5022 // -- conversion of B to A is better than conversion of C to A.
5023 // -- binding of an expression of type B to a reference of type
5024 // A& is better than binding an expression of type C to a
5025 // reference of type A&,
5026 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5027 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5028 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
5030 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
5032 }
5033 }
5034
5036}
5037
5039 if (!T.getQualifiers().hasUnaligned())
5040 return T;
5041
5042 Qualifiers Q;
5043 T = Ctx.getUnqualifiedArrayType(T, Q);
5044 Q.removeUnaligned();
5045 return Ctx.getQualifiedType(T, Q);
5046}
5047
5050 QualType OrigT1, QualType OrigT2,
5051 ReferenceConversions *ConvOut) {
5052 assert(!OrigT1->isReferenceType() &&
5053 "T1 must be the pointee type of the reference type");
5054 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5055
5056 QualType T1 = Context.getCanonicalType(OrigT1);
5057 QualType T2 = Context.getCanonicalType(OrigT2);
5058 Qualifiers T1Quals, T2Quals;
5059 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
5060 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
5061
5062 ReferenceConversions ConvTmp;
5063 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5064 Conv = ReferenceConversions();
5065
5066 // C++2a [dcl.init.ref]p4:
5067 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5068 // reference-related to "cv2 T2" if T1 is similar to T2, or
5069 // T1 is a base class of T2.
5070 // "cv1 T1" is reference-compatible with "cv2 T2" if
5071 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5072 // "pointer to cv1 T1" via a standard conversion sequence.
5073
5074 // Check for standard conversions we can apply to pointers: derived-to-base
5075 // conversions, ObjC pointer conversions, and function pointer conversions.
5076 // (Qualification conversions are checked last.)
5077 if (UnqualT1 == UnqualT2) {
5078 // Nothing to do.
5079 } else if (isCompleteType(Loc, OrigT2) &&
5080 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
5081 Conv |= ReferenceConversions::DerivedToBase;
5082 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5083 UnqualT2->isObjCObjectOrInterfaceType() &&
5084 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
5085 Conv |= ReferenceConversions::ObjC;
5086 else if (UnqualT2->isFunctionType() &&
5087 IsFunctionConversion(UnqualT2, UnqualT1)) {
5088 Conv |= ReferenceConversions::Function;
5089 // No need to check qualifiers; function types don't have them.
5090 return Ref_Compatible;
5091 }
5092 bool ConvertedReferent = Conv != 0;
5093
5094 // We can have a qualification conversion. Compute whether the types are
5095 // similar at the same time.
5096 bool PreviousToQualsIncludeConst = true;
5097 bool TopLevel = true;
5098 do {
5099 if (T1 == T2)
5100 break;
5101
5102 // We will need a qualification conversion.
5103 Conv |= ReferenceConversions::Qualification;
5104
5105 // Track whether we performed a qualification conversion anywhere other
5106 // than the top level. This matters for ranking reference bindings in
5107 // overload resolution.
5108 if (!TopLevel)
5109 Conv |= ReferenceConversions::NestedQualification;
5110
5111 // MS compiler ignores __unaligned qualifier for references; do the same.
5112 T1 = withoutUnaligned(Context, T1);
5113 T2 = withoutUnaligned(Context, T2);
5114
5115 // If we find a qualifier mismatch, the types are not reference-compatible,
5116 // but are still be reference-related if they're similar.
5117 bool ObjCLifetimeConversion = false;
5118 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5119 PreviousToQualsIncludeConst,
5120 ObjCLifetimeConversion, getASTContext()))
5121 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5122 ? Ref_Related
5123 : Ref_Incompatible;
5124
5125 // FIXME: Should we track this for any level other than the first?
5126 if (ObjCLifetimeConversion)
5127 Conv |= ReferenceConversions::ObjCLifetime;
5128
5129 TopLevel = false;
5130 } while (Context.UnwrapSimilarTypes(T1, T2));
5131
5132 // At this point, if the types are reference-related, we must either have the
5133 // same inner type (ignoring qualifiers), or must have already worked out how
5134 // to convert the referent.
5135 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5136 ? Ref_Compatible
5137 : Ref_Incompatible;
5138}
5139
5140/// Look for a user-defined conversion to a value reference-compatible
5141/// with DeclType. Return true if something definite is found.
5142static bool
5144 QualType DeclType, SourceLocation DeclLoc,
5145 Expr *Init, QualType T2, bool AllowRvalues,
5146 bool AllowExplicit) {
5147 assert(T2->isRecordType() && "Can only find conversions of record types.");
5148 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5149 OverloadCandidateSet CandidateSet(
5151 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5152 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5153 NamedDecl *D = *I;
5154 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5155 if (isa<UsingShadowDecl>(D))
5156 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5157
5158 FunctionTemplateDecl *ConvTemplate
5159 = dyn_cast<FunctionTemplateDecl>(D);
5160 CXXConversionDecl *Conv;
5161 if (ConvTemplate)
5162 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5163 else
5164 Conv = cast<CXXConversionDecl>(D);
5165
5166 if (AllowRvalues) {
5167 // If we are initializing an rvalue reference, don't permit conversion
5168 // functions that return lvalues.
5169 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5170 const ReferenceType *RefType
5172 if (RefType && !RefType->getPointeeType()->isFunctionType())
5173 continue;
5174 }
5175
5176 if (!ConvTemplate &&
5178 DeclLoc,
5179 Conv->getConversionType()
5184 continue;
5185 } else {
5186 // If the conversion function doesn't return a reference type,
5187 // it can't be considered for this conversion. An rvalue reference
5188 // is only acceptable if its referencee is a function type.
5189
5190 const ReferenceType *RefType =
5192 if (!RefType ||
5193 (!RefType->isLValueReferenceType() &&
5194 !RefType->getPointeeType()->isFunctionType()))
5195 continue;
5196 }
5197
5198 if (ConvTemplate)
5200 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5201 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5202 else
5204 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5205 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5206 }
5207
5208 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5209
5211 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5212 case OR_Success:
5213
5214 assert(Best->HasFinalConversion);
5215
5216 // C++ [over.ics.ref]p1:
5217 //
5218 // [...] If the parameter binds directly to the result of
5219 // applying a conversion function to the argument
5220 // expression, the implicit conversion sequence is a
5221 // user-defined conversion sequence (13.3.3.1.2), with the
5222 // second standard conversion sequence either an identity
5223 // conversion or, if the conversion function returns an
5224 // entity of a type that is a derived class of the parameter
5225 // type, a derived-to-base Conversion.
5226 if (!Best->FinalConversion.DirectBinding)
5227 return false;
5228
5229 ICS.setUserDefined();
5230 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5231 ICS.UserDefined.After = Best->FinalConversion;
5232 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5233 ICS.UserDefined.ConversionFunction = Best->Function;
5234 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5235 ICS.UserDefined.EllipsisConversion = false;
5236 assert(ICS.UserDefined.After.ReferenceBinding &&
5238 "Expected a direct reference binding!");
5239 return true;
5240
5241 case OR_Ambiguous:
5242 ICS.setAmbiguous();
5243 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5244 Cand != CandidateSet.end(); ++Cand)
5245 if (Cand->Best)
5246 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5247 return true;
5248
5250 case OR_Deleted:
5251 // There was no suitable conversion, or we found a deleted
5252 // conversion; continue with other checks.
5253 return false;
5254 }
5255
5256 llvm_unreachable("Invalid OverloadResult!");
5257}
5258
5259/// Compute an implicit conversion sequence for reference
5260/// initialization.
5263 SourceLocation DeclLoc,
5264 bool SuppressUserConversions,
5265 bool AllowExplicit) {
5266 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5267
5268 // Most paths end in a failed conversion.
5271
5272 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5273 QualType T2 = Init->getType();
5274
5275 // If the initializer is the address of an overloaded function, try
5276 // to resolve the overloaded function. If all goes well, T2 is the
5277 // type of the resulting function.
5278 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5281 false, Found))
5282 T2 = Fn->getType();
5283 }
5284
5285 // Compute some basic properties of the types and the initializer.
5286 bool isRValRef = DeclType->isRValueReferenceType();
5287 Expr::Classification InitCategory = Init->Classify(S.Context);
5288
5290 Sema::ReferenceCompareResult RefRelationship =
5291 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5292
5293 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5294 ICS.setStandard();
5296 // FIXME: A reference binding can be a function conversion too. We should
5297 // consider that when ordering reference-to-function bindings.
5298 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5300 : (RefConv & Sema::ReferenceConversions::ObjC)
5302 : ICK_Identity;
5304 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5305 // a reference binding that performs a non-top-level qualification
5306 // conversion as a qualification conversion, not as an identity conversion.
5307 ICS.Standard.Third = (RefConv &
5308 Sema::ReferenceConversions::NestedQualification)
5310 : ICK_Identity;
5311 ICS.Standard.setFromType(T2);
5312 ICS.Standard.setToType(0, T2);
5313 ICS.Standard.setToType(1, T1);
5314 ICS.Standard.setToType(2, T1);
5315 ICS.Standard.ReferenceBinding = true;
5316 ICS.Standard.DirectBinding = BindsDirectly;
5317 ICS.Standard.IsLvalueReference = !isRValRef;
5319 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5322 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5323 ICS.Standard.FromBracedInitList = false;
5324 ICS.Standard.CopyConstructor = nullptr;
5326 };
5327
5328 // C++0x [dcl.init.ref]p5:
5329 // A reference to type "cv1 T1" is initialized by an expression
5330 // of type "cv2 T2" as follows:
5331
5332 // -- If reference is an lvalue reference and the initializer expression
5333 if (!isRValRef) {
5334 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5335 // reference-compatible with "cv2 T2," or
5336 //
5337 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5338 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5339 // C++ [over.ics.ref]p1:
5340 // When a parameter of reference type binds directly (8.5.3)
5341 // to an argument expression, the implicit conversion sequence
5342 // is the identity conversion, unless the argument expression
5343 // has a type that is a derived class of the parameter type,
5344 // in which case the implicit conversion sequence is a
5345 // derived-to-base Conversion (13.3.3.1).
5346 SetAsReferenceBinding(/*BindsDirectly=*/true);
5347
5348 // Nothing more to do: the inaccessibility/ambiguity check for
5349 // derived-to-base conversions is suppressed when we're
5350 // computing the implicit conversion sequence (C++
5351 // [over.best.ics]p2).
5352 return ICS;
5353 }
5354
5355 // -- has a class type (i.e., T2 is a class type), where T1 is
5356 // not reference-related to T2, and can be implicitly
5357 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5358 // is reference-compatible with "cv3 T3" 92) (this
5359 // conversion is selected by enumerating the applicable
5360 // conversion functions (13.3.1.6) and choosing the best
5361 // one through overload resolution (13.3)),
5362 if (!SuppressUserConversions && T2->isRecordType() &&
5363 S.isCompleteType(DeclLoc, T2) &&
5364 RefRelationship == Sema::Ref_Incompatible) {
5365 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5366 Init, T2, /*AllowRvalues=*/false,
5367 AllowExplicit))
5368 return ICS;
5369 }
5370 }
5371
5372 // -- Otherwise, the reference shall be an lvalue reference to a
5373 // non-volatile const type (i.e., cv1 shall be const), or the reference
5374 // shall be an rvalue reference.
5375 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5376 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5378 return ICS;
5379 }
5380
5381 // -- If the initializer expression
5382 //
5383 // -- is an xvalue, class prvalue, array prvalue or function
5384 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5385 if (RefRelationship == Sema::Ref_Compatible &&
5386 (InitCategory.isXValue() ||
5387 (InitCategory.isPRValue() &&
5388 (T2->isRecordType() || T2->isArrayType())) ||
5389 (InitCategory.isLValue() && T2->isFunctionType()))) {
5390 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5391 // binding unless we're binding to a class prvalue.
5392 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5393 // allow the use of rvalue references in C++98/03 for the benefit of
5394 // standard library implementors; therefore, we need the xvalue check here.
5395 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5396 !(InitCategory.isPRValue() || T2->isRecordType()));
5397 return ICS;
5398 }
5399
5400 // -- has a class type (i.e., T2 is a class type), where T1 is not
5401 // reference-related to T2, and can be implicitly converted to
5402 // an xvalue, class prvalue, or function lvalue of type
5403 // "cv3 T3", where "cv1 T1" is reference-compatible with
5404 // "cv3 T3",
5405 //
5406 // then the reference is bound to the value of the initializer
5407 // expression in the first case and to the result of the conversion
5408 // in the second case (or, in either case, to an appropriate base
5409 // class subobject).
5410 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5411 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5412 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5413 Init, T2, /*AllowRvalues=*/true,
5414 AllowExplicit)) {
5415 // In the second case, if the reference is an rvalue reference
5416 // and the second standard conversion sequence of the
5417 // user-defined conversion sequence includes an lvalue-to-rvalue
5418 // conversion, the program is ill-formed.
5419 if (ICS.isUserDefined() && isRValRef &&
5422
5423 return ICS;
5424 }
5425
5426 // A temporary of function type cannot be created; don't even try.
5427 if (T1->isFunctionType())
5428 return ICS;
5429
5430 // -- Otherwise, a temporary of type "cv1 T1" is created and
5431 // initialized from the initializer expression using the
5432 // rules for a non-reference copy initialization (8.5). The
5433 // reference is then bound to the temporary. If T1 is
5434 // reference-related to T2, cv1 must be the same
5435 // cv-qualification as, or greater cv-qualification than,
5436 // cv2; otherwise, the program is ill-formed.
5437 if (RefRelationship == Sema::Ref_Related) {
5438 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5439 // we would be reference-compatible or reference-compatible with
5440 // added qualification. But that wasn't the case, so the reference
5441 // initialization fails.
5442 //
5443 // Note that we only want to check address spaces and cvr-qualifiers here.
5444 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5445 Qualifiers T1Quals = T1.getQualifiers();
5446 Qualifiers T2Quals = T2.getQualifiers();
5447 T1Quals.removeObjCGCAttr();
5448 T1Quals.removeObjCLifetime();
5449 T2Quals.removeObjCGCAttr();
5450 T2Quals.removeObjCLifetime();
5451 // MS compiler ignores __unaligned qualifier for references; do the same.
5452 T1Quals.removeUnaligned();
5453 T2Quals.removeUnaligned();
5454 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5455 return ICS;
5456 }
5457
5458 // If at least one of the types is a class type, the types are not
5459 // related, and we aren't allowed any user conversions, the
5460 // reference binding fails. This case is important for breaking
5461 // recursion, since TryImplicitConversion below will attempt to
5462 // create a temporary through the use of a copy constructor.
5463 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5464 (T1->isRecordType() || T2->isRecordType()))
5465 return ICS;
5466
5467 // If T1 is reference-related to T2 and the reference is an rvalue
5468 // reference, the initializer expression shall not be an lvalue.
5469 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5470 Init->Classify(S.Context).isLValue()) {
5472 return ICS;
5473 }
5474
5475 // C++ [over.ics.ref]p2:
5476 // When a parameter of reference type is not bound directly to
5477 // an argument expression, the conversion sequence is the one
5478 // required to convert the argument expression to the
5479 // underlying type of the reference according to
5480 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5481 // to copy-initializing a temporary of the underlying type with
5482 // the argument expression. Any difference in top-level
5483 // cv-qualification is subsumed by the initialization itself
5484 // and does not constitute a conversion.
5485 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5486 AllowedExplicit::None,
5487 /*InOverloadResolution=*/false,
5488 /*CStyle=*/false,
5489 /*AllowObjCWritebackConversion=*/false,
5490 /*AllowObjCConversionOnExplicit=*/false);
5491
5492 // Of course, that's still a reference binding.
5493 if (ICS.isStandard()) {
5494 ICS.Standard.ReferenceBinding = true;
5495 ICS.Standard.IsLvalueReference = !isRValRef;
5496 ICS.Standard.BindsToFunctionLvalue = false;
5497 ICS.Standard.BindsToRvalue = true;
5500 } else if (ICS.isUserDefined()) {
5501 const ReferenceType *LValRefType =
5504
5505 // C++ [over.ics.ref]p3:
5506 // Except for an implicit object parameter, for which see 13.3.1, a
5507 // standard conversion sequence cannot be formed if it requires [...]
5508 // binding an rvalue reference to an lvalue other than a function
5509 // lvalue.
5510 // Note that the function case is not possible here.
5511 if (isRValRef && LValRefType) {
5513 return ICS;
5514 }
5515
5517 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5519 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5523 }
5524
5525 return ICS;
5526}
5527
5529TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5530 bool SuppressUserConversions,
5531 bool InOverloadResolution,
5532 bool AllowObjCWritebackConversion,
5533 bool AllowExplicit = false);
5534
5535/// TryListConversion - Try to copy-initialize a value of type ToType from the
5536/// initializer list From.
5539 bool SuppressUserConversions,
5540 bool InOverloadResolution,
5541 bool AllowObjCWritebackConversion) {
5542 // C++11 [over.ics.list]p1:
5543 // When an argument is an initializer list, it is not an expression and
5544 // special rules apply for converting it to a parameter type.
5545
5547 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5548
5549 // We need a complete type for what follows. With one C++20 exception,
5550 // incomplete types can never be initialized from init lists.
5551 QualType InitTy = ToType;
5552 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5553 if (AT && S.getLangOpts().CPlusPlus20)
5554 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5555 // C++20 allows list initialization of an incomplete array type.
5556 InitTy = IAT->getElementType();
5557 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5558 return Result;
5559
5560 // C++20 [over.ics.list]/2:
5561 // If the initializer list is a designated-initializer-list, a conversion
5562 // is only possible if the parameter has an aggregate type
5563 //
5564 // FIXME: The exception for reference initialization here is not part of the
5565 // language rules, but follow other compilers in adding it as a tentative DR
5566 // resolution.
5567 bool IsDesignatedInit = From->hasDesignatedInit();
5568 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5569 IsDesignatedInit)
5570 return Result;
5571
5572 // Per DR1467 and DR2137:
5573 // If the parameter type is an aggregate class X and the initializer list
5574 // has a single element of type cv U, where U is X or a class derived from
5575 // X, the implicit conversion sequence is the one required to convert the
5576 // element to the parameter type.
5577 //
5578 // Otherwise, if the parameter type is a character array [... ]
5579 // and the initializer list has a single element that is an
5580 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5581 // implicit conversion sequence is the identity conversion.
5582 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5583 if (ToType->isRecordType() && ToType->isAggregateType()) {
5584 QualType InitType = From->getInit(0)->getType();
5585 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5586 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5587 return TryCopyInitialization(S, From->getInit(0), ToType,
5588 SuppressUserConversions,
5589 InOverloadResolution,
5590 AllowObjCWritebackConversion);
5591 }
5592
5593 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5594 InitializedEntity Entity =
5596 /*Consumed=*/false);
5597 if (S.CanPerformCopyInitialization(Entity, From)) {
5598 Result.setStandard();
5599 Result.Standard.setAsIdentityConversion();
5600 Result.Standard.setFromType(ToType);
5601 Result.Standard.setAllToTypes(ToType);
5602 return Result;
5603 }
5604 }
5605 }
5606
5607 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5608 // C++11 [over.ics.list]p2:
5609 // If the parameter type is std::initializer_list<X> or "array of X" and
5610 // all the elements can be implicitly converted to X, the implicit
5611 // conversion sequence is the worst conversion necessary to convert an
5612 // element of the list to X.
5613 //
5614 // C++14 [over.ics.list]p3:
5615 // Otherwise, if the parameter type is "array of N X", if the initializer
5616 // list has exactly N elements or if it has fewer than N elements and X is
5617 // default-constructible, and if all the elements of the initializer list
5618 // can be implicitly converted to X, the implicit conversion sequence is
5619 // the worst conversion necessary to convert an element of the list to X.
5620 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5621 unsigned e = From->getNumInits();
5624 QualType());
5625 QualType ContTy = ToType;
5626 bool IsUnbounded = false;
5627 if (AT) {
5628 InitTy = AT->getElementType();
5629 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5630 if (CT->getSize().ult(e)) {
5631 // Too many inits, fatally bad
5633 ToType);
5634 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5635 return Result;
5636 }
5637 if (CT->getSize().ugt(e)) {
5638 // Need an init from empty {}, is there one?
5639 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5640 From->getEndLoc());
5641 EmptyList.setType(S.Context.VoidTy);
5642 DfltElt = TryListConversion(
5643 S, &EmptyList, InitTy, SuppressUserConversions,
5644 InOverloadResolution, AllowObjCWritebackConversion);
5645 if (DfltElt.isBad()) {
5646 // No {} init, fatally bad
5648 ToType);
5649 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5650 return Result;
5651 }
5652 }
5653 } else {
5654 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5655 IsUnbounded = true;
5656 if (!e) {
5657 // Cannot convert to zero-sized.
5659 ToType);
5660 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5661 return Result;
5662 }
5663 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5664 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5666 }
5667 }
5668
5669 Result.setStandard();
5670 Result.Standard.setAsIdentityConversion();
5671 Result.Standard.setFromType(InitTy);
5672 Result.Standard.setAllToTypes(InitTy);
5673 for (unsigned i = 0; i < e; ++i) {
5674 Expr *Init = From->getInit(i);
5676 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5677 AllowObjCWritebackConversion);
5678
5679 // Keep the worse conversion seen so far.
5680 // FIXME: Sequences are not totally ordered, so 'worse' can be
5681 // ambiguous. CWG has been informed.
5683 Result) ==
5685 Result = ICS;
5686 // Bail as soon as we find something unconvertible.
5687 if (Result.isBad()) {
5688 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5689 return Result;
5690 }
5691 }
5692 }
5693
5694 // If we needed any implicit {} initialization, compare that now.
5695 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5696 // has been informed that this might not be the best thing.
5697 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5698 S, From->getEndLoc(), DfltElt, Result) ==
5700 Result = DfltElt;
5701 // Record the type being initialized so that we may compare sequences
5702 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5703 return Result;
5704 }
5705
5706 // C++14 [over.ics.list]p4:
5707 // C++11 [over.ics.list]p3:
5708 // Otherwise, if the parameter is a non-aggregate class X and overload
5709 // resolution chooses a single best constructor [...] the implicit
5710 // conversion sequence is a user-defined conversion sequence. If multiple
5711 // constructors are viable but none is better than the others, the
5712 // implicit conversion sequence is a user-defined conversion sequence.
5713 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5714 // This function can deal with initializer lists.
5715 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5716 AllowedExplicit::None,
5717 InOverloadResolution, /*CStyle=*/false,
5718 AllowObjCWritebackConversion,
5719 /*AllowObjCConversionOnExplicit=*/false);
5720 }
5721
5722 // C++14 [over.ics.list]p5:
5723 // C++11 [over.ics.list]p4:
5724 // Otherwise, if the parameter has an aggregate type which can be
5725 // initialized from the initializer list [...] the implicit conversion
5726 // sequence is a user-defined conversion sequence.
5727 if (ToType->isAggregateType()) {
5728 // Type is an aggregate, argument is an init list. At this point it comes
5729 // down to checking whether the initialization works.
5730 // FIXME: Find out whether this parameter is consumed or not.
5731 InitializedEntity Entity =
5733 /*Consumed=*/false);
5735 From)) {
5736 Result.setUserDefined();
5737 Result.UserDefined.Before.setAsIdentityConversion();
5738 // Initializer lists don't have a type.
5739 Result.UserDefined.Before.setFromType(QualType());
5740 Result.UserDefined.Before.setAllToTypes(QualType());
5741
5742 Result.UserDefined.After.setAsIdentityConversion();
5743 Result.UserDefined.After.setFromType(ToType);
5744 Result.UserDefined.After.setAllToTypes(ToType);
5745 Result.UserDefined.ConversionFunction = nullptr;
5746 }
5747 return Result;
5748 }
5749
5750 // C++14 [over.ics.list]p6:
5751 // C++11 [over.ics.list]p5:
5752 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5753 if (ToType->isReferenceType()) {
5754 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5755 // mention initializer lists in any way. So we go by what list-
5756 // initialization would do and try to extrapolate from that.
5757
5758 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5759
5760 // If the initializer list has a single element that is reference-related
5761 // to the parameter type, we initialize the reference from that.
5762 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5763 Expr *Init = From->getInit(0);
5764
5765 QualType T2 = Init->getType();
5766
5767 // If the initializer is the address of an overloaded function, try
5768 // to resolve the overloaded function. If all goes well, T2 is the
5769 // type of the resulting function.
5770 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5773 Init, ToType, false, Found))
5774 T2 = Fn->getType();
5775 }
5776
5777 // Compute some basic properties of the types and the initializer.
5778 Sema::ReferenceCompareResult RefRelationship =
5779 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5780
5781 if (RefRelationship >= Sema::Ref_Related) {
5782 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5783 SuppressUserConversions,
5784 /*AllowExplicit=*/false);
5785 }
5786 }
5787
5788 // Otherwise, we bind the reference to a temporary created from the
5789 // initializer list.
5790 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5791 InOverloadResolution,
5792 AllowObjCWritebackConversion);
5793 if (Result.isFailure())
5794 return Result;
5795 assert(!Result.isEllipsis() &&
5796 "Sub-initialization cannot result in ellipsis conversion.");
5797
5798 // Can we even bind to a temporary?
5799 if (ToType->isRValueReferenceType() ||
5800 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5801 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5802 Result.UserDefined.After;
5803 SCS.ReferenceBinding = true;
5805 SCS.BindsToRvalue = true;
5806 SCS.BindsToFunctionLvalue = false;
5809 SCS.FromBracedInitList = false;
5810
5811 } else
5813 From, ToType);
5814 return Result;
5815 }
5816
5817 // C++14 [over.ics.list]p7:
5818 // C++11 [over.ics.list]p6:
5819 // Otherwise, if the parameter type is not a class:
5820 if (!ToType->isRecordType()) {
5821 // - if the initializer list has one element that is not itself an
5822 // initializer list, the implicit conversion sequence is the one
5823 // required to convert the element to the parameter type.
5824 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
5825 // single integer.
5826 unsigned NumInits = From->getNumInits();
5827 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)) &&
5828 !isa<EmbedExpr>(From->getInit(0))) {
5830 S, From->getInit(0), ToType, SuppressUserConversions,
5831 InOverloadResolution, AllowObjCWritebackConversion);
5832 if (Result.isStandard())
5833 Result.Standard.FromBracedInitList = true;
5834 }
5835 // - if the initializer list has no elements, the implicit conversion
5836 // sequence is the identity conversion.
5837 else if (NumInits == 0) {
5838 Result.setStandard();
5839 Result.Standard.setAsIdentityConversion();
5840 Result.Standard.setFromType(ToType);
5841 Result.Standard.setAllToTypes(ToType);
5842 }
5843 return Result;
5844 }
5845
5846 // C++14 [over.ics.list]p8:
5847 // C++11 [over.ics.list]p7:
5848 // In all cases other than those enumerated above, no conversion is possible
5849 return Result;
5850}
5851
5852/// TryCopyInitialization - Try to copy-initialize a value of type
5853/// ToType from the expression From. Return the implicit conversion
5854/// sequence required to pass this argument, which may be a bad
5855/// conversion sequence (meaning that the argument cannot be passed to
5856/// a parameter of this type). If @p SuppressUserConversions, then we
5857/// do not permit any user-defined conversion sequences.
5860 bool SuppressUserConversions,
5861 bool InOverloadResolution,
5862 bool AllowObjCWritebackConversion,
5863 bool AllowExplicit) {
5864 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5865 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5866 InOverloadResolution,AllowObjCWritebackConversion);
5867
5868 if (ToType->isReferenceType())
5869 return TryReferenceInit(S, From, ToType,
5870 /*FIXME:*/ From->getBeginLoc(),
5871 SuppressUserConversions, AllowExplicit);
5872
5873 return TryImplicitConversion(S, From, ToType,
5874 SuppressUserConversions,
5875 AllowedExplicit::None,
5876 InOverloadResolution,
5877 /*CStyle=*/false,
5878 AllowObjCWritebackConversion,
5879 /*AllowObjCConversionOnExplicit=*/false);
5880}
5881
5882static bool TryCopyInitialization(const CanQualType FromQTy,
5883 const CanQualType ToQTy,
5884 Sema &S,
5885 SourceLocation Loc,
5886 ExprValueKind FromVK) {
5887 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5889 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5890
5891 return !ICS.isBad();
5892}
5893
5894/// TryObjectArgumentInitialization - Try to initialize the object
5895/// parameter of the given member function (@c Method) from the
5896/// expression @p From.
5898 Sema &S, SourceLocation Loc, QualType FromType,
5899 Expr::Classification FromClassification, CXXMethodDecl *Method,
5900 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5901 QualType ExplicitParameterType = QualType(),
5902 bool SuppressUserConversion = false) {
5903
5904 // We need to have an object of class type.
5905 if (const auto *PT = FromType->getAs<PointerType>()) {
5906 FromType = PT->getPointeeType();
5907
5908 // When we had a pointer, it's implicitly dereferenced, so we
5909 // better have an lvalue.
5910 assert(FromClassification.isLValue());
5911 }
5912
5913 auto ValueKindFromClassification = [](Expr::Classification C) {
5914 if (C.isPRValue())
5915 return clang::VK_PRValue;
5916 if (C.isXValue())
5917 return VK_XValue;
5918 return clang::VK_LValue;
5919 };
5920
5921 if (Method->isExplicitObjectMemberFunction()) {
5922 if (ExplicitParameterType.isNull())
5923 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
5924 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
5925 ValueKindFromClassification(FromClassification));
5927 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
5928 /*InOverloadResolution=*/true, false);
5929 if (ICS.isBad())
5930 ICS.Bad.FromExpr = nullptr;
5931 return ICS;
5932 }
5933
5934 assert(FromType->isRecordType());
5935
5936 CanQualType ClassType = S.Context.getCanonicalTagType(ActingContext);
5937 // C++98 [class.dtor]p2:
5938 // A destructor can be invoked for a const, volatile or const volatile
5939 // object.
5940 // C++98 [over.match.funcs]p4:
5941 // For static member functions, the implicit object parameter is considered
5942 // to match any object (since if the function is selected, the object is
5943 // discarded).
5944 Qualifiers Quals = Method->getMethodQualifiers();
5945 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
5946 Quals.addConst();
5947 Quals.addVolatile();
5948 }
5949
5950 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5951
5952 // Set up the conversion sequence as a "bad" conversion, to allow us
5953 // to exit early.
5955
5956 // C++0x [over.match.funcs]p4:
5957 // For non-static member functions, the type of the implicit object
5958 // parameter is
5959 //
5960 // - "lvalue reference to cv X" for functions declared without a
5961 // ref-qualifier or with the & ref-qualifier
5962 // - "rvalue reference to cv X" for functions declared with the &&
5963 // ref-qualifier
5964 //
5965 // where X is the class of which the function is a member and cv is the
5966 // cv-qualification on the member function declaration.
5967 //
5968 // However, when finding an implicit conversion sequence for the argument, we
5969 // are not allowed to perform user-defined conversions
5970 // (C++ [over.match.funcs]p5). We perform a simplified version of
5971 // reference binding here, that allows class rvalues to bind to
5972 // non-constant references.
5973
5974 // First check the qualifiers.
5975 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5976 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
5977 if (ImplicitParamType.getCVRQualifiers() !=
5978 FromTypeCanon.getLocalCVRQualifiers() &&
5979 !ImplicitParamType.isAtLeastAsQualifiedAs(
5980 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
5982 FromType, ImplicitParamType);
5983 return ICS;
5984 }
5985
5986 if (FromTypeCanon.hasAddressSpace()) {
5987 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5988 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5989 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
5990 S.getASTContext())) {
5992 FromType, ImplicitParamType);
5993 return ICS;
5994 }
5995 }
5996
5997 // Check that we have either the same type or a derived type. It
5998 // affects the conversion rank.
5999 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
6000 ImplicitConversionKind SecondKind;
6001 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6002 SecondKind = ICK_Identity;
6003 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
6004 SecondKind = ICK_Derived_To_Base;
6005 } else if (!Method->isExplicitObjectMemberFunction()) {
6007 FromType, ImplicitParamType);
6008 return ICS;
6009 }
6010
6011 // Check the ref-qualifier.
6012 switch (Method->getRefQualifier()) {
6013 case RQ_None:
6014 // Do nothing; we don't care about lvalueness or rvalueness.
6015 break;
6016
6017 case RQ_LValue:
6018 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6019 // non-const lvalue reference cannot bind to an rvalue
6021 ImplicitParamType);
6022 return ICS;
6023 }
6024 break;
6025
6026 case RQ_RValue:
6027 if (!FromClassification.isRValue()) {
6028 // rvalue reference cannot bind to an lvalue
6030 ImplicitParamType);
6031 return ICS;
6032 }
6033 break;
6034 }
6035
6036 // Success. Mark this as a reference binding.
6037 ICS.setStandard();
6039 ICS.Standard.Second = SecondKind;
6040 ICS.Standard.setFromType(FromType);
6041 ICS.Standard.setAllToTypes(ImplicitParamType);
6042 ICS.Standard.ReferenceBinding = true;
6043 ICS.Standard.DirectBinding = true;
6044 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6045 ICS.Standard.BindsToFunctionLvalue = false;
6046 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6047 ICS.Standard.FromBracedInitList = false;
6049 = (Method->getRefQualifier() == RQ_None);
6050 return ICS;
6051}
6052
6053/// PerformObjectArgumentInitialization - Perform initialization of
6054/// the implicit object parameter for the given Method with the given
6055/// expression.
6057 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6059 QualType FromRecordType, DestType;
6060 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6061
6062 Expr::Classification FromClassification;
6063 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6064 FromRecordType = PT->getPointeeType();
6065 DestType = Method->getThisType();
6066 FromClassification = Expr::Classification::makeSimpleLValue();
6067 } else {
6068 FromRecordType = From->getType();
6069 DestType = ImplicitParamRecordType;
6070 FromClassification = From->Classify(Context);
6071
6072 // CWG2813 [expr.call]p6:
6073 // If the function is an implicit object member function, the object
6074 // expression of the class member access shall be a glvalue [...]
6075 if (From->isPRValue()) {
6076 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
6077 Method->getRefQualifier() !=
6079 }
6080 }
6081
6082 // Note that we always use the true parent context when performing
6083 // the actual argument initialization.
6085 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
6086 Method->getParent());
6087 if (ICS.isBad()) {
6088 switch (ICS.Bad.Kind) {
6090 Qualifiers FromQs = FromRecordType.getQualifiers();
6091 Qualifiers ToQs = DestType.getQualifiers();
6092 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6093 if (CVR) {
6094 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
6095 << Method->getDeclName() << FromRecordType << (CVR - 1)
6096 << From->getSourceRange();
6097 Diag(Method->getLocation(), diag::note_previous_decl)
6098 << Method->getDeclName();
6099 return ExprError();
6100 }
6101 break;
6102 }
6103
6106 bool IsRValueQualified =
6107 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6108 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
6109 << Method->getDeclName() << FromClassification.isRValue()
6110 << IsRValueQualified;
6111 Diag(Method->getLocation(), diag::note_previous_decl)
6112 << Method->getDeclName();
6113 return ExprError();
6114 }
6115
6118 break;
6119
6122 llvm_unreachable("Lists are not objects");
6123 }
6124
6125 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
6126 << ImplicitParamRecordType << FromRecordType
6127 << From->getSourceRange();
6128 }
6129
6130 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6131 ExprResult FromRes =
6132 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6133 if (FromRes.isInvalid())
6134 return ExprError();
6135 From = FromRes.get();
6136 }
6137
6138 if (!Context.hasSameType(From->getType(), DestType)) {
6139 CastKind CK;
6140 QualType PteeTy = DestType->getPointeeType();
6141 LangAS DestAS =
6142 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6143 if (FromRecordType.getAddressSpace() != DestAS)
6144 CK = CK_AddressSpaceConversion;
6145 else
6146 CK = CK_NoOp;
6147 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6148 }
6149 return From;
6150}
6151
6152/// TryContextuallyConvertToBool - Attempt to contextually convert the
6153/// expression From to bool (C++0x [conv]p3).
6156 // C++ [dcl.init]/17.8:
6157 // - Otherwise, if the initialization is direct-initialization, the source
6158 // type is std::nullptr_t, and the destination type is bool, the initial
6159 // value of the object being initialized is false.
6160 if (From->getType()->isNullPtrType())
6162 S.Context.BoolTy,
6163 From->isGLValue());
6164
6165 // All other direct-initialization of bool is equivalent to an implicit
6166 // conversion to bool in which explicit conversions are permitted.
6167 return TryImplicitConversion(S, From, S.Context.BoolTy,
6168 /*SuppressUserConversions=*/false,
6169 AllowedExplicit::Conversions,
6170 /*InOverloadResolution=*/false,
6171 /*CStyle=*/false,
6172 /*AllowObjCWritebackConversion=*/false,
6173 /*AllowObjCConversionOnExplicit=*/false);
6174}
6175
6177 if (checkPlaceholderForOverload(*this, From))
6178 return ExprError();
6179
6181 if (!ICS.isBad())
6182 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6184
6185 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
6186 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6187 << From->getType() << From->getSourceRange();
6188 return ExprError();
6189}
6190
6191/// Check that the specified conversion is permitted in a converted constant
6192/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6193/// is acceptable.
6196 // Since we know that the target type is an integral or unscoped enumeration
6197 // type, most conversion kinds are impossible. All possible First and Third
6198 // conversions are fine.
6199 switch (SCS.Second) {
6200 case ICK_Identity:
6202 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6204 return true;
6205
6207 // Conversion from an integral or unscoped enumeration type to bool is
6208 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6209 // conversion, so we allow it in a converted constant expression.
6210 //
6211 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6212 // a lot of popular code. We should at least add a warning for this
6213 // (non-conforming) extension.
6215 SCS.getToType(2)->isBooleanType();
6216
6218 case ICK_Pointer_Member:
6219 // C++1z: null pointer conversions and null member pointer conversions are
6220 // only permitted if the source type is std::nullptr_t.
6221 return SCS.getFromType()->isNullPtrType();
6222
6234 case ICK_Vector_Splat:
6235 case ICK_Complex_Real:
6244 return false;
6245
6250 llvm_unreachable("found a first conversion kind in Second");
6251
6253 case ICK_Qualification:
6254 llvm_unreachable("found a third conversion kind in Second");
6255
6257 break;
6258 }
6259
6260 llvm_unreachable("unknown conversion kind");
6261}
6262
6263/// BuildConvertedConstantExpression - Check that the expression From is a
6264/// converted constant expression of type T, perform the conversion but
6265/// does not evaluate the expression
6267 QualType T, CCEKind CCE,
6268 NamedDecl *Dest,
6269 APValue &PreNarrowingValue) {
6270 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6272 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6273 "converted constant expression outside C++11 or TTP matching");
6274
6275 if (checkPlaceholderForOverload(S, From))
6276 return ExprError();
6277
6278 // C++1z [expr.const]p3:
6279 // A converted constant expression of type T is an expression,
6280 // implicitly converted to type T, where the converted
6281 // expression is a constant expression and the implicit conversion
6282 // sequence contains only [... list of conversions ...].
6284 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6286 : TryCopyInitialization(S, From, T,
6287 /*SuppressUserConversions=*/false,
6288 /*InOverloadResolution=*/false,
6289 /*AllowObjCWritebackConversion=*/false,
6290 /*AllowExplicit=*/false);
6291 StandardConversionSequence *SCS = nullptr;
6292 switch (ICS.getKind()) {
6294 SCS = &ICS.Standard;
6295 break;
6297 if (T->isRecordType())
6298 SCS = &ICS.UserDefined.Before;
6299 else
6300 SCS = &ICS.UserDefined.After;
6301 break;
6305 return S.Diag(From->getBeginLoc(),
6306 diag::err_typecheck_converted_constant_expression)
6307 << From->getType() << From->getSourceRange() << T;
6308 return ExprError();
6309
6312 llvm_unreachable("bad conversion in converted constant expression");
6313 }
6314
6315 // Check that we would only use permitted conversions.
6316 if (!CheckConvertedConstantConversions(S, *SCS)) {
6317 return S.Diag(From->getBeginLoc(),
6318 diag::err_typecheck_converted_constant_expression_disallowed)
6319 << From->getType() << From->getSourceRange() << T;
6320 }
6321 // [...] and where the reference binding (if any) binds directly.
6322 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6323 return S.Diag(From->getBeginLoc(),
6324 diag::err_typecheck_converted_constant_expression_indirect)
6325 << From->getType() << From->getSourceRange() << T;
6326 }
6327 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6328 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6329 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6330 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6331 // case explicitly.
6332 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6333 return S.Diag(From->getBeginLoc(),
6334 diag::err_reference_bind_to_bitfield_in_cce)
6335 << From->getSourceRange();
6336 }
6337
6338 // Usually we can simply apply the ImplicitConversionSequence we formed
6339 // earlier, but that's not guaranteed to work when initializing an object of
6340 // class type.
6342 bool IsTemplateArgument =
6344 if (T->isRecordType()) {
6345 assert(IsTemplateArgument &&
6346 "unexpected class type converted constant expr");
6349 T, cast<NonTypeTemplateParmDecl>(Dest)),
6350 SourceLocation(), From);
6351 } else {
6352 Result =
6354 }
6355 if (Result.isInvalid())
6356 return Result;
6357
6358 // C++2a [intro.execution]p5:
6359 // A full-expression is [...] a constant-expression [...]
6360 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6361 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6362 IsTemplateArgument);
6363 if (Result.isInvalid())
6364 return Result;
6365
6366 // Check for a narrowing implicit conversion.
6367 bool ReturnPreNarrowingValue = false;
6368 QualType PreNarrowingType;
6369 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6370 PreNarrowingType)) {
6372 // Implicit conversion to a narrower type, and the value is not a constant
6373 // expression. We'll diagnose this in a moment.
6374 case NK_Not_Narrowing:
6375 break;
6376
6378 if (CCE == CCEKind::ArrayBound &&
6379 PreNarrowingType->isIntegralOrEnumerationType() &&
6380 PreNarrowingValue.isInt()) {
6381 // Don't diagnose array bound narrowing here; we produce more precise
6382 // errors by allowing the un-narrowed value through.
6383 ReturnPreNarrowingValue = true;
6384 break;
6385 }
6386 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6387 << CCE << /*Constant*/ 1
6388 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6389 break;
6390
6392 // Implicit conversion to a narrower type, but the expression is
6393 // value-dependent so we can't tell whether it's actually narrowing.
6394 // For matching the parameters of a TTP, the conversion is ill-formed
6395 // if it may narrow.
6396 if (CCE != CCEKind::TempArgStrict)
6397 break;
6398 [[fallthrough]];
6399 case NK_Type_Narrowing:
6400 // FIXME: It would be better to diagnose that the expression is not a
6401 // constant expression.
6402 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6403 << CCE << /*Constant*/ 0 << From->getType() << T;
6404 break;
6405 }
6406 if (!ReturnPreNarrowingValue)
6407 PreNarrowingValue = {};
6408
6409 return Result;
6410}
6411
6412/// CheckConvertedConstantExpression - Check that the expression From is a
6413/// converted constant expression of type T, perform the conversion and produce
6414/// the converted expression, per C++11 [expr.const]p3.
6417 CCEKind CCE, bool RequireInt,
6418 NamedDecl *Dest) {
6419
6420 APValue PreNarrowingValue;
6422 PreNarrowingValue);
6423 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6424 Value = APValue();
6425 return Result;
6426 }
6427 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6428 RequireInt, PreNarrowingValue);
6429}
6430
6432 CCEKind CCE,
6433 NamedDecl *Dest) {
6434 APValue PreNarrowingValue;
6435 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6436 PreNarrowingValue);
6437}
6438
6440 APValue &Value, CCEKind CCE,
6441 NamedDecl *Dest) {
6442 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6443 Dest);
6444}
6445
6447 llvm::APSInt &Value,
6448 CCEKind CCE) {
6449 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6450
6451 APValue V;
6452 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6453 /*Dest=*/nullptr);
6454 if (!R.isInvalid() && !R.get()->isValueDependent())
6455 Value = V.getInt();
6456 return R;
6457}
6458
6461 CCEKind CCE, bool RequireInt,
6462 const APValue &PreNarrowingValue) {
6463
6465 // Check the expression is a constant expression.
6467 Expr::EvalResult Eval;
6468 Eval.Diag = &Notes;
6469
6470 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6471
6472 ConstantExprKind Kind;
6473 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6474 Kind = ConstantExprKind::ClassTemplateArgument;
6475 else if (CCE == CCEKind::TemplateArg)
6476 Kind = ConstantExprKind::NonClassTemplateArgument;
6477 else
6478 Kind = ConstantExprKind::Normal;
6479
6480 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6481 (RequireInt && !Eval.Val.isInt())) {
6482 // The expression can't be folded, so we can't keep it at this position in
6483 // the AST.
6484 Result = ExprError();
6485 } else {
6486 Value = Eval.Val;
6487
6488 if (Notes.empty()) {
6489 // It's a constant expression.
6490 Expr *E = Result.get();
6491 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6492 // We expect a ConstantExpr to have a value associated with it
6493 // by this point.
6494 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6495 "ConstantExpr has no value associated with it");
6496 (void)CE;
6497 } else {
6498 E = ConstantExpr::Create(Context, Result.get(), Value);
6499 }
6500 if (!PreNarrowingValue.isAbsent())
6501 Value = std::move(PreNarrowingValue);
6502 return E;
6503 }
6504 }
6505
6506 // It's not a constant expression. Produce an appropriate diagnostic.
6507 if (Notes.size() == 1 &&
6508 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6509 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6510 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6511 diag::note_constexpr_invalid_template_arg) {
6512 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6513 for (unsigned I = 0; I < Notes.size(); ++I)
6514 Diag(Notes[I].first, Notes[I].second);
6515 } else {
6516 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6517 << CCE << E->getSourceRange();
6518 for (unsigned I = 0; I < Notes.size(); ++I)
6519 Diag(Notes[I].first, Notes[I].second);
6520 }
6521 return ExprError();
6522}
6523
6524/// dropPointerConversions - If the given standard conversion sequence
6525/// involves any pointer conversions, remove them. This may change
6526/// the result type of the conversion sequence.
6528 if (SCS.Second == ICK_Pointer_Conversion) {
6529 SCS.Second = ICK_Identity;
6530 SCS.Dimension = ICK_Identity;
6531 SCS.Third = ICK_Identity;
6532 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6533 }
6534}
6535
6536/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6537/// convert the expression From to an Objective-C pointer type.
6540 // Do an implicit conversion to 'id'.
6543 = TryImplicitConversion(S, From, Ty,
6544 // FIXME: Are these flags correct?
6545 /*SuppressUserConversions=*/false,
6546 AllowedExplicit::Conversions,
6547 /*InOverloadResolution=*/false,
6548 /*CStyle=*/false,
6549 /*AllowObjCWritebackConversion=*/false,
6550 /*AllowObjCConversionOnExplicit=*/true);
6551
6552 // Strip off any final conversions to 'id'.
6553 switch (ICS.getKind()) {
6558 break;
6559
6562 break;
6563
6566 break;
6567 }
6568
6569 return ICS;
6570}
6571
6573 if (checkPlaceholderForOverload(*this, From))
6574 return ExprError();
6575
6576 QualType Ty = Context.getObjCIdType();
6579 if (!ICS.isBad())
6580 return PerformImplicitConversion(From, Ty, ICS,
6582 return ExprResult();
6583}
6584
6585static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6586 const Expr *Base = nullptr;
6587 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6588 "expected a member expression");
6589
6590 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6591 M && !M->isImplicitAccess())
6592 Base = M->getBase();
6593 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6594 M && !M->isImplicitAccess())
6595 Base = M->getBase();
6596
6597 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6598
6599 if (T->isPointerType())
6600 T = T->getPointeeType();
6601
6602 return T;
6603}
6604
6606 const FunctionDecl *Fun) {
6607 QualType ObjType = Obj->getType();
6608 if (ObjType->isPointerType()) {
6609 ObjType = ObjType->getPointeeType();
6610 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6612 /*CanOverflow=*/false, FPOptionsOverride());
6613 }
6614 return Obj;
6615}
6616
6618 FunctionDecl *Fun) {
6619 Obj = GetExplicitObjectExpr(S, Obj, Fun);
6622 Obj->getExprLoc(), Obj);
6623}
6624
6626 Expr *Object, MultiExprArg &Args,
6627 SmallVectorImpl<Expr *> &NewArgs) {
6628 assert(Method->isExplicitObjectMemberFunction() &&
6629 "Method is not an explicit member function");
6630 assert(NewArgs.empty() && "NewArgs should be empty");
6631
6632 NewArgs.reserve(Args.size() + 1);
6633 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6634 NewArgs.push_back(This);
6635 NewArgs.append(Args.begin(), Args.end());
6636 Args = NewArgs;
6638 Method, Object->getBeginLoc());
6639}
6640
6641/// Determine whether the provided type is an integral type, or an enumeration
6642/// type of a permitted flavor.
6644 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6646}
6647
6648static ExprResult
6651 QualType T, UnresolvedSetImpl &ViableConversions) {
6652
6653 if (Converter.Suppress)
6654 return ExprError();
6655
6656 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6657 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6658 CXXConversionDecl *Conv =
6659 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6661 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6662 }
6663 return From;
6664}
6665
6666static bool
6669 QualType T, bool HadMultipleCandidates,
6670 UnresolvedSetImpl &ExplicitConversions) {
6671 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6672 DeclAccessPair Found = ExplicitConversions[0];
6673 CXXConversionDecl *Conversion =
6674 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6675
6676 // The user probably meant to invoke the given explicit
6677 // conversion; use it.
6678 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6679 std::string TypeStr;
6680 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6681
6682 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6684 "static_cast<" + TypeStr + ">(")
6686 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6687 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6688
6689 // If we aren't in a SFINAE context, build a call to the
6690 // explicit conversion function.
6691 if (SemaRef.isSFINAEContext())
6692 return true;
6693
6694 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6695 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6696 HadMultipleCandidates);
6697 if (Result.isInvalid())
6698 return true;
6699
6700 // Replace the conversion with a RecoveryExpr, so we don't try to
6701 // instantiate it later, but can further diagnose here.
6702 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6703 From, Result.get()->getType());
6704 if (Result.isInvalid())
6705 return true;
6706 From = Result.get();
6707 }
6708 return false;
6709}
6710
6711static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6713 QualType T, bool HadMultipleCandidates,
6715 CXXConversionDecl *Conversion =
6716 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6717 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6718
6719 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6720 if (!Converter.SuppressConversion) {
6721 if (SemaRef.isSFINAEContext())
6722 return true;
6723
6724 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6725 << From->getSourceRange();
6726 }
6727
6728 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6729 HadMultipleCandidates);
6730 if (Result.isInvalid())
6731 return true;
6732 // Record usage of conversion in an implicit cast.
6733 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6734 CK_UserDefinedConversion, Result.get(),
6735 nullptr, Result.get()->getValueKind(),
6736 SemaRef.CurFPFeatureOverrides());
6737 return false;
6738}
6739
6741 Sema &SemaRef, SourceLocation Loc, Expr *From,
6743 if (!Converter.match(From->getType()) && !Converter.Suppress)
6744 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6745 << From->getSourceRange();
6746
6747 return SemaRef.DefaultLvalueConversion(From);
6748}
6749
6750static void
6752 UnresolvedSetImpl &ViableConversions,
6753 OverloadCandidateSet &CandidateSet) {
6754 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6755 NamedDecl *D = FoundDecl.getDecl();
6756 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6757 if (isa<UsingShadowDecl>(D))
6758 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6759
6760 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
6762 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6763 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6764 continue;
6765 }
6766 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6767 SemaRef.AddConversionCandidate(
6768 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
6769 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6770 }
6771}
6772
6773/// Attempt to convert the given expression to a type which is accepted
6774/// by the given converter.
6775///
6776/// This routine will attempt to convert an expression of class type to a
6777/// type accepted by the specified converter. In C++11 and before, the class
6778/// must have a single non-explicit conversion function converting to a matching
6779/// type. In C++1y, there can be multiple such conversion functions, but only
6780/// one target type.
6781///
6782/// \param Loc The source location of the construct that requires the
6783/// conversion.
6784///
6785/// \param From The expression we're converting from.
6786///
6787/// \param Converter Used to control and diagnose the conversion process.
6788///
6789/// \returns The expression, converted to an integral or enumeration type if
6790/// successful.
6792 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6793 // We can't perform any more checking for type-dependent expressions.
6794 if (From->isTypeDependent())
6795 return From;
6796
6797 // Process placeholders immediately.
6798 if (From->hasPlaceholderType()) {
6799 ExprResult result = CheckPlaceholderExpr(From);
6800 if (result.isInvalid())
6801 return result;
6802 From = result.get();
6803 }
6804
6805 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6806 ExprResult Converted = DefaultLvalueConversion(From);
6807 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6808 // If the expression already has a matching type, we're golden.
6809 if (Converter.match(T))
6810 return Converted;
6811
6812 // FIXME: Check for missing '()' if T is a function type?
6813
6814 // We can only perform contextual implicit conversions on objects of class
6815 // type.
6816 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
6817 if (!RecordTy || !getLangOpts().CPlusPlus) {
6818 if (!Converter.Suppress)
6819 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6820 return From;
6821 }
6822
6823 // We must have a complete class type.
6824 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6825 ContextualImplicitConverter &Converter;
6826 Expr *From;
6827
6828 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6829 : Converter(Converter), From(From) {}
6830
6831 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6832 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6833 }
6834 } IncompleteDiagnoser(Converter, From);
6835
6836 if (Converter.Suppress ? !isCompleteType(Loc, T)
6837 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6838 return From;
6839
6840 // Look for a conversion to an integral or enumeration type.
6842 ViableConversions; // These are *potentially* viable in C++1y.
6843 UnresolvedSet<4> ExplicitConversions;
6844 const auto &Conversions = cast<CXXRecordDecl>(RecordTy->getOriginalDecl())
6845 ->getDefinitionOrSelf()
6846 ->getVisibleConversionFunctions();
6847
6848 bool HadMultipleCandidates =
6849 (std::distance(Conversions.begin(), Conversions.end()) > 1);
6850
6851 // To check that there is only one target type, in C++1y:
6852 QualType ToType;
6853 bool HasUniqueTargetType = true;
6854
6855 // Collect explicit or viable (potentially in C++1y) conversions.
6856 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6857 NamedDecl *D = (*I)->getUnderlyingDecl();
6858 CXXConversionDecl *Conversion;
6859 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6860 if (ConvTemplate) {
6861 if (getLangOpts().CPlusPlus14)
6862 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6863 else
6864 continue; // C++11 does not consider conversion operator templates(?).
6865 } else
6866 Conversion = cast<CXXConversionDecl>(D);
6867
6868 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6869 "Conversion operator templates are considered potentially "
6870 "viable in C++1y");
6871
6872 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6873 if (Converter.match(CurToType) || ConvTemplate) {
6874
6875 if (Conversion->isExplicit()) {
6876 // FIXME: For C++1y, do we need this restriction?
6877 // cf. diagnoseNoViableConversion()
6878 if (!ConvTemplate)
6879 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6880 } else {
6881 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6882 if (ToType.isNull())
6883 ToType = CurToType.getUnqualifiedType();
6884 else if (HasUniqueTargetType &&
6885 (CurToType.getUnqualifiedType() != ToType))
6886 HasUniqueTargetType = false;
6887 }
6888 ViableConversions.addDecl(I.getDecl(), I.getAccess());
6889 }
6890 }
6891 }
6892
6893 if (getLangOpts().CPlusPlus14) {
6894 // C++1y [conv]p6:
6895 // ... An expression e of class type E appearing in such a context
6896 // is said to be contextually implicitly converted to a specified
6897 // type T and is well-formed if and only if e can be implicitly
6898 // converted to a type T that is determined as follows: E is searched
6899 // for conversion functions whose return type is cv T or reference to
6900 // cv T such that T is allowed by the context. There shall be
6901 // exactly one such T.
6902
6903 // If no unique T is found:
6904 if (ToType.isNull()) {
6905 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6906 HadMultipleCandidates,
6907 ExplicitConversions))
6908 return ExprError();
6909 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6910 }
6911
6912 // If more than one unique Ts are found:
6913 if (!HasUniqueTargetType)
6914 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6915 ViableConversions);
6916
6917 // If one unique T is found:
6918 // First, build a candidate set from the previously recorded
6919 // potentially viable conversions.
6921 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6922 CandidateSet);
6923
6924 // Then, perform overload resolution over the candidate set.
6926 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6927 case OR_Success: {
6928 // Apply this conversion.
6930 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6931 if (recordConversion(*this, Loc, From, Converter, T,
6932 HadMultipleCandidates, Found))
6933 return ExprError();
6934 break;
6935 }
6936 case OR_Ambiguous:
6937 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6938 ViableConversions);
6940 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6941 HadMultipleCandidates,
6942 ExplicitConversions))
6943 return ExprError();
6944 [[fallthrough]];
6945 case OR_Deleted:
6946 // We'll complain below about a non-integral condition type.
6947 break;
6948 }
6949 } else {
6950 switch (ViableConversions.size()) {
6951 case 0: {
6952 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6953 HadMultipleCandidates,
6954 ExplicitConversions))
6955 return ExprError();
6956
6957 // We'll complain below about a non-integral condition type.
6958 break;
6959 }
6960 case 1: {
6961 // Apply this conversion.
6962 DeclAccessPair Found = ViableConversions[0];
6963 if (recordConversion(*this, Loc, From, Converter, T,
6964 HadMultipleCandidates, Found))
6965 return ExprError();
6966 break;
6967 }
6968 default:
6969 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6970 ViableConversions);
6971 }
6972 }
6973
6974 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6975}
6976
6977/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6978/// an acceptable non-member overloaded operator for a call whose
6979/// arguments have types T1 (and, if non-empty, T2). This routine
6980/// implements the check in C++ [over.match.oper]p3b2 concerning
6981/// enumeration types.
6983 FunctionDecl *Fn,
6984 ArrayRef<Expr *> Args) {
6985 QualType T1 = Args[0]->getType();
6986 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6987
6988 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6989 return true;
6990
6991 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6992 return true;
6993
6994 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6995 if (Proto->getNumParams() < 1)
6996 return false;
6997
6998 if (T1->isEnumeralType()) {
6999 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
7000 if (Context.hasSameUnqualifiedType(T1, ArgType))
7001 return true;
7002 }
7003
7004 if (Proto->getNumParams() < 2)
7005 return false;
7006
7007 if (!T2.isNull() && T2->isEnumeralType()) {
7008 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
7009 if (Context.hasSameUnqualifiedType(T2, ArgType))
7010 return true;
7011 }
7012
7013 return false;
7014}
7015
7018 return false;
7019
7020 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7021 return FD->isTargetMultiVersion();
7022
7023 if (!FD->isMultiVersion())
7024 return false;
7025
7026 // Among multiple target versions consider either the default,
7027 // or the first non-default in the absence of default version.
7028 unsigned SeenAt = 0;
7029 unsigned I = 0;
7030 bool HasDefault = false;
7032 FD, [&](const FunctionDecl *CurFD) {
7033 if (FD == CurFD)
7034 SeenAt = I;
7035 else if (CurFD->isTargetMultiVersionDefault())
7036 HasDefault = true;
7037 ++I;
7038 });
7039 return HasDefault || SeenAt != 0;
7040}
7041
7044 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7045 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7046 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7047 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7048 bool StrictPackMatch) {
7049 const FunctionProtoType *Proto
7050 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
7051 assert(Proto && "Functions without a prototype cannot be overloaded");
7052 assert(!Function->getDescribedFunctionTemplate() &&
7053 "Use AddTemplateOverloadCandidate for function templates");
7054
7055 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
7056 if (!isa<CXXConstructorDecl>(Method)) {
7057 // If we get here, it's because we're calling a member function
7058 // that is named without a member access expression (e.g.,
7059 // "this->f") that was either written explicitly or created
7060 // implicitly. This can happen with a qualified call to a member
7061 // function, e.g., X::f(). We use an empty type for the implied
7062 // object argument (C++ [over.call.func]p3), and the acting context
7063 // is irrelevant.
7064 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
7066 CandidateSet, SuppressUserConversions,
7067 PartialOverloading, EarlyConversions, PO,
7068 StrictPackMatch);
7069 return;
7070 }
7071 // We treat a constructor like a non-member function, since its object
7072 // argument doesn't participate in overload resolution.
7073 }
7074
7075 if (!CandidateSet.isNewCandidate(Function, PO))
7076 return;
7077
7078 // C++11 [class.copy]p11: [DR1402]
7079 // A defaulted move constructor that is defined as deleted is ignored by
7080 // overload resolution.
7081 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
7082 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7083 Constructor->isMoveConstructor())
7084 return;
7085
7086 // Overload resolution is always an unevaluated context.
7089
7090 // C++ [over.match.oper]p3:
7091 // if no operand has a class type, only those non-member functions in the
7092 // lookup set that have a first parameter of type T1 or "reference to
7093 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7094 // is a right operand) a second parameter of type T2 or "reference to
7095 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7096 // candidate functions.
7097 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7099 return;
7100
7101 // Add this candidate
7102 OverloadCandidate &Candidate =
7103 CandidateSet.addCandidate(Args.size(), EarlyConversions);
7104 Candidate.FoundDecl = FoundDecl;
7105 Candidate.Function = Function;
7106 Candidate.Viable = true;
7107 Candidate.RewriteKind =
7108 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
7109 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
7110 Candidate.ExplicitCallArguments = Args.size();
7111 Candidate.StrictPackMatch = StrictPackMatch;
7112
7113 // Explicit functions are not actually candidates at all if we're not
7114 // allowing them in this context, but keep them around so we can point
7115 // to them in diagnostics.
7116 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7117 Candidate.Viable = false;
7118 Candidate.FailureKind = ovl_fail_explicit;
7119 return;
7120 }
7121
7122 // Functions with internal linkage are only viable in the same module unit.
7123 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7124 /// FIXME: Currently, the semantics of linkage in clang is slightly
7125 /// different from the semantics in C++ spec. In C++ spec, only names
7126 /// have linkage. So that all entities of the same should share one
7127 /// linkage. But in clang, different entities of the same could have
7128 /// different linkage.
7129 const NamedDecl *ND = Function;
7130 bool IsImplicitlyInstantiated = false;
7131 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7132 ND = SpecInfo->getTemplate();
7133 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7135 }
7136
7137 /// Don't remove inline functions with internal linkage from the overload
7138 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7139 /// However:
7140 /// - Inline functions with internal linkage are a common pattern in
7141 /// headers to avoid ODR issues.
7142 /// - The global module is meant to be a transition mechanism for C and C++
7143 /// headers, and the current rules as written work against that goal.
7144 const bool IsInlineFunctionInGMF =
7145 Function->isFromGlobalModule() &&
7146 (IsImplicitlyInstantiated || Function->isInlined());
7147
7148 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7149 Candidate.Viable = false;
7151 return;
7152 }
7153 }
7154
7156 Candidate.Viable = false;
7158 return;
7159 }
7160
7161 if (Constructor) {
7162 // C++ [class.copy]p3:
7163 // A member function template is never instantiated to perform the copy
7164 // of a class object to an object of its class type.
7165 CanQualType ClassType =
7166 Context.getCanonicalTagType(Constructor->getParent());
7167 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7168 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7169 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7170 ClassType))) {
7171 Candidate.Viable = false;
7173 return;
7174 }
7175
7176 // C++ [over.match.funcs]p8: (proposed DR resolution)
7177 // A constructor inherited from class type C that has a first parameter
7178 // of type "reference to P" (including such a constructor instantiated
7179 // from a template) is excluded from the set of candidate functions when
7180 // constructing an object of type cv D if the argument list has exactly
7181 // one argument and D is reference-related to P and P is reference-related
7182 // to C.
7183 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7184 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7185 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7186 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7187 CanQualType C = Context.getCanonicalTagType(Constructor->getParent());
7188 CanQualType D = Context.getCanonicalTagType(Shadow->getParent());
7189 SourceLocation Loc = Args.front()->getExprLoc();
7190 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7191 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7192 Candidate.Viable = false;
7194 return;
7195 }
7196 }
7197
7198 // Check that the constructor is capable of constructing an object in the
7199 // destination address space.
7201 Constructor->getMethodQualifiers().getAddressSpace(),
7202 CandidateSet.getDestAS(), getASTContext())) {
7203 Candidate.Viable = false;
7205 }
7206 }
7207
7208 unsigned NumParams = Proto->getNumParams();
7209
7210 // (C++ 13.3.2p2): A candidate function having fewer than m
7211 // parameters is viable only if it has an ellipsis in its parameter
7212 // list (8.3.5).
7213 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7214 !Proto->isVariadic() &&
7215 shouldEnforceArgLimit(PartialOverloading, Function)) {
7216 Candidate.Viable = false;
7218 return;
7219 }
7220
7221 // (C++ 13.3.2p2): A candidate function having more than m parameters
7222 // is viable only if the (m+1)st parameter has a default argument
7223 // (8.3.6). For the purposes of overload resolution, the
7224 // parameter list is truncated on the right, so that there are
7225 // exactly m parameters.
7226 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7227 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7228 !PartialOverloading) {
7229 // Not enough arguments.
7230 Candidate.Viable = false;
7232 return;
7233 }
7234
7235 // (CUDA B.1): Check for invalid calls between targets.
7236 if (getLangOpts().CUDA) {
7237 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7238 // Skip the check for callers that are implicit members, because in this
7239 // case we may not yet know what the member's target is; the target is
7240 // inferred for the member automatically, based on the bases and fields of
7241 // the class.
7242 if (!(Caller && Caller->isImplicit()) &&
7243 !CUDA().IsAllowedCall(Caller, Function)) {
7244 Candidate.Viable = false;
7245 Candidate.FailureKind = ovl_fail_bad_target;
7246 return;
7247 }
7248 }
7249
7250 if (Function->getTrailingRequiresClause()) {
7251 ConstraintSatisfaction Satisfaction;
7252 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7253 /*ForOverloadResolution*/ true) ||
7254 !Satisfaction.IsSatisfied) {
7255 Candidate.Viable = false;
7257 return;
7258 }
7259 }
7260
7261 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7262 // Determine the implicit conversion sequences for each of the
7263 // arguments.
7264 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7265 unsigned ConvIdx =
7266 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7267 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7268 // We already formed a conversion sequence for this parameter during
7269 // template argument deduction.
7270 } else if (ArgIdx < NumParams) {
7271 // (C++ 13.3.2p3): for F to be a viable function, there shall
7272 // exist for each argument an implicit conversion sequence
7273 // (13.3.3.1) that converts that argument to the corresponding
7274 // parameter of F.
7275 QualType ParamType = Proto->getParamType(ArgIdx);
7276 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7277 if (ParamABI == ParameterABI::HLSLOut ||
7278 ParamABI == ParameterABI::HLSLInOut)
7279 ParamType = ParamType.getNonReferenceType();
7280 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7281 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7282 /*InOverloadResolution=*/true,
7283 /*AllowObjCWritebackConversion=*/
7284 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7285 if (Candidate.Conversions[ConvIdx].isBad()) {
7286 Candidate.Viable = false;
7288 return;
7289 }
7290 } else {
7291 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7292 // argument for which there is no corresponding parameter is
7293 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7294 Candidate.Conversions[ConvIdx].setEllipsis();
7295 }
7296 }
7297
7298 if (EnableIfAttr *FailedAttr =
7299 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7300 Candidate.Viable = false;
7301 Candidate.FailureKind = ovl_fail_enable_if;
7302 Candidate.DeductionFailure.Data = FailedAttr;
7303 return;
7304 }
7305}
7306
7310 if (Methods.size() <= 1)
7311 return nullptr;
7312
7313 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7314 bool Match = true;
7315 ObjCMethodDecl *Method = Methods[b];
7316 unsigned NumNamedArgs = Sel.getNumArgs();
7317 // Method might have more arguments than selector indicates. This is due
7318 // to addition of c-style arguments in method.
7319 if (Method->param_size() > NumNamedArgs)
7320 NumNamedArgs = Method->param_size();
7321 if (Args.size() < NumNamedArgs)
7322 continue;
7323
7324 for (unsigned i = 0; i < NumNamedArgs; i++) {
7325 // We can't do any type-checking on a type-dependent argument.
7326 if (Args[i]->isTypeDependent()) {
7327 Match = false;
7328 break;
7329 }
7330
7331 ParmVarDecl *param = Method->parameters()[i];
7332 Expr *argExpr = Args[i];
7333 assert(argExpr && "SelectBestMethod(): missing expression");
7334
7335 // Strip the unbridged-cast placeholder expression off unless it's
7336 // a consumed argument.
7337 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7338 !param->hasAttr<CFConsumedAttr>())
7339 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7340
7341 // If the parameter is __unknown_anytype, move on to the next method.
7342 if (param->getType() == Context.UnknownAnyTy) {
7343 Match = false;
7344 break;
7345 }
7346
7347 ImplicitConversionSequence ConversionState
7348 = TryCopyInitialization(*this, argExpr, param->getType(),
7349 /*SuppressUserConversions*/false,
7350 /*InOverloadResolution=*/true,
7351 /*AllowObjCWritebackConversion=*/
7352 getLangOpts().ObjCAutoRefCount,
7353 /*AllowExplicit*/false);
7354 // This function looks for a reasonably-exact match, so we consider
7355 // incompatible pointer conversions to be a failure here.
7356 if (ConversionState.isBad() ||
7357 (ConversionState.isStandard() &&
7358 ConversionState.Standard.Second ==
7360 Match = false;
7361 break;
7362 }
7363 }
7364 // Promote additional arguments to variadic methods.
7365 if (Match && Method->isVariadic()) {
7366 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7367 if (Args[i]->isTypeDependent()) {
7368 Match = false;
7369 break;
7370 }
7371 ExprResult Arg = DefaultVariadicArgumentPromotion(
7372 Args[i], VariadicCallType::Method, nullptr);
7373 if (Arg.isInvalid()) {
7374 Match = false;
7375 break;
7376 }
7377 }
7378 } else {
7379 // Check for extra arguments to non-variadic methods.
7380 if (Args.size() != NumNamedArgs)
7381 Match = false;
7382 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7383 // Special case when selectors have no argument. In this case, select
7384 // one with the most general result type of 'id'.
7385 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7386 QualType ReturnT = Methods[b]->getReturnType();
7387 if (ReturnT->isObjCIdType())
7388 return Methods[b];
7389 }
7390 }
7391 }
7392
7393 if (Match)
7394 return Method;
7395 }
7396 return nullptr;
7397}
7398
7400 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7401 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7402 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7403 if (ThisArg) {
7404 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7405 assert(!isa<CXXConstructorDecl>(Method) &&
7406 "Shouldn't have `this` for ctors!");
7407 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7409 ThisArg, /*Qualifier=*/std::nullopt, Method, Method);
7410 if (R.isInvalid())
7411 return false;
7412 ConvertedThis = R.get();
7413 } else {
7414 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7415 (void)MD;
7416 assert((MissingImplicitThis || MD->isStatic() ||
7417 isa<CXXConstructorDecl>(MD)) &&
7418 "Expected `this` for non-ctor instance methods");
7419 }
7420 ConvertedThis = nullptr;
7421 }
7422
7423 // Ignore any variadic arguments. Converting them is pointless, since the
7424 // user can't refer to them in the function condition.
7425 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7426
7427 // Convert the arguments.
7428 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7429 ExprResult R;
7431 S.Context, Function->getParamDecl(I)),
7432 SourceLocation(), Args[I]);
7433
7434 if (R.isInvalid())
7435 return false;
7436
7437 ConvertedArgs.push_back(R.get());
7438 }
7439
7440 if (Trap.hasErrorOccurred())
7441 return false;
7442
7443 // Push default arguments if needed.
7444 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7445 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7446 ParmVarDecl *P = Function->getParamDecl(i);
7447 if (!P->hasDefaultArg())
7448 return false;
7450 if (R.isInvalid())
7451 return false;
7452 ConvertedArgs.push_back(R.get());
7453 }
7454
7455 if (Trap.hasErrorOccurred())
7456 return false;
7457 }
7458 return true;
7459}
7460
7462 SourceLocation CallLoc,
7463 ArrayRef<Expr *> Args,
7464 bool MissingImplicitThis) {
7465 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7466 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7467 return nullptr;
7468
7469 SFINAETrap Trap(*this);
7470 SmallVector<Expr *, 16> ConvertedArgs;
7471 // FIXME: We should look into making enable_if late-parsed.
7472 Expr *DiscardedThis;
7474 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7475 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7476 return *EnableIfAttrs.begin();
7477
7478 for (auto *EIA : EnableIfAttrs) {
7480 // FIXME: This doesn't consider value-dependent cases, because doing so is
7481 // very difficult. Ideally, we should handle them more gracefully.
7482 if (EIA->getCond()->isValueDependent() ||
7483 !EIA->getCond()->EvaluateWithSubstitution(
7484 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7485 return EIA;
7486
7487 if (!Result.isInt() || !Result.getInt().getBoolValue())
7488 return EIA;
7489 }
7490 return nullptr;
7491}
7492
7493template <typename CheckFn>
7495 bool ArgDependent, SourceLocation Loc,
7496 CheckFn &&IsSuccessful) {
7498 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7499 if (ArgDependent == DIA->getArgDependent())
7500 Attrs.push_back(DIA);
7501 }
7502
7503 // Common case: No diagnose_if attributes, so we can quit early.
7504 if (Attrs.empty())
7505 return false;
7506
7507 auto WarningBegin = std::stable_partition(
7508 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7509 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7510 DIA->getWarningGroup().empty();
7511 });
7512
7513 // Note that diagnose_if attributes are late-parsed, so they appear in the
7514 // correct order (unlike enable_if attributes).
7515 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7516 IsSuccessful);
7517 if (ErrAttr != WarningBegin) {
7518 const DiagnoseIfAttr *DIA = *ErrAttr;
7519 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7520 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7521 << DIA->getParent() << DIA->getCond()->getSourceRange();
7522 return true;
7523 }
7524
7525 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7526 switch (Sev) {
7527 case DiagnoseIfAttr::DS_warning:
7529 case DiagnoseIfAttr::DS_error:
7530 return diag::Severity::Error;
7531 }
7532 llvm_unreachable("Fully covered switch above!");
7533 };
7534
7535 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7536 if (IsSuccessful(DIA)) {
7537 if (DIA->getWarningGroup().empty() &&
7538 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7539 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7540 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7541 << DIA->getParent() << DIA->getCond()->getSourceRange();
7542 } else {
7543 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7544 DIA->getWarningGroup());
7545 assert(DiagGroup);
7546 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7547 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7548 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7549 S.Diag(Loc, DiagID) << DIA->getMessage();
7550 }
7551 }
7552
7553 return false;
7554}
7555
7557 const Expr *ThisArg,
7559 SourceLocation Loc) {
7561 *this, Function, /*ArgDependent=*/true, Loc,
7562 [&](const DiagnoseIfAttr *DIA) {
7564 // It's sane to use the same Args for any redecl of this function, since
7565 // EvaluateWithSubstitution only cares about the position of each
7566 // argument in the arg list, not the ParmVarDecl* it maps to.
7567 if (!DIA->getCond()->EvaluateWithSubstitution(
7568 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7569 return false;
7570 return Result.isInt() && Result.getInt().getBoolValue();
7571 });
7572}
7573
7575 SourceLocation Loc) {
7577 *this, ND, /*ArgDependent=*/false, Loc,
7578 [&](const DiagnoseIfAttr *DIA) {
7579 bool Result;
7580 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7581 Result;
7582 });
7583}
7584
7586 ArrayRef<Expr *> Args,
7587 OverloadCandidateSet &CandidateSet,
7588 TemplateArgumentListInfo *ExplicitTemplateArgs,
7589 bool SuppressUserConversions,
7590 bool PartialOverloading,
7591 bool FirstArgumentIsBase) {
7592 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7593 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7594 ArrayRef<Expr *> FunctionArgs = Args;
7595
7596 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7597 FunctionDecl *FD =
7598 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7599
7600 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7601 QualType ObjectType;
7602 Expr::Classification ObjectClassification;
7603 if (Args.size() > 0) {
7604 if (Expr *E = Args[0]) {
7605 // Use the explicit base to restrict the lookup:
7606 ObjectType = E->getType();
7607 // Pointers in the object arguments are implicitly dereferenced, so we
7608 // always classify them as l-values.
7609 if (!ObjectType.isNull() && ObjectType->isPointerType())
7610 ObjectClassification = Expr::Classification::makeSimpleLValue();
7611 else
7612 ObjectClassification = E->Classify(Context);
7613 } // .. else there is an implicit base.
7614 FunctionArgs = Args.slice(1);
7615 }
7616 if (FunTmpl) {
7617 AddMethodTemplateCandidate(
7618 FunTmpl, F.getPair(),
7619 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
7620 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7621 FunctionArgs, CandidateSet, SuppressUserConversions,
7622 PartialOverloading);
7623 } else {
7624 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7625 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7626 ObjectClassification, FunctionArgs, CandidateSet,
7627 SuppressUserConversions, PartialOverloading);
7628 }
7629 } else {
7630 // This branch handles both standalone functions and static methods.
7631
7632 // Slice the first argument (which is the base) when we access
7633 // static method as non-static.
7634 if (Args.size() > 0 &&
7635 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7636 !isa<CXXConstructorDecl>(FD)))) {
7637 assert(cast<CXXMethodDecl>(FD)->isStatic());
7638 FunctionArgs = Args.slice(1);
7639 }
7640 if (FunTmpl) {
7641 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7642 ExplicitTemplateArgs, FunctionArgs,
7643 CandidateSet, SuppressUserConversions,
7644 PartialOverloading);
7645 } else {
7646 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7647 SuppressUserConversions, PartialOverloading);
7648 }
7649 }
7650 }
7651}
7652
7654 Expr::Classification ObjectClassification,
7655 ArrayRef<Expr *> Args,
7656 OverloadCandidateSet &CandidateSet,
7657 bool SuppressUserConversions,
7659 NamedDecl *Decl = FoundDecl.getDecl();
7660 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
7661
7662 if (isa<UsingShadowDecl>(Decl))
7663 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7664
7665 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7666 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7667 "Expected a member function template");
7668 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7669 /*ExplicitArgs*/ nullptr, ObjectType,
7670 ObjectClassification, Args, CandidateSet,
7671 SuppressUserConversions, false, PO);
7672 } else {
7673 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7674 ObjectType, ObjectClassification, Args, CandidateSet,
7675 SuppressUserConversions, false, {}, PO);
7676 }
7677}
7678
7681 CXXRecordDecl *ActingContext, QualType ObjectType,
7682 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7683 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7684 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7685 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7686 const FunctionProtoType *Proto
7687 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7688 assert(Proto && "Methods without a prototype cannot be overloaded");
7689 assert(!isa<CXXConstructorDecl>(Method) &&
7690 "Use AddOverloadCandidate for constructors");
7691
7692 if (!CandidateSet.isNewCandidate(Method, PO))
7693 return;
7694
7695 // C++11 [class.copy]p23: [DR1402]
7696 // A defaulted move assignment operator that is defined as deleted is
7697 // ignored by overload resolution.
7698 if (Method->isDefaulted() && Method->isDeleted() &&
7699 Method->isMoveAssignmentOperator())
7700 return;
7701
7702 // Overload resolution is always an unevaluated context.
7705
7706 bool IgnoreExplicitObject =
7707 (Method->isExplicitObjectMemberFunction() &&
7708 CandidateSet.getKind() ==
7710 bool ImplicitObjectMethodTreatedAsStatic =
7711 CandidateSet.getKind() ==
7713 Method->isImplicitObjectMemberFunction();
7714
7715 unsigned ExplicitOffset =
7716 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7717
7718 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7719 int(ImplicitObjectMethodTreatedAsStatic);
7720
7721 unsigned ExtraArgs =
7723 ? 0
7724 : 1;
7725
7726 // Add this candidate
7727 OverloadCandidate &Candidate =
7728 CandidateSet.addCandidate(Args.size() + ExtraArgs, EarlyConversions);
7729 Candidate.FoundDecl = FoundDecl;
7730 Candidate.Function = Method;
7731 Candidate.RewriteKind =
7732 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7733 Candidate.TookAddressOfOverload =
7735 Candidate.ExplicitCallArguments = Args.size();
7736 Candidate.StrictPackMatch = StrictPackMatch;
7737
7738 // (C++ 13.3.2p2): A candidate function having fewer than m
7739 // parameters is viable only if it has an ellipsis in its parameter
7740 // list (8.3.5).
7741 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7742 !Proto->isVariadic() &&
7743 shouldEnforceArgLimit(PartialOverloading, Method)) {
7744 Candidate.Viable = false;
7746 return;
7747 }
7748
7749 // (C++ 13.3.2p2): A candidate function having more than m parameters
7750 // is viable only if the (m+1)st parameter has a default argument
7751 // (8.3.6). For the purposes of overload resolution, the
7752 // parameter list is truncated on the right, so that there are
7753 // exactly m parameters.
7754 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7755 ExplicitOffset +
7756 int(ImplicitObjectMethodTreatedAsStatic);
7757
7758 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7759 // Not enough arguments.
7760 Candidate.Viable = false;
7762 return;
7763 }
7764
7765 Candidate.Viable = true;
7766
7767 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7768 if (!IgnoreExplicitObject) {
7769 if (ObjectType.isNull())
7770 Candidate.IgnoreObjectArgument = true;
7771 else if (Method->isStatic()) {
7772 // [over.best.ics.general]p8
7773 // When the parameter is the implicit object parameter of a static member
7774 // function, the implicit conversion sequence is a standard conversion
7775 // sequence that is neither better nor worse than any other standard
7776 // conversion sequence.
7777 //
7778 // This is a rule that was introduced in C++23 to support static lambdas.
7779 // We apply it retroactively because we want to support static lambdas as
7780 // an extension and it doesn't hurt previous code.
7781 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7782 } else {
7783 // Determine the implicit conversion sequence for the object
7784 // parameter.
7785 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7786 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7787 Method, ActingContext, /*InOverloadResolution=*/true);
7788 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7789 Candidate.Viable = false;
7791 return;
7792 }
7793 }
7794 }
7795
7796 // (CUDA B.1): Check for invalid calls between targets.
7797 if (getLangOpts().CUDA)
7798 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
7799 Method)) {
7800 Candidate.Viable = false;
7801 Candidate.FailureKind = ovl_fail_bad_target;
7802 return;
7803 }
7804
7805 if (Method->getTrailingRequiresClause()) {
7806 ConstraintSatisfaction Satisfaction;
7807 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7808 /*ForOverloadResolution*/ true) ||
7809 !Satisfaction.IsSatisfied) {
7810 Candidate.Viable = false;
7812 return;
7813 }
7814 }
7815
7816 // Determine the implicit conversion sequences for each of the
7817 // arguments.
7818 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7819 unsigned ConvIdx =
7820 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
7821 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7822 // We already formed a conversion sequence for this parameter during
7823 // template argument deduction.
7824 } else if (ArgIdx < NumParams) {
7825 // (C++ 13.3.2p3): for F to be a viable function, there shall
7826 // exist for each argument an implicit conversion sequence
7827 // (13.3.3.1) that converts that argument to the corresponding
7828 // parameter of F.
7829 QualType ParamType;
7830 if (ImplicitObjectMethodTreatedAsStatic) {
7831 ParamType = ArgIdx == 0
7832 ? Method->getFunctionObjectParameterReferenceType()
7833 : Proto->getParamType(ArgIdx - 1);
7834 } else {
7835 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
7836 }
7837 Candidate.Conversions[ConvIdx]
7838 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7839 SuppressUserConversions,
7840 /*InOverloadResolution=*/true,
7841 /*AllowObjCWritebackConversion=*/
7842 getLangOpts().ObjCAutoRefCount);
7843 if (Candidate.Conversions[ConvIdx].isBad()) {
7844 Candidate.Viable = false;
7846 return;
7847 }
7848 } else {
7849 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7850 // argument for which there is no corresponding parameter is
7851 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7852 Candidate.Conversions[ConvIdx].setEllipsis();
7853 }
7854 }
7855
7856 if (EnableIfAttr *FailedAttr =
7857 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7858 Candidate.Viable = false;
7859 Candidate.FailureKind = ovl_fail_enable_if;
7860 Candidate.DeductionFailure.Data = FailedAttr;
7861 return;
7862 }
7863
7865 Candidate.Viable = false;
7867 }
7868}
7869
7871 Sema &S, OverloadCandidateSet &CandidateSet,
7872 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7873 CXXRecordDecl *ActingContext,
7874 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7875 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7876 bool SuppressUserConversions, bool PartialOverloading,
7878
7879 // C++ [over.match.funcs]p7:
7880 // In each case where a candidate is a function template, candidate
7881 // function template specializations are generated using template argument
7882 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7883 // candidate functions in the usual way.113) A given name can refer to one
7884 // or more function templates and also to a set of overloaded non-template
7885 // functions. In such a case, the candidate functions generated from each
7886 // function template are combined with the set of non-template candidate
7887 // functions.
7888 TemplateDeductionInfo Info(CandidateSet.getLocation());
7889 auto *Method = cast<CXXMethodDecl>(MethodTmpl->getTemplatedDecl());
7890 FunctionDecl *Specialization = nullptr;
7891 ConversionSequenceList Conversions;
7893 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7894 PartialOverloading, /*AggregateDeductionCandidate=*/false,
7895 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
7896 CandidateSet.getKind() ==
7898 [&](ArrayRef<QualType> ParamTypes,
7899 bool OnlyInitializeNonUserDefinedConversions) {
7900 return S.CheckNonDependentConversions(
7901 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7902 Sema::CheckNonDependentConversionsFlag(
7903 SuppressUserConversions,
7904 OnlyInitializeNonUserDefinedConversions),
7905 ActingContext, ObjectType, ObjectClassification, PO);
7906 });
7908 OverloadCandidate &Candidate =
7909 CandidateSet.addCandidate(Conversions.size(), Conversions);
7910 Candidate.FoundDecl = FoundDecl;
7911 Candidate.Function = Method;
7912 Candidate.Viable = false;
7913 Candidate.RewriteKind =
7914 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7915 Candidate.IsSurrogate = false;
7916 Candidate.TookAddressOfOverload =
7917 CandidateSet.getKind() ==
7919
7920 Candidate.IgnoreObjectArgument =
7921 Method->isStatic() ||
7922 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
7923 Candidate.ExplicitCallArguments = Args.size();
7926 else {
7928 Candidate.DeductionFailure =
7930 }
7931 return;
7932 }
7933
7934 // Add the function template specialization produced by template argument
7935 // deduction as a candidate.
7936 assert(Specialization && "Missing member function template specialization?");
7937 assert(isa<CXXMethodDecl>(Specialization) &&
7938 "Specialization is not a member function?");
7940 cast<CXXMethodDecl>(Specialization), FoundDecl, ActingContext, ObjectType,
7941 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
7942 PartialOverloading, Conversions, PO, Info.hasStrictPackMatch());
7943}
7944
7946 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7947 CXXRecordDecl *ActingContext,
7948 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7949 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7950 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7951 bool PartialOverloading, OverloadCandidateParamOrder PO) {
7952 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7953 return;
7954
7955 if (ExplicitTemplateArgs ||
7956 !CandidateSet.shouldDeferTemplateArgumentDeduction(getLangOpts())) {
7958 *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
7959 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
7960 SuppressUserConversions, PartialOverloading, PO);
7961 return;
7962 }
7963
7965 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
7966 Args, SuppressUserConversions, PartialOverloading, PO);
7967}
7968
7969/// Determine whether a given function template has a simple explicit specifier
7970/// or a non-value-dependent explicit-specification that evaluates to true.
7973}
7974
7978}
7979
7981 Sema &S, OverloadCandidateSet &CandidateSet,
7983 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7984 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
7986 bool AggregateCandidateDeduction) {
7987
7988 // If the function template has a non-dependent explicit specification,
7989 // exclude it now if appropriate; we are not permitted to perform deduction
7990 // and substitution in this case.
7991 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7992 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7993 Candidate.FoundDecl = FoundDecl;
7994 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7995 Candidate.Viable = false;
7996 Candidate.FailureKind = ovl_fail_explicit;
7997 return;
7998 }
7999
8000 // C++ [over.match.funcs]p7:
8001 // In each case where a candidate is a function template, candidate
8002 // function template specializations are generated using template argument
8003 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8004 // candidate functions in the usual way.113) A given name can refer to one
8005 // or more function templates and also to a set of overloaded non-template
8006 // functions. In such a case, the candidate functions generated from each
8007 // function template are combined with the set of non-template candidate
8008 // functions.
8009 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8010 FunctionTemplate->getTemplateDepth());
8011 FunctionDecl *Specialization = nullptr;
8012 ConversionSequenceList Conversions;
8014 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8015 PartialOverloading, AggregateCandidateDeduction,
8016 /*PartialOrdering=*/false,
8017 /*ObjectType=*/QualType(),
8018 /*ObjectClassification=*/Expr::Classification(),
8019 CandidateSet.getKind() ==
8021 [&](ArrayRef<QualType> ParamTypes,
8022 bool OnlyInitializeNonUserDefinedConversions) {
8023 return S.CheckNonDependentConversions(
8024 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8025 Sema::CheckNonDependentConversionsFlag(
8026 SuppressUserConversions,
8027 OnlyInitializeNonUserDefinedConversions),
8028 nullptr, QualType(), {}, PO);
8029 });
8031 OverloadCandidate &Candidate =
8032 CandidateSet.addCandidate(Conversions.size(), Conversions);
8033 Candidate.FoundDecl = FoundDecl;
8034 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8035 Candidate.Viable = false;
8036 Candidate.RewriteKind =
8037 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8038 Candidate.IsSurrogate = false;
8039 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
8040 // Ignore the object argument if there is one, since we don't have an object
8041 // type.
8042 Candidate.TookAddressOfOverload =
8043 CandidateSet.getKind() ==
8045
8046 Candidate.IgnoreObjectArgument =
8047 isa<CXXMethodDecl>(Candidate.Function) &&
8048 !cast<CXXMethodDecl>(Candidate.Function)
8049 ->isExplicitObjectMemberFunction() &&
8050 !isa<CXXConstructorDecl>(Candidate.Function);
8051
8052 Candidate.ExplicitCallArguments = Args.size();
8055 else {
8057 Candidate.DeductionFailure =
8059 }
8060 return;
8061 }
8062
8063 // Add the function template specialization produced by template argument
8064 // deduction as a candidate.
8065 assert(Specialization && "Missing function template specialization?");
8067 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8068 PartialOverloading, AllowExplicit,
8069 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
8070 Info.AggregateDeductionCandidateHasMismatchedArity,
8071 Info.hasStrictPackMatch());
8072}
8073
8076 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8077 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8078 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8079 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8080 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
8081 return;
8082
8083 bool DependentExplicitSpecifier = hasDependentExplicit(FunctionTemplate);
8084
8085 if (ExplicitTemplateArgs ||
8086 !CandidateSet.shouldDeferTemplateArgumentDeduction(getLangOpts()) ||
8087 (isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl()) &&
8088 DependentExplicitSpecifier)) {
8089
8091 *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8092 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8093 IsADLCandidate, PO, AggregateCandidateDeduction);
8094
8095 if (DependentExplicitSpecifier)
8097 return;
8098 }
8099
8100 CandidateSet.AddDeferredTemplateCandidate(
8101 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8102 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8103 AggregateCandidateDeduction);
8104}
8105
8108 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8109 ConversionSequenceList &Conversions,
8110 CheckNonDependentConversionsFlag UserConversionFlag,
8111 CXXRecordDecl *ActingContext, QualType ObjectType,
8112 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8113 // FIXME: The cases in which we allow explicit conversions for constructor
8114 // arguments never consider calling a constructor template. It's not clear
8115 // that is correct.
8116 const bool AllowExplicit = false;
8117
8118 bool ForOverloadSetAddressResolution =
8120 auto *FD = FunctionTemplate->getTemplatedDecl();
8121 auto *Method = dyn_cast<CXXMethodDecl>(FD);
8122 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8123 !isa<CXXConstructorDecl>(Method);
8124 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8125
8126 if (Conversions.empty())
8127 Conversions =
8128 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
8129
8130 // Overload resolution is always an unevaluated context.
8133
8134 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8135 // require that, but this check should never result in a hard error, and
8136 // overload resolution is permitted to sidestep instantiations.
8137 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
8138 !ObjectType.isNull()) {
8139 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8140 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8141 !ParamTypes[0]->isDependentType()) {
8142 Conversions[ConvIdx] = TryObjectArgumentInitialization(
8143 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8144 Method, ActingContext, /*InOverloadResolution=*/true,
8145 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8146 : QualType());
8147 if (Conversions[ConvIdx].isBad())
8148 return true;
8149 }
8150 }
8151
8152 // A speculative workaround for self-dependent constraint bugs that manifest
8153 // after CWG2369.
8154 // FIXME: Add references to the standard once P3606 is adopted.
8155 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8156 QualType ArgType) {
8157 ParamType = ParamType.getNonReferenceType();
8158 ArgType = ArgType.getNonReferenceType();
8159 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8160 if (PointerConv) {
8161 ParamType = ParamType->getPointeeType();
8162 ArgType = ArgType->getPointeeType();
8163 }
8164
8165 if (auto *RD = ParamType->getAsCXXRecordDecl();
8166 RD && RD->hasDefinition() &&
8167 llvm::any_of(LookupConstructors(RD), [](NamedDecl *ND) {
8168 auto Info = getConstructorInfo(ND);
8169 if (!Info)
8170 return false;
8171 CXXConstructorDecl *Ctor = Info.Constructor;
8172 /// isConvertingConstructor takes copy/move constructors into
8173 /// account!
8174 return !Ctor->isCopyOrMoveConstructor() &&
8176 /*AllowExplicit=*/true);
8177 }))
8178 return true;
8179 if (auto *RD = ArgType->getAsCXXRecordDecl();
8180 RD && RD->hasDefinition() &&
8181 !RD->getVisibleConversionFunctions().empty())
8182 return true;
8183
8184 return false;
8185 };
8186
8187 unsigned Offset =
8188 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8189 : 0;
8190
8191 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
8192 I != N; ++I) {
8193 QualType ParamType = ParamTypes[I + Offset];
8194 if (!ParamType->isDependentType()) {
8195 unsigned ConvIdx;
8197 ConvIdx = Args.size() - 1 - I;
8198 assert(Args.size() + ThisConversions == 2 &&
8199 "number of args (including 'this') must be exactly 2 for "
8200 "reversed order");
8201 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8202 // would also be 0. 'this' got ConvIdx = 1 previously.
8203 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8204 } else {
8205 // For members, 'this' got ConvIdx = 0 previously.
8206 ConvIdx = ThisConversions + I;
8207 }
8208 if (Conversions[ConvIdx].isInitialized())
8209 continue;
8210 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8211 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8212 continue;
8213 Conversions[ConvIdx] = TryCopyInitialization(
8214 *this, Args[I], ParamType, UserConversionFlag.SuppressUserConversions,
8215 /*InOverloadResolution=*/true,
8216 /*AllowObjCWritebackConversion=*/
8217 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8218 if (Conversions[ConvIdx].isBad())
8219 return true;
8220 }
8221 }
8222
8223 return false;
8224}
8225
8226/// Determine whether this is an allowable conversion from the result
8227/// of an explicit conversion operator to the expected type, per C++
8228/// [over.match.conv]p1 and [over.match.ref]p1.
8229///
8230/// \param ConvType The return type of the conversion function.
8231///
8232/// \param ToType The type we are converting to.
8233///
8234/// \param AllowObjCPointerConversion Allow a conversion from one
8235/// Objective-C pointer to another.
8236///
8237/// \returns true if the conversion is allowable, false otherwise.
8239 QualType ConvType, QualType ToType,
8240 bool AllowObjCPointerConversion) {
8241 QualType ToNonRefType = ToType.getNonReferenceType();
8242
8243 // Easy case: the types are the same.
8244 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
8245 return true;
8246
8247 // Allow qualification conversions.
8248 bool ObjCLifetimeConversion;
8249 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
8250 ObjCLifetimeConversion))
8251 return true;
8252
8253 // If we're not allowed to consider Objective-C pointer conversions,
8254 // we're done.
8255 if (!AllowObjCPointerConversion)
8256 return false;
8257
8258 // Is this an Objective-C pointer conversion?
8259 bool IncompatibleObjC = false;
8260 QualType ConvertedType;
8261 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
8262 IncompatibleObjC);
8263}
8264
8266 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8267 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8268 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8269 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8270 assert(!Conversion->getDescribedFunctionTemplate() &&
8271 "Conversion function templates use AddTemplateConversionCandidate");
8272 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8273 if (!CandidateSet.isNewCandidate(Conversion))
8274 return;
8275
8276 // If the conversion function has an undeduced return type, trigger its
8277 // deduction now.
8278 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8279 if (DeduceReturnType(Conversion, From->getExprLoc()))
8280 return;
8281 ConvType = Conversion->getConversionType().getNonReferenceType();
8282 }
8283
8284 // If we don't allow any conversion of the result type, ignore conversion
8285 // functions that don't convert to exactly (possibly cv-qualified) T.
8286 if (!AllowResultConversion &&
8287 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
8288 return;
8289
8290 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8291 // operator is only a candidate if its return type is the target type or
8292 // can be converted to the target type with a qualification conversion.
8293 //
8294 // FIXME: Include such functions in the candidate list and explain why we
8295 // can't select them.
8296 if (Conversion->isExplicit() &&
8297 !isAllowableExplicitConversion(*this, ConvType, ToType,
8298 AllowObjCConversionOnExplicit))
8299 return;
8300
8301 // Overload resolution is always an unevaluated context.
8304
8305 // Add this candidate
8306 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8307 Candidate.FoundDecl = FoundDecl;
8308 Candidate.Function = Conversion;
8310 Candidate.FinalConversion.setFromType(ConvType);
8311 Candidate.FinalConversion.setAllToTypes(ToType);
8312 Candidate.HasFinalConversion = true;
8313 Candidate.Viable = true;
8314 Candidate.ExplicitCallArguments = 1;
8315 Candidate.StrictPackMatch = StrictPackMatch;
8316
8317 // Explicit functions are not actually candidates at all if we're not
8318 // allowing them in this context, but keep them around so we can point
8319 // to them in diagnostics.
8320 if (!AllowExplicit && Conversion->isExplicit()) {
8321 Candidate.Viable = false;
8322 Candidate.FailureKind = ovl_fail_explicit;
8323 return;
8324 }
8325
8326 // C++ [over.match.funcs]p4:
8327 // For conversion functions, the function is considered to be a member of
8328 // the class of the implicit implied object argument for the purpose of
8329 // defining the type of the implicit object parameter.
8330 //
8331 // Determine the implicit conversion sequence for the implicit
8332 // object parameter.
8333 QualType ObjectType = From->getType();
8334 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8335 ObjectType = FromPtrType->getPointeeType();
8336 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8337 // C++23 [over.best.ics.general]
8338 // However, if the target is [...]
8339 // - the object parameter of a user-defined conversion function
8340 // [...] user-defined conversion sequences are not considered.
8342 *this, CandidateSet.getLocation(), From->getType(),
8343 From->Classify(Context), Conversion, ConversionContext,
8344 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8345 /*SuppressUserConversion*/ true);
8346
8347 if (Candidate.Conversions[0].isBad()) {
8348 Candidate.Viable = false;
8350 return;
8351 }
8352
8353 if (Conversion->getTrailingRequiresClause()) {
8354 ConstraintSatisfaction Satisfaction;
8355 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8356 !Satisfaction.IsSatisfied) {
8357 Candidate.Viable = false;
8359 return;
8360 }
8361 }
8362
8363 // We won't go through a user-defined type conversion function to convert a
8364 // derived to base as such conversions are given Conversion Rank. They only
8365 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8366 QualType FromCanon
8367 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8368 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8369 if (FromCanon == ToCanon ||
8370 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8371 Candidate.Viable = false;
8373 return;
8374 }
8375
8376 // To determine what the conversion from the result of calling the
8377 // conversion function to the type we're eventually trying to
8378 // convert to (ToType), we need to synthesize a call to the
8379 // conversion function and attempt copy initialization from it. This
8380 // makes sure that we get the right semantics with respect to
8381 // lvalues/rvalues and the type. Fortunately, we can allocate this
8382 // call on the stack and we don't need its arguments to be
8383 // well-formed.
8384 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8385 VK_LValue, From->getBeginLoc());
8387 Context.getPointerType(Conversion->getType()),
8388 CK_FunctionToPointerDecay, &ConversionRef,
8390
8391 QualType ConversionType = Conversion->getConversionType();
8392 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8393 Candidate.Viable = false;
8395 return;
8396 }
8397
8398 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8399
8400 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8401
8402 // Introduce a temporary expression with the right type and value category
8403 // that we can use for deduction purposes.
8404 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8405
8407 TryCopyInitialization(*this, &FakeCall, ToType,
8408 /*SuppressUserConversions=*/true,
8409 /*InOverloadResolution=*/false,
8410 /*AllowObjCWritebackConversion=*/false);
8411
8412 switch (ICS.getKind()) {
8414 Candidate.FinalConversion = ICS.Standard;
8415 Candidate.HasFinalConversion = true;
8416
8417 // C++ [over.ics.user]p3:
8418 // If the user-defined conversion is specified by a specialization of a
8419 // conversion function template, the second standard conversion sequence
8420 // shall have exact match rank.
8421 if (Conversion->getPrimaryTemplate() &&
8423 Candidate.Viable = false;
8425 return;
8426 }
8427
8428 // C++0x [dcl.init.ref]p5:
8429 // In the second case, if the reference is an rvalue reference and
8430 // the second standard conversion sequence of the user-defined
8431 // conversion sequence includes an lvalue-to-rvalue conversion, the
8432 // program is ill-formed.
8433 if (ToType->isRValueReferenceType() &&
8435 Candidate.Viable = false;
8437 return;
8438 }
8439 break;
8440
8442 Candidate.Viable = false;
8444 return;
8445
8446 default:
8447 llvm_unreachable(
8448 "Can only end up with a standard conversion sequence or failure");
8449 }
8450
8451 if (EnableIfAttr *FailedAttr =
8452 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8453 Candidate.Viable = false;
8454 Candidate.FailureKind = ovl_fail_enable_if;
8455 Candidate.DeductionFailure.Data = FailedAttr;
8456 return;
8457 }
8458
8459 if (isNonViableMultiVersionOverload(Conversion)) {
8460 Candidate.Viable = false;
8462 }
8463}
8464
8466 Sema &S, OverloadCandidateSet &CandidateSet,
8468 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8469 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8470 bool AllowResultConversion) {
8471
8472 // If the function template has a non-dependent explicit specification,
8473 // exclude it now if appropriate; we are not permitted to perform deduction
8474 // and substitution in this case.
8475 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8476 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8477 Candidate.FoundDecl = FoundDecl;
8478 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8479 Candidate.Viable = false;
8480 Candidate.FailureKind = ovl_fail_explicit;
8481 return;
8482 }
8483
8484 QualType ObjectType = From->getType();
8485 Expr::Classification ObjectClassification = From->Classify(S.Context);
8486
8487 TemplateDeductionInfo Info(CandidateSet.getLocation());
8490 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8491 Specialization, Info);
8493 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8494 Candidate.FoundDecl = FoundDecl;
8495 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8496 Candidate.Viable = false;
8498 Candidate.ExplicitCallArguments = 1;
8499 Candidate.DeductionFailure =
8501 return;
8502 }
8503
8504 // Add the conversion function template specialization produced by
8505 // template argument deduction as a candidate.
8506 assert(Specialization && "Missing function template specialization?");
8507 S.AddConversionCandidate(Specialization, FoundDecl, ActingContext, From,
8508 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8509 AllowExplicit, AllowResultConversion,
8510 Info.hasStrictPackMatch());
8511}
8512
8515 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8516 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8517 bool AllowExplicit, bool AllowResultConversion) {
8518 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8519 "Only conversion function templates permitted here");
8520
8521 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8522 return;
8523
8524 if (!CandidateSet.shouldDeferTemplateArgumentDeduction(getLangOpts()) ||
8525 CandidateSet.getKind() ==
8529 *this, CandidateSet, FunctionTemplate, FoundDecl, ActingDC, From,
8530 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8531 AllowResultConversion);
8532
8534 return;
8535 }
8536
8538 FunctionTemplate, FoundDecl, ActingDC, From, ToType,
8539 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8540}
8541
8543 DeclAccessPair FoundDecl,
8544 CXXRecordDecl *ActingContext,
8545 const FunctionProtoType *Proto,
8546 Expr *Object,
8547 ArrayRef<Expr *> Args,
8548 OverloadCandidateSet& CandidateSet) {
8549 if (!CandidateSet.isNewCandidate(Conversion))
8550 return;
8551
8552 // Overload resolution is always an unevaluated context.
8555
8556 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8557 Candidate.FoundDecl = FoundDecl;
8558 Candidate.Function = nullptr;
8559 Candidate.Surrogate = Conversion;
8560 Candidate.IsSurrogate = true;
8561 Candidate.Viable = true;
8562 Candidate.ExplicitCallArguments = Args.size();
8563
8564 // Determine the implicit conversion sequence for the implicit
8565 // object parameter.
8566 ImplicitConversionSequence ObjectInit;
8567 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8568 ObjectInit = TryCopyInitialization(*this, Object,
8569 Conversion->getParamDecl(0)->getType(),
8570 /*SuppressUserConversions=*/false,
8571 /*InOverloadResolution=*/true, false);
8572 } else {
8574 *this, CandidateSet.getLocation(), Object->getType(),
8575 Object->Classify(Context), Conversion, ActingContext);
8576 }
8577
8578 if (ObjectInit.isBad()) {
8579 Candidate.Viable = false;
8581 Candidate.Conversions[0] = ObjectInit;
8582 return;
8583 }
8584
8585 // The first conversion is actually a user-defined conversion whose
8586 // first conversion is ObjectInit's standard conversion (which is
8587 // effectively a reference binding). Record it as such.
8588 Candidate.Conversions[0].setUserDefined();
8589 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8590 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8591 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8592 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8593 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8594 Candidate.Conversions[0].UserDefined.After
8595 = Candidate.Conversions[0].UserDefined.Before;
8596 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8597
8598 // Find the
8599 unsigned NumParams = Proto->getNumParams();
8600
8601 // (C++ 13.3.2p2): A candidate function having fewer than m
8602 // parameters is viable only if it has an ellipsis in its parameter
8603 // list (8.3.5).
8604 if (Args.size() > NumParams && !Proto->isVariadic()) {
8605 Candidate.Viable = false;
8607 return;
8608 }
8609
8610 // Function types don't have any default arguments, so just check if
8611 // we have enough arguments.
8612 if (Args.size() < NumParams) {
8613 // Not enough arguments.
8614 Candidate.Viable = false;
8616 return;
8617 }
8618
8619 // Determine the implicit conversion sequences for each of the
8620 // arguments.
8621 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8622 if (ArgIdx < NumParams) {
8623 // (C++ 13.3.2p3): for F to be a viable function, there shall
8624 // exist for each argument an implicit conversion sequence
8625 // (13.3.3.1) that converts that argument to the corresponding
8626 // parameter of F.
8627 QualType ParamType = Proto->getParamType(ArgIdx);
8628 Candidate.Conversions[ArgIdx + 1]
8629 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8630 /*SuppressUserConversions=*/false,
8631 /*InOverloadResolution=*/false,
8632 /*AllowObjCWritebackConversion=*/
8633 getLangOpts().ObjCAutoRefCount);
8634 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8635 Candidate.Viable = false;
8637 return;
8638 }
8639 } else {
8640 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8641 // argument for which there is no corresponding parameter is
8642 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8643 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8644 }
8645 }
8646
8647 if (Conversion->getTrailingRequiresClause()) {
8648 ConstraintSatisfaction Satisfaction;
8649 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8650 /*ForOverloadResolution*/ true) ||
8651 !Satisfaction.IsSatisfied) {
8652 Candidate.Viable = false;
8654 return;
8655 }
8656 }
8657
8658 if (EnableIfAttr *FailedAttr =
8659 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8660 Candidate.Viable = false;
8661 Candidate.FailureKind = ovl_fail_enable_if;
8662 Candidate.DeductionFailure.Data = FailedAttr;
8663 return;
8664 }
8665}
8666
8668 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8669 OverloadCandidateSet &CandidateSet,
8670 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8671 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8672 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8673 ArrayRef<Expr *> FunctionArgs = Args;
8674
8675 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8676 FunctionDecl *FD =
8677 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8678
8679 // Don't consider rewritten functions if we're not rewriting.
8680 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8681 continue;
8682
8683 assert(!isa<CXXMethodDecl>(FD) &&
8684 "unqualified operator lookup found a member function");
8685
8686 if (FunTmpl) {
8687 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8688 FunctionArgs, CandidateSet);
8689 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
8690
8691 // As template candidates are not deduced immediately,
8692 // persist the array in the overload set.
8694 FunctionArgs[1], FunctionArgs[0]);
8695 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8696 Reversed, CandidateSet, false, false, true,
8697 ADLCallKind::NotADL,
8699 }
8700 } else {
8701 if (ExplicitTemplateArgs)
8702 continue;
8703 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8704 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8705 AddOverloadCandidate(FD, F.getPair(),
8706 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8707 false, false, true, false, ADLCallKind::NotADL, {},
8709 }
8710 }
8711}
8712
8714 SourceLocation OpLoc,
8715 ArrayRef<Expr *> Args,
8716 OverloadCandidateSet &CandidateSet,
8719
8720 // C++ [over.match.oper]p3:
8721 // For a unary operator @ with an operand of a type whose
8722 // cv-unqualified version is T1, and for a binary operator @ with
8723 // a left operand of a type whose cv-unqualified version is T1 and
8724 // a right operand of a type whose cv-unqualified version is T2,
8725 // three sets of candidate functions, designated member
8726 // candidates, non-member candidates and built-in candidates, are
8727 // constructed as follows:
8728 QualType T1 = Args[0]->getType();
8729
8730 // -- If T1 is a complete class type or a class currently being
8731 // defined, the set of member candidates is the result of the
8732 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8733 // the set of member candidates is empty.
8734 if (T1->isRecordType()) {
8735 bool IsComplete = isCompleteType(OpLoc, T1);
8736 auto *T1RD = T1->getAsCXXRecordDecl();
8737 // Complete the type if it can be completed.
8738 // If the type is neither complete nor being defined, bail out now.
8739 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
8740 return;
8741
8742 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8743 LookupQualifiedName(Operators, T1RD);
8744 Operators.suppressAccessDiagnostics();
8745
8746 for (LookupResult::iterator Oper = Operators.begin(),
8747 OperEnd = Operators.end();
8748 Oper != OperEnd; ++Oper) {
8749 if (Oper->getAsFunction() &&
8751 !CandidateSet.getRewriteInfo().shouldAddReversed(
8752 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8753 continue;
8754 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8755 Args[0]->Classify(Context), Args.slice(1),
8756 CandidateSet, /*SuppressUserConversion=*/false, PO);
8757 }
8758 }
8759}
8760
8762 OverloadCandidateSet& CandidateSet,
8763 bool IsAssignmentOperator,
8764 unsigned NumContextualBoolArguments) {
8765 // Overload resolution is always an unevaluated context.
8768
8769 // Add this candidate
8770 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8771 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8772 Candidate.Function = nullptr;
8773 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8774
8775 // Determine the implicit conversion sequences for each of the
8776 // arguments.
8777 Candidate.Viable = true;
8778 Candidate.ExplicitCallArguments = Args.size();
8779 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8780 // C++ [over.match.oper]p4:
8781 // For the built-in assignment operators, conversions of the
8782 // left operand are restricted as follows:
8783 // -- no temporaries are introduced to hold the left operand, and
8784 // -- no user-defined conversions are applied to the left
8785 // operand to achieve a type match with the left-most
8786 // parameter of a built-in candidate.
8787 //
8788 // We block these conversions by turning off user-defined
8789 // conversions, since that is the only way that initialization of
8790 // a reference to a non-class type can occur from something that
8791 // is not of the same type.
8792 if (ArgIdx < NumContextualBoolArguments) {
8793 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8794 "Contextual conversion to bool requires bool type");
8795 Candidate.Conversions[ArgIdx]
8796 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
8797 } else {
8798 Candidate.Conversions[ArgIdx]
8799 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
8800 ArgIdx == 0 && IsAssignmentOperator,
8801 /*InOverloadResolution=*/false,
8802 /*AllowObjCWritebackConversion=*/
8803 getLangOpts().ObjCAutoRefCount);
8804 }
8805 if (Candidate.Conversions[ArgIdx].isBad()) {
8806 Candidate.Viable = false;
8808 break;
8809 }
8810 }
8811}
8812
8813namespace {
8814
8815/// BuiltinCandidateTypeSet - A set of types that will be used for the
8816/// candidate operator functions for built-in operators (C++
8817/// [over.built]). The types are separated into pointer types and
8818/// enumeration types.
8819class BuiltinCandidateTypeSet {
8820 /// TypeSet - A set of types.
8821 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8822
8823 /// PointerTypes - The set of pointer types that will be used in the
8824 /// built-in candidates.
8825 TypeSet PointerTypes;
8826
8827 /// MemberPointerTypes - The set of member pointer types that will be
8828 /// used in the built-in candidates.
8829 TypeSet MemberPointerTypes;
8830
8831 /// EnumerationTypes - The set of enumeration types that will be
8832 /// used in the built-in candidates.
8833 TypeSet EnumerationTypes;
8834
8835 /// The set of vector types that will be used in the built-in
8836 /// candidates.
8837 TypeSet VectorTypes;
8838
8839 /// The set of matrix types that will be used in the built-in
8840 /// candidates.
8841 TypeSet MatrixTypes;
8842
8843 /// The set of _BitInt types that will be used in the built-in candidates.
8844 TypeSet BitIntTypes;
8845
8846 /// A flag indicating non-record types are viable candidates
8847 bool HasNonRecordTypes;
8848
8849 /// A flag indicating whether either arithmetic or enumeration types
8850 /// were present in the candidate set.
8851 bool HasArithmeticOrEnumeralTypes;
8852
8853 /// A flag indicating whether the nullptr type was present in the
8854 /// candidate set.
8855 bool HasNullPtrType;
8856
8857 /// Sema - The semantic analysis instance where we are building the
8858 /// candidate type set.
8859 Sema &SemaRef;
8860
8861 /// Context - The AST context in which we will build the type sets.
8862 ASTContext &Context;
8863
8864 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8865 const Qualifiers &VisibleQuals);
8866 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8867
8868public:
8869 /// iterator - Iterates through the types that are part of the set.
8870 typedef TypeSet::iterator iterator;
8871
8872 BuiltinCandidateTypeSet(Sema &SemaRef)
8873 : HasNonRecordTypes(false),
8874 HasArithmeticOrEnumeralTypes(false),
8875 HasNullPtrType(false),
8876 SemaRef(SemaRef),
8877 Context(SemaRef.Context) { }
8878
8879 void AddTypesConvertedFrom(QualType Ty,
8881 bool AllowUserConversions,
8882 bool AllowExplicitConversions,
8883 const Qualifiers &VisibleTypeConversionsQuals);
8884
8885 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8886 llvm::iterator_range<iterator> member_pointer_types() {
8887 return MemberPointerTypes;
8888 }
8889 llvm::iterator_range<iterator> enumeration_types() {
8890 return EnumerationTypes;
8891 }
8892 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8893 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8894 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8895
8896 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
8897 bool hasNonRecordTypes() { return HasNonRecordTypes; }
8898 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8899 bool hasNullPtrType() const { return HasNullPtrType; }
8900};
8901
8902} // end anonymous namespace
8903
8904/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8905/// the set of pointer types along with any more-qualified variants of
8906/// that type. For example, if @p Ty is "int const *", this routine
8907/// will add "int const *", "int const volatile *", "int const
8908/// restrict *", and "int const volatile restrict *" to the set of
8909/// pointer types. Returns true if the add of @p Ty itself succeeded,
8910/// false otherwise.
8911///
8912/// FIXME: what to do about extended qualifiers?
8913bool
8914BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8915 const Qualifiers &VisibleQuals) {
8916
8917 // Insert this type.
8918 if (!PointerTypes.insert(Ty))
8919 return false;
8920
8921 QualType PointeeTy;
8922 const PointerType *PointerTy = Ty->getAs<PointerType>();
8923 bool buildObjCPtr = false;
8924 if (!PointerTy) {
8926 PointeeTy = PTy->getPointeeType();
8927 buildObjCPtr = true;
8928 } else {
8929 PointeeTy = PointerTy->getPointeeType();
8930 }
8931
8932 // Don't add qualified variants of arrays. For one, they're not allowed
8933 // (the qualifier would sink to the element type), and for another, the
8934 // only overload situation where it matters is subscript or pointer +- int,
8935 // and those shouldn't have qualifier variants anyway.
8936 if (PointeeTy->isArrayType())
8937 return true;
8938
8939 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8940 bool hasVolatile = VisibleQuals.hasVolatile();
8941 bool hasRestrict = VisibleQuals.hasRestrict();
8942
8943 // Iterate through all strict supersets of BaseCVR.
8944 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8945 if ((CVR | BaseCVR) != CVR) continue;
8946 // Skip over volatile if no volatile found anywhere in the types.
8947 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8948
8949 // Skip over restrict if no restrict found anywhere in the types, or if
8950 // the type cannot be restrict-qualified.
8951 if ((CVR & Qualifiers::Restrict) &&
8952 (!hasRestrict ||
8953 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8954 continue;
8955
8956 // Build qualified pointee type.
8957 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8958
8959 // Build qualified pointer type.
8960 QualType QPointerTy;
8961 if (!buildObjCPtr)
8962 QPointerTy = Context.getPointerType(QPointeeTy);
8963 else
8964 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8965
8966 // Insert qualified pointer type.
8967 PointerTypes.insert(QPointerTy);
8968 }
8969
8970 return true;
8971}
8972
8973/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8974/// to the set of pointer types along with any more-qualified variants of
8975/// that type. For example, if @p Ty is "int const *", this routine
8976/// will add "int const *", "int const volatile *", "int const
8977/// restrict *", and "int const volatile restrict *" to the set of
8978/// pointer types. Returns true if the add of @p Ty itself succeeded,
8979/// false otherwise.
8980///
8981/// FIXME: what to do about extended qualifiers?
8982bool
8983BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8984 QualType Ty) {
8985 // Insert this type.
8986 if (!MemberPointerTypes.insert(Ty))
8987 return false;
8988
8989 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8990 assert(PointerTy && "type was not a member pointer type!");
8991
8992 QualType PointeeTy = PointerTy->getPointeeType();
8993 // Don't add qualified variants of arrays. For one, they're not allowed
8994 // (the qualifier would sink to the element type), and for another, the
8995 // only overload situation where it matters is subscript or pointer +- int,
8996 // and those shouldn't have qualifier variants anyway.
8997 if (PointeeTy->isArrayType())
8998 return true;
8999 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9000
9001 // Iterate through all strict supersets of the pointee type's CVR
9002 // qualifiers.
9003 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9004 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9005 if ((CVR | BaseCVR) != CVR) continue;
9006
9007 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9008 MemberPointerTypes.insert(Context.getMemberPointerType(
9009 QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9010 }
9011
9012 return true;
9013}
9014
9015/// AddTypesConvertedFrom - Add each of the types to which the type @p
9016/// Ty can be implicit converted to the given set of @p Types. We're
9017/// primarily interested in pointer types and enumeration types. We also
9018/// take member pointer types, for the conditional operator.
9019/// AllowUserConversions is true if we should look at the conversion
9020/// functions of a class type, and AllowExplicitConversions if we
9021/// should also include the explicit conversion functions of a class
9022/// type.
9023void
9024BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9025 SourceLocation Loc,
9026 bool AllowUserConversions,
9027 bool AllowExplicitConversions,
9028 const Qualifiers &VisibleQuals) {
9029 // Only deal with canonical types.
9030 Ty = Context.getCanonicalType(Ty);
9031
9032 // Look through reference types; they aren't part of the type of an
9033 // expression for the purposes of conversions.
9034 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9035 Ty = RefTy->getPointeeType();
9036
9037 // If we're dealing with an array type, decay to the pointer.
9038 if (Ty->isArrayType())
9039 Ty = SemaRef.Context.getArrayDecayedType(Ty);
9040
9041 // Otherwise, we don't care about qualifiers on the type.
9042 Ty = Ty.getLocalUnqualifiedType();
9043
9044 // Flag if we ever add a non-record type.
9045 bool TyIsRec = Ty->isRecordType();
9046 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9047
9048 // Flag if we encounter an arithmetic type.
9049 HasArithmeticOrEnumeralTypes =
9050 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9051
9052 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9053 PointerTypes.insert(Ty);
9054 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9055 // Insert our type, and its more-qualified variants, into the set
9056 // of types.
9057 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9058 return;
9059 } else if (Ty->isMemberPointerType()) {
9060 // Member pointers are far easier, since the pointee can't be converted.
9061 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9062 return;
9063 } else if (Ty->isEnumeralType()) {
9064 HasArithmeticOrEnumeralTypes = true;
9065 EnumerationTypes.insert(Ty);
9066 } else if (Ty->isBitIntType()) {
9067 HasArithmeticOrEnumeralTypes = true;
9068 BitIntTypes.insert(Ty);
9069 } else if (Ty->isVectorType()) {
9070 // We treat vector types as arithmetic types in many contexts as an
9071 // extension.
9072 HasArithmeticOrEnumeralTypes = true;
9073 VectorTypes.insert(Ty);
9074 } else if (Ty->isMatrixType()) {
9075 // Similar to vector types, we treat vector types as arithmetic types in
9076 // many contexts as an extension.
9077 HasArithmeticOrEnumeralTypes = true;
9078 MatrixTypes.insert(Ty);
9079 } else if (Ty->isNullPtrType()) {
9080 HasNullPtrType = true;
9081 } else if (AllowUserConversions && TyIsRec) {
9082 // No conversion functions in incomplete types.
9083 if (!SemaRef.isCompleteType(Loc, Ty))
9084 return;
9085
9086 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9087 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9088 if (isa<UsingShadowDecl>(D))
9089 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9090
9091 // Skip conversion function templates; they don't tell us anything
9092 // about which builtin types we can convert to.
9093 if (isa<FunctionTemplateDecl>(D))
9094 continue;
9095
9096 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
9097 if (AllowExplicitConversions || !Conv->isExplicit()) {
9098 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
9099 VisibleQuals);
9100 }
9101 }
9102 }
9103}
9104/// Helper function for adjusting address spaces for the pointer or reference
9105/// operands of builtin operators depending on the argument.
9107 Expr *Arg) {
9109}
9110
9111/// Helper function for AddBuiltinOperatorCandidates() that adds
9112/// the volatile- and non-volatile-qualified assignment operators for the
9113/// given type to the candidate set.
9115 QualType T,
9116 ArrayRef<Expr *> Args,
9117 OverloadCandidateSet &CandidateSet) {
9118 QualType ParamTypes[2];
9119
9120 // T& operator=(T&, T)
9121 ParamTypes[0] = S.Context.getLValueReferenceType(
9123 ParamTypes[1] = T;
9124 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9125 /*IsAssignmentOperator=*/true);
9126
9128 // volatile T& operator=(volatile T&, T)
9129 ParamTypes[0] = S.Context.getLValueReferenceType(
9131 Args[0]));
9132 ParamTypes[1] = T;
9133 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9134 /*IsAssignmentOperator=*/true);
9135 }
9136}
9137
9138/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9139/// if any, found in visible type conversion functions found in ArgExpr's type.
9140static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9141 Qualifiers VRQuals;
9142 CXXRecordDecl *ClassDecl;
9143 if (const MemberPointerType *RHSMPType =
9144 ArgExpr->getType()->getAs<MemberPointerType>())
9145 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9146 else
9147 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9148 if (!ClassDecl) {
9149 // Just to be safe, assume the worst case.
9150 VRQuals.addVolatile();
9151 VRQuals.addRestrict();
9152 return VRQuals;
9153 }
9154 if (!ClassDecl->hasDefinition())
9155 return VRQuals;
9156
9157 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9158 if (isa<UsingShadowDecl>(D))
9159 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9160 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
9161 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
9162 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9163 CanTy = ResTypeRef->getPointeeType();
9164 // Need to go down the pointer/mempointer chain and add qualifiers
9165 // as see them.
9166 bool done = false;
9167 while (!done) {
9168 if (CanTy.isRestrictQualified())
9169 VRQuals.addRestrict();
9170 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9171 CanTy = ResTypePtr->getPointeeType();
9172 else if (const MemberPointerType *ResTypeMPtr =
9173 CanTy->getAs<MemberPointerType>())
9174 CanTy = ResTypeMPtr->getPointeeType();
9175 else
9176 done = true;
9177 if (CanTy.isVolatileQualified())
9178 VRQuals.addVolatile();
9179 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9180 return VRQuals;
9181 }
9182 }
9183 }
9184 return VRQuals;
9185}
9186
9187// Note: We're currently only handling qualifiers that are meaningful for the
9188// LHS of compound assignment overloading.
9190 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9191 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9192 // _Atomic
9193 if (Available.hasAtomic()) {
9194 Available.removeAtomic();
9195 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
9196 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9197 return;
9198 }
9199
9200 // volatile
9201 if (Available.hasVolatile()) {
9202 Available.removeVolatile();
9203 assert(!Applied.hasVolatile());
9204 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
9205 Callback);
9206 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9207 return;
9208 }
9209
9210 Callback(Applied);
9211}
9212
9214 QualifiersAndAtomic Quals,
9215 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9217 Callback);
9218}
9219
9221 QualifiersAndAtomic Quals,
9222 Sema &S) {
9223 if (Quals.hasAtomic())
9225 if (Quals.hasVolatile())
9228}
9229
9230namespace {
9231
9232/// Helper class to manage the addition of builtin operator overload
9233/// candidates. It provides shared state and utility methods used throughout
9234/// the process, as well as a helper method to add each group of builtin
9235/// operator overloads from the standard to a candidate set.
9236class BuiltinOperatorOverloadBuilder {
9237 // Common instance state available to all overload candidate addition methods.
9238 Sema &S;
9239 ArrayRef<Expr *> Args;
9240 QualifiersAndAtomic VisibleTypeConversionsQuals;
9241 bool HasArithmeticOrEnumeralCandidateType;
9243 OverloadCandidateSet &CandidateSet;
9244
9245 static constexpr int ArithmeticTypesCap = 26;
9247
9248 // Define some indices used to iterate over the arithmetic types in
9249 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9250 // types are that preserved by promotion (C++ [over.built]p2).
9251 unsigned FirstIntegralType,
9252 LastIntegralType;
9253 unsigned FirstPromotedIntegralType,
9254 LastPromotedIntegralType;
9255 unsigned FirstPromotedArithmeticType,
9256 LastPromotedArithmeticType;
9257 unsigned NumArithmeticTypes;
9258
9259 void InitArithmeticTypes() {
9260 // Start of promoted types.
9261 FirstPromotedArithmeticType = 0;
9262 ArithmeticTypes.push_back(S.Context.FloatTy);
9263 ArithmeticTypes.push_back(S.Context.DoubleTy);
9264 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
9266 ArithmeticTypes.push_back(S.Context.Float128Ty);
9268 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
9269
9270 // Start of integral types.
9271 FirstIntegralType = ArithmeticTypes.size();
9272 FirstPromotedIntegralType = ArithmeticTypes.size();
9273 ArithmeticTypes.push_back(S.Context.IntTy);
9274 ArithmeticTypes.push_back(S.Context.LongTy);
9275 ArithmeticTypes.push_back(S.Context.LongLongTy);
9279 ArithmeticTypes.push_back(S.Context.Int128Ty);
9280 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
9281 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
9282 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
9286 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
9287
9288 /// We add candidates for the unique, unqualified _BitInt types present in
9289 /// the candidate type set. The candidate set already handled ensuring the
9290 /// type is unqualified and canonical, but because we're adding from N
9291 /// different sets, we need to do some extra work to unique things. Insert
9292 /// the candidates into a unique set, then move from that set into the list
9293 /// of arithmetic types.
9294 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9295 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9296 for (QualType BitTy : Candidate.bitint_types())
9297 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
9298 }
9299 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
9300 LastPromotedIntegralType = ArithmeticTypes.size();
9301 LastPromotedArithmeticType = ArithmeticTypes.size();
9302 // End of promoted types.
9303
9304 ArithmeticTypes.push_back(S.Context.BoolTy);
9305 ArithmeticTypes.push_back(S.Context.CharTy);
9306 ArithmeticTypes.push_back(S.Context.WCharTy);
9307 if (S.Context.getLangOpts().Char8)
9308 ArithmeticTypes.push_back(S.Context.Char8Ty);
9309 ArithmeticTypes.push_back(S.Context.Char16Ty);
9310 ArithmeticTypes.push_back(S.Context.Char32Ty);
9311 ArithmeticTypes.push_back(S.Context.SignedCharTy);
9312 ArithmeticTypes.push_back(S.Context.ShortTy);
9313 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9314 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9315 LastIntegralType = ArithmeticTypes.size();
9316 NumArithmeticTypes = ArithmeticTypes.size();
9317 // End of integral types.
9318 // FIXME: What about complex? What about half?
9319
9320 // We don't know for sure how many bit-precise candidates were involved, so
9321 // we subtract those from the total when testing whether we're under the
9322 // cap or not.
9323 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9324 ArithmeticTypesCap &&
9325 "Enough inline storage for all arithmetic types.");
9326 }
9327
9328 /// Helper method to factor out the common pattern of adding overloads
9329 /// for '++' and '--' builtin operators.
9330 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9331 bool HasVolatile,
9332 bool HasRestrict) {
9333 QualType ParamTypes[2] = {
9334 S.Context.getLValueReferenceType(CandidateTy),
9335 S.Context.IntTy
9336 };
9337
9338 // Non-volatile version.
9339 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9340
9341 // Use a heuristic to reduce number of builtin candidates in the set:
9342 // add volatile version only if there are conversions to a volatile type.
9343 if (HasVolatile) {
9344 ParamTypes[0] =
9346 S.Context.getVolatileType(CandidateTy));
9347 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9348 }
9349
9350 // Add restrict version only if there are conversions to a restrict type
9351 // and our candidate type is a non-restrict-qualified pointer.
9352 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9353 !CandidateTy.isRestrictQualified()) {
9354 ParamTypes[0]
9357 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9358
9359 if (HasVolatile) {
9360 ParamTypes[0]
9362 S.Context.getCVRQualifiedType(CandidateTy,
9365 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9366 }
9367 }
9368
9369 }
9370
9371 /// Helper to add an overload candidate for a binary builtin with types \p L
9372 /// and \p R.
9373 void AddCandidate(QualType L, QualType R) {
9374 QualType LandR[2] = {L, R};
9375 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9376 }
9377
9378public:
9379 BuiltinOperatorOverloadBuilder(
9380 Sema &S, ArrayRef<Expr *> Args,
9381 QualifiersAndAtomic VisibleTypeConversionsQuals,
9382 bool HasArithmeticOrEnumeralCandidateType,
9384 OverloadCandidateSet &CandidateSet)
9385 : S(S), Args(Args),
9386 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9387 HasArithmeticOrEnumeralCandidateType(
9388 HasArithmeticOrEnumeralCandidateType),
9389 CandidateTypes(CandidateTypes),
9390 CandidateSet(CandidateSet) {
9391
9392 InitArithmeticTypes();
9393 }
9394
9395 // Increment is deprecated for bool since C++17.
9396 //
9397 // C++ [over.built]p3:
9398 //
9399 // For every pair (T, VQ), where T is an arithmetic type other
9400 // than bool, and VQ is either volatile or empty, there exist
9401 // candidate operator functions of the form
9402 //
9403 // VQ T& operator++(VQ T&);
9404 // T operator++(VQ T&, int);
9405 //
9406 // C++ [over.built]p4:
9407 //
9408 // For every pair (T, VQ), where T is an arithmetic type other
9409 // than bool, and VQ is either volatile or empty, there exist
9410 // candidate operator functions of the form
9411 //
9412 // VQ T& operator--(VQ T&);
9413 // T operator--(VQ T&, int);
9414 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9415 if (!HasArithmeticOrEnumeralCandidateType)
9416 return;
9417
9418 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9419 const auto TypeOfT = ArithmeticTypes[Arith];
9420 if (TypeOfT == S.Context.BoolTy) {
9421 if (Op == OO_MinusMinus)
9422 continue;
9423 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9424 continue;
9425 }
9426 addPlusPlusMinusMinusStyleOverloads(
9427 TypeOfT,
9428 VisibleTypeConversionsQuals.hasVolatile(),
9429 VisibleTypeConversionsQuals.hasRestrict());
9430 }
9431 }
9432
9433 // C++ [over.built]p5:
9434 //
9435 // For every pair (T, VQ), where T is a cv-qualified or
9436 // cv-unqualified object type, and VQ is either volatile or
9437 // empty, there exist candidate operator functions of the form
9438 //
9439 // T*VQ& operator++(T*VQ&);
9440 // T*VQ& operator--(T*VQ&);
9441 // T* operator++(T*VQ&, int);
9442 // T* operator--(T*VQ&, int);
9443 void addPlusPlusMinusMinusPointerOverloads() {
9444 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9445 // Skip pointer types that aren't pointers to object types.
9446 if (!PtrTy->getPointeeType()->isObjectType())
9447 continue;
9448
9449 addPlusPlusMinusMinusStyleOverloads(
9450 PtrTy,
9451 (!PtrTy.isVolatileQualified() &&
9452 VisibleTypeConversionsQuals.hasVolatile()),
9453 (!PtrTy.isRestrictQualified() &&
9454 VisibleTypeConversionsQuals.hasRestrict()));
9455 }
9456 }
9457
9458 // C++ [over.built]p6:
9459 // For every cv-qualified or cv-unqualified object type T, there
9460 // exist candidate operator functions of the form
9461 //
9462 // T& operator*(T*);
9463 //
9464 // C++ [over.built]p7:
9465 // For every function type T that does not have cv-qualifiers or a
9466 // ref-qualifier, there exist candidate operator functions of the form
9467 // T& operator*(T*);
9468 void addUnaryStarPointerOverloads() {
9469 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9470 QualType PointeeTy = ParamTy->getPointeeType();
9471 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9472 continue;
9473
9474 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9475 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9476 continue;
9477
9478 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9479 }
9480 }
9481
9482 // C++ [over.built]p9:
9483 // For every promoted arithmetic type T, there exist candidate
9484 // operator functions of the form
9485 //
9486 // T operator+(T);
9487 // T operator-(T);
9488 void addUnaryPlusOrMinusArithmeticOverloads() {
9489 if (!HasArithmeticOrEnumeralCandidateType)
9490 return;
9491
9492 for (unsigned Arith = FirstPromotedArithmeticType;
9493 Arith < LastPromotedArithmeticType; ++Arith) {
9494 QualType ArithTy = ArithmeticTypes[Arith];
9495 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9496 }
9497
9498 // Extension: We also add these operators for vector types.
9499 for (QualType VecTy : CandidateTypes[0].vector_types())
9500 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9501 }
9502
9503 // C++ [over.built]p8:
9504 // For every type T, there exist candidate operator functions of
9505 // the form
9506 //
9507 // T* operator+(T*);
9508 void addUnaryPlusPointerOverloads() {
9509 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9510 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9511 }
9512
9513 // C++ [over.built]p10:
9514 // For every promoted integral type T, there exist candidate
9515 // operator functions of the form
9516 //
9517 // T operator~(T);
9518 void addUnaryTildePromotedIntegralOverloads() {
9519 if (!HasArithmeticOrEnumeralCandidateType)
9520 return;
9521
9522 for (unsigned Int = FirstPromotedIntegralType;
9523 Int < LastPromotedIntegralType; ++Int) {
9524 QualType IntTy = ArithmeticTypes[Int];
9525 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9526 }
9527
9528 // Extension: We also add this operator for vector types.
9529 for (QualType VecTy : CandidateTypes[0].vector_types())
9530 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9531 }
9532
9533 // C++ [over.match.oper]p16:
9534 // For every pointer to member type T or type std::nullptr_t, there
9535 // exist candidate operator functions of the form
9536 //
9537 // bool operator==(T,T);
9538 // bool operator!=(T,T);
9539 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9540 /// Set of (canonical) types that we've already handled.
9542
9543 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9544 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9545 // Don't add the same builtin candidate twice.
9546 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9547 continue;
9548
9549 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9550 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9551 }
9552
9553 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9555 if (AddedTypes.insert(NullPtrTy).second) {
9556 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9557 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9558 }
9559 }
9560 }
9561 }
9562
9563 // C++ [over.built]p15:
9564 //
9565 // For every T, where T is an enumeration type or a pointer type,
9566 // there exist candidate operator functions of the form
9567 //
9568 // bool operator<(T, T);
9569 // bool operator>(T, T);
9570 // bool operator<=(T, T);
9571 // bool operator>=(T, T);
9572 // bool operator==(T, T);
9573 // bool operator!=(T, T);
9574 // R operator<=>(T, T)
9575 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9576 // C++ [over.match.oper]p3:
9577 // [...]the built-in candidates include all of the candidate operator
9578 // functions defined in 13.6 that, compared to the given operator, [...]
9579 // do not have the same parameter-type-list as any non-template non-member
9580 // candidate.
9581 //
9582 // Note that in practice, this only affects enumeration types because there
9583 // aren't any built-in candidates of record type, and a user-defined operator
9584 // must have an operand of record or enumeration type. Also, the only other
9585 // overloaded operator with enumeration arguments, operator=,
9586 // cannot be overloaded for enumeration types, so this is the only place
9587 // where we must suppress candidates like this.
9588 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9589 UserDefinedBinaryOperators;
9590
9591 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9592 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9593 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9594 CEnd = CandidateSet.end();
9595 C != CEnd; ++C) {
9596 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9597 continue;
9598
9599 if (C->Function->isFunctionTemplateSpecialization())
9600 continue;
9601
9602 // We interpret "same parameter-type-list" as applying to the
9603 // "synthesized candidate, with the order of the two parameters
9604 // reversed", not to the original function.
9605 bool Reversed = C->isReversed();
9606 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9607 ->getType()
9608 .getUnqualifiedType();
9609 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9610 ->getType()
9611 .getUnqualifiedType();
9612
9613 // Skip if either parameter isn't of enumeral type.
9614 if (!FirstParamType->isEnumeralType() ||
9615 !SecondParamType->isEnumeralType())
9616 continue;
9617
9618 // Add this operator to the set of known user-defined operators.
9619 UserDefinedBinaryOperators.insert(
9620 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9621 S.Context.getCanonicalType(SecondParamType)));
9622 }
9623 }
9624 }
9625
9626 /// Set of (canonical) types that we've already handled.
9628
9629 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9630 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9631 // Don't add the same builtin candidate twice.
9632 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9633 continue;
9634 if (IsSpaceship && PtrTy->isFunctionPointerType())
9635 continue;
9636
9637 QualType ParamTypes[2] = {PtrTy, PtrTy};
9638 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9639 }
9640 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9641 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9642
9643 // Don't add the same builtin candidate twice, or if a user defined
9644 // candidate exists.
9645 if (!AddedTypes.insert(CanonType).second ||
9646 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9647 CanonType)))
9648 continue;
9649 QualType ParamTypes[2] = {EnumTy, EnumTy};
9650 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9651 }
9652 }
9653 }
9654
9655 // C++ [over.built]p13:
9656 //
9657 // For every cv-qualified or cv-unqualified object type T
9658 // there exist candidate operator functions of the form
9659 //
9660 // T* operator+(T*, ptrdiff_t);
9661 // T& operator[](T*, ptrdiff_t); [BELOW]
9662 // T* operator-(T*, ptrdiff_t);
9663 // T* operator+(ptrdiff_t, T*);
9664 // T& operator[](ptrdiff_t, T*); [BELOW]
9665 //
9666 // C++ [over.built]p14:
9667 //
9668 // For every T, where T is a pointer to object type, there
9669 // exist candidate operator functions of the form
9670 //
9671 // ptrdiff_t operator-(T, T);
9672 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9673 /// Set of (canonical) types that we've already handled.
9675
9676 for (int Arg = 0; Arg < 2; ++Arg) {
9677 QualType AsymmetricParamTypes[2] = {
9680 };
9681 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9682 QualType PointeeTy = PtrTy->getPointeeType();
9683 if (!PointeeTy->isObjectType())
9684 continue;
9685
9686 AsymmetricParamTypes[Arg] = PtrTy;
9687 if (Arg == 0 || Op == OO_Plus) {
9688 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9689 // T* operator+(ptrdiff_t, T*);
9690 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9691 }
9692 if (Op == OO_Minus) {
9693 // ptrdiff_t operator-(T, T);
9694 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9695 continue;
9696
9697 QualType ParamTypes[2] = {PtrTy, PtrTy};
9698 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9699 }
9700 }
9701 }
9702 }
9703
9704 // C++ [over.built]p12:
9705 //
9706 // For every pair of promoted arithmetic types L and R, there
9707 // exist candidate operator functions of the form
9708 //
9709 // LR operator*(L, R);
9710 // LR operator/(L, R);
9711 // LR operator+(L, R);
9712 // LR operator-(L, R);
9713 // bool operator<(L, R);
9714 // bool operator>(L, R);
9715 // bool operator<=(L, R);
9716 // bool operator>=(L, R);
9717 // bool operator==(L, R);
9718 // bool operator!=(L, R);
9719 //
9720 // where LR is the result of the usual arithmetic conversions
9721 // between types L and R.
9722 //
9723 // C++ [over.built]p24:
9724 //
9725 // For every pair of promoted arithmetic types L and R, there exist
9726 // candidate operator functions of the form
9727 //
9728 // LR operator?(bool, L, R);
9729 //
9730 // where LR is the result of the usual arithmetic conversions
9731 // between types L and R.
9732 // Our candidates ignore the first parameter.
9733 void addGenericBinaryArithmeticOverloads() {
9734 if (!HasArithmeticOrEnumeralCandidateType)
9735 return;
9736
9737 for (unsigned Left = FirstPromotedArithmeticType;
9738 Left < LastPromotedArithmeticType; ++Left) {
9739 for (unsigned Right = FirstPromotedArithmeticType;
9740 Right < LastPromotedArithmeticType; ++Right) {
9741 QualType LandR[2] = { ArithmeticTypes[Left],
9742 ArithmeticTypes[Right] };
9743 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9744 }
9745 }
9746
9747 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9748 // conditional operator for vector types.
9749 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9750 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9751 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9752 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9753 }
9754 }
9755
9756 /// Add binary operator overloads for each candidate matrix type M1, M2:
9757 /// * (M1, M1) -> M1
9758 /// * (M1, M1.getElementType()) -> M1
9759 /// * (M2.getElementType(), M2) -> M2
9760 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9761 void addMatrixBinaryArithmeticOverloads() {
9762 if (!HasArithmeticOrEnumeralCandidateType)
9763 return;
9764
9765 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9766 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9767 AddCandidate(M1, M1);
9768 }
9769
9770 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9771 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9772 if (!CandidateTypes[0].containsMatrixType(M2))
9773 AddCandidate(M2, M2);
9774 }
9775 }
9776
9777 // C++2a [over.built]p14:
9778 //
9779 // For every integral type T there exists a candidate operator function
9780 // of the form
9781 //
9782 // std::strong_ordering operator<=>(T, T)
9783 //
9784 // C++2a [over.built]p15:
9785 //
9786 // For every pair of floating-point types L and R, there exists a candidate
9787 // operator function of the form
9788 //
9789 // std::partial_ordering operator<=>(L, R);
9790 //
9791 // FIXME: The current specification for integral types doesn't play nice with
9792 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9793 // comparisons. Under the current spec this can lead to ambiguity during
9794 // overload resolution. For example:
9795 //
9796 // enum A : int {a};
9797 // auto x = (a <=> (long)42);
9798 //
9799 // error: call is ambiguous for arguments 'A' and 'long'.
9800 // note: candidate operator<=>(int, int)
9801 // note: candidate operator<=>(long, long)
9802 //
9803 // To avoid this error, this function deviates from the specification and adds
9804 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9805 // arithmetic types (the same as the generic relational overloads).
9806 //
9807 // For now this function acts as a placeholder.
9808 void addThreeWayArithmeticOverloads() {
9809 addGenericBinaryArithmeticOverloads();
9810 }
9811
9812 // C++ [over.built]p17:
9813 //
9814 // For every pair of promoted integral types L and R, there
9815 // exist candidate operator functions of the form
9816 //
9817 // LR operator%(L, R);
9818 // LR operator&(L, R);
9819 // LR operator^(L, R);
9820 // LR operator|(L, R);
9821 // L operator<<(L, R);
9822 // L operator>>(L, R);
9823 //
9824 // where LR is the result of the usual arithmetic conversions
9825 // between types L and R.
9826 void addBinaryBitwiseArithmeticOverloads() {
9827 if (!HasArithmeticOrEnumeralCandidateType)
9828 return;
9829
9830 for (unsigned Left = FirstPromotedIntegralType;
9831 Left < LastPromotedIntegralType; ++Left) {
9832 for (unsigned Right = FirstPromotedIntegralType;
9833 Right < LastPromotedIntegralType; ++Right) {
9834 QualType LandR[2] = { ArithmeticTypes[Left],
9835 ArithmeticTypes[Right] };
9836 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9837 }
9838 }
9839 }
9840
9841 // C++ [over.built]p20:
9842 //
9843 // For every pair (T, VQ), where T is an enumeration or
9844 // pointer to member type and VQ is either volatile or
9845 // empty, there exist candidate operator functions of the form
9846 //
9847 // VQ T& operator=(VQ T&, T);
9848 void addAssignmentMemberPointerOrEnumeralOverloads() {
9849 /// Set of (canonical) types that we've already handled.
9851
9852 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9853 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9854 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9855 continue;
9856
9857 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9858 }
9859
9860 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9861 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9862 continue;
9863
9864 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9865 }
9866 }
9867 }
9868
9869 // C++ [over.built]p19:
9870 //
9871 // For every pair (T, VQ), where T is any type and VQ is either
9872 // volatile or empty, there exist candidate operator functions
9873 // of the form
9874 //
9875 // T*VQ& operator=(T*VQ&, T*);
9876 //
9877 // C++ [over.built]p21:
9878 //
9879 // For every pair (T, VQ), where T is a cv-qualified or
9880 // cv-unqualified object type and VQ is either volatile or
9881 // empty, there exist candidate operator functions of the form
9882 //
9883 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9884 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9885 void addAssignmentPointerOverloads(bool isEqualOp) {
9886 /// Set of (canonical) types that we've already handled.
9888
9889 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9890 // If this is operator=, keep track of the builtin candidates we added.
9891 if (isEqualOp)
9892 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9893 else if (!PtrTy->getPointeeType()->isObjectType())
9894 continue;
9895
9896 // non-volatile version
9897 QualType ParamTypes[2] = {
9899 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9900 };
9901 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9902 /*IsAssignmentOperator=*/ isEqualOp);
9903
9904 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9905 VisibleTypeConversionsQuals.hasVolatile();
9906 if (NeedVolatile) {
9907 // volatile version
9908 ParamTypes[0] =
9910 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9911 /*IsAssignmentOperator=*/isEqualOp);
9912 }
9913
9914 if (!PtrTy.isRestrictQualified() &&
9915 VisibleTypeConversionsQuals.hasRestrict()) {
9916 // restrict version
9917 ParamTypes[0] =
9919 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9920 /*IsAssignmentOperator=*/isEqualOp);
9921
9922 if (NeedVolatile) {
9923 // volatile restrict version
9924 ParamTypes[0] =
9927 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9928 /*IsAssignmentOperator=*/isEqualOp);
9929 }
9930 }
9931 }
9932
9933 if (isEqualOp) {
9934 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9935 // Make sure we don't add the same candidate twice.
9936 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9937 continue;
9938
9939 QualType ParamTypes[2] = {
9941 PtrTy,
9942 };
9943
9944 // non-volatile version
9945 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9946 /*IsAssignmentOperator=*/true);
9947
9948 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9949 VisibleTypeConversionsQuals.hasVolatile();
9950 if (NeedVolatile) {
9951 // volatile version
9952 ParamTypes[0] = S.Context.getLValueReferenceType(
9953 S.Context.getVolatileType(PtrTy));
9954 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9955 /*IsAssignmentOperator=*/true);
9956 }
9957
9958 if (!PtrTy.isRestrictQualified() &&
9959 VisibleTypeConversionsQuals.hasRestrict()) {
9960 // restrict version
9961 ParamTypes[0] = S.Context.getLValueReferenceType(
9962 S.Context.getRestrictType(PtrTy));
9963 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9964 /*IsAssignmentOperator=*/true);
9965
9966 if (NeedVolatile) {
9967 // volatile restrict version
9968 ParamTypes[0] =
9971 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9972 /*IsAssignmentOperator=*/true);
9973 }
9974 }
9975 }
9976 }
9977 }
9978
9979 // C++ [over.built]p18:
9980 //
9981 // For every triple (L, VQ, R), where L is an arithmetic type,
9982 // VQ is either volatile or empty, and R is a promoted
9983 // arithmetic type, there exist candidate operator functions of
9984 // the form
9985 //
9986 // VQ L& operator=(VQ L&, R);
9987 // VQ L& operator*=(VQ L&, R);
9988 // VQ L& operator/=(VQ L&, R);
9989 // VQ L& operator+=(VQ L&, R);
9990 // VQ L& operator-=(VQ L&, R);
9991 void addAssignmentArithmeticOverloads(bool isEqualOp) {
9992 if (!HasArithmeticOrEnumeralCandidateType)
9993 return;
9994
9995 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9996 for (unsigned Right = FirstPromotedArithmeticType;
9997 Right < LastPromotedArithmeticType; ++Right) {
9998 QualType ParamTypes[2];
9999 ParamTypes[1] = ArithmeticTypes[Right];
10001 S, ArithmeticTypes[Left], Args[0]);
10002
10004 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10005 ParamTypes[0] =
10006 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10007 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10008 /*IsAssignmentOperator=*/isEqualOp);
10009 });
10010 }
10011 }
10012
10013 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10014 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10015 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10016 QualType ParamTypes[2];
10017 ParamTypes[1] = Vec2Ty;
10018 // Add this built-in operator as a candidate (VQ is empty).
10019 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
10020 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10021 /*IsAssignmentOperator=*/isEqualOp);
10022
10023 // Add this built-in operator as a candidate (VQ is 'volatile').
10024 if (VisibleTypeConversionsQuals.hasVolatile()) {
10025 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
10026 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
10027 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10028 /*IsAssignmentOperator=*/isEqualOp);
10029 }
10030 }
10031 }
10032
10033 // C++ [over.built]p22:
10034 //
10035 // For every triple (L, VQ, R), where L is an integral type, VQ
10036 // is either volatile or empty, and R is a promoted integral
10037 // type, there exist candidate operator functions of the form
10038 //
10039 // VQ L& operator%=(VQ L&, R);
10040 // VQ L& operator<<=(VQ L&, R);
10041 // VQ L& operator>>=(VQ L&, R);
10042 // VQ L& operator&=(VQ L&, R);
10043 // VQ L& operator^=(VQ L&, R);
10044 // VQ L& operator|=(VQ L&, R);
10045 void addAssignmentIntegralOverloads() {
10046 if (!HasArithmeticOrEnumeralCandidateType)
10047 return;
10048
10049 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10050 for (unsigned Right = FirstPromotedIntegralType;
10051 Right < LastPromotedIntegralType; ++Right) {
10052 QualType ParamTypes[2];
10053 ParamTypes[1] = ArithmeticTypes[Right];
10055 S, ArithmeticTypes[Left], Args[0]);
10056
10058 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10059 ParamTypes[0] =
10060 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10061 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10062 });
10063 }
10064 }
10065 }
10066
10067 // C++ [over.operator]p23:
10068 //
10069 // There also exist candidate operator functions of the form
10070 //
10071 // bool operator!(bool);
10072 // bool operator&&(bool, bool);
10073 // bool operator||(bool, bool);
10074 void addExclaimOverload() {
10075 QualType ParamTy = S.Context.BoolTy;
10076 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
10077 /*IsAssignmentOperator=*/false,
10078 /*NumContextualBoolArguments=*/1);
10079 }
10080 void addAmpAmpOrPipePipeOverload() {
10081 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10082 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10083 /*IsAssignmentOperator=*/false,
10084 /*NumContextualBoolArguments=*/2);
10085 }
10086
10087 // C++ [over.built]p13:
10088 //
10089 // For every cv-qualified or cv-unqualified object type T there
10090 // exist candidate operator functions of the form
10091 //
10092 // T* operator+(T*, ptrdiff_t); [ABOVE]
10093 // T& operator[](T*, ptrdiff_t);
10094 // T* operator-(T*, ptrdiff_t); [ABOVE]
10095 // T* operator+(ptrdiff_t, T*); [ABOVE]
10096 // T& operator[](ptrdiff_t, T*);
10097 void addSubscriptOverloads() {
10098 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10099 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10100 QualType PointeeType = PtrTy->getPointeeType();
10101 if (!PointeeType->isObjectType())
10102 continue;
10103
10104 // T& operator[](T*, ptrdiff_t)
10105 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10106 }
10107
10108 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10109 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10110 QualType PointeeType = PtrTy->getPointeeType();
10111 if (!PointeeType->isObjectType())
10112 continue;
10113
10114 // T& operator[](ptrdiff_t, T*)
10115 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10116 }
10117 }
10118
10119 // C++ [over.built]p11:
10120 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10121 // C1 is the same type as C2 or is a derived class of C2, T is an object
10122 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10123 // there exist candidate operator functions of the form
10124 //
10125 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10126 //
10127 // where CV12 is the union of CV1 and CV2.
10128 void addArrowStarOverloads() {
10129 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10130 QualType C1Ty = PtrTy;
10131 QualType C1;
10133 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
10134 if (!isa<RecordType>(C1))
10135 continue;
10136 // heuristic to reduce number of builtin candidates in the set.
10137 // Add volatile/restrict version only if there are conversions to a
10138 // volatile/restrict type.
10139 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10140 continue;
10141 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10142 continue;
10143 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10144 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
10146 *D2 = mptr->getMostRecentCXXRecordDecl();
10147 if (!declaresSameEntity(D1, D2) &&
10148 !S.IsDerivedFrom(CandidateSet.getLocation(), D1, D2))
10149 break;
10150 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10151 // build CV12 T&
10152 QualType T = mptr->getPointeeType();
10153 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10154 T.isVolatileQualified())
10155 continue;
10156 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10157 T.isRestrictQualified())
10158 continue;
10159 T = Q1.apply(S.Context, T);
10160 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10161 }
10162 }
10163 }
10164
10165 // Note that we don't consider the first argument, since it has been
10166 // contextually converted to bool long ago. The candidates below are
10167 // therefore added as binary.
10168 //
10169 // C++ [over.built]p25:
10170 // For every type T, where T is a pointer, pointer-to-member, or scoped
10171 // enumeration type, there exist candidate operator functions of the form
10172 //
10173 // T operator?(bool, T, T);
10174 //
10175 void addConditionalOperatorOverloads() {
10176 /// Set of (canonical) types that we've already handled.
10178
10179 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10180 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10181 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10182 continue;
10183
10184 QualType ParamTypes[2] = {PtrTy, PtrTy};
10185 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10186 }
10187
10188 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10189 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10190 continue;
10191
10192 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10193 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10194 }
10195
10196 if (S.getLangOpts().CPlusPlus11) {
10197 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10198 if (!EnumTy->castAsCanonical<EnumType>()
10199 ->getOriginalDecl()
10200 ->isScoped())
10201 continue;
10202
10203 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10204 continue;
10205
10206 QualType ParamTypes[2] = {EnumTy, EnumTy};
10207 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10208 }
10209 }
10210 }
10211 }
10212};
10213
10214} // end anonymous namespace
10215
10217 SourceLocation OpLoc,
10218 ArrayRef<Expr *> Args,
10219 OverloadCandidateSet &CandidateSet) {
10220 // Find all of the types that the arguments can convert to, but only
10221 // if the operator we're looking at has built-in operator candidates
10222 // that make use of these types. Also record whether we encounter non-record
10223 // candidate types or either arithmetic or enumeral candidate types.
10224 QualifiersAndAtomic VisibleTypeConversionsQuals;
10225 VisibleTypeConversionsQuals.addConst();
10226 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10227 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
10228 if (Args[ArgIdx]->getType()->isAtomicType())
10229 VisibleTypeConversionsQuals.addAtomic();
10230 }
10231
10232 bool HasNonRecordCandidateType = false;
10233 bool HasArithmeticOrEnumeralCandidateType = false;
10235 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10236 CandidateTypes.emplace_back(*this);
10237 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
10238 OpLoc,
10239 true,
10240 (Op == OO_Exclaim ||
10241 Op == OO_AmpAmp ||
10242 Op == OO_PipePipe),
10243 VisibleTypeConversionsQuals);
10244 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10245 CandidateTypes[ArgIdx].hasNonRecordTypes();
10246 HasArithmeticOrEnumeralCandidateType =
10247 HasArithmeticOrEnumeralCandidateType ||
10248 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10249 }
10250
10251 // Exit early when no non-record types have been added to the candidate set
10252 // for any of the arguments to the operator.
10253 //
10254 // We can't exit early for !, ||, or &&, since there we have always have
10255 // 'bool' overloads.
10256 if (!HasNonRecordCandidateType &&
10257 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10258 return;
10259
10260 // Setup an object to manage the common state for building overloads.
10261 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10262 VisibleTypeConversionsQuals,
10263 HasArithmeticOrEnumeralCandidateType,
10264 CandidateTypes, CandidateSet);
10265
10266 // Dispatch over the operation to add in only those overloads which apply.
10267 switch (Op) {
10268 case OO_None:
10270 llvm_unreachable("Expected an overloaded operator");
10271
10272 case OO_New:
10273 case OO_Delete:
10274 case OO_Array_New:
10275 case OO_Array_Delete:
10276 case OO_Call:
10277 llvm_unreachable(
10278 "Special operators don't use AddBuiltinOperatorCandidates");
10279
10280 case OO_Comma:
10281 case OO_Arrow:
10282 case OO_Coawait:
10283 // C++ [over.match.oper]p3:
10284 // -- For the operator ',', the unary operator '&', the
10285 // operator '->', or the operator 'co_await', the
10286 // built-in candidates set is empty.
10287 break;
10288
10289 case OO_Plus: // '+' is either unary or binary
10290 if (Args.size() == 1)
10291 OpBuilder.addUnaryPlusPointerOverloads();
10292 [[fallthrough]];
10293
10294 case OO_Minus: // '-' is either unary or binary
10295 if (Args.size() == 1) {
10296 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10297 } else {
10298 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10299 OpBuilder.addGenericBinaryArithmeticOverloads();
10300 OpBuilder.addMatrixBinaryArithmeticOverloads();
10301 }
10302 break;
10303
10304 case OO_Star: // '*' is either unary or binary
10305 if (Args.size() == 1)
10306 OpBuilder.addUnaryStarPointerOverloads();
10307 else {
10308 OpBuilder.addGenericBinaryArithmeticOverloads();
10309 OpBuilder.addMatrixBinaryArithmeticOverloads();
10310 }
10311 break;
10312
10313 case OO_Slash:
10314 OpBuilder.addGenericBinaryArithmeticOverloads();
10315 break;
10316
10317 case OO_PlusPlus:
10318 case OO_MinusMinus:
10319 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10320 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10321 break;
10322
10323 case OO_EqualEqual:
10324 case OO_ExclaimEqual:
10325 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10326 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10327 OpBuilder.addGenericBinaryArithmeticOverloads();
10328 break;
10329
10330 case OO_Less:
10331 case OO_Greater:
10332 case OO_LessEqual:
10333 case OO_GreaterEqual:
10334 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10335 OpBuilder.addGenericBinaryArithmeticOverloads();
10336 break;
10337
10338 case OO_Spaceship:
10339 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10340 OpBuilder.addThreeWayArithmeticOverloads();
10341 break;
10342
10343 case OO_Percent:
10344 case OO_Caret:
10345 case OO_Pipe:
10346 case OO_LessLess:
10347 case OO_GreaterGreater:
10348 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10349 break;
10350
10351 case OO_Amp: // '&' is either unary or binary
10352 if (Args.size() == 1)
10353 // C++ [over.match.oper]p3:
10354 // -- For the operator ',', the unary operator '&', or the
10355 // operator '->', the built-in candidates set is empty.
10356 break;
10357
10358 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10359 break;
10360
10361 case OO_Tilde:
10362 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10363 break;
10364
10365 case OO_Equal:
10366 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10367 [[fallthrough]];
10368
10369 case OO_PlusEqual:
10370 case OO_MinusEqual:
10371 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10372 [[fallthrough]];
10373
10374 case OO_StarEqual:
10375 case OO_SlashEqual:
10376 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10377 break;
10378
10379 case OO_PercentEqual:
10380 case OO_LessLessEqual:
10381 case OO_GreaterGreaterEqual:
10382 case OO_AmpEqual:
10383 case OO_CaretEqual:
10384 case OO_PipeEqual:
10385 OpBuilder.addAssignmentIntegralOverloads();
10386 break;
10387
10388 case OO_Exclaim:
10389 OpBuilder.addExclaimOverload();
10390 break;
10391
10392 case OO_AmpAmp:
10393 case OO_PipePipe:
10394 OpBuilder.addAmpAmpOrPipePipeOverload();
10395 break;
10396
10397 case OO_Subscript:
10398 if (Args.size() == 2)
10399 OpBuilder.addSubscriptOverloads();
10400 break;
10401
10402 case OO_ArrowStar:
10403 OpBuilder.addArrowStarOverloads();
10404 break;
10405
10406 case OO_Conditional:
10407 OpBuilder.addConditionalOperatorOverloads();
10408 OpBuilder.addGenericBinaryArithmeticOverloads();
10409 break;
10410 }
10411}
10412
10413void
10415 SourceLocation Loc,
10416 ArrayRef<Expr *> Args,
10417 TemplateArgumentListInfo *ExplicitTemplateArgs,
10418 OverloadCandidateSet& CandidateSet,
10419 bool PartialOverloading) {
10420 ADLResult Fns;
10421
10422 // FIXME: This approach for uniquing ADL results (and removing
10423 // redundant candidates from the set) relies on pointer-equality,
10424 // which means we need to key off the canonical decl. However,
10425 // always going back to the canonical decl might not get us the
10426 // right set of default arguments. What default arguments are
10427 // we supposed to consider on ADL candidates, anyway?
10428
10429 // FIXME: Pass in the explicit template arguments?
10430 ArgumentDependentLookup(Name, Loc, Args, Fns);
10431
10432 ArrayRef<Expr *> ReversedArgs;
10433
10434 // Erase all of the candidates we already knew about.
10435 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10436 CandEnd = CandidateSet.end();
10437 Cand != CandEnd; ++Cand)
10438 if (Cand->Function) {
10439 FunctionDecl *Fn = Cand->Function;
10440 Fns.erase(Fn);
10441 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10442 Fns.erase(FunTmpl);
10443 }
10444
10445 // For each of the ADL candidates we found, add it to the overload
10446 // set.
10447 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10449
10450 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10451 if (ExplicitTemplateArgs)
10452 continue;
10453
10454 AddOverloadCandidate(
10455 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10456 PartialOverloading, /*AllowExplicit=*/true,
10457 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10458 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10459 AddOverloadCandidate(
10460 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10461 /*SuppressUserConversions=*/false, PartialOverloading,
10462 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10463 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10464 }
10465 } else {
10466 auto *FTD = cast<FunctionTemplateDecl>(*I);
10468 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10469 /*SuppressUserConversions=*/false, PartialOverloading,
10470 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10471 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10472 *this, Args, FTD->getTemplatedDecl())) {
10473
10474 // As template candidates are not deduced immediately,
10475 // persist the array in the overload set.
10476 if (ReversedArgs.empty())
10477 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
10478
10480 FTD, FoundDecl, ExplicitTemplateArgs, ReversedArgs, CandidateSet,
10481 /*SuppressUserConversions=*/false, PartialOverloading,
10482 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10484 }
10485 }
10486 }
10487}
10488
10489namespace {
10490enum class Comparison { Equal, Better, Worse };
10491}
10492
10493/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10494/// overload resolution.
10495///
10496/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10497/// Cand1's first N enable_if attributes have precisely the same conditions as
10498/// Cand2's first N enable_if attributes (where N = the number of enable_if
10499/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10500///
10501/// Note that you can have a pair of candidates such that Cand1's enable_if
10502/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10503/// worse than Cand1's.
10504static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10505 const FunctionDecl *Cand2) {
10506 // Common case: One (or both) decls don't have enable_if attrs.
10507 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10508 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10509 if (!Cand1Attr || !Cand2Attr) {
10510 if (Cand1Attr == Cand2Attr)
10511 return Comparison::Equal;
10512 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10513 }
10514
10515 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10516 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10517
10518 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10519 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10520 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10521 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10522
10523 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10524 // has fewer enable_if attributes than Cand2, and vice versa.
10525 if (!Cand1A)
10526 return Comparison::Worse;
10527 if (!Cand2A)
10528 return Comparison::Better;
10529
10530 Cand1ID.clear();
10531 Cand2ID.clear();
10532
10533 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10534 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10535 if (Cand1ID != Cand2ID)
10536 return Comparison::Worse;
10537 }
10538
10539 return Comparison::Equal;
10540}
10541
10542static Comparison
10544 const OverloadCandidate &Cand2) {
10545 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10546 !Cand2.Function->isMultiVersion())
10547 return Comparison::Equal;
10548
10549 // If both are invalid, they are equal. If one of them is invalid, the other
10550 // is better.
10551 if (Cand1.Function->isInvalidDecl()) {
10552 if (Cand2.Function->isInvalidDecl())
10553 return Comparison::Equal;
10554 return Comparison::Worse;
10555 }
10556 if (Cand2.Function->isInvalidDecl())
10557 return Comparison::Better;
10558
10559 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10560 // cpu_dispatch, else arbitrarily based on the identifiers.
10561 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10562 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10563 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10564 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10565
10566 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10567 return Comparison::Equal;
10568
10569 if (Cand1CPUDisp && !Cand2CPUDisp)
10570 return Comparison::Better;
10571 if (Cand2CPUDisp && !Cand1CPUDisp)
10572 return Comparison::Worse;
10573
10574 if (Cand1CPUSpec && Cand2CPUSpec) {
10575 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10576 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10577 ? Comparison::Better
10578 : Comparison::Worse;
10579
10580 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10581 FirstDiff = std::mismatch(
10582 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10583 Cand2CPUSpec->cpus_begin(),
10584 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10585 return LHS->getName() == RHS->getName();
10586 });
10587
10588 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10589 "Two different cpu-specific versions should not have the same "
10590 "identifier list, otherwise they'd be the same decl!");
10591 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10592 ? Comparison::Better
10593 : Comparison::Worse;
10594 }
10595 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10596}
10597
10598/// Compute the type of the implicit object parameter for the given function,
10599/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10600/// null QualType if there is a 'matches anything' implicit object parameter.
10601static std::optional<QualType>
10603 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
10604 return std::nullopt;
10605
10606 auto *M = cast<CXXMethodDecl>(F);
10607 // Static member functions' object parameters match all types.
10608 if (M->isStatic())
10609 return QualType();
10610 return M->getFunctionObjectParameterReferenceType();
10611}
10612
10613// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10614// represent the same entity.
10615static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10616 const FunctionDecl *F2) {
10617 if (declaresSameEntity(F1, F2))
10618 return true;
10619 auto PT1 = F1->getPrimaryTemplate();
10620 auto PT2 = F2->getPrimaryTemplate();
10621 if (PT1 && PT2) {
10622 if (declaresSameEntity(PT1, PT2) ||
10623 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10624 PT2->getInstantiatedFromMemberTemplate()))
10625 return true;
10626 }
10627 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10628 // different functions with same params). Consider removing this (as no test
10629 // fail w/o it).
10630 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10631 if (First) {
10632 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10633 return *T;
10634 }
10635 assert(I < F->getNumParams());
10636 return F->getParamDecl(I++)->getType();
10637 };
10638
10639 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10640 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10641
10642 if (F1NumParams != F2NumParams)
10643 return false;
10644
10645 unsigned I1 = 0, I2 = 0;
10646 for (unsigned I = 0; I != F1NumParams; ++I) {
10647 QualType T1 = NextParam(F1, I1, I == 0);
10648 QualType T2 = NextParam(F2, I2, I == 0);
10649 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10650 if (!Context.hasSameUnqualifiedType(T1, T2))
10651 return false;
10652 }
10653 return true;
10654}
10655
10656/// We're allowed to use constraints partial ordering only if the candidates
10657/// have the same parameter types:
10658/// [over.match.best.general]p2.6
10659/// F1 and F2 are non-template functions with the same
10660/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10662 FunctionDecl *Fn2,
10663 bool IsFn1Reversed,
10664 bool IsFn2Reversed) {
10665 assert(Fn1 && Fn2);
10666 if (Fn1->isVariadic() != Fn2->isVariadic())
10667 return false;
10668
10669 if (!S.FunctionNonObjectParamTypesAreEqual(Fn1, Fn2, nullptr,
10670 IsFn1Reversed ^ IsFn2Reversed))
10671 return false;
10672
10673 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10674 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10675 if (Mem1 && Mem2) {
10676 // if they are member functions, both are direct members of the same class,
10677 // and
10678 if (Mem1->getParent() != Mem2->getParent())
10679 return false;
10680 // if both are non-static member functions, they have the same types for
10681 // their object parameters
10682 if (Mem1->isInstance() && Mem2->isInstance() &&
10684 Mem1->getFunctionObjectParameterReferenceType(),
10685 Mem1->getFunctionObjectParameterReferenceType()))
10686 return false;
10687 }
10688 return true;
10689}
10690
10691static FunctionDecl *
10693 bool IsFn1Reversed, bool IsFn2Reversed) {
10694 if (!Fn1 || !Fn2)
10695 return nullptr;
10696
10697 // C++ [temp.constr.order]:
10698 // A non-template function F1 is more partial-ordering-constrained than a
10699 // non-template function F2 if:
10700 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10701 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10702
10703 if (Cand1IsSpecialization || Cand2IsSpecialization)
10704 return nullptr;
10705
10706 // - they have the same non-object-parameter-type-lists, and [...]
10707 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10708 IsFn2Reversed))
10709 return nullptr;
10710
10711 // - the declaration of F1 is more constrained than the declaration of F2.
10712 return S.getMoreConstrainedFunction(Fn1, Fn2);
10713}
10714
10715/// isBetterOverloadCandidate - Determines whether the first overload
10716/// candidate is a better candidate than the second (C++ 13.3.3p1).
10718 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10720 bool PartialOverloading) {
10721 // Define viable functions to be better candidates than non-viable
10722 // functions.
10723 if (!Cand2.Viable)
10724 return Cand1.Viable;
10725 else if (!Cand1.Viable)
10726 return false;
10727
10728 // [CUDA] A function with 'never' preference is marked not viable, therefore
10729 // is never shown up here. The worst preference shown up here is 'wrong side',
10730 // e.g. an H function called by a HD function in device compilation. This is
10731 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10732 // function which is called only by an H function. A deferred diagnostic will
10733 // be triggered if it is emitted. However a wrong-sided function is still
10734 // a viable candidate here.
10735 //
10736 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10737 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10738 // can be emitted, Cand1 is not better than Cand2. This rule should have
10739 // precedence over other rules.
10740 //
10741 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10742 // other rules should be used to determine which is better. This is because
10743 // host/device based overloading resolution is mostly for determining
10744 // viability of a function. If two functions are both viable, other factors
10745 // should take precedence in preference, e.g. the standard-defined preferences
10746 // like argument conversion ranks or enable_if partial-ordering. The
10747 // preference for pass-object-size parameters is probably most similar to a
10748 // type-based-overloading decision and so should take priority.
10749 //
10750 // If other rules cannot determine which is better, CUDA preference will be
10751 // used again to determine which is better.
10752 //
10753 // TODO: Currently IdentifyPreference does not return correct values
10754 // for functions called in global variable initializers due to missing
10755 // correct context about device/host. Therefore we can only enforce this
10756 // rule when there is a caller. We should enforce this rule for functions
10757 // in global variable initializers once proper context is added.
10758 //
10759 // TODO: We can only enable the hostness based overloading resolution when
10760 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10761 // overloading resolution diagnostics.
10762 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10763 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10764 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10765 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
10766 bool IsCand1ImplicitHD =
10768 bool IsCand2ImplicitHD =
10770 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
10771 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10772 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10773 // The implicit HD function may be a function in a system header which
10774 // is forced by pragma. In device compilation, if we prefer HD candidates
10775 // over wrong-sided candidates, overloading resolution may change, which
10776 // may result in non-deferrable diagnostics. As a workaround, we let
10777 // implicit HD candidates take equal preference as wrong-sided candidates.
10778 // This will preserve the overloading resolution.
10779 // TODO: We still need special handling of implicit HD functions since
10780 // they may incur other diagnostics to be deferred. We should make all
10781 // host/device related diagnostics deferrable and remove special handling
10782 // of implicit HD functions.
10783 auto EmitThreshold =
10784 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10785 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10788 auto Cand1Emittable = P1 > EmitThreshold;
10789 auto Cand2Emittable = P2 > EmitThreshold;
10790 if (Cand1Emittable && !Cand2Emittable)
10791 return true;
10792 if (!Cand1Emittable && Cand2Emittable)
10793 return false;
10794 }
10795 }
10796
10797 // C++ [over.match.best]p1: (Changed in C++23)
10798 //
10799 // -- if F is a static member function, ICS1(F) is defined such
10800 // that ICS1(F) is neither better nor worse than ICS1(G) for
10801 // any function G, and, symmetrically, ICS1(G) is neither
10802 // better nor worse than ICS1(F).
10803 unsigned StartArg = 0;
10804 if (!Cand1.TookAddressOfOverload &&
10806 StartArg = 1;
10807
10808 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10809 // We don't allow incompatible pointer conversions in C++.
10810 if (!S.getLangOpts().CPlusPlus)
10811 return ICS.isStandard() &&
10812 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10813
10814 // The only ill-formed conversion we allow in C++ is the string literal to
10815 // char* conversion, which is only considered ill-formed after C++11.
10816 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10818 };
10819
10820 // Define functions that don't require ill-formed conversions for a given
10821 // argument to be better candidates than functions that do.
10822 unsigned NumArgs = Cand1.Conversions.size();
10823 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10824 bool HasBetterConversion = false;
10825 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10826 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10827 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10828 if (Cand1Bad != Cand2Bad) {
10829 if (Cand1Bad)
10830 return false;
10831 HasBetterConversion = true;
10832 }
10833 }
10834
10835 if (HasBetterConversion)
10836 return true;
10837
10838 // C++ [over.match.best]p1:
10839 // A viable function F1 is defined to be a better function than another
10840 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10841 // conversion sequence than ICSi(F2), and then...
10842 bool HasWorseConversion = false;
10843 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10845 Cand1.Conversions[ArgIdx],
10846 Cand2.Conversions[ArgIdx])) {
10848 // Cand1 has a better conversion sequence.
10849 HasBetterConversion = true;
10850 break;
10851
10853 if (Cand1.Function && Cand2.Function &&
10854 Cand1.isReversed() != Cand2.isReversed() &&
10855 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
10856 // Work around large-scale breakage caused by considering reversed
10857 // forms of operator== in C++20:
10858 //
10859 // When comparing a function against a reversed function, if we have a
10860 // better conversion for one argument and a worse conversion for the
10861 // other, the implicit conversion sequences are treated as being equally
10862 // good.
10863 //
10864 // This prevents a comparison function from being considered ambiguous
10865 // with a reversed form that is written in the same way.
10866 //
10867 // We diagnose this as an extension from CreateOverloadedBinOp.
10868 HasWorseConversion = true;
10869 break;
10870 }
10871
10872 // Cand1 can't be better than Cand2.
10873 return false;
10874
10876 // Do nothing.
10877 break;
10878 }
10879 }
10880
10881 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10882 // ICSj(F2), or, if not that,
10883 if (HasBetterConversion && !HasWorseConversion)
10884 return true;
10885
10886 // -- the context is an initialization by user-defined conversion
10887 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10888 // from the return type of F1 to the destination type (i.e.,
10889 // the type of the entity being initialized) is a better
10890 // conversion sequence than the standard conversion sequence
10891 // from the return type of F2 to the destination type.
10893 Cand1.Function && Cand2.Function &&
10894 isa<CXXConversionDecl>(Cand1.Function) &&
10895 isa<CXXConversionDecl>(Cand2.Function)) {
10896
10897 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
10898 // First check whether we prefer one of the conversion functions over the
10899 // other. This only distinguishes the results in non-standard, extension
10900 // cases such as the conversion from a lambda closure type to a function
10901 // pointer or block.
10906 Cand1.FinalConversion,
10907 Cand2.FinalConversion);
10908
10911
10912 // FIXME: Compare kind of reference binding if conversion functions
10913 // convert to a reference type used in direct reference binding, per
10914 // C++14 [over.match.best]p1 section 2 bullet 3.
10915 }
10916
10917 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10918 // as combined with the resolution to CWG issue 243.
10919 //
10920 // When the context is initialization by constructor ([over.match.ctor] or
10921 // either phase of [over.match.list]), a constructor is preferred over
10922 // a conversion function.
10923 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10924 Cand1.Function && Cand2.Function &&
10925 isa<CXXConstructorDecl>(Cand1.Function) !=
10926 isa<CXXConstructorDecl>(Cand2.Function))
10927 return isa<CXXConstructorDecl>(Cand1.Function);
10928
10929 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
10930 return Cand2.StrictPackMatch;
10931
10932 // -- F1 is a non-template function and F2 is a function template
10933 // specialization, or, if not that,
10934 bool Cand1IsSpecialization = Cand1.Function &&
10936 bool Cand2IsSpecialization = Cand2.Function &&
10938 if (Cand1IsSpecialization != Cand2IsSpecialization)
10939 return Cand2IsSpecialization;
10940
10941 // -- F1 and F2 are function template specializations, and the function
10942 // template for F1 is more specialized than the template for F2
10943 // according to the partial ordering rules described in 14.5.5.2, or,
10944 // if not that,
10945 if (Cand1IsSpecialization && Cand2IsSpecialization) {
10946 const auto *Obj1Context =
10947 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
10948 const auto *Obj2Context =
10949 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
10950 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10953 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
10954 : TPOC_Call,
10956 Obj1Context ? S.Context.getCanonicalTagType(Obj1Context)
10957 : QualType{},
10958 Obj2Context ? S.Context.getCanonicalTagType(Obj2Context)
10959 : QualType{},
10960 Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
10961 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10962 }
10963 }
10964
10965 // -— F1 and F2 are non-template functions and F1 is more
10966 // partial-ordering-constrained than F2 [...],
10968 S, Cand1.Function, Cand2.Function, Cand1.isReversed(),
10969 Cand2.isReversed());
10970 F && F == Cand1.Function)
10971 return true;
10972
10973 // -- F1 is a constructor for a class D, F2 is a constructor for a base
10974 // class B of D, and for all arguments the corresponding parameters of
10975 // F1 and F2 have the same type.
10976 // FIXME: Implement the "all parameters have the same type" check.
10977 bool Cand1IsInherited =
10978 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
10979 bool Cand2IsInherited =
10980 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
10981 if (Cand1IsInherited != Cand2IsInherited)
10982 return Cand2IsInherited;
10983 else if (Cand1IsInherited) {
10984 assert(Cand2IsInherited);
10985 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
10986 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
10987 if (Cand1Class->isDerivedFrom(Cand2Class))
10988 return true;
10989 if (Cand2Class->isDerivedFrom(Cand1Class))
10990 return false;
10991 // Inherited from sibling base classes: still ambiguous.
10992 }
10993
10994 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
10995 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
10996 // with reversed order of parameters and F1 is not
10997 //
10998 // We rank reversed + different operator as worse than just reversed, but
10999 // that comparison can never happen, because we only consider reversing for
11000 // the maximally-rewritten operator (== or <=>).
11001 if (Cand1.RewriteKind != Cand2.RewriteKind)
11002 return Cand1.RewriteKind < Cand2.RewriteKind;
11003
11004 // Check C++17 tie-breakers for deduction guides.
11005 {
11006 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
11007 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
11008 if (Guide1 && Guide2) {
11009 // -- F1 is generated from a deduction-guide and F2 is not
11010 if (Guide1->isImplicit() != Guide2->isImplicit())
11011 return Guide2->isImplicit();
11012
11013 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11014 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11015 return true;
11016 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11017 return false;
11018
11019 // --F1 is generated from a non-template constructor and F2 is generated
11020 // from a constructor template
11021 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11022 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11023 if (Constructor1 && Constructor2) {
11024 bool isC1Templated = Constructor1->getTemplatedKind() !=
11026 bool isC2Templated = Constructor2->getTemplatedKind() !=
11028 if (isC1Templated != isC2Templated)
11029 return isC2Templated;
11030 }
11031 }
11032 }
11033
11034 // Check for enable_if value-based overload resolution.
11035 if (Cand1.Function && Cand2.Function) {
11036 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
11037 if (Cmp != Comparison::Equal)
11038 return Cmp == Comparison::Better;
11039 }
11040
11041 bool HasPS1 = Cand1.Function != nullptr &&
11043 bool HasPS2 = Cand2.Function != nullptr &&
11045 if (HasPS1 != HasPS2 && HasPS1)
11046 return true;
11047
11048 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11049 if (MV == Comparison::Better)
11050 return true;
11051 if (MV == Comparison::Worse)
11052 return false;
11053
11054 // If other rules cannot determine which is better, CUDA preference is used
11055 // to determine which is better.
11056 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11057 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11058 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
11059 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11060 }
11061
11062 // General member function overloading is handled above, so this only handles
11063 // constructors with address spaces.
11064 // This only handles address spaces since C++ has no other
11065 // qualifier that can be used with constructors.
11066 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
11067 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
11068 if (CD1 && CD2) {
11069 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11070 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11071 if (AS1 != AS2) {
11073 return true;
11075 return false;
11076 }
11077 }
11078
11079 return false;
11080}
11081
11082/// Determine whether two declarations are "equivalent" for the purposes of
11083/// name lookup and overload resolution. This applies when the same internal/no
11084/// linkage entity is defined by two modules (probably by textually including
11085/// the same header). In such a case, we don't consider the declarations to
11086/// declare the same entity, but we also don't want lookups with both
11087/// declarations visible to be ambiguous in some cases (this happens when using
11088/// a modularized libstdc++).
11090 const NamedDecl *B) {
11091 auto *VA = dyn_cast_or_null<ValueDecl>(A);
11092 auto *VB = dyn_cast_or_null<ValueDecl>(B);
11093 if (!VA || !VB)
11094 return false;
11095
11096 // The declarations must be declaring the same name as an internal linkage
11097 // entity in different modules.
11098 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11099 VB->getDeclContext()->getRedeclContext()) ||
11100 getOwningModule(VA) == getOwningModule(VB) ||
11101 VA->isExternallyVisible() || VB->isExternallyVisible())
11102 return false;
11103
11104 // Check that the declarations appear to be equivalent.
11105 //
11106 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11107 // For constants and functions, we should check the initializer or body is
11108 // the same. For non-constant variables, we shouldn't allow it at all.
11109 if (Context.hasSameType(VA->getType(), VB->getType()))
11110 return true;
11111
11112 // Enum constants within unnamed enumerations will have different types, but
11113 // may still be similar enough to be interchangeable for our purposes.
11114 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
11115 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
11116 // Only handle anonymous enums. If the enumerations were named and
11117 // equivalent, they would have been merged to the same type.
11118 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
11119 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
11120 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11121 !Context.hasSameType(EnumA->getIntegerType(),
11122 EnumB->getIntegerType()))
11123 return false;
11124 // Allow this only if the value is the same for both enumerators.
11125 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
11126 }
11127 }
11128
11129 // Nothing else is sufficiently similar.
11130 return false;
11131}
11132
11135 assert(D && "Unknown declaration");
11136 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11137
11138 Module *M = getOwningModule(D);
11139 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
11140 << !M << (M ? M->getFullModuleName() : "");
11141
11142 for (auto *E : Equiv) {
11143 Module *M = getOwningModule(E);
11144 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
11145 << !M << (M ? M->getFullModuleName() : "");
11146 }
11147}
11148
11150 return FailureKind == ovl_fail_bad_deduction &&
11151 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11153 static_cast<CNSInfo *>(DeductionFailure.Data)
11154 ->Satisfaction.ContainsErrors;
11155}
11156
11159 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11160 bool PartialOverloading, bool AllowExplicit,
11162 bool AggregateCandidateDeduction) {
11163
11164 auto *C =
11165 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11166
11169 /*AllowObjCConversionOnExplicit=*/false,
11170 /*AllowResultConversion=*/false, AllowExplicit, SuppressUserConversions,
11171 PartialOverloading, AggregateCandidateDeduction},
11173 FoundDecl,
11174 Args,
11175 IsADLCandidate,
11176 PO};
11177
11178 HasDeferredTemplateConstructors |=
11179 isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl());
11180}
11181
11183 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11184 CXXRecordDecl *ActingContext, QualType ObjectType,
11185 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11186 bool SuppressUserConversions, bool PartialOverloading,
11188
11189 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11190
11191 auto *C =
11192 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11193
11196 /*AllowObjCConversionOnExplicit=*/false,
11197 /*AllowResultConversion=*/false,
11198 /*AllowExplicit=*/false, SuppressUserConversions, PartialOverloading,
11199 /*AggregateCandidateDeduction=*/false},
11200 MethodTmpl,
11201 FoundDecl,
11202 Args,
11203 ActingContext,
11204 ObjectClassification,
11205 ObjectType,
11206 PO};
11207}
11208
11211 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11212 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11213 bool AllowResultConversion) {
11214
11215 auto *C =
11216 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11217
11220 AllowObjCConversionOnExplicit, AllowResultConversion,
11221 /*AllowExplicit=*/false,
11222 /*SuppressUserConversions=*/false,
11223 /*PartialOverloading*/ false,
11224 /*AggregateCandidateDeduction=*/false},
11226 FoundDecl,
11227 ActingContext,
11228 From,
11229 ToType};
11230}
11231
11232static void
11235
11237 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext,
11238 /*ExplicitTemplateArgs=*/nullptr, C.ObjectType, C.ObjectClassification,
11239 C.Args, C.SuppressUserConversions, C.PartialOverloading, C.PO);
11240}
11241
11242static void
11246 S, CandidateSet, C.FunctionTemplate, C.FoundDecl,
11247 /*ExplicitTemplateArgs=*/nullptr, C.Args, C.SuppressUserConversions,
11248 C.PartialOverloading, C.AllowExplicit, C.IsADLCandidate, C.PO,
11249 C.AggregateCandidateDeduction);
11250}
11251
11252static void
11256 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From,
11257 C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit,
11258 C.AllowResultConversion);
11259}
11260
11262 Candidates.reserve(Candidates.size() + DeferredCandidatesCount);
11263 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11264 while (Cand) {
11265 switch (Cand->Kind) {
11268 S, *this,
11269 *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11270 break;
11273 S, *this,
11274 *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11275 break;
11278 S, *this,
11279 *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11280 break;
11281 }
11282 Cand = Cand->Next;
11283 }
11284 FirstDeferredCandidate = nullptr;
11285 DeferredCandidatesCount = 0;
11286}
11287
11289OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11290 Best->Best = true;
11291 if (Best->Function && Best->Function->isDeleted())
11292 return OR_Deleted;
11293 return OR_Success;
11294}
11295
11296void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11298 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11299 // are accepted by both clang and NVCC. However, during a particular
11300 // compilation mode only one call variant is viable. We need to
11301 // exclude non-viable overload candidates from consideration based
11302 // only on their host/device attributes. Specifically, if one
11303 // candidate call is WrongSide and the other is SameSide, we ignore
11304 // the WrongSide candidate.
11305 // We only need to remove wrong-sided candidates here if
11306 // -fgpu-exclude-wrong-side-overloads is off. When
11307 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11308 // uniformly in isBetterOverloadCandidate.
11309 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11310 return;
11311 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11312
11313 bool ContainsSameSideCandidate =
11314 llvm::any_of(Candidates, [&](const OverloadCandidate *Cand) {
11315 // Check viable function only.
11316 return Cand->Viable && Cand->Function &&
11317 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11319 });
11320
11321 if (!ContainsSameSideCandidate)
11322 return;
11323
11324 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11325 // Check viable function only to avoid unnecessary data copying/moving.
11326 return Cand->Viable && Cand->Function &&
11327 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11329 };
11330 llvm::erase_if(Candidates, IsWrongSideCandidate);
11331}
11332
11333/// Computes the best viable function (C++ 13.3.3)
11334/// within an overload candidate set.
11335///
11336/// \param Loc The location of the function name (or operator symbol) for
11337/// which overload resolution occurs.
11338///
11339/// \param Best If overload resolution was successful or found a deleted
11340/// function, \p Best points to the candidate function found.
11341///
11342/// \returns The result of overload resolution.
11344 SourceLocation Loc,
11345 iterator &Best) {
11346
11348 DeferredCandidatesCount == 0) &&
11349 "Unexpected deferred template candidates");
11350
11351 bool TwoPhaseResolution =
11352 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11353
11354 if (TwoPhaseResolution) {
11355 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11356 if (Best != end() && Best->isPerfectMatch(S.Context)) {
11357 if (!(HasDeferredTemplateConstructors &&
11358 isa_and_nonnull<CXXConversionDecl>(Best->Function)))
11359 return Res;
11360 }
11361 }
11362
11364 return BestViableFunctionImpl(S, Loc, Best);
11365}
11366
11367OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11369
11371 Candidates.reserve(this->Candidates.size());
11372 std::transform(this->Candidates.begin(), this->Candidates.end(),
11373 std::back_inserter(Candidates),
11374 [](OverloadCandidate &Cand) { return &Cand; });
11375
11376 if (S.getLangOpts().CUDA)
11377 CudaExcludeWrongSideCandidates(S, Candidates);
11378
11379 Best = end();
11380 for (auto *Cand : Candidates) {
11381 Cand->Best = false;
11382 if (Cand->Viable) {
11383 if (Best == end() ||
11384 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
11385 Best = Cand;
11386 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11387 // This candidate has constraint that we were unable to evaluate because
11388 // it referenced an expression that contained an error. Rather than fall
11389 // back onto a potentially unintended candidate (made worse by
11390 // subsuming constraints), treat this as 'no viable candidate'.
11391 Best = end();
11392 return OR_No_Viable_Function;
11393 }
11394 }
11395
11396 // If we didn't find any viable functions, abort.
11397 if (Best == end())
11398 return OR_No_Viable_Function;
11399
11402 PendingBest.push_back(&*Best);
11403 Best->Best = true;
11404
11405 // Make sure that this function is better than every other viable
11406 // function. If not, we have an ambiguity.
11407 while (!PendingBest.empty()) {
11408 auto *Curr = PendingBest.pop_back_val();
11409 for (auto *Cand : Candidates) {
11410 if (Cand->Viable && !Cand->Best &&
11411 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
11412 PendingBest.push_back(Cand);
11413 Cand->Best = true;
11414
11416 Curr->Function))
11417 EquivalentCands.push_back(Cand->Function);
11418 else
11419 Best = end();
11420 }
11421 }
11422 }
11423
11424 if (Best == end())
11425 return OR_Ambiguous;
11426
11427 OverloadingResult R = ResultForBestCandidate(Best);
11428
11429 if (!EquivalentCands.empty())
11431 EquivalentCands);
11432 return R;
11433}
11434
11435namespace {
11436
11437enum OverloadCandidateKind {
11438 oc_function,
11439 oc_method,
11440 oc_reversed_binary_operator,
11441 oc_constructor,
11442 oc_implicit_default_constructor,
11443 oc_implicit_copy_constructor,
11444 oc_implicit_move_constructor,
11445 oc_implicit_copy_assignment,
11446 oc_implicit_move_assignment,
11447 oc_implicit_equality_comparison,
11448 oc_inherited_constructor
11449};
11450
11451enum OverloadCandidateSelect {
11452 ocs_non_template,
11453 ocs_template,
11454 ocs_described_template,
11455};
11456
11457static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11458ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11459 const FunctionDecl *Fn,
11461 std::string &Description) {
11462
11463 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11464 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11465 isTemplate = true;
11466 Description = S.getTemplateArgumentBindingsText(
11467 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11468 }
11469
11470 OverloadCandidateSelect Select = [&]() {
11471 if (!Description.empty())
11472 return ocs_described_template;
11473 return isTemplate ? ocs_template : ocs_non_template;
11474 }();
11475
11476 OverloadCandidateKind Kind = [&]() {
11477 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11478 return oc_implicit_equality_comparison;
11479
11480 if (CRK & CRK_Reversed)
11481 return oc_reversed_binary_operator;
11482
11483 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
11484 if (!Ctor->isImplicit()) {
11485 if (isa<ConstructorUsingShadowDecl>(Found))
11486 return oc_inherited_constructor;
11487 else
11488 return oc_constructor;
11489 }
11490
11491 if (Ctor->isDefaultConstructor())
11492 return oc_implicit_default_constructor;
11493
11494 if (Ctor->isMoveConstructor())
11495 return oc_implicit_move_constructor;
11496
11497 assert(Ctor->isCopyConstructor() &&
11498 "unexpected sort of implicit constructor");
11499 return oc_implicit_copy_constructor;
11500 }
11501
11502 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11503 // This actually gets spelled 'candidate function' for now, but
11504 // it doesn't hurt to split it out.
11505 if (!Meth->isImplicit())
11506 return oc_method;
11507
11508 if (Meth->isMoveAssignmentOperator())
11509 return oc_implicit_move_assignment;
11510
11511 if (Meth->isCopyAssignmentOperator())
11512 return oc_implicit_copy_assignment;
11513
11514 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11515 return oc_method;
11516 }
11517
11518 return oc_function;
11519 }();
11520
11521 return std::make_pair(Kind, Select);
11522}
11523
11524void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11525 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11526 // set.
11527 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11528 S.Diag(FoundDecl->getLocation(),
11529 diag::note_ovl_candidate_inherited_constructor)
11530 << Shadow->getNominatedBaseClass();
11531}
11532
11533} // end anonymous namespace
11534
11536 const FunctionDecl *FD) {
11537 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11538 bool AlwaysTrue;
11539 if (EnableIf->getCond()->isValueDependent() ||
11540 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11541 return false;
11542 if (!AlwaysTrue)
11543 return false;
11544 }
11545 return true;
11546}
11547
11548/// Returns true if we can take the address of the function.
11549///
11550/// \param Complain - If true, we'll emit a diagnostic
11551/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11552/// we in overload resolution?
11553/// \param Loc - The location of the statement we're complaining about. Ignored
11554/// if we're not complaining, or if we're in overload resolution.
11556 bool Complain,
11557 bool InOverloadResolution,
11558 SourceLocation Loc) {
11559 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11560 if (Complain) {
11561 if (InOverloadResolution)
11562 S.Diag(FD->getBeginLoc(),
11563 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11564 else
11565 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11566 }
11567 return false;
11568 }
11569
11570 if (FD->getTrailingRequiresClause()) {
11571 ConstraintSatisfaction Satisfaction;
11572 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11573 return false;
11574 if (!Satisfaction.IsSatisfied) {
11575 if (Complain) {
11576 if (InOverloadResolution) {
11577 SmallString<128> TemplateArgString;
11578 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11579 TemplateArgString += " ";
11580 TemplateArgString += S.getTemplateArgumentBindingsText(
11581 FunTmpl->getTemplateParameters(),
11583 }
11584
11585 S.Diag(FD->getBeginLoc(),
11586 diag::note_ovl_candidate_unsatisfied_constraints)
11587 << TemplateArgString;
11588 } else
11589 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11590 << FD;
11591 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11592 }
11593 return false;
11594 }
11595 }
11596
11597 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11598 return P->hasAttr<PassObjectSizeAttr>();
11599 });
11600 if (I == FD->param_end())
11601 return true;
11602
11603 if (Complain) {
11604 // Add one to ParamNo because it's user-facing
11605 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11606 if (InOverloadResolution)
11607 S.Diag(FD->getLocation(),
11608 diag::note_ovl_candidate_has_pass_object_size_params)
11609 << ParamNo;
11610 else
11611 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11612 << FD << ParamNo;
11613 }
11614 return false;
11615}
11616
11618 const FunctionDecl *FD) {
11619 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11620 /*InOverloadResolution=*/true,
11621 /*Loc=*/SourceLocation());
11622}
11623
11625 bool Complain,
11626 SourceLocation Loc) {
11627 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11628 /*InOverloadResolution=*/false,
11629 Loc);
11630}
11631
11632// Don't print candidates other than the one that matches the calling
11633// convention of the call operator, since that is guaranteed to exist.
11635 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11636
11637 if (!ConvD)
11638 return false;
11639 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11640 if (!RD->isLambda())
11641 return false;
11642
11643 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11644 CallingConv CallOpCC =
11645 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11646 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11647 CallingConv ConvToCC =
11648 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11649
11650 return ConvToCC != CallOpCC;
11651}
11652
11653// Notes the location of an overload candidate.
11655 OverloadCandidateRewriteKind RewriteKind,
11656 QualType DestType, bool TakingAddress) {
11657 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11658 return;
11659 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11660 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11661 return;
11662 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11663 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11664 return;
11666 return;
11667
11668 std::string FnDesc;
11669 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11670 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11671 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11672 << (unsigned)KSPair.first << (unsigned)KSPair.second
11673 << Fn << FnDesc;
11674
11675 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11676 Diag(Fn->getLocation(), PD);
11677 MaybeEmitInheritedConstructorNote(*this, Found);
11678}
11679
11680static void
11682 // Perhaps the ambiguity was caused by two atomic constraints that are
11683 // 'identical' but not equivalent:
11684 //
11685 // void foo() requires (sizeof(T) > 4) { } // #1
11686 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11687 //
11688 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11689 // #2 to subsume #1, but these constraint are not considered equivalent
11690 // according to the subsumption rules because they are not the same
11691 // source-level construct. This behavior is quite confusing and we should try
11692 // to help the user figure out what happened.
11693
11694 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11695 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11696 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11697 if (!I->Function)
11698 continue;
11700 if (auto *Template = I->Function->getPrimaryTemplate())
11701 Template->getAssociatedConstraints(AC);
11702 else
11703 I->Function->getAssociatedConstraints(AC);
11704 if (AC.empty())
11705 continue;
11706 if (FirstCand == nullptr) {
11707 FirstCand = I->Function;
11708 FirstAC = AC;
11709 } else if (SecondCand == nullptr) {
11710 SecondCand = I->Function;
11711 SecondAC = AC;
11712 } else {
11713 // We have more than one pair of constrained functions - this check is
11714 // expensive and we'd rather not try to diagnose it.
11715 return;
11716 }
11717 }
11718 if (!SecondCand)
11719 return;
11720 // The diagnostic can only happen if there are associated constraints on
11721 // both sides (there needs to be some identical atomic constraint).
11722 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11723 SecondCand, SecondAC))
11724 // Just show the user one diagnostic, they'll probably figure it out
11725 // from here.
11726 return;
11727}
11728
11729// Notes the location of all overload candidates designated through
11730// OverloadedExpr
11731void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11732 bool TakingAddress) {
11733 assert(OverloadedExpr->getType() == Context.OverloadTy);
11734
11735 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11736 OverloadExpr *OvlExpr = Ovl.Expression;
11737
11738 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11739 IEnd = OvlExpr->decls_end();
11740 I != IEnd; ++I) {
11741 if (FunctionTemplateDecl *FunTmpl =
11742 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11743 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11744 TakingAddress);
11745 } else if (FunctionDecl *Fun
11746 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11747 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11748 }
11749 }
11750}
11751
11752/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11753/// "lead" diagnostic; it will be given two arguments, the source and
11754/// target types of the conversion.
11756 Sema &S,
11757 SourceLocation CaretLoc,
11758 const PartialDiagnostic &PDiag) const {
11759 S.Diag(CaretLoc, PDiag)
11760 << Ambiguous.getFromType() << Ambiguous.getToType();
11761 unsigned CandsShown = 0;
11763 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11764 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11765 break;
11766 ++CandsShown;
11767 S.NoteOverloadCandidate(I->first, I->second);
11768 }
11769 S.Diags.overloadCandidatesShown(CandsShown);
11770 if (I != E)
11771 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11772}
11773
11775 unsigned I, bool TakingCandidateAddress) {
11776 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11777 assert(Conv.isBad());
11778 assert(Cand->Function && "for now, candidate must be a function");
11779 FunctionDecl *Fn = Cand->Function;
11780
11781 // There's a conversion slot for the object argument if this is a
11782 // non-constructor method. Note that 'I' corresponds the
11783 // conversion-slot index.
11784 bool isObjectArgument = false;
11785 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Fn) &&
11786 !isa<CXXConstructorDecl>(Fn)) {
11787 if (I == 0)
11788 isObjectArgument = true;
11789 else if (!Fn->hasCXXExplicitFunctionObjectParameter())
11790 I--;
11791 }
11792
11793 std::string FnDesc;
11794 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11795 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
11796 FnDesc);
11797
11798 Expr *FromExpr = Conv.Bad.FromExpr;
11799 QualType FromTy = Conv.Bad.getFromType();
11800 QualType ToTy = Conv.Bad.getToType();
11801 SourceRange ToParamRange;
11802
11803 // FIXME: In presence of parameter packs we can't determine parameter range
11804 // reliably, as we don't have access to instantiation.
11805 bool HasParamPack =
11806 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
11807 return Parm->isParameterPack();
11808 });
11809 if (!isObjectArgument && !HasParamPack)
11810 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
11811
11812 if (FromTy == S.Context.OverloadTy) {
11813 assert(FromExpr && "overload set argument came from implicit argument?");
11814 Expr *E = FromExpr->IgnoreParens();
11815 if (isa<UnaryOperator>(E))
11816 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11817 DeclarationName Name = cast<OverloadExpr>(E)->getName();
11818
11819 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
11820 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11821 << ToParamRange << ToTy << Name << I + 1;
11822 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11823 return;
11824 }
11825
11826 // Do some hand-waving analysis to see if the non-viability is due
11827 // to a qualifier mismatch.
11828 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
11829 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
11830 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11831 CToTy = RT->getPointeeType();
11832 else {
11833 // TODO: detect and diagnose the full richness of const mismatches.
11834 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11835 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11836 CFromTy = FromPT->getPointeeType();
11837 CToTy = ToPT->getPointeeType();
11838 }
11839 }
11840
11841 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11842 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
11843 Qualifiers FromQs = CFromTy.getQualifiers();
11844 Qualifiers ToQs = CToTy.getQualifiers();
11845
11846 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11847 if (isObjectArgument)
11848 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
11849 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11850 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11851 else
11852 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
11853 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11854 << FnDesc << ToParamRange << FromQs.getAddressSpace()
11855 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11856 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11857 return;
11858 }
11859
11860 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11861 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
11862 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11863 << ToParamRange << FromTy << FromQs.getObjCLifetime()
11864 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11865 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11866 return;
11867 }
11868
11869 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11870 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
11871 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11872 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11873 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11874 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11875 return;
11876 }
11877
11878 if (!FromQs.getPointerAuth().isEquivalent(ToQs.getPointerAuth())) {
11879 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ptrauth)
11880 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11881 << FromTy << !!FromQs.getPointerAuth()
11882 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
11883 << ToQs.getPointerAuth().getAsString() << I + 1
11884 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
11885 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11886 return;
11887 }
11888
11889 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11890 assert(CVR && "expected qualifiers mismatch");
11891
11892 if (isObjectArgument) {
11893 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
11894 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11895 << FromTy << (CVR - 1);
11896 } else {
11897 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
11898 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11899 << ToParamRange << FromTy << (CVR - 1) << I + 1;
11900 }
11901 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11902 return;
11903 }
11904
11907 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
11908 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11909 << (unsigned)isObjectArgument << I + 1
11911 << ToParamRange;
11912 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11913 return;
11914 }
11915
11916 // Special diagnostic for failure to convert an initializer list, since
11917 // telling the user that it has type void is not useful.
11918 if (FromExpr && isa<InitListExpr>(FromExpr)) {
11919 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
11920 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11921 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11924 ? 2
11925 : 0);
11926 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11927 return;
11928 }
11929
11930 // Diagnose references or pointers to incomplete types differently,
11931 // since it's far from impossible that the incompleteness triggered
11932 // the failure.
11933 QualType TempFromTy = FromTy.getNonReferenceType();
11934 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
11935 TempFromTy = PTy->getPointeeType();
11936 if (TempFromTy->isIncompleteType()) {
11937 // Emit the generic diagnostic and, optionally, add the hints to it.
11938 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
11939 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11940 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11941 << (unsigned)(Cand->Fix.Kind);
11942
11943 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11944 return;
11945 }
11946
11947 // Diagnose base -> derived pointer conversions.
11948 unsigned BaseToDerivedConversion = 0;
11949 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
11950 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
11951 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11952 FromPtrTy->getPointeeType(), S.getASTContext()) &&
11953 !FromPtrTy->getPointeeType()->isIncompleteType() &&
11954 !ToPtrTy->getPointeeType()->isIncompleteType() &&
11955 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
11956 FromPtrTy->getPointeeType()))
11957 BaseToDerivedConversion = 1;
11958 }
11959 } else if (const ObjCObjectPointerType *FromPtrTy
11960 = FromTy->getAs<ObjCObjectPointerType>()) {
11961 if (const ObjCObjectPointerType *ToPtrTy
11962 = ToTy->getAs<ObjCObjectPointerType>())
11963 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
11964 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
11965 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11966 FromPtrTy->getPointeeType(), S.getASTContext()) &&
11967 FromIface->isSuperClassOf(ToIface))
11968 BaseToDerivedConversion = 2;
11969 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
11970 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
11971 S.getASTContext()) &&
11972 !FromTy->isIncompleteType() &&
11973 !ToRefTy->getPointeeType()->isIncompleteType() &&
11974 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
11975 BaseToDerivedConversion = 3;
11976 }
11977 }
11978
11979 if (BaseToDerivedConversion) {
11980 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
11981 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11982 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
11983 << I + 1;
11984 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11985 return;
11986 }
11987
11988 if (isa<ObjCObjectPointerType>(CFromTy) &&
11989 isa<PointerType>(CToTy)) {
11990 Qualifiers FromQs = CFromTy.getQualifiers();
11991 Qualifiers ToQs = CToTy.getQualifiers();
11992 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11993 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
11994 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11995 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
11996 << I + 1;
11997 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11998 return;
11999 }
12000 }
12001
12002 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
12003 return;
12004
12005 // Emit the generic diagnostic and, optionally, add the hints to it.
12006 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
12007 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12008 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12009 << (unsigned)(Cand->Fix.Kind);
12010
12011 // Check that location of Fn is not in system header.
12012 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
12013 // If we can fix the conversion, suggest the FixIts.
12014 for (const FixItHint &HI : Cand->Fix.Hints)
12015 FDiag << HI;
12016 }
12017
12018 S.Diag(Fn->getLocation(), FDiag);
12019
12020 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12021}
12022
12023/// Additional arity mismatch diagnosis specific to a function overload
12024/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12025/// over a candidate in any candidate set.
12027 unsigned NumArgs, bool IsAddressOf = false) {
12028 assert(Cand->Function && "Candidate is required to be a function.");
12029 FunctionDecl *Fn = Cand->Function;
12030 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12031 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12032
12033 // With invalid overloaded operators, it's possible that we think we
12034 // have an arity mismatch when in fact it looks like we have the
12035 // right number of arguments, because only overloaded operators have
12036 // the weird behavior of overloading member and non-member functions.
12037 // Just don't report anything.
12038 if (Fn->isInvalidDecl() &&
12039 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12040 return true;
12041
12042 if (NumArgs < MinParams) {
12043 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12045 Cand->DeductionFailure.getResult() ==
12047 } else {
12048 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12050 Cand->DeductionFailure.getResult() ==
12052 }
12053
12054 return false;
12055}
12056
12057/// General arity mismatch diagnosis over a candidate in a candidate set.
12059 unsigned NumFormalArgs,
12060 bool IsAddressOf = false) {
12061 assert(isa<FunctionDecl>(D) &&
12062 "The templated declaration should at least be a function"
12063 " when diagnosing bad template argument deduction due to too many"
12064 " or too few arguments");
12065
12066 FunctionDecl *Fn = cast<FunctionDecl>(D);
12067
12068 // TODO: treat calls to a missing default constructor as a special case
12069 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12070 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12071 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12072
12073 // at least / at most / exactly
12074 bool HasExplicitObjectParam =
12075 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12076
12077 unsigned ParamCount =
12078 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12079 unsigned mode, modeCount;
12080
12081 if (NumFormalArgs < MinParams) {
12082 if (MinParams != ParamCount || FnTy->isVariadic() ||
12083 FnTy->isTemplateVariadic())
12084 mode = 0; // "at least"
12085 else
12086 mode = 2; // "exactly"
12087 modeCount = MinParams;
12088 } else {
12089 if (MinParams != ParamCount)
12090 mode = 1; // "at most"
12091 else
12092 mode = 2; // "exactly"
12093 modeCount = ParamCount;
12094 }
12095
12096 std::string Description;
12097 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12098 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
12099
12100 if (modeCount == 1 && !IsAddressOf &&
12101 Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())
12102 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
12103 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12104 << Description << mode
12105 << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
12106 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12107 else
12108 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
12109 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12110 << Description << mode << modeCount << NumFormalArgs
12111 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12112
12113 MaybeEmitInheritedConstructorNote(S, Found);
12114}
12115
12116/// Arity mismatch diagnosis specific to a function overload candidate.
12118 unsigned NumFormalArgs) {
12119 assert(Cand->Function && "Candidate must be a function");
12120 FunctionDecl *Fn = Cand->Function;
12121 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
12122 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
12123 Cand->TookAddressOfOverload);
12124}
12125
12127 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12128 return TD;
12129 llvm_unreachable("Unsupported: Getting the described template declaration"
12130 " for bad deduction diagnosis");
12131}
12132
12133/// Diagnose a failed template-argument deduction.
12134static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12135 DeductionFailureInfo &DeductionFailure,
12136 unsigned NumArgs,
12137 bool TakingCandidateAddress) {
12138 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12139 NamedDecl *ParamD;
12140 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12141 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12142 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12143 switch (DeductionFailure.getResult()) {
12145 llvm_unreachable(
12146 "TemplateDeductionResult::Success while diagnosing bad deduction");
12148 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12149 "while diagnosing bad deduction");
12152 return;
12153
12155 assert(ParamD && "no parameter found for incomplete deduction result");
12156 S.Diag(Templated->getLocation(),
12157 diag::note_ovl_candidate_incomplete_deduction)
12158 << ParamD->getDeclName();
12159 MaybeEmitInheritedConstructorNote(S, Found);
12160 return;
12161 }
12162
12164 assert(ParamD && "no parameter found for incomplete deduction result");
12165 S.Diag(Templated->getLocation(),
12166 diag::note_ovl_candidate_incomplete_deduction_pack)
12167 << ParamD->getDeclName()
12168 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12169 << *DeductionFailure.getFirstArg();
12170 MaybeEmitInheritedConstructorNote(S, Found);
12171 return;
12172 }
12173
12175 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12176 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
12177
12178 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12179
12180 // Param will have been canonicalized, but it should just be a
12181 // qualified version of ParamD, so move the qualifiers to that.
12183 Qs.strip(Param);
12184 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
12185 assert(S.Context.hasSameType(Param, NonCanonParam));
12186
12187 // Arg has also been canonicalized, but there's nothing we can do
12188 // about that. It also doesn't matter as much, because it won't
12189 // have any template parameters in it (because deduction isn't
12190 // done on dependent types).
12191 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12192
12193 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
12194 << ParamD->getDeclName() << Arg << NonCanonParam;
12195 MaybeEmitInheritedConstructorNote(S, Found);
12196 return;
12197 }
12198
12200 assert(ParamD && "no parameter found for inconsistent deduction result");
12201 int which = 0;
12202 if (isa<TemplateTypeParmDecl>(ParamD))
12203 which = 0;
12204 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
12205 // Deduction might have failed because we deduced arguments of two
12206 // different types for a non-type template parameter.
12207 // FIXME: Use a different TDK value for this.
12208 QualType T1 =
12209 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12210 QualType T2 =
12211 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12212 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12213 S.Diag(Templated->getLocation(),
12214 diag::note_ovl_candidate_inconsistent_deduction_types)
12215 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12216 << *DeductionFailure.getSecondArg() << T2;
12217 MaybeEmitInheritedConstructorNote(S, Found);
12218 return;
12219 }
12220
12221 which = 1;
12222 } else {
12223 which = 2;
12224 }
12225
12226 // Tweak the diagnostic if the problem is that we deduced packs of
12227 // different arities. We'll print the actual packs anyway in case that
12228 // includes additional useful information.
12229 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12230 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12231 DeductionFailure.getFirstArg()->pack_size() !=
12232 DeductionFailure.getSecondArg()->pack_size()) {
12233 which = 3;
12234 }
12235
12236 S.Diag(Templated->getLocation(),
12237 diag::note_ovl_candidate_inconsistent_deduction)
12238 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12239 << *DeductionFailure.getSecondArg();
12240 MaybeEmitInheritedConstructorNote(S, Found);
12241 return;
12242 }
12243
12245 assert(ParamD && "no parameter found for invalid explicit arguments");
12246 if (ParamD->getDeclName())
12247 S.Diag(Templated->getLocation(),
12248 diag::note_ovl_candidate_explicit_arg_mismatch_named)
12249 << ParamD->getDeclName();
12250 else {
12251 int index = 0;
12252 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
12253 index = TTP->getIndex();
12254 else if (NonTypeTemplateParmDecl *NTTP
12255 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
12256 index = NTTP->getIndex();
12257 else
12258 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
12259 S.Diag(Templated->getLocation(),
12260 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
12261 << (index + 1);
12262 }
12263 MaybeEmitInheritedConstructorNote(S, Found);
12264 return;
12265
12267 // Format the template argument list into the argument string.
12268 SmallString<128> TemplateArgString;
12269 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12270 TemplateArgString = " ";
12271 TemplateArgString += S.getTemplateArgumentBindingsText(
12272 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12273 if (TemplateArgString.size() == 1)
12274 TemplateArgString.clear();
12275 S.Diag(Templated->getLocation(),
12276 diag::note_ovl_candidate_unsatisfied_constraints)
12277 << TemplateArgString;
12278
12280 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12281 return;
12282 }
12285 DiagnoseArityMismatch(S, Found, Templated, NumArgs, TakingCandidateAddress);
12286 return;
12287
12289 S.Diag(Templated->getLocation(),
12290 diag::note_ovl_candidate_instantiation_depth);
12291 MaybeEmitInheritedConstructorNote(S, Found);
12292 return;
12293
12295 // Format the template argument list into the argument string.
12296 SmallString<128> TemplateArgString;
12297 if (TemplateArgumentList *Args =
12298 DeductionFailure.getTemplateArgumentList()) {
12299 TemplateArgString = " ";
12300 TemplateArgString += S.getTemplateArgumentBindingsText(
12301 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12302 if (TemplateArgString.size() == 1)
12303 TemplateArgString.clear();
12304 }
12305
12306 // If this candidate was disabled by enable_if, say so.
12307 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12308 if (PDiag && PDiag->second.getDiagID() ==
12309 diag::err_typename_nested_not_found_enable_if) {
12310 // FIXME: Use the source range of the condition, and the fully-qualified
12311 // name of the enable_if template. These are both present in PDiag.
12312 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
12313 << "'enable_if'" << TemplateArgString;
12314 return;
12315 }
12316
12317 // We found a specific requirement that disabled the enable_if.
12318 if (PDiag && PDiag->second.getDiagID() ==
12319 diag::err_typename_nested_not_found_requirement) {
12320 S.Diag(Templated->getLocation(),
12321 diag::note_ovl_candidate_disabled_by_requirement)
12322 << PDiag->second.getStringArg(0) << TemplateArgString;
12323 return;
12324 }
12325
12326 // Format the SFINAE diagnostic into the argument string.
12327 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12328 // formatted message in another diagnostic.
12329 SmallString<128> SFINAEArgString;
12330 SourceRange R;
12331 if (PDiag) {
12332 SFINAEArgString = ": ";
12333 R = SourceRange(PDiag->first, PDiag->first);
12334 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
12335 }
12336
12337 S.Diag(Templated->getLocation(),
12338 diag::note_ovl_candidate_substitution_failure)
12339 << TemplateArgString << SFINAEArgString << R;
12340 MaybeEmitInheritedConstructorNote(S, Found);
12341 return;
12342 }
12343
12346 // Format the template argument list into the argument string.
12347 SmallString<128> TemplateArgString;
12348 if (TemplateArgumentList *Args =
12349 DeductionFailure.getTemplateArgumentList()) {
12350 TemplateArgString = " ";
12351 TemplateArgString += S.getTemplateArgumentBindingsText(
12352 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12353 if (TemplateArgString.size() == 1)
12354 TemplateArgString.clear();
12355 }
12356
12357 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
12358 << (*DeductionFailure.getCallArgIndex() + 1)
12359 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12360 << TemplateArgString
12361 << (DeductionFailure.getResult() ==
12363 break;
12364 }
12365
12367 // FIXME: Provide a source location to indicate what we couldn't match.
12368 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12369 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12370 if (FirstTA.getKind() == TemplateArgument::Template &&
12371 SecondTA.getKind() == TemplateArgument::Template) {
12372 TemplateName FirstTN = FirstTA.getAsTemplate();
12373 TemplateName SecondTN = SecondTA.getAsTemplate();
12374 if (FirstTN.getKind() == TemplateName::Template &&
12375 SecondTN.getKind() == TemplateName::Template) {
12376 if (FirstTN.getAsTemplateDecl()->getName() ==
12377 SecondTN.getAsTemplateDecl()->getName()) {
12378 // FIXME: This fixes a bad diagnostic where both templates are named
12379 // the same. This particular case is a bit difficult since:
12380 // 1) It is passed as a string to the diagnostic printer.
12381 // 2) The diagnostic printer only attempts to find a better
12382 // name for types, not decls.
12383 // Ideally, this should folded into the diagnostic printer.
12384 S.Diag(Templated->getLocation(),
12385 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12386 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12387 return;
12388 }
12389 }
12390 }
12391
12392 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
12393 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
12394 return;
12395
12396 // FIXME: For generic lambda parameters, check if the function is a lambda
12397 // call operator, and if so, emit a prettier and more informative
12398 // diagnostic that mentions 'auto' and lambda in addition to
12399 // (or instead of?) the canonical template type parameters.
12400 S.Diag(Templated->getLocation(),
12401 diag::note_ovl_candidate_non_deduced_mismatch)
12402 << FirstTA << SecondTA;
12403 return;
12404 }
12405 // TODO: diagnose these individually, then kill off
12406 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12408 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
12409 MaybeEmitInheritedConstructorNote(S, Found);
12410 return;
12412 S.Diag(Templated->getLocation(),
12413 diag::note_cuda_ovl_candidate_target_mismatch);
12414 return;
12415 }
12416}
12417
12418/// Diagnose a failed template-argument deduction, for function calls.
12420 unsigned NumArgs,
12421 bool TakingCandidateAddress) {
12422 assert(Cand->Function && "Candidate must be a function");
12423 FunctionDecl *Fn = Cand->Function;
12427 if (CheckArityMismatch(S, Cand, NumArgs))
12428 return;
12429 }
12430 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
12431 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12432}
12433
12434/// CUDA: diagnose an invalid call across targets.
12436 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12437 assert(Cand->Function && "Candidate must be a Function.");
12438 FunctionDecl *Callee = Cand->Function;
12439
12440 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
12441 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
12442
12443 std::string FnDesc;
12444 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12445 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
12446 Cand->getRewriteKind(), FnDesc);
12447
12448 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
12449 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12450 << FnDesc /* Ignored */
12451 << CalleeTarget << CallerTarget;
12452
12453 // This could be an implicit constructor for which we could not infer the
12454 // target due to a collsion. Diagnose that case.
12455 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
12456 if (Meth != nullptr && Meth->isImplicit()) {
12457 CXXRecordDecl *ParentClass = Meth->getParent();
12459
12460 switch (FnKindPair.first) {
12461 default:
12462 return;
12463 case oc_implicit_default_constructor:
12465 break;
12466 case oc_implicit_copy_constructor:
12468 break;
12469 case oc_implicit_move_constructor:
12471 break;
12472 case oc_implicit_copy_assignment:
12474 break;
12475 case oc_implicit_move_assignment:
12477 break;
12478 };
12479
12480 bool ConstRHS = false;
12481 if (Meth->getNumParams()) {
12482 if (const ReferenceType *RT =
12483 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
12484 ConstRHS = RT->getPointeeType().isConstQualified();
12485 }
12486 }
12487
12488 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
12489 /* ConstRHS */ ConstRHS,
12490 /* Diagnose */ true);
12491 }
12492}
12493
12495 assert(Cand->Function && "Candidate must be a function");
12496 FunctionDecl *Callee = Cand->Function;
12497 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12498
12499 S.Diag(Callee->getLocation(),
12500 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12501 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12502}
12503
12505 assert(Cand->Function && "Candidate must be a function");
12506 FunctionDecl *Fn = Cand->Function;
12508 assert(ES.isExplicit() && "not an explicit candidate");
12509
12510 unsigned Kind;
12511 switch (Fn->getDeclKind()) {
12512 case Decl::Kind::CXXConstructor:
12513 Kind = 0;
12514 break;
12515 case Decl::Kind::CXXConversion:
12516 Kind = 1;
12517 break;
12518 case Decl::Kind::CXXDeductionGuide:
12519 Kind = Fn->isImplicit() ? 0 : 2;
12520 break;
12521 default:
12522 llvm_unreachable("invalid Decl");
12523 }
12524
12525 // Note the location of the first (in-class) declaration; a redeclaration
12526 // (particularly an out-of-class definition) will typically lack the
12527 // 'explicit' specifier.
12528 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12529 FunctionDecl *First = Fn->getFirstDecl();
12530 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12531 First = Pattern->getFirstDecl();
12532
12533 S.Diag(First->getLocation(),
12534 diag::note_ovl_candidate_explicit)
12535 << Kind << (ES.getExpr() ? 1 : 0)
12536 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12537}
12538
12540 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
12541 if (!DG)
12542 return;
12543 TemplateDecl *OriginTemplate =
12545 // We want to always print synthesized deduction guides for type aliases.
12546 // They would retain the explicit bit of the corresponding constructor.
12547 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12548 return;
12549 std::string FunctionProto;
12550 llvm::raw_string_ostream OS(FunctionProto);
12551 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12552 if (!Template) {
12553 // This also could be an instantiation. Find out the primary template.
12554 FunctionDecl *Pattern =
12555 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12556 if (!Pattern) {
12557 // The implicit deduction guide is built on an explicit non-template
12558 // deduction guide. Currently, this might be the case only for type
12559 // aliases.
12560 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12561 // gets merged.
12562 assert(OriginTemplate->isTypeAlias() &&
12563 "Non-template implicit deduction guides are only possible for "
12564 "type aliases");
12565 DG->print(OS);
12566 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12567 << FunctionProto;
12568 return;
12569 }
12571 assert(Template && "Cannot find the associated function template of "
12572 "CXXDeductionGuideDecl?");
12573 }
12574 Template->print(OS);
12575 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12576 << FunctionProto;
12577}
12578
12579/// Generates a 'note' diagnostic for an overload candidate. We've
12580/// already generated a primary error at the call site.
12581///
12582/// It really does need to be a single diagnostic with its caret
12583/// pointed at the candidate declaration. Yes, this creates some
12584/// major challenges of technical writing. Yes, this makes pointing
12585/// out problems with specific arguments quite awkward. It's still
12586/// better than generating twenty screens of text for every failed
12587/// overload.
12588///
12589/// It would be great to be able to express per-candidate problems
12590/// more richly for those diagnostic clients that cared, but we'd
12591/// still have to be just as careful with the default diagnostics.
12592/// \param CtorDestAS Addr space of object being constructed (for ctor
12593/// candidates only).
12595 unsigned NumArgs,
12596 bool TakingCandidateAddress,
12597 LangAS CtorDestAS = LangAS::Default) {
12598 assert(Cand->Function && "Candidate must be a function");
12599 FunctionDecl *Fn = Cand->Function;
12601 return;
12602
12603 // There is no physical candidate declaration to point to for OpenCL builtins.
12604 // Except for failed conversions, the notes are identical for each candidate,
12605 // so do not generate such notes.
12606 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12608 return;
12609
12610 // Skip implicit member functions when trying to resolve
12611 // the address of a an overload set for a function pointer.
12612 if (Cand->TookAddressOfOverload &&
12613 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12614 return;
12615
12616 // Note deleted candidates, but only if they're viable.
12617 if (Cand->Viable) {
12618 if (Fn->isDeleted()) {
12619 std::string FnDesc;
12620 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12621 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12622 Cand->getRewriteKind(), FnDesc);
12623
12624 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12625 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12626 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12627 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12628 return;
12629 }
12630
12631 // We don't really have anything else to say about viable candidates.
12632 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12633 return;
12634 }
12635
12636 // If this is a synthesized deduction guide we're deducing against, add a note
12637 // for it. These deduction guides are not explicitly spelled in the source
12638 // code, so simply printing a deduction failure note mentioning synthesized
12639 // template parameters or pointing to the header of the surrounding RecordDecl
12640 // would be confusing.
12641 //
12642 // We prefer adding such notes at the end of the deduction failure because
12643 // duplicate code snippets appearing in the diagnostic would likely become
12644 // noisy.
12645 auto _ = llvm::make_scope_exit([&] { NoteImplicitDeductionGuide(S, Fn); });
12646
12647 switch (Cand->FailureKind) {
12650 return DiagnoseArityMismatch(S, Cand, NumArgs);
12651
12653 return DiagnoseBadDeduction(S, Cand, NumArgs,
12654 TakingCandidateAddress);
12655
12657 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12658 << (Fn->getPrimaryTemplate() ? 1 : 0);
12659 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12660 return;
12661 }
12662
12664 Qualifiers QualsForPrinting;
12665 QualsForPrinting.setAddressSpace(CtorDestAS);
12666 S.Diag(Fn->getLocation(),
12667 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12668 << QualsForPrinting;
12669 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12670 return;
12671 }
12672
12676 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12677
12679 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12680 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12681 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12682 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12683
12684 // FIXME: this currently happens when we're called from SemaInit
12685 // when user-conversion overload fails. Figure out how to handle
12686 // those conditions and diagnose them well.
12687 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12688 }
12689
12691 return DiagnoseBadTarget(S, Cand);
12692
12693 case ovl_fail_enable_if:
12694 return DiagnoseFailedEnableIfAttr(S, Cand);
12695
12696 case ovl_fail_explicit:
12697 return DiagnoseFailedExplicitSpec(S, Cand);
12698
12700 // It's generally not interesting to note copy/move constructors here.
12701 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12702 return;
12703 S.Diag(Fn->getLocation(),
12704 diag::note_ovl_candidate_inherited_constructor_slice)
12705 << (Fn->getPrimaryTemplate() ? 1 : 0)
12706 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12707 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12708 return;
12709
12711 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
12712 (void)Available;
12713 assert(!Available);
12714 break;
12715 }
12717 // Do nothing, these should simply be ignored.
12718 break;
12719
12721 std::string FnDesc;
12722 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12723 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12724 Cand->getRewriteKind(), FnDesc);
12725
12726 S.Diag(Fn->getLocation(),
12727 diag::note_ovl_candidate_constraints_not_satisfied)
12728 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12729 << FnDesc /* Ignored */;
12730 ConstraintSatisfaction Satisfaction;
12731 if (S.CheckFunctionConstraints(Fn, Satisfaction))
12732 break;
12733 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12734 }
12735 }
12736}
12737
12740 return;
12741
12742 // Desugar the type of the surrogate down to a function type,
12743 // retaining as many typedefs as possible while still showing
12744 // the function type (and, therefore, its parameter types).
12745 QualType FnType = Cand->Surrogate->getConversionType();
12746 bool isLValueReference = false;
12747 bool isRValueReference = false;
12748 bool isPointer = false;
12749 if (const LValueReferenceType *FnTypeRef =
12750 FnType->getAs<LValueReferenceType>()) {
12751 FnType = FnTypeRef->getPointeeType();
12752 isLValueReference = true;
12753 } else if (const RValueReferenceType *FnTypeRef =
12754 FnType->getAs<RValueReferenceType>()) {
12755 FnType = FnTypeRef->getPointeeType();
12756 isRValueReference = true;
12757 }
12758 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12759 FnType = FnTypePtr->getPointeeType();
12760 isPointer = true;
12761 }
12762 // Desugar down to a function type.
12763 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12764 // Reconstruct the pointer/reference as appropriate.
12765 if (isPointer) FnType = S.Context.getPointerType(FnType);
12766 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
12767 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
12768
12769 if (!Cand->Viable &&
12771 S.Diag(Cand->Surrogate->getLocation(),
12772 diag::note_ovl_surrogate_constraints_not_satisfied)
12773 << Cand->Surrogate;
12774 ConstraintSatisfaction Satisfaction;
12775 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12776 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12777 } else {
12778 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
12779 << FnType;
12780 }
12781}
12782
12783static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12784 SourceLocation OpLoc,
12785 OverloadCandidate *Cand) {
12786 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12787 std::string TypeStr("operator");
12788 TypeStr += Opc;
12789 TypeStr += "(";
12790 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12791 if (Cand->Conversions.size() == 1) {
12792 TypeStr += ")";
12793 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12794 } else {
12795 TypeStr += ", ";
12796 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12797 TypeStr += ")";
12798 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12799 }
12800}
12801
12803 OverloadCandidate *Cand) {
12804 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12805 if (ICS.isBad()) break; // all meaningless after first invalid
12806 if (!ICS.isAmbiguous()) continue;
12807
12809 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
12810 }
12811}
12812
12814 if (Cand->Function)
12815 return Cand->Function->getLocation();
12816 if (Cand->IsSurrogate)
12817 return Cand->Surrogate->getLocation();
12818 return SourceLocation();
12819}
12820
12821static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12822 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12826 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12827
12831 return 1;
12832
12835 return 2;
12836
12844 return 3;
12845
12847 return 4;
12848
12850 return 5;
12851
12854 return 6;
12855 }
12856 llvm_unreachable("Unhandled deduction result");
12857}
12858
12859namespace {
12860
12861struct CompareOverloadCandidatesForDisplay {
12862 Sema &S;
12864 size_t NumArgs;
12866
12867 CompareOverloadCandidatesForDisplay(
12868 Sema &S, SourceLocation Loc, size_t NArgs,
12870 : S(S), NumArgs(NArgs), CSK(CSK) {}
12871
12872 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12873 // If there are too many or too few arguments, that's the high-order bit we
12874 // want to sort by, even if the immediate failure kind was something else.
12875 if (C->FailureKind == ovl_fail_too_many_arguments ||
12876 C->FailureKind == ovl_fail_too_few_arguments)
12877 return static_cast<OverloadFailureKind>(C->FailureKind);
12878
12879 if (C->Function) {
12880 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12882 if (NumArgs < C->Function->getMinRequiredArguments())
12884 }
12885
12886 return static_cast<OverloadFailureKind>(C->FailureKind);
12887 }
12888
12889 bool operator()(const OverloadCandidate *L,
12890 const OverloadCandidate *R) {
12891 // Fast-path this check.
12892 if (L == R) return false;
12893
12894 // Order first by viability.
12895 if (L->Viable) {
12896 if (!R->Viable) return true;
12897
12898 if (int Ord = CompareConversions(*L, *R))
12899 return Ord < 0;
12900 // Use other tie breakers.
12901 } else if (R->Viable)
12902 return false;
12903
12904 assert(L->Viable == R->Viable);
12905
12906 // Criteria by which we can sort non-viable candidates:
12907 if (!L->Viable) {
12908 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
12909 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
12910
12911 // 1. Arity mismatches come after other candidates.
12912 if (LFailureKind == ovl_fail_too_many_arguments ||
12913 LFailureKind == ovl_fail_too_few_arguments) {
12914 if (RFailureKind == ovl_fail_too_many_arguments ||
12915 RFailureKind == ovl_fail_too_few_arguments) {
12916 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
12917 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
12918 if (LDist == RDist) {
12919 if (LFailureKind == RFailureKind)
12920 // Sort non-surrogates before surrogates.
12921 return !L->IsSurrogate && R->IsSurrogate;
12922 // Sort candidates requiring fewer parameters than there were
12923 // arguments given after candidates requiring more parameters
12924 // than there were arguments given.
12925 return LFailureKind == ovl_fail_too_many_arguments;
12926 }
12927 return LDist < RDist;
12928 }
12929 return false;
12930 }
12931 if (RFailureKind == ovl_fail_too_many_arguments ||
12932 RFailureKind == ovl_fail_too_few_arguments)
12933 return true;
12934
12935 // 2. Bad conversions come first and are ordered by the number
12936 // of bad conversions and quality of good conversions.
12937 if (LFailureKind == ovl_fail_bad_conversion) {
12938 if (RFailureKind != ovl_fail_bad_conversion)
12939 return true;
12940
12941 // The conversion that can be fixed with a smaller number of changes,
12942 // comes first.
12943 unsigned numLFixes = L->Fix.NumConversionsFixed;
12944 unsigned numRFixes = R->Fix.NumConversionsFixed;
12945 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
12946 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
12947 if (numLFixes != numRFixes) {
12948 return numLFixes < numRFixes;
12949 }
12950
12951 // If there's any ordering between the defined conversions...
12952 if (int Ord = CompareConversions(*L, *R))
12953 return Ord < 0;
12954 } else if (RFailureKind == ovl_fail_bad_conversion)
12955 return false;
12956
12957 if (LFailureKind == ovl_fail_bad_deduction) {
12958 if (RFailureKind != ovl_fail_bad_deduction)
12959 return true;
12960
12962 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
12963 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
12964 if (LRank != RRank)
12965 return LRank < RRank;
12966 }
12967 } else if (RFailureKind == ovl_fail_bad_deduction)
12968 return false;
12969
12970 // TODO: others?
12971 }
12972
12973 // Sort everything else by location.
12976
12977 // Put candidates without locations (e.g. builtins) at the end.
12978 if (LLoc.isValid() && RLoc.isValid())
12979 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12980 if (LLoc.isValid() && !RLoc.isValid())
12981 return true;
12982 if (RLoc.isValid() && !LLoc.isValid())
12983 return false;
12984 assert(!LLoc.isValid() && !RLoc.isValid());
12985 // For builtins and other functions without locations, fallback to the order
12986 // in which they were added into the candidate set.
12987 return L < R;
12988 }
12989
12990private:
12991 struct ConversionSignals {
12992 unsigned KindRank = 0;
12994
12995 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
12996 ConversionSignals Sig;
12997 Sig.KindRank = Seq.getKindRank();
12998 if (Seq.isStandard())
12999 Sig.Rank = Seq.Standard.getRank();
13000 else if (Seq.isUserDefined())
13001 Sig.Rank = Seq.UserDefined.After.getRank();
13002 // We intend StaticObjectArgumentConversion to compare the same as
13003 // StandardConversion with ICR_ExactMatch rank.
13004 return Sig;
13005 }
13006
13007 static ConversionSignals ForObjectArgument() {
13008 // We intend StaticObjectArgumentConversion to compare the same as
13009 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13010 return {};
13011 }
13012 };
13013
13014 // Returns -1 if conversions in L are considered better.
13015 // 0 if they are considered indistinguishable.
13016 // 1 if conversions in R are better.
13017 int CompareConversions(const OverloadCandidate &L,
13018 const OverloadCandidate &R) {
13019 // We cannot use `isBetterOverloadCandidate` because it is defined
13020 // according to the C++ standard and provides a partial order, but we need
13021 // a total order as this function is used in sort.
13022 assert(L.Conversions.size() == R.Conversions.size());
13023 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13024 auto LS = L.IgnoreObjectArgument && I == 0
13025 ? ConversionSignals::ForObjectArgument()
13026 : ConversionSignals::ForSequence(L.Conversions[I]);
13027 auto RS = R.IgnoreObjectArgument
13028 ? ConversionSignals::ForObjectArgument()
13029 : ConversionSignals::ForSequence(R.Conversions[I]);
13030 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
13031 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
13032 ? -1
13033 : 1;
13034 }
13035 // FIXME: find a way to compare templates for being more or less
13036 // specialized that provides a strict weak ordering.
13037 return 0;
13038 }
13039};
13040}
13041
13042/// CompleteNonViableCandidate - Normally, overload resolution only
13043/// computes up to the first bad conversion. Produces the FixIt set if
13044/// possible.
13045static void
13047 ArrayRef<Expr *> Args,
13049 assert(!Cand->Viable);
13050
13051 // Don't do anything on failures other than bad conversion.
13053 return;
13054
13055 // We only want the FixIts if all the arguments can be corrected.
13056 bool Unfixable = false;
13057 // Use a implicit copy initialization to check conversion fixes.
13059
13060 // Attempt to fix the bad conversion.
13061 unsigned ConvCount = Cand->Conversions.size();
13062 for (unsigned ConvIdx =
13063 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13064 : 0);
13065 /**/; ++ConvIdx) {
13066 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13067 if (Cand->Conversions[ConvIdx].isInitialized() &&
13068 Cand->Conversions[ConvIdx].isBad()) {
13069 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13070 break;
13071 }
13072 }
13073
13074 // FIXME: this should probably be preserved from the overload
13075 // operation somehow.
13076 bool SuppressUserConversions = false;
13077
13078 unsigned ConvIdx = 0;
13079 unsigned ArgIdx = 0;
13080 ArrayRef<QualType> ParamTypes;
13081 bool Reversed = Cand->isReversed();
13082
13083 if (Cand->IsSurrogate) {
13084 QualType ConvType
13086 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13087 ConvType = ConvPtrType->getPointeeType();
13088 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13089 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13090 ConvIdx = 1;
13091 } else if (Cand->Function) {
13092 ParamTypes =
13093 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13094 if (isa<CXXMethodDecl>(Cand->Function) &&
13095 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed &&
13097 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13098 ConvIdx = 1;
13100 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13102 OO_Subscript)
13103 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13104 ArgIdx = 1;
13105 }
13106 } else {
13107 // Builtin operator.
13108 assert(ConvCount <= 3);
13109 ParamTypes = Cand->BuiltinParamTypes;
13110 }
13111
13112 // Fill in the rest of the conversions.
13113 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13114 ConvIdx != ConvCount && ArgIdx < Args.size();
13115 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13116 if (Cand->Conversions[ConvIdx].isInitialized()) {
13117 // We've already checked this conversion.
13118 } else if (ParamIdx < ParamTypes.size()) {
13119 if (ParamTypes[ParamIdx]->isDependentType())
13120 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13121 Args[ArgIdx]->getType());
13122 else {
13123 Cand->Conversions[ConvIdx] =
13124 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
13125 SuppressUserConversions,
13126 /*InOverloadResolution=*/true,
13127 /*AllowObjCWritebackConversion=*/
13128 S.getLangOpts().ObjCAutoRefCount);
13129 // Store the FixIt in the candidate if it exists.
13130 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13131 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13132 }
13133 } else
13134 Cand->Conversions[ConvIdx].setEllipsis();
13135 }
13136}
13137
13140 SourceLocation OpLoc,
13141 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13142
13144
13145 // Sort the candidates by viability and position. Sorting directly would
13146 // be prohibitive, so we make a set of pointers and sort those.
13148 if (OCD == OCD_AllCandidates) Cands.reserve(size());
13149 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13150 Cand != LastCand; ++Cand) {
13151 if (!Filter(*Cand))
13152 continue;
13153 switch (OCD) {
13154 case OCD_AllCandidates:
13155 if (!Cand->Viable) {
13156 if (!Cand->Function && !Cand->IsSurrogate) {
13157 // This a non-viable builtin candidate. We do not, in general,
13158 // want to list every possible builtin candidate.
13159 continue;
13160 }
13161 CompleteNonViableCandidate(S, Cand, Args, Kind);
13162 }
13163 break;
13164
13166 if (!Cand->Viable)
13167 continue;
13168 break;
13169
13171 if (!Cand->Best)
13172 continue;
13173 break;
13174 }
13175
13176 Cands.push_back(Cand);
13177 }
13178
13179 llvm::stable_sort(
13180 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13181
13182 return Cands;
13183}
13184
13186 SourceLocation OpLoc) {
13187 bool DeferHint = false;
13188 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13189 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13190 // host device candidates.
13191 auto WrongSidedCands =
13192 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
13193 return (Cand.Viable == false &&
13195 (Cand.Function &&
13196 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13197 Cand.Function->template hasAttr<CUDADeviceAttr>());
13198 });
13199 DeferHint = !WrongSidedCands.empty();
13200 }
13201 return DeferHint;
13202}
13203
13204/// When overload resolution fails, prints diagnostic messages containing the
13205/// candidates in the candidate set.
13208 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13209 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13210
13211 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13212
13213 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
13214
13215 // In WebAssembly we don't want to emit further diagnostics if a table is
13216 // passed as an argument to a function.
13217 bool NoteCands = true;
13218 for (const Expr *Arg : Args) {
13219 if (Arg->getType()->isWebAssemblyTableType())
13220 NoteCands = false;
13221 }
13222
13223 if (NoteCands)
13224 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13225
13226 if (OCD == OCD_AmbiguousCandidates)
13228 {Candidates.begin(), Candidates.end()});
13229}
13230
13233 StringRef Opc, SourceLocation OpLoc) {
13234 bool ReportedAmbiguousConversions = false;
13235
13236 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13237 unsigned CandsShown = 0;
13238 auto I = Cands.begin(), E = Cands.end();
13239 for (; I != E; ++I) {
13240 OverloadCandidate *Cand = *I;
13241
13242 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13243 ShowOverloads == Ovl_Best) {
13244 break;
13245 }
13246 ++CandsShown;
13247
13248 if (Cand->Function)
13249 NoteFunctionCandidate(S, Cand, Args.size(),
13250 Kind == CSK_AddressOfOverloadSet, DestAS);
13251 else if (Cand->IsSurrogate)
13252 NoteSurrogateCandidate(S, Cand);
13253 else {
13254 assert(Cand->Viable &&
13255 "Non-viable built-in candidates are not added to Cands.");
13256 // Generally we only see ambiguities including viable builtin
13257 // operators if overload resolution got screwed up by an
13258 // ambiguous user-defined conversion.
13259 //
13260 // FIXME: It's quite possible for different conversions to see
13261 // different ambiguities, though.
13262 if (!ReportedAmbiguousConversions) {
13263 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13264 ReportedAmbiguousConversions = true;
13265 }
13266
13267 // If this is a viable builtin, print it.
13268 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13269 }
13270 }
13271
13272 // Inform S.Diags that we've shown an overload set with N elements. This may
13273 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13274 S.Diags.overloadCandidatesShown(CandsShown);
13275
13276 if (I != E)
13277 S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
13278 shouldDeferDiags(S, Args, OpLoc))
13279 << int(E - I);
13280}
13281
13282static SourceLocation
13284 return Cand->Specialization ? Cand->Specialization->getLocation()
13285 : SourceLocation();
13286}
13287
13288namespace {
13289struct CompareTemplateSpecCandidatesForDisplay {
13290 Sema &S;
13291 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13292
13293 bool operator()(const TemplateSpecCandidate *L,
13294 const TemplateSpecCandidate *R) {
13295 // Fast-path this check.
13296 if (L == R)
13297 return false;
13298
13299 // Assuming that both candidates are not matches...
13300
13301 // Sort by the ranking of deduction failures.
13305
13306 // Sort everything else by location.
13309
13310 // Put candidates without locations (e.g. builtins) at the end.
13311 if (LLoc.isInvalid())
13312 return false;
13313 if (RLoc.isInvalid())
13314 return true;
13315
13316 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13317 }
13318};
13319}
13320
13321/// Diagnose a template argument deduction failure.
13322/// We are treating these failures as overload failures due to bad
13323/// deductions.
13325 bool ForTakingAddress) {
13326 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
13327 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
13328}
13329
13330void TemplateSpecCandidateSet::destroyCandidates() {
13331 for (iterator i = begin(), e = end(); i != e; ++i) {
13332 i->DeductionFailure.Destroy();
13333 }
13334}
13335
13337 destroyCandidates();
13338 Candidates.clear();
13339}
13340
13341/// NoteCandidates - When no template specialization match is found, prints
13342/// diagnostic messages containing the non-matching specializations that form
13343/// the candidate set.
13344/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13345/// OCD == OCD_AllCandidates and Cand->Viable == false.
13347 // Sort the candidates by position (assuming no candidate is a match).
13348 // Sorting directly would be prohibitive, so we make a set of pointers
13349 // and sort those.
13351 Cands.reserve(size());
13352 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13353 if (Cand->Specialization)
13354 Cands.push_back(Cand);
13355 // Otherwise, this is a non-matching builtin candidate. We do not,
13356 // in general, want to list every possible builtin candidate.
13357 }
13358
13359 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
13360
13361 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13362 // for generalization purposes (?).
13363 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13364
13366 unsigned CandsShown = 0;
13367 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13368 TemplateSpecCandidate *Cand = *I;
13369
13370 // Set an arbitrary limit on the number of candidates we'll spam
13371 // the user with. FIXME: This limit should depend on details of the
13372 // candidate list.
13373 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13374 break;
13375 ++CandsShown;
13376
13377 assert(Cand->Specialization &&
13378 "Non-matching built-in candidates are not added to Cands.");
13379 Cand->NoteDeductionFailure(S, ForTakingAddress);
13380 }
13381
13382 if (I != E)
13383 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
13384}
13385
13386// [PossiblyAFunctionType] --> [Return]
13387// NonFunctionType --> NonFunctionType
13388// R (A) --> R(A)
13389// R (*)(A) --> R (A)
13390// R (&)(A) --> R (A)
13391// R (S::*)(A) --> R (A)
13393 QualType Ret = PossiblyAFunctionType;
13394 if (const PointerType *ToTypePtr =
13395 PossiblyAFunctionType->getAs<PointerType>())
13396 Ret = ToTypePtr->getPointeeType();
13397 else if (const ReferenceType *ToTypeRef =
13398 PossiblyAFunctionType->getAs<ReferenceType>())
13399 Ret = ToTypeRef->getPointeeType();
13400 else if (const MemberPointerType *MemTypePtr =
13401 PossiblyAFunctionType->getAs<MemberPointerType>())
13402 Ret = MemTypePtr->getPointeeType();
13403 Ret =
13404 Context.getCanonicalType(Ret).getUnqualifiedType();
13405 return Ret;
13406}
13407
13409 bool Complain = true) {
13410 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13411 S.DeduceReturnType(FD, Loc, Complain))
13412 return true;
13413
13414 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13415 if (S.getLangOpts().CPlusPlus17 &&
13416 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
13417 !S.ResolveExceptionSpec(Loc, FPT))
13418 return true;
13419
13420 return false;
13421}
13422
13423namespace {
13424// A helper class to help with address of function resolution
13425// - allows us to avoid passing around all those ugly parameters
13426class AddressOfFunctionResolver {
13427 Sema& S;
13428 Expr* SourceExpr;
13429 const QualType& TargetType;
13430 QualType TargetFunctionType; // Extracted function type from target type
13431
13432 bool Complain;
13433 //DeclAccessPair& ResultFunctionAccessPair;
13434 ASTContext& Context;
13435
13436 bool TargetTypeIsNonStaticMemberFunction;
13437 bool FoundNonTemplateFunction;
13438 bool StaticMemberFunctionFromBoundPointer;
13439 bool HasComplained;
13440
13441 OverloadExpr::FindResult OvlExprInfo;
13442 OverloadExpr *OvlExpr;
13443 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13445 TemplateSpecCandidateSet FailedCandidates;
13446
13447public:
13448 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13449 const QualType &TargetType, bool Complain)
13450 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13451 Complain(Complain), Context(S.getASTContext()),
13452 TargetTypeIsNonStaticMemberFunction(
13453 !!TargetType->getAs<MemberPointerType>()),
13454 FoundNonTemplateFunction(false),
13455 StaticMemberFunctionFromBoundPointer(false),
13456 HasComplained(false),
13457 OvlExprInfo(OverloadExpr::find(SourceExpr)),
13458 OvlExpr(OvlExprInfo.Expression),
13459 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13460 ExtractUnqualifiedFunctionTypeFromTargetType();
13461
13462 if (TargetFunctionType->isFunctionType()) {
13463 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
13464 if (!UME->isImplicitAccess() &&
13466 StaticMemberFunctionFromBoundPointer = true;
13467 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13468 DeclAccessPair dap;
13470 OvlExpr, false, &dap)) {
13471 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
13472 if (!Method->isStatic()) {
13473 // If the target type is a non-function type and the function found
13474 // is a non-static member function, pretend as if that was the
13475 // target, it's the only possible type to end up with.
13476 TargetTypeIsNonStaticMemberFunction = true;
13477
13478 // And skip adding the function if its not in the proper form.
13479 // We'll diagnose this due to an empty set of functions.
13480 if (!OvlExprInfo.HasFormOfMemberPointer)
13481 return;
13482 }
13483
13484 Matches.push_back(std::make_pair(dap, Fn));
13485 }
13486 return;
13487 }
13488
13489 if (OvlExpr->hasExplicitTemplateArgs())
13490 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
13491
13492 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13493 // C++ [over.over]p4:
13494 // If more than one function is selected, [...]
13495 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13496 if (FoundNonTemplateFunction) {
13497 EliminateAllTemplateMatches();
13498 EliminateLessPartialOrderingConstrainedMatches();
13499 } else
13500 EliminateAllExceptMostSpecializedTemplate();
13501 }
13502 }
13503
13504 if (S.getLangOpts().CUDA && Matches.size() > 1)
13505 EliminateSuboptimalCudaMatches();
13506 }
13507
13508 bool hasComplained() const { return HasComplained; }
13509
13510private:
13511 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13512 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
13513 S.IsFunctionConversion(FD->getType(), TargetFunctionType);
13514 }
13515
13516 /// \return true if A is considered a better overload candidate for the
13517 /// desired type than B.
13518 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13519 // If A doesn't have exactly the correct type, we don't want to classify it
13520 // as "better" than anything else. This way, the user is required to
13521 // disambiguate for us if there are multiple candidates and no exact match.
13522 return candidateHasExactlyCorrectType(A) &&
13523 (!candidateHasExactlyCorrectType(B) ||
13524 compareEnableIfAttrs(S, A, B) == Comparison::Better);
13525 }
13526
13527 /// \return true if we were able to eliminate all but one overload candidate,
13528 /// false otherwise.
13529 bool eliminiateSuboptimalOverloadCandidates() {
13530 // Same algorithm as overload resolution -- one pass to pick the "best",
13531 // another pass to be sure that nothing is better than the best.
13532 auto Best = Matches.begin();
13533 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13534 if (isBetterCandidate(I->second, Best->second))
13535 Best = I;
13536
13537 const FunctionDecl *BestFn = Best->second;
13538 auto IsBestOrInferiorToBest = [this, BestFn](
13539 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13540 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
13541 };
13542
13543 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13544 // option, so we can potentially give the user a better error
13545 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
13546 return false;
13547 Matches[0] = *Best;
13548 Matches.resize(1);
13549 return true;
13550 }
13551
13552 bool isTargetTypeAFunction() const {
13553 return TargetFunctionType->isFunctionType();
13554 }
13555
13556 // [ToType] [Return]
13557
13558 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13559 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13560 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13561 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13562 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13563 }
13564
13565 // return true if any matching specializations were found
13566 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13567 const DeclAccessPair& CurAccessFunPair) {
13568 if (CXXMethodDecl *Method
13569 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13570 // Skip non-static function templates when converting to pointer, and
13571 // static when converting to member pointer.
13572 bool CanConvertToFunctionPointer =
13573 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13574 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13575 return false;
13576 }
13577 else if (TargetTypeIsNonStaticMemberFunction)
13578 return false;
13579
13580 // C++ [over.over]p2:
13581 // If the name is a function template, template argument deduction is
13582 // done (14.8.2.2), and if the argument deduction succeeds, the
13583 // resulting template argument list is used to generate a single
13584 // function template specialization, which is added to the set of
13585 // overloaded functions considered.
13586 FunctionDecl *Specialization = nullptr;
13587 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13589 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13590 Specialization, Info, /*IsAddressOfFunction*/ true);
13591 Result != TemplateDeductionResult::Success) {
13592 // Make a note of the failed deduction for diagnostics.
13593 FailedCandidates.addCandidate()
13594 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13595 MakeDeductionFailureInfo(Context, Result, Info));
13596 return false;
13597 }
13598
13599 // Template argument deduction ensures that we have an exact match or
13600 // compatible pointer-to-function arguments that would be adjusted by ICS.
13601 // This function template specicalization works.
13603 Context.getCanonicalType(Specialization->getType()),
13604 Context.getCanonicalType(TargetFunctionType)));
13605
13607 return false;
13608
13609 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13610 return true;
13611 }
13612
13613 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13614 const DeclAccessPair& CurAccessFunPair) {
13615 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13616 // Skip non-static functions when converting to pointer, and static
13617 // when converting to member pointer.
13618 bool CanConvertToFunctionPointer =
13619 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13620 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13621 return false;
13622 }
13623 else if (TargetTypeIsNonStaticMemberFunction)
13624 return false;
13625
13626 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13627 if (S.getLangOpts().CUDA) {
13628 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13629 if (!(Caller && Caller->isImplicit()) &&
13630 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13631 return false;
13632 }
13633 if (FunDecl->isMultiVersion()) {
13634 const auto *TA = FunDecl->getAttr<TargetAttr>();
13635 if (TA && !TA->isDefaultVersion())
13636 return false;
13637 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13638 if (TVA && !TVA->isDefaultVersion())
13639 return false;
13640 }
13641
13642 // If any candidate has a placeholder return type, trigger its deduction
13643 // now.
13644 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13645 Complain)) {
13646 HasComplained |= Complain;
13647 return false;
13648 }
13649
13650 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13651 return false;
13652
13653 // If we're in C, we need to support types that aren't exactly identical.
13654 if (!S.getLangOpts().CPlusPlus ||
13655 candidateHasExactlyCorrectType(FunDecl)) {
13656 Matches.push_back(std::make_pair(
13657 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13658 FoundNonTemplateFunction = true;
13659 return true;
13660 }
13661 }
13662
13663 return false;
13664 }
13665
13666 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13667 bool Ret = false;
13668
13669 // If the overload expression doesn't have the form of a pointer to
13670 // member, don't try to convert it to a pointer-to-member type.
13671 if (IsInvalidFormOfPointerToMemberFunction())
13672 return false;
13673
13674 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13675 E = OvlExpr->decls_end();
13676 I != E; ++I) {
13677 // Look through any using declarations to find the underlying function.
13678 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13679
13680 // C++ [over.over]p3:
13681 // Non-member functions and static member functions match
13682 // targets of type "pointer-to-function" or "reference-to-function."
13683 // Nonstatic member functions match targets of
13684 // type "pointer-to-member-function."
13685 // Note that according to DR 247, the containing class does not matter.
13687 = dyn_cast<FunctionTemplateDecl>(Fn)) {
13688 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13689 Ret = true;
13690 }
13691 // If we have explicit template arguments supplied, skip non-templates.
13692 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13693 AddMatchingNonTemplateFunction(Fn, I.getPair()))
13694 Ret = true;
13695 }
13696 assert(Ret || Matches.empty());
13697 return Ret;
13698 }
13699
13700 void EliminateAllExceptMostSpecializedTemplate() {
13701 // [...] and any given function template specialization F1 is
13702 // eliminated if the set contains a second function template
13703 // specialization whose function template is more specialized
13704 // than the function template of F1 according to the partial
13705 // ordering rules of 14.5.5.2.
13706
13707 // The algorithm specified above is quadratic. We instead use a
13708 // two-pass algorithm (similar to the one used to identify the
13709 // best viable function in an overload set) that identifies the
13710 // best function template (if it exists).
13711
13712 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13713 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13714 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13715
13716 // TODO: It looks like FailedCandidates does not serve much purpose
13717 // here, since the no_viable diagnostic has index 0.
13719 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13720 SourceExpr->getBeginLoc(), S.PDiag(),
13721 S.PDiag(diag::err_addr_ovl_ambiguous)
13722 << Matches[0].second->getDeclName(),
13723 S.PDiag(diag::note_ovl_candidate)
13724 << (unsigned)oc_function << (unsigned)ocs_described_template,
13725 Complain, TargetFunctionType);
13726
13727 if (Result != MatchesCopy.end()) {
13728 // Make it the first and only element
13729 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13730 Matches[0].second = cast<FunctionDecl>(*Result);
13731 Matches.resize(1);
13732 } else
13733 HasComplained |= Complain;
13734 }
13735
13736 void EliminateAllTemplateMatches() {
13737 // [...] any function template specializations in the set are
13738 // eliminated if the set also contains a non-template function, [...]
13739 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13740 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13741 ++I;
13742 else {
13743 Matches[I] = Matches[--N];
13744 Matches.resize(N);
13745 }
13746 }
13747 }
13748
13749 void EliminateLessPartialOrderingConstrainedMatches() {
13750 // C++ [over.over]p5:
13751 // [...] Any given non-template function F0 is eliminated if the set
13752 // contains a second non-template function that is more
13753 // partial-ordering-constrained than F0. [...]
13754 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
13755 "Call EliminateAllTemplateMatches() first");
13757 Results.push_back(Matches[0]);
13758 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
13759 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
13761 S, Matches[I].second, Results[0].second,
13762 /*IsFn1Reversed=*/false,
13763 /*IsFn2Reversed=*/false);
13764 if (!F) {
13765 Results.push_back(Matches[I]);
13766 continue;
13767 }
13768 if (F == Matches[I].second) {
13769 Results.clear();
13770 Results.push_back(Matches[I]);
13771 }
13772 }
13773 std::swap(Matches, Results);
13774 }
13775
13776 void EliminateSuboptimalCudaMatches() {
13777 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
13778 Matches);
13779 }
13780
13781public:
13782 void ComplainNoMatchesFound() const {
13783 assert(Matches.empty());
13784 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
13785 << OvlExpr->getName() << TargetFunctionType
13786 << OvlExpr->getSourceRange();
13787 if (FailedCandidates.empty())
13788 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13789 /*TakingAddress=*/true);
13790 else {
13791 // We have some deduction failure messages. Use them to diagnose
13792 // the function templates, and diagnose the non-template candidates
13793 // normally.
13794 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13795 IEnd = OvlExpr->decls_end();
13796 I != IEnd; ++I)
13797 if (FunctionDecl *Fun =
13798 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
13800 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
13801 /*TakingAddress=*/true);
13802 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
13803 }
13804 }
13805
13806 bool IsInvalidFormOfPointerToMemberFunction() const {
13807 return TargetTypeIsNonStaticMemberFunction &&
13808 !OvlExprInfo.HasFormOfMemberPointer;
13809 }
13810
13811 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13812 // TODO: Should we condition this on whether any functions might
13813 // have matched, or is it more appropriate to do that in callers?
13814 // TODO: a fixit wouldn't hurt.
13815 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
13816 << TargetType << OvlExpr->getSourceRange();
13817 }
13818
13819 bool IsStaticMemberFunctionFromBoundPointer() const {
13820 return StaticMemberFunctionFromBoundPointer;
13821 }
13822
13823 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13824 S.Diag(OvlExpr->getBeginLoc(),
13825 diag::err_invalid_form_pointer_member_function)
13826 << OvlExpr->getSourceRange();
13827 }
13828
13829 void ComplainOfInvalidConversion() const {
13830 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
13831 << OvlExpr->getName() << TargetType;
13832 }
13833
13834 void ComplainMultipleMatchesFound() const {
13835 assert(Matches.size() > 1);
13836 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
13837 << OvlExpr->getName() << OvlExpr->getSourceRange();
13838 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13839 /*TakingAddress=*/true);
13840 }
13841
13842 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13843
13844 int getNumMatches() const { return Matches.size(); }
13845
13846 FunctionDecl* getMatchingFunctionDecl() const {
13847 if (Matches.size() != 1) return nullptr;
13848 return Matches[0].second;
13849 }
13850
13851 const DeclAccessPair* getMatchingFunctionAccessPair() const {
13852 if (Matches.size() != 1) return nullptr;
13853 return &Matches[0].first;
13854 }
13855};
13856}
13857
13860 QualType TargetType,
13861 bool Complain,
13862 DeclAccessPair &FoundResult,
13863 bool *pHadMultipleCandidates) {
13864 assert(AddressOfExpr->getType() == Context.OverloadTy);
13865
13866 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13867 Complain);
13868 int NumMatches = Resolver.getNumMatches();
13869 FunctionDecl *Fn = nullptr;
13870 bool ShouldComplain = Complain && !Resolver.hasComplained();
13871 if (NumMatches == 0 && ShouldComplain) {
13872 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13873 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13874 else
13875 Resolver.ComplainNoMatchesFound();
13876 }
13877 else if (NumMatches > 1 && ShouldComplain)
13878 Resolver.ComplainMultipleMatchesFound();
13879 else if (NumMatches == 1) {
13880 Fn = Resolver.getMatchingFunctionDecl();
13881 assert(Fn);
13882 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13883 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
13884 FoundResult = *Resolver.getMatchingFunctionAccessPair();
13885 if (Complain) {
13886 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13887 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13888 else
13889 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
13890 }
13891 }
13892
13893 if (pHadMultipleCandidates)
13894 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13895 return Fn;
13896}
13897
13901 OverloadExpr *Ovl = R.Expression;
13902 bool IsResultAmbiguous = false;
13903 FunctionDecl *Result = nullptr;
13904 DeclAccessPair DAP;
13905 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
13906
13907 // Return positive for better, negative for worse, 0 for equal preference.
13908 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
13909 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
13910 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
13911 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
13912 };
13913
13914 // Don't use the AddressOfResolver because we're specifically looking for
13915 // cases where we have one overload candidate that lacks
13916 // enable_if/pass_object_size/...
13917 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
13918 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
13919 if (!FD)
13920 return nullptr;
13921
13923 continue;
13924
13925 // If we found a better result, update Result.
13926 auto FoundBetter = [&]() {
13927 IsResultAmbiguous = false;
13928 DAP = I.getPair();
13929 Result = FD;
13930 };
13931
13932 // We have more than one result - see if it is more
13933 // partial-ordering-constrained than the previous one.
13934 if (Result) {
13935 // Check CUDA preference first. If the candidates have differennt CUDA
13936 // preference, choose the one with higher CUDA preference. Otherwise,
13937 // choose the one with more constraints.
13938 if (getLangOpts().CUDA) {
13939 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
13940 // FD has different preference than Result.
13941 if (PreferenceByCUDA != 0) {
13942 // FD is more preferable than Result.
13943 if (PreferenceByCUDA > 0)
13944 FoundBetter();
13945 continue;
13946 }
13947 }
13948 // FD has the same CUDA preference than Result. Continue to check
13949 // constraints.
13950
13951 // C++ [over.over]p5:
13952 // [...] Any given non-template function F0 is eliminated if the set
13953 // contains a second non-template function that is more
13954 // partial-ordering-constrained than F0 [...]
13955 FunctionDecl *MoreConstrained =
13957 /*IsFn1Reversed=*/false,
13958 /*IsFn2Reversed=*/false);
13959 if (MoreConstrained != FD) {
13960 if (!MoreConstrained) {
13961 IsResultAmbiguous = true;
13962 AmbiguousDecls.push_back(FD);
13963 }
13964 continue;
13965 }
13966 // FD is more constrained - replace Result with it.
13967 }
13968 FoundBetter();
13969 }
13970
13971 if (IsResultAmbiguous)
13972 return nullptr;
13973
13974 if (Result) {
13975 // We skipped over some ambiguous declarations which might be ambiguous with
13976 // the selected result.
13977 for (FunctionDecl *Skipped : AmbiguousDecls) {
13978 // If skipped candidate has different CUDA preference than the result,
13979 // there is no ambiguity. Otherwise check whether they have different
13980 // constraints.
13981 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
13982 continue;
13983 if (!getMoreConstrainedFunction(Skipped, Result))
13984 return nullptr;
13985 }
13986 Pair = DAP;
13987 }
13988 return Result;
13989}
13990
13992 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
13993 Expr *E = SrcExpr.get();
13994 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
13995
13996 DeclAccessPair DAP;
13997 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
13998 if (!Found || Found->isCPUDispatchMultiVersion() ||
13999 Found->isCPUSpecificMultiVersion())
14000 return false;
14001
14002 // Emitting multiple diagnostics for a function that is both inaccessible and
14003 // unavailable is consistent with our behavior elsewhere. So, always check
14004 // for both.
14005 DiagnoseUseOfDecl(Found, E->getExprLoc());
14006 CheckAddressOfMemberAccess(E, DAP);
14007 ExprResult Res = FixOverloadedFunctionReference(E, DAP, Found);
14008 if (Res.isInvalid())
14009 return false;
14010 Expr *Fixed = Res.get();
14011 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14012 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
14013 else
14014 SrcExpr = Fixed;
14015 return true;
14016}
14017
14019 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14020 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14021 // C++ [over.over]p1:
14022 // [...] [Note: any redundant set of parentheses surrounding the
14023 // overloaded function name is ignored (5.1). ]
14024 // C++ [over.over]p1:
14025 // [...] The overloaded function name can be preceded by the &
14026 // operator.
14027
14028 // If we didn't actually find any template-ids, we're done.
14029 if (!ovl->hasExplicitTemplateArgs())
14030 return nullptr;
14031
14032 TemplateArgumentListInfo ExplicitTemplateArgs;
14033 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
14034
14035 // Look through all of the overloaded functions, searching for one
14036 // whose type matches exactly.
14037 FunctionDecl *Matched = nullptr;
14038 for (UnresolvedSetIterator I = ovl->decls_begin(),
14039 E = ovl->decls_end(); I != E; ++I) {
14040 // C++0x [temp.arg.explicit]p3:
14041 // [...] In contexts where deduction is done and fails, or in contexts
14042 // where deduction is not done, if a template argument list is
14043 // specified and it, along with any default template arguments,
14044 // identifies a single function template specialization, then the
14045 // template-id is an lvalue for the function template specialization.
14047 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
14048 if (!FunctionTemplate)
14049 continue;
14050
14051 // C++ [over.over]p2:
14052 // If the name is a function template, template argument deduction is
14053 // done (14.8.2.2), and if the argument deduction succeeds, the
14054 // resulting template argument list is used to generate a single
14055 // function template specialization, which is added to the set of
14056 // overloaded functions considered.
14057 FunctionDecl *Specialization = nullptr;
14058 TemplateDeductionInfo Info(ovl->getNameLoc());
14060 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
14061 /*IsAddressOfFunction*/ true);
14063 // Make a note of the failed deduction for diagnostics.
14064 if (FailedTSC)
14065 FailedTSC->addCandidate().set(
14066 I.getPair(), FunctionTemplate->getTemplatedDecl(),
14067 MakeDeductionFailureInfo(Context, Result, Info));
14068 continue;
14069 }
14070
14071 assert(Specialization && "no specialization and no error?");
14072
14073 // C++ [temp.deduct.call]p6:
14074 // [...] If all successful deductions yield the same deduced A, that
14075 // deduced A is the result of deduction; otherwise, the parameter is
14076 // treated as a non-deduced context.
14077 if (Matched) {
14078 if (ForTypeDeduction &&
14079 isSameOrCompatibleFunctionType(Matched->getType(),
14080 Specialization->getType()))
14081 continue;
14082 // Multiple matches; we can't resolve to a single declaration.
14083 if (Complain) {
14084 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
14085 << ovl->getName();
14086 NoteAllOverloadCandidates(ovl);
14087 }
14088 return nullptr;
14089 }
14090
14091 Matched = Specialization;
14092 if (FoundResult) *FoundResult = I.getPair();
14093 }
14094
14095 if (Matched &&
14096 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
14097 return nullptr;
14098
14099 return Matched;
14100}
14101
14103 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14104 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14105 unsigned DiagIDForComplaining) {
14106 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14107
14109
14110 DeclAccessPair found;
14111 ExprResult SingleFunctionExpression;
14112 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
14113 ovl.Expression, /*complain*/ false, &found)) {
14114 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
14115 SrcExpr = ExprError();
14116 return true;
14117 }
14118
14119 // It is only correct to resolve to an instance method if we're
14120 // resolving a form that's permitted to be a pointer to member.
14121 // Otherwise we'll end up making a bound member expression, which
14122 // is illegal in all the contexts we resolve like this.
14123 if (!ovl.HasFormOfMemberPointer &&
14124 isa<CXXMethodDecl>(fn) &&
14125 cast<CXXMethodDecl>(fn)->isInstance()) {
14126 if (!complain) return false;
14127
14128 Diag(ovl.Expression->getExprLoc(),
14129 diag::err_bound_member_function)
14130 << 0 << ovl.Expression->getSourceRange();
14131
14132 // TODO: I believe we only end up here if there's a mix of
14133 // static and non-static candidates (otherwise the expression
14134 // would have 'bound member' type, not 'overload' type).
14135 // Ideally we would note which candidate was chosen and why
14136 // the static candidates were rejected.
14137 SrcExpr = ExprError();
14138 return true;
14139 }
14140
14141 // Fix the expression to refer to 'fn'.
14142 SingleFunctionExpression =
14143 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
14144
14145 // If desired, do function-to-pointer decay.
14146 if (doFunctionPointerConversion) {
14147 SingleFunctionExpression =
14148 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
14149 if (SingleFunctionExpression.isInvalid()) {
14150 SrcExpr = ExprError();
14151 return true;
14152 }
14153 }
14154 }
14155
14156 if (!SingleFunctionExpression.isUsable()) {
14157 if (complain) {
14158 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
14159 << ovl.Expression->getName()
14160 << DestTypeForComplaining
14161 << OpRangeForComplaining
14163 NoteAllOverloadCandidates(SrcExpr.get());
14164
14165 SrcExpr = ExprError();
14166 return true;
14167 }
14168
14169 return false;
14170 }
14171
14172 SrcExpr = SingleFunctionExpression;
14173 return true;
14174}
14175
14176/// Add a single candidate to the overload set.
14178 DeclAccessPair FoundDecl,
14179 TemplateArgumentListInfo *ExplicitTemplateArgs,
14180 ArrayRef<Expr *> Args,
14181 OverloadCandidateSet &CandidateSet,
14182 bool PartialOverloading,
14183 bool KnownValid) {
14184 NamedDecl *Callee = FoundDecl.getDecl();
14185 if (isa<UsingShadowDecl>(Callee))
14186 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
14187
14188 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
14189 if (ExplicitTemplateArgs) {
14190 assert(!KnownValid && "Explicit template arguments?");
14191 return;
14192 }
14193 // Prevent ill-formed function decls to be added as overload candidates.
14194 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
14195 return;
14196
14197 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
14198 /*SuppressUserConversions=*/false,
14199 PartialOverloading);
14200 return;
14201 }
14202
14203 if (FunctionTemplateDecl *FuncTemplate
14204 = dyn_cast<FunctionTemplateDecl>(Callee)) {
14205 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
14206 ExplicitTemplateArgs, Args, CandidateSet,
14207 /*SuppressUserConversions=*/false,
14208 PartialOverloading);
14209 return;
14210 }
14211
14212 assert(!KnownValid && "unhandled case in overloaded call candidate");
14213}
14214
14216 ArrayRef<Expr *> Args,
14217 OverloadCandidateSet &CandidateSet,
14218 bool PartialOverloading) {
14219
14220#ifndef NDEBUG
14221 // Verify that ArgumentDependentLookup is consistent with the rules
14222 // in C++0x [basic.lookup.argdep]p3:
14223 //
14224 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14225 // and let Y be the lookup set produced by argument dependent
14226 // lookup (defined as follows). If X contains
14227 //
14228 // -- a declaration of a class member, or
14229 //
14230 // -- a block-scope function declaration that is not a
14231 // using-declaration, or
14232 //
14233 // -- a declaration that is neither a function or a function
14234 // template
14235 //
14236 // then Y is empty.
14237
14238 if (ULE->requiresADL()) {
14240 E = ULE->decls_end(); I != E; ++I) {
14241 assert(!(*I)->getDeclContext()->isRecord());
14242 assert(isa<UsingShadowDecl>(*I) ||
14243 !(*I)->getDeclContext()->isFunctionOrMethod());
14244 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14245 }
14246 }
14247#endif
14248
14249 // It would be nice to avoid this copy.
14250 TemplateArgumentListInfo TABuffer;
14251 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14252 if (ULE->hasExplicitTemplateArgs()) {
14253 ULE->copyTemplateArgumentsInto(TABuffer);
14254 ExplicitTemplateArgs = &TABuffer;
14255 }
14256
14258 E = ULE->decls_end(); I != E; ++I)
14259 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14260 CandidateSet, PartialOverloading,
14261 /*KnownValid*/ true);
14262
14263 if (ULE->requiresADL())
14264 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
14265 Args, ExplicitTemplateArgs,
14266 CandidateSet, PartialOverloading);
14267}
14268
14270 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14271 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14272 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14273 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14274 CandidateSet, false, /*KnownValid*/ false);
14275}
14276
14277/// Determine whether a declaration with the specified name could be moved into
14278/// a different namespace.
14280 switch (Name.getCXXOverloadedOperator()) {
14281 case OO_New: case OO_Array_New:
14282 case OO_Delete: case OO_Array_Delete:
14283 return false;
14284
14285 default:
14286 return true;
14287 }
14288}
14289
14290/// Attempt to recover from an ill-formed use of a non-dependent name in a
14291/// template, where the non-dependent name was declared after the template
14292/// was defined. This is common in code written for a compilers which do not
14293/// correctly implement two-stage name lookup.
14294///
14295/// Returns true if a viable candidate was found and a diagnostic was issued.
14297 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14299 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14300 CXXRecordDecl **FoundInClass = nullptr) {
14301 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14302 return false;
14303
14304 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14305 if (DC->isTransparentContext())
14306 continue;
14307
14308 SemaRef.LookupQualifiedName(R, DC);
14309
14310 if (!R.empty()) {
14312
14313 OverloadCandidateSet Candidates(FnLoc, CSK);
14314 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14315 Candidates);
14316
14319 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
14320
14321 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
14322 // We either found non-function declarations or a best viable function
14323 // at class scope. A class-scope lookup result disables ADL. Don't
14324 // look past this, but let the caller know that we found something that
14325 // either is, or might be, usable in this class.
14326 if (FoundInClass) {
14327 *FoundInClass = RD;
14328 if (OR == OR_Success) {
14329 R.clear();
14330 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
14331 R.resolveKind();
14332 }
14333 }
14334 return false;
14335 }
14336
14337 if (OR != OR_Success) {
14338 // There wasn't a unique best function or function template.
14339 return false;
14340 }
14341
14342 // Find the namespaces where ADL would have looked, and suggest
14343 // declaring the function there instead.
14344 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14345 Sema::AssociatedClassSet AssociatedClasses;
14346 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
14347 AssociatedNamespaces,
14348 AssociatedClasses);
14349 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14351 DeclContext *Std = SemaRef.getStdNamespace();
14352 for (Sema::AssociatedNamespaceSet::iterator
14353 it = AssociatedNamespaces.begin(),
14354 end = AssociatedNamespaces.end(); it != end; ++it) {
14355 // Never suggest declaring a function within namespace 'std'.
14356 if (Std && Std->Encloses(*it))
14357 continue;
14358
14359 // Never suggest declaring a function within a namespace with a
14360 // reserved name, like __gnu_cxx.
14361 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
14362 if (NS &&
14363 NS->getQualifiedNameAsString().find("__") != std::string::npos)
14364 continue;
14365
14366 SuggestedNamespaces.insert(*it);
14367 }
14368 }
14369
14370 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
14371 << R.getLookupName();
14372 if (SuggestedNamespaces.empty()) {
14373 SemaRef.Diag(Best->Function->getLocation(),
14374 diag::note_not_found_by_two_phase_lookup)
14375 << R.getLookupName() << 0;
14376 } else if (SuggestedNamespaces.size() == 1) {
14377 SemaRef.Diag(Best->Function->getLocation(),
14378 diag::note_not_found_by_two_phase_lookup)
14379 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14380 } else {
14381 // FIXME: It would be useful to list the associated namespaces here,
14382 // but the diagnostics infrastructure doesn't provide a way to produce
14383 // a localized representation of a list of items.
14384 SemaRef.Diag(Best->Function->getLocation(),
14385 diag::note_not_found_by_two_phase_lookup)
14386 << R.getLookupName() << 2;
14387 }
14388
14389 // Try to recover by calling this function.
14390 return true;
14391 }
14392
14393 R.clear();
14394 }
14395
14396 return false;
14397}
14398
14399/// Attempt to recover from ill-formed use of a non-dependent operator in a
14400/// template, where the non-dependent operator was declared after the template
14401/// was defined.
14402///
14403/// Returns true if a viable candidate was found and a diagnostic was issued.
14404static bool
14406 SourceLocation OpLoc,
14407 ArrayRef<Expr *> Args) {
14408 DeclarationName OpName =
14410 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14411 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
14413 /*ExplicitTemplateArgs=*/nullptr, Args);
14414}
14415
14416namespace {
14417class BuildRecoveryCallExprRAII {
14418 Sema &SemaRef;
14420
14421public:
14422 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14423 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14424 SemaRef.IsBuildingRecoveryCallExpr = true;
14425 }
14426
14427 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14428};
14429}
14430
14431/// Attempts to recover from a call where no functions were found.
14432///
14433/// This function will do one of three things:
14434/// * Diagnose, recover, and return a recovery expression.
14435/// * Diagnose, fail to recover, and return ExprError().
14436/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14437/// expected to diagnose as appropriate.
14438static ExprResult
14441 SourceLocation LParenLoc,
14443 SourceLocation RParenLoc,
14444 bool EmptyLookup, bool AllowTypoCorrection) {
14445 // Do not try to recover if it is already building a recovery call.
14446 // This stops infinite loops for template instantiations like
14447 //
14448 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14449 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14450 if (SemaRef.IsBuildingRecoveryCallExpr)
14451 return ExprResult();
14452 BuildRecoveryCallExprRAII RCE(SemaRef);
14453
14454 CXXScopeSpec SS;
14455 SS.Adopt(ULE->getQualifierLoc());
14456 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14457
14458 TemplateArgumentListInfo TABuffer;
14459 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14460 if (ULE->hasExplicitTemplateArgs()) {
14461 ULE->copyTemplateArgumentsInto(TABuffer);
14462 ExplicitTemplateArgs = &TABuffer;
14463 }
14464
14465 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14467 CXXRecordDecl *FoundInClass = nullptr;
14468 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
14470 ExplicitTemplateArgs, Args, &FoundInClass)) {
14471 // OK, diagnosed a two-phase lookup issue.
14472 } else if (EmptyLookup) {
14473 // Try to recover from an empty lookup with typo correction.
14474 R.clear();
14475 NoTypoCorrectionCCC NoTypoValidator{};
14476 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14477 ExplicitTemplateArgs != nullptr,
14478 dyn_cast<MemberExpr>(Fn));
14479 CorrectionCandidateCallback &Validator =
14480 AllowTypoCorrection
14481 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14482 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14483 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
14484 Args))
14485 return ExprError();
14486 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14487 // We found a usable declaration of the name in a dependent base of some
14488 // enclosing class.
14489 // FIXME: We should also explain why the candidates found by name lookup
14490 // were not viable.
14491 if (SemaRef.DiagnoseDependentMemberLookup(R))
14492 return ExprError();
14493 } else {
14494 // We had viable candidates and couldn't recover; let the caller diagnose
14495 // this.
14496 return ExprResult();
14497 }
14498
14499 // If we get here, we should have issued a diagnostic and formed a recovery
14500 // lookup result.
14501 assert(!R.empty() && "lookup results empty despite recovery");
14502
14503 // If recovery created an ambiguity, just bail out.
14504 if (R.isAmbiguous()) {
14506 return ExprError();
14507 }
14508
14509 // Build an implicit member call if appropriate. Just drop the
14510 // casts and such from the call, we don't really care.
14511 ExprResult NewFn = ExprError();
14512 if ((*R.begin())->isCXXClassMember())
14513 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14514 ExplicitTemplateArgs, S);
14515 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14516 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
14517 ExplicitTemplateArgs);
14518 else
14519 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
14520
14521 if (NewFn.isInvalid())
14522 return ExprError();
14523
14524 // This shouldn't cause an infinite loop because we're giving it
14525 // an expression with viable lookup results, which should never
14526 // end up here.
14527 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
14528 MultiExprArg(Args.data(), Args.size()),
14529 RParenLoc);
14530}
14531
14534 MultiExprArg Args,
14535 SourceLocation RParenLoc,
14536 OverloadCandidateSet *CandidateSet,
14537 ExprResult *Result) {
14538#ifndef NDEBUG
14539 if (ULE->requiresADL()) {
14540 // To do ADL, we must have found an unqualified name.
14541 assert(!ULE->getQualifier() && "qualified name with ADL");
14542
14543 // We don't perform ADL for implicit declarations of builtins.
14544 // Verify that this was correctly set up.
14545 FunctionDecl *F;
14546 if (ULE->decls_begin() != ULE->decls_end() &&
14547 ULE->decls_begin() + 1 == ULE->decls_end() &&
14548 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14549 F->getBuiltinID() && F->isImplicit())
14550 llvm_unreachable("performing ADL for builtin");
14551
14552 // We don't perform ADL in C.
14553 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14554 }
14555#endif
14556
14557 UnbridgedCastsSet UnbridgedCasts;
14558 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14559 *Result = ExprError();
14560 return true;
14561 }
14562
14563 // Add the functions denoted by the callee to the set of candidate
14564 // functions, including those from argument-dependent lookup.
14565 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
14566
14567 if (getLangOpts().MSVCCompat &&
14568 CurContext->isDependentContext() && !isSFINAEContext() &&
14569 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
14570
14572 if (CandidateSet->empty() ||
14573 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
14575 // In Microsoft mode, if we are inside a template class member function
14576 // then create a type dependent CallExpr. The goal is to postpone name
14577 // lookup to instantiation time to be able to search into type dependent
14578 // base classes.
14579 CallExpr *CE =
14580 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
14581 RParenLoc, CurFPFeatureOverrides());
14583 *Result = CE;
14584 return true;
14585 }
14586 }
14587
14588 if (CandidateSet->empty())
14589 return false;
14590
14591 UnbridgedCasts.restore();
14592 return false;
14593}
14594
14595// Guess at what the return type for an unresolvable overload should be.
14598 std::optional<QualType> Result;
14599 // Adjust Type after seeing a candidate.
14600 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14601 if (!Candidate.Function)
14602 return;
14603 if (Candidate.Function->isInvalidDecl())
14604 return;
14605 QualType T = Candidate.Function->getReturnType();
14606 if (T.isNull())
14607 return;
14608 if (!Result)
14609 Result = T;
14610 else if (Result != T)
14611 Result = QualType();
14612 };
14613
14614 // Look for an unambiguous type from a progressively larger subset.
14615 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14616 //
14617 // First, consider only the best candidate.
14618 if (Best && *Best != CS.end())
14619 ConsiderCandidate(**Best);
14620 // Next, consider only viable candidates.
14621 if (!Result)
14622 for (const auto &C : CS)
14623 if (C.Viable)
14624 ConsiderCandidate(C);
14625 // Finally, consider all candidates.
14626 if (!Result)
14627 for (const auto &C : CS)
14628 ConsiderCandidate(C);
14629
14630 if (!Result)
14631 return QualType();
14632 auto Value = *Result;
14633 if (Value.isNull() || Value->isUndeducedType())
14634 return QualType();
14635 return Value;
14636}
14637
14638/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14639/// the completed call expression. If overload resolution fails, emits
14640/// diagnostics and returns ExprError()
14643 SourceLocation LParenLoc,
14644 MultiExprArg Args,
14645 SourceLocation RParenLoc,
14646 Expr *ExecConfig,
14647 OverloadCandidateSet *CandidateSet,
14649 OverloadingResult OverloadResult,
14650 bool AllowTypoCorrection) {
14651 switch (OverloadResult) {
14652 case OR_Success: {
14653 FunctionDecl *FDecl = (*Best)->Function;
14654 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14655 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14656 return ExprError();
14657 ExprResult Res =
14658 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14659 if (Res.isInvalid())
14660 return ExprError();
14661 return SemaRef.BuildResolvedCallExpr(
14662 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14663 /*IsExecConfig=*/false,
14664 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14665 }
14666
14667 case OR_No_Viable_Function: {
14668 if (*Best != CandidateSet->end() &&
14669 CandidateSet->getKind() ==
14671 if (CXXMethodDecl *M =
14672 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
14674 CandidateSet->NoteCandidates(
14676 Fn->getBeginLoc(),
14677 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
14678 SemaRef, OCD_AmbiguousCandidates, Args);
14679 return ExprError();
14680 }
14681 }
14682
14683 // Try to recover by looking for viable functions which the user might
14684 // have meant to call.
14685 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14686 Args, RParenLoc,
14687 CandidateSet->empty(),
14688 AllowTypoCorrection);
14689 if (Recovery.isInvalid() || Recovery.isUsable())
14690 return Recovery;
14691
14692 // If the user passes in a function that we can't take the address of, we
14693 // generally end up emitting really bad error messages. Here, we attempt to
14694 // emit better ones.
14695 for (const Expr *Arg : Args) {
14696 if (!Arg->getType()->isFunctionType())
14697 continue;
14698 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14699 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14700 if (FD &&
14701 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14702 Arg->getExprLoc()))
14703 return ExprError();
14704 }
14705 }
14706
14707 CandidateSet->NoteCandidates(
14709 Fn->getBeginLoc(),
14710 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14711 << ULE->getName() << Fn->getSourceRange()),
14712 SemaRef, OCD_AllCandidates, Args);
14713 break;
14714 }
14715
14716 case OR_Ambiguous:
14717 CandidateSet->NoteCandidates(
14718 PartialDiagnosticAt(Fn->getBeginLoc(),
14719 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14720 << ULE->getName() << Fn->getSourceRange()),
14721 SemaRef, OCD_AmbiguousCandidates, Args);
14722 break;
14723
14724 case OR_Deleted: {
14725 FunctionDecl *FDecl = (*Best)->Function;
14726 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
14727 Fn->getSourceRange(), ULE->getName(),
14728 *CandidateSet, FDecl, Args);
14729
14730 // We emitted an error for the unavailable/deleted function call but keep
14731 // the call in the AST.
14732 ExprResult Res =
14733 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14734 if (Res.isInvalid())
14735 return ExprError();
14736 return SemaRef.BuildResolvedCallExpr(
14737 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14738 /*IsExecConfig=*/false,
14739 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14740 }
14741 }
14742
14743 // Overload resolution failed, try to recover.
14744 SmallVector<Expr *, 8> SubExprs = {Fn};
14745 SubExprs.append(Args.begin(), Args.end());
14746 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
14747 chooseRecoveryType(*CandidateSet, Best));
14748}
14749
14752 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14753 if (I->Viable &&
14754 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
14755 I->Viable = false;
14756 I->FailureKind = ovl_fail_addr_not_available;
14757 }
14758 }
14759}
14760
14763 SourceLocation LParenLoc,
14764 MultiExprArg Args,
14765 SourceLocation RParenLoc,
14766 Expr *ExecConfig,
14767 bool AllowTypoCorrection,
14768 bool CalleesAddressIsTaken) {
14769
14773
14774 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
14775 ExprResult result;
14776
14777 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
14778 &result))
14779 return result;
14780
14781 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14782 // functions that aren't addressible are considered unviable.
14783 if (CalleesAddressIsTaken)
14784 markUnaddressableCandidatesUnviable(*this, CandidateSet);
14785
14787 OverloadingResult OverloadResult =
14788 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
14789
14790 // [C++23][over.call.func]
14791 // if overload resolution selects a non-static member function,
14792 // the call is ill-formed;
14794 Best != CandidateSet.end()) {
14795 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
14796 M && M->isImplicitObjectMemberFunction()) {
14797 OverloadResult = OR_No_Viable_Function;
14798 }
14799 }
14800
14801 // Model the case with a call to a templated function whose definition
14802 // encloses the call and whose return type contains a placeholder type as if
14803 // the UnresolvedLookupExpr was type-dependent.
14804 if (OverloadResult == OR_Success) {
14805 const FunctionDecl *FDecl = Best->Function;
14806 if (LangOpts.CUDA)
14807 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
14808 if (FDecl && FDecl->isTemplateInstantiation() &&
14809 FDecl->getReturnType()->isUndeducedType()) {
14810
14811 // Creating dependent CallExpr is not okay if the enclosing context itself
14812 // is not dependent. This situation notably arises if a non-dependent
14813 // member function calls the later-defined overloaded static function.
14814 //
14815 // For example, in
14816 // class A {
14817 // void c() { callee(1); }
14818 // static auto callee(auto x) { }
14819 // };
14820 //
14821 // Here callee(1) is unresolved at the call site, but is not inside a
14822 // dependent context. There will be no further attempt to resolve this
14823 // call if it is made dependent.
14824
14825 if (const auto *TP =
14826 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14827 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
14828 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
14829 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
14830 }
14831 }
14832 }
14833
14834 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14835 ExecConfig, &CandidateSet, &Best,
14836 OverloadResult, AllowTypoCorrection);
14837}
14838
14842 const UnresolvedSetImpl &Fns,
14843 bool PerformADL) {
14845 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
14846 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
14847}
14848
14851 bool HadMultipleCandidates) {
14852 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
14853 // the FoundDecl as it impedes TransformMemberExpr.
14854 // We go a bit further here: if there's no difference in UnderlyingDecl,
14855 // then using FoundDecl vs Method shouldn't make a difference either.
14856 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
14857 FoundDecl = Method;
14858 // Convert the expression to match the conversion function's implicit object
14859 // parameter.
14860 ExprResult Exp;
14861 if (Method->isExplicitObjectMemberFunction())
14862 Exp = InitializeExplicitObjectArgument(*this, E, Method);
14863 else
14864 Exp = PerformImplicitObjectArgumentInitialization(
14865 E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
14866 if (Exp.isInvalid())
14867 return true;
14868
14869 if (Method->getParent()->isLambda() &&
14870 Method->getConversionType()->isBlockPointerType()) {
14871 // This is a lambda conversion to block pointer; check if the argument
14872 // was a LambdaExpr.
14873 Expr *SubE = E;
14874 auto *CE = dyn_cast<CastExpr>(SubE);
14875 if (CE && CE->getCastKind() == CK_NoOp)
14876 SubE = CE->getSubExpr();
14877 SubE = SubE->IgnoreParens();
14878 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
14879 SubE = BE->getSubExpr();
14880 if (isa<LambdaExpr>(SubE)) {
14881 // For the conversion to block pointer on a lambda expression, we
14882 // construct a special BlockLiteral instead; this doesn't really make
14883 // a difference in ARC, but outside of ARC the resulting block literal
14884 // follows the normal lifetime rules for block literals instead of being
14885 // autoreleased.
14886 PushExpressionEvaluationContext(
14887 ExpressionEvaluationContext::PotentiallyEvaluated);
14888 ExprResult BlockExp = BuildBlockForLambdaConversion(
14889 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
14890 PopExpressionEvaluationContext();
14891
14892 // FIXME: This note should be produced by a CodeSynthesisContext.
14893 if (BlockExp.isInvalid())
14894 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
14895 return BlockExp;
14896 }
14897 }
14898 CallExpr *CE;
14899 QualType ResultType = Method->getReturnType();
14901 ResultType = ResultType.getNonLValueExprType(Context);
14902 if (Method->isExplicitObjectMemberFunction()) {
14903 ExprResult FnExpr =
14904 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
14905 HadMultipleCandidates, E->getBeginLoc());
14906 if (FnExpr.isInvalid())
14907 return ExprError();
14908 Expr *ObjectParam = Exp.get();
14909 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
14910 ResultType, VK, Exp.get()->getEndLoc(),
14911 CurFPFeatureOverrides());
14912 CE->setUsesMemberSyntax(true);
14913 } else {
14914 MemberExpr *ME =
14915 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
14917 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
14918 HadMultipleCandidates, DeclarationNameInfo(),
14920
14921 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
14922 Exp.get()->getEndLoc(),
14923 CurFPFeatureOverrides());
14924 }
14925
14926 if (CheckFunctionCall(Method, CE,
14927 Method->getType()->castAs<FunctionProtoType>()))
14928 return ExprError();
14929
14930 return CheckForImmediateInvocation(CE, CE->getDirectCallee());
14931}
14932
14935 const UnresolvedSetImpl &Fns,
14936 Expr *Input, bool PerformADL) {
14938 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
14940 // TODO: provide better source location info.
14941 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14942
14943 if (checkPlaceholderForOverload(*this, Input))
14944 return ExprError();
14945
14946 Expr *Args[2] = { Input, nullptr };
14947 unsigned NumArgs = 1;
14948
14949 // For post-increment and post-decrement, add the implicit '0' as
14950 // the second argument, so that we know this is a post-increment or
14951 // post-decrement.
14952 if (Opc == UO_PostInc || Opc == UO_PostDec) {
14953 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14954 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
14955 SourceLocation());
14956 NumArgs = 2;
14957 }
14958
14959 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
14960
14961 if (Input->isTypeDependent()) {
14963 // [C++26][expr.unary.op][expr.pre.incr]
14964 // The * operator yields an lvalue of type
14965 // The pre/post increment operators yied an lvalue.
14966 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
14967 VK = VK_LValue;
14968
14969 if (Fns.empty())
14970 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
14971 OK_Ordinary, OpLoc, false,
14972 CurFPFeatureOverrides());
14973
14974 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14975 ExprResult Fn = CreateUnresolvedLookupExpr(
14976 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
14977 if (Fn.isInvalid())
14978 return ExprError();
14979 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
14980 Context.DependentTy, VK_PRValue, OpLoc,
14981 CurFPFeatureOverrides());
14982 }
14983
14984 // Build an empty overload set.
14986
14987 // Add the candidates from the given function set.
14988 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
14989
14990 // Add operator candidates that are member functions.
14991 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14992
14993 // Add candidates from ADL.
14994 if (PerformADL) {
14995 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
14996 /*ExplicitTemplateArgs*/nullptr,
14997 CandidateSet);
14998 }
14999
15000 // Add builtin operator candidates.
15001 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15002
15003 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15004
15005 // Perform overload resolution.
15007 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15008 case OR_Success: {
15009 // We found a built-in operator or an overloaded operator.
15010 FunctionDecl *FnDecl = Best->Function;
15011
15012 if (FnDecl) {
15013 Expr *Base = nullptr;
15014 // We matched an overloaded operator. Build a call to that
15015 // operator.
15016
15017 // Convert the arguments.
15018 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15019 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
15020
15021 ExprResult InputInit;
15022 if (Method->isExplicitObjectMemberFunction())
15023 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
15024 else
15025 InputInit = PerformImplicitObjectArgumentInitialization(
15026 Input, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15027 if (InputInit.isInvalid())
15028 return ExprError();
15029 Base = Input = InputInit.get();
15030 } else {
15031 // Convert the arguments.
15032 ExprResult InputInit
15033 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
15034 Context,
15035 FnDecl->getParamDecl(0)),
15037 Input);
15038 if (InputInit.isInvalid())
15039 return ExprError();
15040 Input = InputInit.get();
15041 }
15042
15043 // Build the actual expression node.
15044 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
15045 Base, HadMultipleCandidates,
15046 OpLoc);
15047 if (FnExpr.isInvalid())
15048 return ExprError();
15049
15050 // Determine the result type.
15051 QualType ResultTy = FnDecl->getReturnType();
15053 ResultTy = ResultTy.getNonLValueExprType(Context);
15054
15055 Args[0] = Input;
15057 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
15058 CurFPFeatureOverrides(),
15059 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15060
15061 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
15062 return ExprError();
15063
15064 if (CheckFunctionCall(FnDecl, TheCall,
15065 FnDecl->getType()->castAs<FunctionProtoType>()))
15066 return ExprError();
15067 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
15068 } else {
15069 // We matched a built-in operator. Convert the arguments, then
15070 // break out so that we will build the appropriate built-in
15071 // operator node.
15072 ExprResult InputRes = PerformImplicitConversion(
15073 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
15076 if (InputRes.isInvalid())
15077 return ExprError();
15078 Input = InputRes.get();
15079 break;
15080 }
15081 }
15082
15084 // This is an erroneous use of an operator which can be overloaded by
15085 // a non-member function. Check for non-member operators which were
15086 // defined too late to be candidates.
15087 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
15088 // FIXME: Recover by calling the found function.
15089 return ExprError();
15090
15091 // No viable function; fall through to handling this as a
15092 // built-in operator, which will produce an error message for us.
15093 break;
15094
15095 case OR_Ambiguous:
15096 CandidateSet.NoteCandidates(
15097 PartialDiagnosticAt(OpLoc,
15098 PDiag(diag::err_ovl_ambiguous_oper_unary)
15100 << Input->getType() << Input->getSourceRange()),
15101 *this, OCD_AmbiguousCandidates, ArgsArray,
15102 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15103 return ExprError();
15104
15105 case OR_Deleted: {
15106 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15107 // object whose method was called. Later in NoteCandidates size of ArgsArray
15108 // is passed further and it eventually ends up compared to number of
15109 // function candidate parameters which never includes the object parameter,
15110 // so slice ArgsArray to make sure apples are compared to apples.
15111 StringLiteral *Msg = Best->Function->getDeletedMessage();
15112 CandidateSet.NoteCandidates(
15113 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15115 << (Msg != nullptr)
15116 << (Msg ? Msg->getString() : StringRef())
15117 << Input->getSourceRange()),
15118 *this, OCD_AllCandidates, ArgsArray.drop_front(),
15119 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15120 return ExprError();
15121 }
15122 }
15123
15124 // Either we found no viable overloaded operator or we matched a
15125 // built-in operator. In either case, fall through to trying to
15126 // build a built-in operation.
15127 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15128}
15129
15132 const UnresolvedSetImpl &Fns,
15133 ArrayRef<Expr *> Args, bool PerformADL) {
15134 SourceLocation OpLoc = CandidateSet.getLocation();
15135
15136 OverloadedOperatorKind ExtraOp =
15139 : OO_None;
15140
15141 // Add the candidates from the given function set. This also adds the
15142 // rewritten candidates using these functions if necessary.
15143 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15144
15145 // As template candidates are not deduced immediately,
15146 // persist the array in the overload set.
15147 ArrayRef<Expr *> ReversedArgs;
15148 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15149 CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15150 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
15151
15152 // Add operator candidates that are member functions.
15153 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15154 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15155 AddMemberOperatorCandidates(Op, OpLoc, ReversedArgs, CandidateSet,
15157
15158 // In C++20, also add any rewritten member candidates.
15159 if (ExtraOp) {
15160 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
15161 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15162 AddMemberOperatorCandidates(ExtraOp, OpLoc, ReversedArgs, CandidateSet,
15164 }
15165
15166 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15167 // performed for an assignment operator (nor for operator[] nor operator->,
15168 // which don't get here).
15169 if (Op != OO_Equal && PerformADL) {
15171 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15172 /*ExplicitTemplateArgs*/ nullptr,
15173 CandidateSet);
15174 if (ExtraOp) {
15175 DeclarationName ExtraOpName =
15176 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
15177 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
15178 /*ExplicitTemplateArgs*/ nullptr,
15179 CandidateSet);
15180 }
15181 }
15182
15183 // Add builtin operator candidates.
15184 //
15185 // FIXME: We don't add any rewritten candidates here. This is strictly
15186 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15187 // resulting in our selecting a rewritten builtin candidate. For example:
15188 //
15189 // enum class E { e };
15190 // bool operator!=(E, E) requires false;
15191 // bool k = E::e != E::e;
15192 //
15193 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15194 // it seems unreasonable to consider rewritten builtin candidates. A core
15195 // issue has been filed proposing to removed this requirement.
15196 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15197}
15198
15201 const UnresolvedSetImpl &Fns, Expr *LHS,
15202 Expr *RHS, bool PerformADL,
15203 bool AllowRewrittenCandidates,
15204 FunctionDecl *DefaultedFn) {
15205 Expr *Args[2] = { LHS, RHS };
15206 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15207
15208 if (!getLangOpts().CPlusPlus20)
15209 AllowRewrittenCandidates = false;
15210
15212
15213 // If either side is type-dependent, create an appropriate dependent
15214 // expression.
15215 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15216 if (Fns.empty()) {
15217 // If there are no functions to store, just build a dependent
15218 // BinaryOperator or CompoundAssignment.
15221 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
15222 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
15223 Context.DependentTy);
15225 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
15226 OK_Ordinary, OpLoc, CurFPFeatureOverrides());
15227 }
15228
15229 // FIXME: save results of ADL from here?
15230 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15231 // TODO: provide better source location info in DNLoc component.
15233 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15234 ExprResult Fn = CreateUnresolvedLookupExpr(
15235 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
15236 if (Fn.isInvalid())
15237 return ExprError();
15238 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
15239 Context.DependentTy, VK_PRValue, OpLoc,
15240 CurFPFeatureOverrides());
15241 }
15242
15243 // If this is the .* operator, which is not overloadable, just
15244 // create a built-in binary operator.
15245 if (Opc == BO_PtrMemD) {
15246 auto CheckPlaceholder = [&](Expr *&Arg) {
15247 ExprResult Res = CheckPlaceholderExpr(Arg);
15248 if (Res.isUsable())
15249 Arg = Res.get();
15250 return !Res.isUsable();
15251 };
15252
15253 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15254 // expression that contains placeholders (in either the LHS or RHS).
15255 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15256 return ExprError();
15257 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15258 }
15259
15260 // Always do placeholder-like conversions on the RHS.
15261 if (checkPlaceholderForOverload(*this, Args[1]))
15262 return ExprError();
15263
15264 // Do placeholder-like conversion on the LHS; note that we should
15265 // not get here with a PseudoObject LHS.
15266 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15267 if (checkPlaceholderForOverload(*this, Args[0]))
15268 return ExprError();
15269
15270 // If this is the assignment operator, we only perform overload resolution
15271 // if the left-hand side is a class or enumeration type. This is actually
15272 // a hack. The standard requires that we do overload resolution between the
15273 // various built-in candidates, but as DR507 points out, this can lead to
15274 // problems. So we do it this way, which pretty much follows what GCC does.
15275 // Note that we go the traditional code path for compound assignment forms.
15276 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
15277 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15278
15279 // Build the overload set.
15282 Op, OpLoc, AllowRewrittenCandidates));
15283 if (DefaultedFn)
15284 CandidateSet.exclude(DefaultedFn);
15285 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15286
15287 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15288
15289 // Perform overload resolution.
15291 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15292 case OR_Success: {
15293 // We found a built-in operator or an overloaded operator.
15294 FunctionDecl *FnDecl = Best->Function;
15295
15296 bool IsReversed = Best->isReversed();
15297 if (IsReversed)
15298 std::swap(Args[0], Args[1]);
15299
15300 if (FnDecl) {
15301
15302 if (FnDecl->isInvalidDecl())
15303 return ExprError();
15304
15305 Expr *Base = nullptr;
15306 // We matched an overloaded operator. Build a call to that
15307 // operator.
15308
15309 OverloadedOperatorKind ChosenOp =
15311
15312 // C++2a [over.match.oper]p9:
15313 // If a rewritten operator== candidate is selected by overload
15314 // resolution for an operator@, its return type shall be cv bool
15315 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15316 !FnDecl->getReturnType()->isBooleanType()) {
15317 bool IsExtension =
15319 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15320 : diag::err_ovl_rewrite_equalequal_not_bool)
15321 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
15322 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15323 Diag(FnDecl->getLocation(), diag::note_declared_at);
15324 if (!IsExtension)
15325 return ExprError();
15326 }
15327
15328 if (AllowRewrittenCandidates && !IsReversed &&
15329 CandidateSet.getRewriteInfo().isReversible()) {
15330 // We could have reversed this operator, but didn't. Check if some
15331 // reversed form was a viable candidate, and if so, if it had a
15332 // better conversion for either parameter. If so, this call is
15333 // formally ambiguous, and allowing it is an extension.
15335 for (OverloadCandidate &Cand : CandidateSet) {
15336 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15337 allowAmbiguity(Context, Cand.Function, FnDecl)) {
15338 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15340 *this, OpLoc, Cand.Conversions[ArgIdx],
15341 Best->Conversions[ArgIdx]) ==
15343 AmbiguousWith.push_back(Cand.Function);
15344 break;
15345 }
15346 }
15347 }
15348 }
15349
15350 if (!AmbiguousWith.empty()) {
15351 bool AmbiguousWithSelf =
15352 AmbiguousWith.size() == 1 &&
15353 declaresSameEntity(AmbiguousWith.front(), FnDecl);
15354 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
15356 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15357 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15358 if (AmbiguousWithSelf) {
15359 Diag(FnDecl->getLocation(),
15360 diag::note_ovl_ambiguous_oper_binary_reversed_self);
15361 // Mark member== const or provide matching != to disallow reversed
15362 // args. Eg.
15363 // struct S { bool operator==(const S&); };
15364 // S()==S();
15365 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
15366 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15367 !MD->isConst() &&
15368 !MD->hasCXXExplicitFunctionObjectParameter() &&
15369 Context.hasSameUnqualifiedType(
15370 MD->getFunctionObjectParameterType(),
15371 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
15372 Context.hasSameUnqualifiedType(
15373 MD->getFunctionObjectParameterType(),
15374 Args[0]->getType()) &&
15375 Context.hasSameUnqualifiedType(
15376 MD->getFunctionObjectParameterType(),
15377 Args[1]->getType()))
15378 Diag(FnDecl->getLocation(),
15379 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15380 } else {
15381 Diag(FnDecl->getLocation(),
15382 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15383 for (auto *F : AmbiguousWith)
15384 Diag(F->getLocation(),
15385 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15386 }
15387 }
15388 }
15389
15390 // Check for nonnull = nullable.
15391 // This won't be caught in the arg's initialization: the parameter to
15392 // the assignment operator is not marked nonnull.
15393 if (Op == OO_Equal)
15394 diagnoseNullableToNonnullConversion(Args[0]->getType(),
15395 Args[1]->getType(), OpLoc);
15396
15397 // Convert the arguments.
15398 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15399 // Best->Access is only meaningful for class members.
15400 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
15401
15402 ExprResult Arg0, Arg1;
15403 unsigned ParamIdx = 0;
15404 if (Method->isExplicitObjectMemberFunction()) {
15405 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
15406 ParamIdx = 1;
15407 } else {
15408 Arg0 = PerformImplicitObjectArgumentInitialization(
15409 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15410 }
15411 Arg1 = PerformCopyInitialization(
15413 Context, FnDecl->getParamDecl(ParamIdx)),
15414 SourceLocation(), Args[1]);
15415 if (Arg0.isInvalid() || Arg1.isInvalid())
15416 return ExprError();
15417
15418 Base = Args[0] = Arg0.getAs<Expr>();
15419 Args[1] = RHS = Arg1.getAs<Expr>();
15420 } else {
15421 // Convert the arguments.
15422 ExprResult Arg0 = PerformCopyInitialization(
15424 FnDecl->getParamDecl(0)),
15425 SourceLocation(), Args[0]);
15426 if (Arg0.isInvalid())
15427 return ExprError();
15428
15429 ExprResult Arg1 =
15430 PerformCopyInitialization(
15432 FnDecl->getParamDecl(1)),
15433 SourceLocation(), Args[1]);
15434 if (Arg1.isInvalid())
15435 return ExprError();
15436 Args[0] = LHS = Arg0.getAs<Expr>();
15437 Args[1] = RHS = Arg1.getAs<Expr>();
15438 }
15439
15440 // Build the actual expression node.
15441 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
15442 Best->FoundDecl, Base,
15443 HadMultipleCandidates, OpLoc);
15444 if (FnExpr.isInvalid())
15445 return ExprError();
15446
15447 // Determine the result type.
15448 QualType ResultTy = FnDecl->getReturnType();
15450 ResultTy = ResultTy.getNonLValueExprType(Context);
15451
15452 CallExpr *TheCall;
15453 ArrayRef<const Expr *> ArgsArray(Args, 2);
15454 const Expr *ImplicitThis = nullptr;
15455
15456 // We always create a CXXOperatorCallExpr, even for explicit object
15457 // members; CodeGen should take care not to emit the this pointer.
15459 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
15460 CurFPFeatureOverrides(),
15461 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15462
15463 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
15464 Method && Method->isImplicitObjectMemberFunction()) {
15465 // Cut off the implicit 'this'.
15466 ImplicitThis = ArgsArray[0];
15467 ArgsArray = ArgsArray.slice(1);
15468 }
15469
15470 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
15471 FnDecl))
15472 return ExprError();
15473
15474 if (Op == OO_Equal) {
15475 // Check for a self move.
15476 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
15477 // lifetime check.
15479 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
15480 Args[1]);
15481 }
15482 if (ImplicitThis) {
15483 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
15484 QualType ThisTypeFromDecl = Context.getPointerType(
15485 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
15486
15487 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
15488 ThisTypeFromDecl);
15489 }
15490
15491 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
15492 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
15494
15495 ExprResult R = MaybeBindToTemporary(TheCall);
15496 if (R.isInvalid())
15497 return ExprError();
15498
15499 R = CheckForImmediateInvocation(R, FnDecl);
15500 if (R.isInvalid())
15501 return ExprError();
15502
15503 // For a rewritten candidate, we've already reversed the arguments
15504 // if needed. Perform the rest of the rewrite now.
15505 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15506 (Op == OO_Spaceship && IsReversed)) {
15507 if (Op == OO_ExclaimEqual) {
15508 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15509 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
15510 } else {
15511 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15512 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15513 Expr *ZeroLiteral =
15514 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
15515
15518 Ctx.Entity = FnDecl;
15519 pushCodeSynthesisContext(Ctx);
15520
15521 R = CreateOverloadedBinOp(
15522 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
15523 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15524 /*AllowRewrittenCandidates=*/false);
15525
15526 popCodeSynthesisContext();
15527 }
15528 if (R.isInvalid())
15529 return ExprError();
15530 } else {
15531 assert(ChosenOp == Op && "unexpected operator name");
15532 }
15533
15534 // Make a note in the AST if we did any rewriting.
15535 if (Best->RewriteKind != CRK_None)
15536 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15537
15538 return R;
15539 } else {
15540 // We matched a built-in operator. Convert the arguments, then
15541 // break out so that we will build the appropriate built-in
15542 // operator node.
15543 ExprResult ArgsRes0 = PerformImplicitConversion(
15544 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15547 if (ArgsRes0.isInvalid())
15548 return ExprError();
15549 Args[0] = ArgsRes0.get();
15550
15551 ExprResult ArgsRes1 = PerformImplicitConversion(
15552 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15555 if (ArgsRes1.isInvalid())
15556 return ExprError();
15557 Args[1] = ArgsRes1.get();
15558 break;
15559 }
15560 }
15561
15562 case OR_No_Viable_Function: {
15563 // C++ [over.match.oper]p9:
15564 // If the operator is the operator , [...] and there are no
15565 // viable functions, then the operator is assumed to be the
15566 // built-in operator and interpreted according to clause 5.
15567 if (Opc == BO_Comma)
15568 break;
15569
15570 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15571 // compare result using '==' and '<'.
15572 if (DefaultedFn && Opc == BO_Cmp) {
15573 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
15574 Args[1], DefaultedFn);
15575 if (E.isInvalid() || E.isUsable())
15576 return E;
15577 }
15578
15579 // For class as left operand for assignment or compound assignment
15580 // operator do not fall through to handling in built-in, but report that
15581 // no overloaded assignment operator found
15583 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
15584 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
15585 Args, OpLoc);
15586 DeferDiagsRAII DDR(*this,
15587 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
15588 if (Args[0]->getType()->isRecordType() &&
15589 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15590 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15592 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15593 if (Args[0]->getType()->isIncompleteType()) {
15594 Diag(OpLoc, diag::note_assign_lhs_incomplete)
15595 << Args[0]->getType()
15596 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15597 }
15598 } else {
15599 // This is an erroneous use of an operator which can be overloaded by
15600 // a non-member function. Check for non-member operators which were
15601 // defined too late to be candidates.
15602 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
15603 // FIXME: Recover by calling the found function.
15604 return ExprError();
15605
15606 // No viable function; try to create a built-in operation, which will
15607 // produce an error. Then, show the non-viable candidates.
15608 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15609 }
15610 assert(Result.isInvalid() &&
15611 "C++ binary operator overloading is missing candidates!");
15612 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
15613 return Result;
15614 }
15615
15616 case OR_Ambiguous:
15617 CandidateSet.NoteCandidates(
15618 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15620 << Args[0]->getType()
15621 << Args[1]->getType()
15622 << Args[0]->getSourceRange()
15623 << Args[1]->getSourceRange()),
15625 OpLoc);
15626 return ExprError();
15627
15628 case OR_Deleted: {
15629 if (isImplicitlyDeleted(Best->Function)) {
15630 FunctionDecl *DeletedFD = Best->Function;
15631 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
15632 if (DFK.isSpecialMember()) {
15633 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15634 << Args[0]->getType() << DFK.asSpecialMember();
15635 } else {
15636 assert(DFK.isComparison());
15637 Diag(OpLoc, diag::err_ovl_deleted_comparison)
15638 << Args[0]->getType() << DeletedFD;
15639 }
15640
15641 // The user probably meant to call this special member. Just
15642 // explain why it's deleted.
15643 NoteDeletedFunction(DeletedFD);
15644 return ExprError();
15645 }
15646
15647 StringLiteral *Msg = Best->Function->getDeletedMessage();
15648 CandidateSet.NoteCandidates(
15650 OpLoc,
15651 PDiag(diag::err_ovl_deleted_oper)
15652 << getOperatorSpelling(Best->Function->getDeclName()
15653 .getCXXOverloadedOperator())
15654 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15655 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15657 OpLoc);
15658 return ExprError();
15659 }
15660 }
15661
15662 // We matched a built-in operator; build it.
15663 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15664}
15665
15667 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15668 FunctionDecl *DefaultedFn) {
15669 const ComparisonCategoryInfo *Info =
15670 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
15671 // If we're not producing a known comparison category type, we can't
15672 // synthesize a three-way comparison. Let the caller diagnose this.
15673 if (!Info)
15674 return ExprResult((Expr*)nullptr);
15675
15676 // If we ever want to perform this synthesis more generally, we will need to
15677 // apply the temporary materialization conversion to the operands.
15678 assert(LHS->isGLValue() && RHS->isGLValue() &&
15679 "cannot use prvalue expressions more than once");
15680 Expr *OrigLHS = LHS;
15681 Expr *OrigRHS = RHS;
15682
15683 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15684 // each of them multiple times below.
15685 LHS = new (Context)
15686 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15687 LHS->getObjectKind(), LHS);
15688 RHS = new (Context)
15689 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15690 RHS->getObjectKind(), RHS);
15691
15692 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
15693 DefaultedFn);
15694 if (Eq.isInvalid())
15695 return ExprError();
15696
15697 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
15698 true, DefaultedFn);
15699 if (Less.isInvalid())
15700 return ExprError();
15701
15703 if (Info->isPartial()) {
15704 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
15705 DefaultedFn);
15706 if (Greater.isInvalid())
15707 return ExprError();
15708 }
15709
15710 // Form the list of comparisons we're going to perform.
15711 struct Comparison {
15712 ExprResult Cmp;
15714 } Comparisons[4] =
15720 };
15721
15722 int I = Info->isPartial() ? 3 : 2;
15723
15724 // Combine the comparisons with suitable conditional expressions.
15726 for (; I >= 0; --I) {
15727 // Build a reference to the comparison category constant.
15728 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
15729 // FIXME: Missing a constant for a comparison category. Diagnose this?
15730 if (!VI)
15731 return ExprResult((Expr*)nullptr);
15732 ExprResult ThisResult =
15733 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
15734 if (ThisResult.isInvalid())
15735 return ExprError();
15736
15737 // Build a conditional unless this is the final case.
15738 if (Result.get()) {
15739 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
15740 ThisResult.get(), Result.get());
15741 if (Result.isInvalid())
15742 return ExprError();
15743 } else {
15744 Result = ThisResult;
15745 }
15746 }
15747
15748 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15749 // bind the OpaqueValueExprs before they're (repeatedly) used.
15750 Expr *SyntacticForm = BinaryOperator::Create(
15751 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
15752 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
15753 CurFPFeatureOverrides());
15754 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15755 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
15756}
15757
15760 MultiExprArg Args, SourceLocation LParenLoc) {
15761
15762 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15763 unsigned NumParams = Proto->getNumParams();
15764 unsigned NumArgsSlots =
15765 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
15766 // Build the full argument list for the method call (the implicit object
15767 // parameter is placed at the beginning of the list).
15768 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
15769 bool IsError = false;
15770 // Initialize the implicit object parameter.
15771 // Check the argument types.
15772 for (unsigned i = 0; i != NumParams; i++) {
15773 Expr *Arg;
15774 if (i < Args.size()) {
15775 Arg = Args[i];
15776 ExprResult InputInit =
15778 S.Context, Method->getParamDecl(i)),
15779 SourceLocation(), Arg);
15780 IsError |= InputInit.isInvalid();
15781 Arg = InputInit.getAs<Expr>();
15782 } else {
15783 ExprResult DefArg =
15784 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
15785 if (DefArg.isInvalid()) {
15786 IsError = true;
15787 break;
15788 }
15789 Arg = DefArg.getAs<Expr>();
15790 }
15791
15792 MethodArgs.push_back(Arg);
15793 }
15794 return IsError;
15795}
15796
15798 SourceLocation RLoc,
15799 Expr *Base,
15800 MultiExprArg ArgExpr) {
15802 Args.push_back(Base);
15803 for (auto *e : ArgExpr) {
15804 Args.push_back(e);
15805 }
15806 DeclarationName OpName =
15807 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
15808
15809 SourceRange Range = ArgExpr.empty()
15810 ? SourceRange{}
15811 : SourceRange(ArgExpr.front()->getBeginLoc(),
15812 ArgExpr.back()->getEndLoc());
15813
15814 // If either side is type-dependent, create an appropriate dependent
15815 // expression.
15817
15818 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15819 // CHECKME: no 'operator' keyword?
15820 DeclarationNameInfo OpNameInfo(OpName, LLoc);
15821 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15822 ExprResult Fn = CreateUnresolvedLookupExpr(
15823 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
15824 if (Fn.isInvalid())
15825 return ExprError();
15826 // Can't add any actual overloads yet
15827
15828 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
15829 Context.DependentTy, VK_PRValue, RLoc,
15830 CurFPFeatureOverrides());
15831 }
15832
15833 // Handle placeholders
15834 UnbridgedCastsSet UnbridgedCasts;
15835 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
15836 return ExprError();
15837 }
15838 // Build an empty overload set.
15840
15841 // Subscript can only be overloaded as a member function.
15842
15843 // Add operator candidates that are member functions.
15844 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15845
15846 // Add builtin operator candidates.
15847 if (Args.size() == 2)
15848 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15849
15850 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15851
15852 // Perform overload resolution.
15854 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
15855 case OR_Success: {
15856 // We found a built-in operator or an overloaded operator.
15857 FunctionDecl *FnDecl = Best->Function;
15858
15859 if (FnDecl) {
15860 // We matched an overloaded operator. Build a call to that
15861 // operator.
15862
15863 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
15864
15865 // Convert the arguments.
15866 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
15867 SmallVector<Expr *, 2> MethodArgs;
15868
15869 // Initialize the object parameter.
15870 if (Method->isExplicitObjectMemberFunction()) {
15871 ExprResult Res =
15872 InitializeExplicitObjectArgument(*this, Args[0], Method);
15873 if (Res.isInvalid())
15874 return ExprError();
15875 Args[0] = Res.get();
15876 ArgExpr = Args;
15877 } else {
15878 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
15879 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15880 if (Arg0.isInvalid())
15881 return ExprError();
15882
15883 MethodArgs.push_back(Arg0.get());
15884 }
15885
15887 *this, MethodArgs, Method, ArgExpr, LLoc);
15888 if (IsError)
15889 return ExprError();
15890
15891 // Build the actual expression node.
15892 DeclarationNameInfo OpLocInfo(OpName, LLoc);
15893 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15895 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
15896 OpLocInfo.getLoc(), OpLocInfo.getInfo());
15897 if (FnExpr.isInvalid())
15898 return ExprError();
15899
15900 // Determine the result type
15901 QualType ResultTy = FnDecl->getReturnType();
15903 ResultTy = ResultTy.getNonLValueExprType(Context);
15904
15906 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
15907 CurFPFeatureOverrides());
15908
15909 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
15910 return ExprError();
15911
15912 if (CheckFunctionCall(Method, TheCall,
15913 Method->getType()->castAs<FunctionProtoType>()))
15914 return ExprError();
15915
15916 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
15917 FnDecl);
15918 } else {
15919 // We matched a built-in operator. Convert the arguments, then
15920 // break out so that we will build the appropriate built-in
15921 // operator node.
15922 ExprResult ArgsRes0 = PerformImplicitConversion(
15923 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15926 if (ArgsRes0.isInvalid())
15927 return ExprError();
15928 Args[0] = ArgsRes0.get();
15929
15930 ExprResult ArgsRes1 = PerformImplicitConversion(
15931 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15934 if (ArgsRes1.isInvalid())
15935 return ExprError();
15936 Args[1] = ArgsRes1.get();
15937
15938 break;
15939 }
15940 }
15941
15942 case OR_No_Viable_Function: {
15944 CandidateSet.empty()
15945 ? (PDiag(diag::err_ovl_no_oper)
15946 << Args[0]->getType() << /*subscript*/ 0
15947 << Args[0]->getSourceRange() << Range)
15948 : (PDiag(diag::err_ovl_no_viable_subscript)
15949 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
15950 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
15951 OCD_AllCandidates, ArgExpr, "[]", LLoc);
15952 return ExprError();
15953 }
15954
15955 case OR_Ambiguous:
15956 if (Args.size() == 2) {
15957 CandidateSet.NoteCandidates(
15959 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15960 << "[]" << Args[0]->getType() << Args[1]->getType()
15961 << Args[0]->getSourceRange() << Range),
15962 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15963 } else {
15964 CandidateSet.NoteCandidates(
15966 PDiag(diag::err_ovl_ambiguous_subscript_call)
15967 << Args[0]->getType()
15968 << Args[0]->getSourceRange() << Range),
15969 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15970 }
15971 return ExprError();
15972
15973 case OR_Deleted: {
15974 StringLiteral *Msg = Best->Function->getDeletedMessage();
15975 CandidateSet.NoteCandidates(
15977 PDiag(diag::err_ovl_deleted_oper)
15978 << "[]" << (Msg != nullptr)
15979 << (Msg ? Msg->getString() : StringRef())
15980 << Args[0]->getSourceRange() << Range),
15981 *this, OCD_AllCandidates, Args, "[]", LLoc);
15982 return ExprError();
15983 }
15984 }
15985
15986 // We matched a built-in operator; build it.
15987 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
15988}
15989
15991 SourceLocation LParenLoc,
15992 MultiExprArg Args,
15993 SourceLocation RParenLoc,
15994 Expr *ExecConfig, bool IsExecConfig,
15995 bool AllowRecovery) {
15996 assert(MemExprE->getType() == Context.BoundMemberTy ||
15997 MemExprE->getType() == Context.OverloadTy);
15998
15999 // Dig out the member expression. This holds both the object
16000 // argument and the member function we're referring to.
16001 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16002
16003 // Determine whether this is a call to a pointer-to-member function.
16004 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
16005 assert(op->getType() == Context.BoundMemberTy);
16006 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16007
16008 QualType fnType =
16009 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16010
16011 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16012 QualType resultType = proto->getCallResultType(Context);
16014
16015 // Check that the object type isn't more qualified than the
16016 // member function we're calling.
16017 Qualifiers funcQuals = proto->getMethodQuals();
16018
16019 QualType objectType = op->getLHS()->getType();
16020 if (op->getOpcode() == BO_PtrMemI)
16021 objectType = objectType->castAs<PointerType>()->getPointeeType();
16022 Qualifiers objectQuals = objectType.getQualifiers();
16023
16024 Qualifiers difference = objectQuals - funcQuals;
16025 difference.removeObjCGCAttr();
16026 difference.removeAddressSpace();
16027 if (difference) {
16028 std::string qualsString = difference.getAsString();
16029 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
16030 << fnType.getUnqualifiedType()
16031 << qualsString
16032 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
16033 }
16034
16036 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
16037 CurFPFeatureOverrides(), proto->getNumParams());
16038
16039 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
16040 call, nullptr))
16041 return ExprError();
16042
16043 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
16044 return ExprError();
16045
16046 if (CheckOtherCall(call, proto))
16047 return ExprError();
16048
16049 return MaybeBindToTemporary(call);
16050 }
16051
16052 // We only try to build a recovery expr at this level if we can preserve
16053 // the return type, otherwise we return ExprError() and let the caller
16054 // recover.
16055 auto BuildRecoveryExpr = [&](QualType Type) {
16056 if (!AllowRecovery)
16057 return ExprError();
16058 std::vector<Expr *> SubExprs = {MemExprE};
16059 llvm::append_range(SubExprs, Args);
16060 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
16061 Type);
16062 };
16063 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
16064 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
16065 RParenLoc, CurFPFeatureOverrides());
16066
16067 UnbridgedCastsSet UnbridgedCasts;
16068 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16069 return ExprError();
16070
16071 MemberExpr *MemExpr;
16072 CXXMethodDecl *Method = nullptr;
16073 bool HadMultipleCandidates = false;
16074 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
16075 NestedNameSpecifier Qualifier = std::nullopt;
16076 if (isa<MemberExpr>(NakedMemExpr)) {
16077 MemExpr = cast<MemberExpr>(NakedMemExpr);
16078 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
16079 FoundDecl = MemExpr->getFoundDecl();
16080 Qualifier = MemExpr->getQualifier();
16081 UnbridgedCasts.restore();
16082 } else {
16083 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
16084 Qualifier = UnresExpr->getQualifier();
16085
16086 QualType ObjectType = UnresExpr->getBaseType();
16087 Expr::Classification ObjectClassification
16089 : UnresExpr->getBase()->Classify(Context);
16090
16091 // Add overload candidates
16092 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16094
16095 // FIXME: avoid copy.
16096 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16097 if (UnresExpr->hasExplicitTemplateArgs()) {
16098 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16099 TemplateArgs = &TemplateArgsBuffer;
16100 }
16101
16103 E = UnresExpr->decls_end(); I != E; ++I) {
16104
16105 QualType ExplicitObjectType = ObjectType;
16106
16107 NamedDecl *Func = *I;
16108 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
16109 if (isa<UsingShadowDecl>(Func))
16110 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
16111
16112 bool HasExplicitParameter = false;
16113 if (const auto *M = dyn_cast<FunctionDecl>(Func);
16114 M && M->hasCXXExplicitFunctionObjectParameter())
16115 HasExplicitParameter = true;
16116 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
16117 M &&
16118 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16119 HasExplicitParameter = true;
16120
16121 if (HasExplicitParameter)
16122 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
16123
16124 // Microsoft supports direct constructor calls.
16125 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
16126 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
16127 CandidateSet,
16128 /*SuppressUserConversions*/ false);
16129 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
16130 // If explicit template arguments were provided, we can't call a
16131 // non-template member function.
16132 if (TemplateArgs)
16133 continue;
16134
16135 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
16136 ObjectClassification, Args, CandidateSet,
16137 /*SuppressUserConversions=*/false);
16138 } else {
16139 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
16140 I.getPair(), ActingDC, TemplateArgs,
16141 ExplicitObjectType, ObjectClassification,
16142 Args, CandidateSet,
16143 /*SuppressUserConversions=*/false);
16144 }
16145 }
16146
16147 HadMultipleCandidates = (CandidateSet.size() > 1);
16148
16149 DeclarationName DeclName = UnresExpr->getMemberName();
16150
16151 UnbridgedCasts.restore();
16152
16154 bool Succeeded = false;
16155 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
16156 Best)) {
16157 case OR_Success:
16158 Method = cast<CXXMethodDecl>(Best->Function);
16159 FoundDecl = Best->FoundDecl;
16160 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
16161 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
16162 break;
16163 // If FoundDecl is different from Method (such as if one is a template
16164 // and the other a specialization), make sure DiagnoseUseOfDecl is
16165 // called on both.
16166 // FIXME: This would be more comprehensively addressed by modifying
16167 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16168 // being used.
16169 if (Method != FoundDecl.getDecl() &&
16170 DiagnoseUseOfOverloadedDecl(Method, UnresExpr->getNameLoc()))
16171 break;
16172 Succeeded = true;
16173 break;
16174
16176 CandidateSet.NoteCandidates(
16178 UnresExpr->getMemberLoc(),
16179 PDiag(diag::err_ovl_no_viable_member_function_in_call)
16180 << DeclName << MemExprE->getSourceRange()),
16181 *this, OCD_AllCandidates, Args);
16182 break;
16183 case OR_Ambiguous:
16184 CandidateSet.NoteCandidates(
16185 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16186 PDiag(diag::err_ovl_ambiguous_member_call)
16187 << DeclName << MemExprE->getSourceRange()),
16188 *this, OCD_AmbiguousCandidates, Args);
16189 break;
16190 case OR_Deleted:
16191 DiagnoseUseOfDeletedFunction(
16192 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
16193 CandidateSet, Best->Function, Args, /*IsMember=*/true);
16194 break;
16195 }
16196 // Overload resolution fails, try to recover.
16197 if (!Succeeded)
16198 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
16199
16200 ExprResult Res =
16201 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
16202 if (Res.isInvalid())
16203 return ExprError();
16204 MemExprE = Res.get();
16205
16206 // If overload resolution picked a static member
16207 // build a non-member call based on that function.
16208 if (Method->isStatic()) {
16209 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
16210 ExecConfig, IsExecConfig);
16211 }
16212
16213 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
16214 }
16215
16216 QualType ResultType = Method->getReturnType();
16218 ResultType = ResultType.getNonLValueExprType(Context);
16219
16220 assert(Method && "Member call to something that isn't a method?");
16221 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16222
16223 CallExpr *TheCall = nullptr;
16225 if (Method->isExplicitObjectMemberFunction()) {
16226 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
16227 NewArgs))
16228 return ExprError();
16229
16230 // Build the actual expression node.
16231 ExprResult FnExpr =
16232 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
16233 HadMultipleCandidates, MemExpr->getExprLoc());
16234 if (FnExpr.isInvalid())
16235 return ExprError();
16236
16237 TheCall =
16238 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
16239 CurFPFeatureOverrides(), Proto->getNumParams());
16240 TheCall->setUsesMemberSyntax(true);
16241 } else {
16242 // Convert the object argument (for a non-static member function call).
16243 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
16244 MemExpr->getBase(), Qualifier, FoundDecl, Method);
16245 if (ObjectArg.isInvalid())
16246 return ExprError();
16247 MemExpr->setBase(ObjectArg.get());
16248 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
16249 RParenLoc, CurFPFeatureOverrides(),
16250 Proto->getNumParams());
16251 }
16252
16253 // Check for a valid return type.
16254 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
16255 TheCall, Method))
16256 return BuildRecoveryExpr(ResultType);
16257
16258 // Convert the rest of the arguments
16259 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
16260 RParenLoc))
16261 return BuildRecoveryExpr(ResultType);
16262
16263 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16264
16265 if (CheckFunctionCall(Method, TheCall, Proto))
16266 return ExprError();
16267
16268 // In the case the method to call was not selected by the overloading
16269 // resolution process, we still need to handle the enable_if attribute. Do
16270 // that here, so it will not hide previous -- and more relevant -- errors.
16271 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
16272 if (const EnableIfAttr *Attr =
16273 CheckEnableIf(Method, LParenLoc, Args, true)) {
16274 Diag(MemE->getMemberLoc(),
16275 diag::err_ovl_no_viable_member_function_in_call)
16276 << Method << Method->getSourceRange();
16277 Diag(Method->getLocation(),
16278 diag::note_ovl_candidate_disabled_by_function_cond_attr)
16279 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16280 return ExprError();
16281 }
16282 }
16283
16284 if (isa<CXXConstructorDecl, CXXDestructorDecl>(CurContext) &&
16285 TheCall->getDirectCallee()->isPureVirtual()) {
16286 const FunctionDecl *MD = TheCall->getDirectCallee();
16287
16288 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
16289 MemExpr->performsVirtualDispatch(getLangOpts())) {
16290 Diag(MemExpr->getBeginLoc(),
16291 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16292 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
16293 << MD->getParent();
16294
16295 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
16296 if (getLangOpts().AppleKext)
16297 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
16298 << MD->getParent() << MD->getDeclName();
16299 }
16300 }
16301
16302 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
16303 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16304 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16305 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
16306 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16307 MemExpr->getMemberLoc());
16308 }
16309
16310 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
16311 TheCall->getDirectCallee());
16312}
16313
16316 SourceLocation LParenLoc,
16317 MultiExprArg Args,
16318 SourceLocation RParenLoc) {
16319 if (checkPlaceholderForOverload(*this, Obj))
16320 return ExprError();
16321 ExprResult Object = Obj;
16322
16323 UnbridgedCastsSet UnbridgedCasts;
16324 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16325 return ExprError();
16326
16327 assert(Object.get()->getType()->isRecordType() &&
16328 "Requires object type argument");
16329
16330 // C++ [over.call.object]p1:
16331 // If the primary-expression E in the function call syntax
16332 // evaluates to a class object of type "cv T", then the set of
16333 // candidate functions includes at least the function call
16334 // operators of T. The function call operators of T are obtained by
16335 // ordinary lookup of the name operator() in the context of
16336 // (E).operator().
16337 OverloadCandidateSet CandidateSet(LParenLoc,
16339 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
16340
16341 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
16342 diag::err_incomplete_object_call, Object.get()))
16343 return true;
16344
16345 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16346 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16347 LookupQualifiedName(R, Record);
16349
16350 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16351 Oper != OperEnd; ++Oper) {
16352 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
16353 Object.get()->Classify(Context), Args, CandidateSet,
16354 /*SuppressUserConversion=*/false);
16355 }
16356
16357 // When calling a lambda, both the call operator, and
16358 // the conversion operator to function pointer
16359 // are considered. But when constraint checking
16360 // on the call operator fails, it will also fail on the
16361 // conversion operator as the constraints are always the same.
16362 // As the user probably does not intend to perform a surrogate call,
16363 // we filter them out to produce better error diagnostics, ie to avoid
16364 // showing 2 failed overloads instead of one.
16365 bool IgnoreSurrogateFunctions = false;
16366 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16367 const OverloadCandidate &Candidate = *CandidateSet.begin();
16368 if (!Candidate.Viable &&
16370 IgnoreSurrogateFunctions = true;
16371 }
16372
16373 // C++ [over.call.object]p2:
16374 // In addition, for each (non-explicit in C++0x) conversion function
16375 // declared in T of the form
16376 //
16377 // operator conversion-type-id () cv-qualifier;
16378 //
16379 // where cv-qualifier is the same cv-qualification as, or a
16380 // greater cv-qualification than, cv, and where conversion-type-id
16381 // denotes the type "pointer to function of (P1,...,Pn) returning
16382 // R", or the type "reference to pointer to function of
16383 // (P1,...,Pn) returning R", or the type "reference to function
16384 // of (P1,...,Pn) returning R", a surrogate call function [...]
16385 // is also considered as a candidate function. Similarly,
16386 // surrogate call functions are added to the set of candidate
16387 // functions for each conversion function declared in an
16388 // accessible base class provided the function is not hidden
16389 // within T by another intervening declaration.
16390 const auto &Conversions = Record->getVisibleConversionFunctions();
16391 for (auto I = Conversions.begin(), E = Conversions.end();
16392 !IgnoreSurrogateFunctions && I != E; ++I) {
16393 NamedDecl *D = *I;
16394 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
16395 if (isa<UsingShadowDecl>(D))
16396 D = cast<UsingShadowDecl>(D)->getTargetDecl();
16397
16398 // Skip over templated conversion functions; they aren't
16399 // surrogates.
16400 if (isa<FunctionTemplateDecl>(D))
16401 continue;
16402
16403 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
16404 if (!Conv->isExplicit()) {
16405 // Strip the reference type (if any) and then the pointer type (if
16406 // any) to get down to what might be a function type.
16407 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16408 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16409 ConvType = ConvPtrType->getPointeeType();
16410
16411 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16412 {
16413 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
16414 Object.get(), Args, CandidateSet);
16415 }
16416 }
16417 }
16418
16419 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16420
16421 // Perform overload resolution.
16423 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
16424 Best)) {
16425 case OR_Success:
16426 // Overload resolution succeeded; we'll build the appropriate call
16427 // below.
16428 break;
16429
16430 case OR_No_Viable_Function: {
16432 CandidateSet.empty()
16433 ? (PDiag(diag::err_ovl_no_oper)
16434 << Object.get()->getType() << /*call*/ 1
16435 << Object.get()->getSourceRange())
16436 : (PDiag(diag::err_ovl_no_viable_object_call)
16437 << Object.get()->getType() << Object.get()->getSourceRange());
16438 CandidateSet.NoteCandidates(
16439 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
16440 OCD_AllCandidates, Args);
16441 break;
16442 }
16443 case OR_Ambiguous:
16444 if (!R.isAmbiguous())
16445 CandidateSet.NoteCandidates(
16446 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16447 PDiag(diag::err_ovl_ambiguous_object_call)
16448 << Object.get()->getType()
16449 << Object.get()->getSourceRange()),
16450 *this, OCD_AmbiguousCandidates, Args);
16451 break;
16452
16453 case OR_Deleted: {
16454 // FIXME: Is this diagnostic here really necessary? It seems that
16455 // 1. we don't have any tests for this diagnostic, and
16456 // 2. we already issue err_deleted_function_use for this later on anyway.
16457 StringLiteral *Msg = Best->Function->getDeletedMessage();
16458 CandidateSet.NoteCandidates(
16459 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16460 PDiag(diag::err_ovl_deleted_object_call)
16461 << Object.get()->getType() << (Msg != nullptr)
16462 << (Msg ? Msg->getString() : StringRef())
16463 << Object.get()->getSourceRange()),
16464 *this, OCD_AllCandidates, Args);
16465 break;
16466 }
16467 }
16468
16469 if (Best == CandidateSet.end())
16470 return true;
16471
16472 UnbridgedCasts.restore();
16473
16474 if (Best->Function == nullptr) {
16475 // Since there is no function declaration, this is one of the
16476 // surrogate candidates. Dig out the conversion function.
16477 CXXConversionDecl *Conv
16478 = cast<CXXConversionDecl>(
16479 Best->Conversions[0].UserDefined.ConversionFunction);
16480
16481 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
16482 Best->FoundDecl);
16483 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
16484 return ExprError();
16485 assert(Conv == Best->FoundDecl.getDecl() &&
16486 "Found Decl & conversion-to-functionptr should be same, right?!");
16487 // We selected one of the surrogate functions that converts the
16488 // object parameter to a function pointer. Perform the conversion
16489 // on the object argument, then let BuildCallExpr finish the job.
16490
16491 // Create an implicit member expr to refer to the conversion operator.
16492 // and then call it.
16493 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
16494 Conv, HadMultipleCandidates);
16495 if (Call.isInvalid())
16496 return ExprError();
16497 // Record usage of conversion in an implicit cast.
16499 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
16500 nullptr, VK_PRValue, CurFPFeatureOverrides());
16501
16502 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
16503 }
16504
16505 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
16506
16507 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16508 // that calls this method, using Object for the implicit object
16509 // parameter and passing along the remaining arguments.
16510 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16511
16512 // An error diagnostic has already been printed when parsing the declaration.
16513 if (Method->isInvalidDecl())
16514 return ExprError();
16515
16516 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16517 unsigned NumParams = Proto->getNumParams();
16518
16519 DeclarationNameInfo OpLocInfo(
16520 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
16521 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16522 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16523 Obj, HadMultipleCandidates,
16524 OpLocInfo.getLoc(),
16525 OpLocInfo.getInfo());
16526 if (NewFn.isInvalid())
16527 return true;
16528
16529 SmallVector<Expr *, 8> MethodArgs;
16530 MethodArgs.reserve(NumParams + 1);
16531
16532 bool IsError = false;
16533
16534 // Initialize the object parameter.
16536 if (Method->isExplicitObjectMemberFunction()) {
16537 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
16538 } else {
16539 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
16540 Object.get(), /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16541 if (ObjRes.isInvalid())
16542 IsError = true;
16543 else
16544 Object = ObjRes;
16545 MethodArgs.push_back(Object.get());
16546 }
16547
16549 *this, MethodArgs, Method, Args, LParenLoc);
16550
16551 // If this is a variadic call, handle args passed through "...".
16552 if (Proto->isVariadic()) {
16553 // Promote the arguments (C99 6.5.2.2p7).
16554 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16555 ExprResult Arg = DefaultVariadicArgumentPromotion(
16556 Args[i], VariadicCallType::Method, nullptr);
16557 IsError |= Arg.isInvalid();
16558 MethodArgs.push_back(Arg.get());
16559 }
16560 }
16561
16562 if (IsError)
16563 return true;
16564
16565 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16566
16567 // Once we've built TheCall, all of the expressions are properly owned.
16568 QualType ResultTy = Method->getReturnType();
16570 ResultTy = ResultTy.getNonLValueExprType(Context);
16571
16573 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
16574 CurFPFeatureOverrides());
16575
16576 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
16577 return true;
16578
16579 if (CheckFunctionCall(Method, TheCall, Proto))
16580 return true;
16581
16582 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
16583}
16584
16586 SourceLocation OpLoc,
16587 bool *NoArrowOperatorFound) {
16588 assert(Base->getType()->isRecordType() &&
16589 "left-hand side must have class type");
16590
16592 return ExprError();
16593
16594 SourceLocation Loc = Base->getExprLoc();
16595
16596 // C++ [over.ref]p1:
16597 //
16598 // [...] An expression x->m is interpreted as (x.operator->())->m
16599 // for a class object x of type T if T::operator->() exists and if
16600 // the operator is selected as the best match function by the
16601 // overload resolution mechanism (13.3).
16602 DeclarationName OpName =
16603 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
16605
16606 if (RequireCompleteType(Loc, Base->getType(),
16607 diag::err_typecheck_incomplete_tag, Base))
16608 return ExprError();
16609
16610 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16611 LookupQualifiedName(R, Base->getType()->castAsRecordDecl());
16613
16614 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16615 Oper != OperEnd; ++Oper) {
16616 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
16617 {}, CandidateSet,
16618 /*SuppressUserConversion=*/false);
16619 }
16620
16621 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16622
16623 // Perform overload resolution.
16625 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
16626 case OR_Success:
16627 // Overload resolution succeeded; we'll build the call below.
16628 break;
16629
16630 case OR_No_Viable_Function: {
16631 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
16632 if (CandidateSet.empty()) {
16633 QualType BaseType = Base->getType();
16634 if (NoArrowOperatorFound) {
16635 // Report this specific error to the caller instead of emitting a
16636 // diagnostic, as requested.
16637 *NoArrowOperatorFound = true;
16638 return ExprError();
16639 }
16640 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16641 << BaseType << Base->getSourceRange();
16642 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16643 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16644 << FixItHint::CreateReplacement(OpLoc, ".");
16645 }
16646 } else
16647 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16648 << "operator->" << Base->getSourceRange();
16649 CandidateSet.NoteCandidates(*this, Base, Cands);
16650 return ExprError();
16651 }
16652 case OR_Ambiguous:
16653 if (!R.isAmbiguous())
16654 CandidateSet.NoteCandidates(
16655 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16656 << "->" << Base->getType()
16657 << Base->getSourceRange()),
16659 return ExprError();
16660
16661 case OR_Deleted: {
16662 StringLiteral *Msg = Best->Function->getDeletedMessage();
16663 CandidateSet.NoteCandidates(
16664 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16665 << "->" << (Msg != nullptr)
16666 << (Msg ? Msg->getString() : StringRef())
16667 << Base->getSourceRange()),
16668 *this, OCD_AllCandidates, Base);
16669 return ExprError();
16670 }
16671 }
16672
16673 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
16674
16675 // Convert the object parameter.
16676 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16677
16678 if (Method->isExplicitObjectMemberFunction()) {
16679 ExprResult R = InitializeExplicitObjectArgument(*this, Base, Method);
16680 if (R.isInvalid())
16681 return ExprError();
16682 Base = R.get();
16683 } else {
16684 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
16685 Base, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16686 if (BaseResult.isInvalid())
16687 return ExprError();
16688 Base = BaseResult.get();
16689 }
16690
16691 // Build the operator call.
16692 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16693 Base, HadMultipleCandidates, OpLoc);
16694 if (FnExpr.isInvalid())
16695 return ExprError();
16696
16697 QualType ResultTy = Method->getReturnType();
16699 ResultTy = ResultTy.getNonLValueExprType(Context);
16700
16701 CallExpr *TheCall =
16702 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
16703 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
16704
16705 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
16706 return ExprError();
16707
16708 if (CheckFunctionCall(Method, TheCall,
16709 Method->getType()->castAs<FunctionProtoType>()))
16710 return ExprError();
16711
16712 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
16713}
16714
16716 DeclarationNameInfo &SuffixInfo,
16717 ArrayRef<Expr*> Args,
16718 SourceLocation LitEndLoc,
16719 TemplateArgumentListInfo *TemplateArgs) {
16720 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16721
16722 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16724 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
16725 TemplateArgs);
16726
16727 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16728
16729 // Perform overload resolution. This will usually be trivial, but might need
16730 // to perform substitutions for a literal operator template.
16732 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
16733 case OR_Success:
16734 case OR_Deleted:
16735 break;
16736
16738 CandidateSet.NoteCandidates(
16739 PartialDiagnosticAt(UDSuffixLoc,
16740 PDiag(diag::err_ovl_no_viable_function_in_call)
16741 << R.getLookupName()),
16742 *this, OCD_AllCandidates, Args);
16743 return ExprError();
16744
16745 case OR_Ambiguous:
16746 CandidateSet.NoteCandidates(
16747 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
16748 << R.getLookupName()),
16749 *this, OCD_AmbiguousCandidates, Args);
16750 return ExprError();
16751 }
16752
16753 FunctionDecl *FD = Best->Function;
16754 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
16755 nullptr, HadMultipleCandidates,
16756 SuffixInfo.getLoc(),
16757 SuffixInfo.getInfo());
16758 if (Fn.isInvalid())
16759 return true;
16760
16761 // Check the argument types. This should almost always be a no-op, except
16762 // that array-to-pointer decay is applied to string literals.
16763 Expr *ConvArgs[2];
16764 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16765 ExprResult InputInit = PerformCopyInitialization(
16767 SourceLocation(), Args[ArgIdx]);
16768 if (InputInit.isInvalid())
16769 return true;
16770 ConvArgs[ArgIdx] = InputInit.get();
16771 }
16772
16773 QualType ResultTy = FD->getReturnType();
16775 ResultTy = ResultTy.getNonLValueExprType(Context);
16776
16778 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
16779 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
16780
16781 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
16782 return ExprError();
16783
16784 if (CheckFunctionCall(FD, UDL, nullptr))
16785 return ExprError();
16786
16787 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
16788}
16789
16792 SourceLocation RangeLoc,
16793 const DeclarationNameInfo &NameInfo,
16794 LookupResult &MemberLookup,
16795 OverloadCandidateSet *CandidateSet,
16797 Scope *S = nullptr;
16798
16800 if (!MemberLookup.empty()) {
16801 ExprResult MemberRef =
16802 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
16803 /*IsPtr=*/false, CXXScopeSpec(),
16804 /*TemplateKWLoc=*/SourceLocation(),
16805 /*FirstQualifierInScope=*/nullptr,
16806 MemberLookup,
16807 /*TemplateArgs=*/nullptr, S);
16808 if (MemberRef.isInvalid()) {
16809 *CallExpr = ExprError();
16810 return FRS_DiagnosticIssued;
16811 }
16812 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
16813 if (CallExpr->isInvalid()) {
16814 *CallExpr = ExprError();
16815 return FRS_DiagnosticIssued;
16816 }
16817 } else {
16818 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16820 NameInfo, UnresolvedSet<0>());
16821 if (FnR.isInvalid())
16822 return FRS_DiagnosticIssued;
16823 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
16824
16825 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
16826 CandidateSet, CallExpr);
16827 if (CandidateSet->empty() || CandidateSetError) {
16828 *CallExpr = ExprError();
16829 return FRS_NoViableFunction;
16830 }
16832 OverloadingResult OverloadResult =
16833 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
16834
16835 if (OverloadResult == OR_No_Viable_Function) {
16836 *CallExpr = ExprError();
16837 return FRS_NoViableFunction;
16838 }
16839 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
16840 Loc, nullptr, CandidateSet, &Best,
16841 OverloadResult,
16842 /*AllowTypoCorrection=*/false);
16843 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16844 *CallExpr = ExprError();
16845 return FRS_DiagnosticIssued;
16846 }
16847 }
16848 return FRS_Success;
16849}
16850
16852 FunctionDecl *Fn) {
16853 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
16854 ExprResult SubExpr =
16855 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
16856 if (SubExpr.isInvalid())
16857 return ExprError();
16858 if (SubExpr.get() == PE->getSubExpr())
16859 return PE;
16860
16861 return new (Context)
16862 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16863 }
16864
16865 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
16866 ExprResult SubExpr =
16867 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
16868 if (SubExpr.isInvalid())
16869 return ExprError();
16870 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16871 SubExpr.get()->getType()) &&
16872 "Implicit cast type cannot be determined from overload");
16873 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16874 if (SubExpr.get() == ICE->getSubExpr())
16875 return ICE;
16876
16877 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
16878 SubExpr.get(), nullptr, ICE->getValueKind(),
16879 CurFPFeatureOverrides());
16880 }
16881
16882 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
16883 if (!GSE->isResultDependent()) {
16884 ExprResult SubExpr =
16885 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
16886 if (SubExpr.isInvalid())
16887 return ExprError();
16888 if (SubExpr.get() == GSE->getResultExpr())
16889 return GSE;
16890
16891 // Replace the resulting type information before rebuilding the generic
16892 // selection expression.
16893 ArrayRef<Expr *> A = GSE->getAssocExprs();
16894 SmallVector<Expr *, 4> AssocExprs(A);
16895 unsigned ResultIdx = GSE->getResultIndex();
16896 AssocExprs[ResultIdx] = SubExpr.get();
16897
16898 if (GSE->isExprPredicate())
16900 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
16901 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16902 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16903 ResultIdx);
16905 Context, GSE->getGenericLoc(), GSE->getControllingType(),
16906 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16907 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16908 ResultIdx);
16909 }
16910 // Rather than fall through to the unreachable, return the original generic
16911 // selection expression.
16912 return GSE;
16913 }
16914
16915 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
16916 assert(UnOp->getOpcode() == UO_AddrOf &&
16917 "Can only take the address of an overloaded function");
16918 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
16919 if (!Method->isImplicitObjectMemberFunction()) {
16920 // Do nothing: the address of static and
16921 // explicit object member functions is a (non-member) function pointer.
16922 } else {
16923 // Fix the subexpression, which really has to be an
16924 // UnresolvedLookupExpr holding an overloaded member function
16925 // or template.
16926 ExprResult SubExpr =
16927 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16928 if (SubExpr.isInvalid())
16929 return ExprError();
16930 if (SubExpr.get() == UnOp->getSubExpr())
16931 return UnOp;
16932
16933 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
16934 SubExpr.get(), Method))
16935 return ExprError();
16936
16937 assert(isa<DeclRefExpr>(SubExpr.get()) &&
16938 "fixed to something other than a decl ref");
16939 NestedNameSpecifier Qualifier =
16940 cast<DeclRefExpr>(SubExpr.get())->getQualifier();
16941 assert(Qualifier &&
16942 "fixed to a member ref with no nested name qualifier");
16943
16944 // We have taken the address of a pointer to member
16945 // function. Perform the computation here so that we get the
16946 // appropriate pointer to member type.
16947 QualType MemPtrType = Context.getMemberPointerType(
16948 Fn->getType(), Qualifier,
16949 cast<CXXRecordDecl>(Method->getDeclContext()));
16950 // Under the MS ABI, lock down the inheritance model now.
16951 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
16952 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
16953
16954 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
16955 MemPtrType, VK_PRValue, OK_Ordinary,
16956 UnOp->getOperatorLoc(), false,
16957 CurFPFeatureOverrides());
16958 }
16959 }
16960 ExprResult SubExpr =
16961 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16962 if (SubExpr.isInvalid())
16963 return ExprError();
16964 if (SubExpr.get() == UnOp->getSubExpr())
16965 return UnOp;
16966
16967 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
16968 SubExpr.get());
16969 }
16970
16971 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16972 if (Found.getAccess() == AS_none) {
16973 CheckUnresolvedLookupAccess(ULE, Found);
16974 }
16975 // FIXME: avoid copy.
16976 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16977 if (ULE->hasExplicitTemplateArgs()) {
16978 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
16979 TemplateArgs = &TemplateArgsBuffer;
16980 }
16981
16982 QualType Type = Fn->getType();
16983 ExprValueKind ValueKind =
16984 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
16985 ? VK_LValue
16986 : VK_PRValue;
16987
16988 // FIXME: Duplicated from BuildDeclarationNameExpr.
16989 if (unsigned BID = Fn->getBuiltinID()) {
16990 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
16991 Type = Context.BuiltinFnTy;
16992 ValueKind = VK_PRValue;
16993 }
16994 }
16995
16996 DeclRefExpr *DRE = BuildDeclRefExpr(
16997 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
16998 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
16999 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17000 return DRE;
17001 }
17002
17003 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
17004 // FIXME: avoid copy.
17005 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17006 if (MemExpr->hasExplicitTemplateArgs()) {
17007 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
17008 TemplateArgs = &TemplateArgsBuffer;
17009 }
17010
17011 Expr *Base;
17012
17013 // If we're filling in a static method where we used to have an
17014 // implicit member access, rewrite to a simple decl ref.
17015 if (MemExpr->isImplicitAccess()) {
17016 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17017 DeclRefExpr *DRE = BuildDeclRefExpr(
17018 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
17019 MemExpr->getQualifierLoc(), Found.getDecl(),
17020 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17021 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17022 return DRE;
17023 } else {
17024 SourceLocation Loc = MemExpr->getMemberLoc();
17025 if (MemExpr->getQualifier())
17026 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17027 Base =
17028 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
17029 }
17030 } else
17031 Base = MemExpr->getBase();
17032
17033 ExprValueKind valueKind;
17034 QualType type;
17035 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17036 valueKind = VK_LValue;
17037 type = Fn->getType();
17038 } else {
17039 valueKind = VK_PRValue;
17040 type = Context.BoundMemberTy;
17041 }
17042
17043 return BuildMemberExpr(
17044 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
17045 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
17046 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
17047 type, valueKind, OK_Ordinary, TemplateArgs);
17048 }
17049
17050 llvm_unreachable("Invalid reference to overloaded function");
17051}
17052
17055 FunctionDecl *Fn) {
17056 return FixOverloadedFunctionReference(E.get(), Found, Fn);
17057}
17058
17059bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17061 if (!PartialOverloading || !Function)
17062 return true;
17063 if (Function->isVariadic())
17064 return false;
17065 if (const auto *Proto =
17066 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
17067 if (Proto->isTemplateVariadic())
17068 return false;
17069 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17070 if (const auto *Proto =
17071 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
17072 if (Proto->isTemplateVariadic())
17073 return false;
17074 return true;
17075}
17076
17078 DeclarationName Name,
17079 OverloadCandidateSet &CandidateSet,
17080 FunctionDecl *Fn, MultiExprArg Args,
17081 bool IsMember) {
17082 StringLiteral *Msg = Fn->getDeletedMessage();
17083 CandidateSet.NoteCandidates(
17084 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
17085 << IsMember << Name << (Msg != nullptr)
17086 << (Msg ? Msg->getString() : StringRef())
17087 << Range),
17088 *this, OCD_AllCandidates, Args);
17089}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3597
StringRef P
Defines the Diagnostic-related interfaces.
static bool isBooleanType(QualType Ty)
const Decl * D
Expr * E
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, EvalInfo &Info)
LangStandard::Kind Std
#define X(type, name)
Definition: Value.h:145
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition: MachO.h:31
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
This file declares semantic analysis functions specific to ARM.
static bool hasExplicitAttr(const VarDecl *D)
Definition: SemaCUDA.cpp:31
This file declares semantic analysis for CUDA constructs.
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
static bool isRecordType(QualType T)
static void TryUserDefinedConversion(Sema &S, QualType DestType, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence, bool TopLevelOfInitList)
Attempt a user-defined conversion between two types (C++ [dcl.init]), which enumerates all conversion...
Definition: SemaInit.cpp:6060
SourceRange Range
Definition: SemaObjC.cpp:753
SourceLocation Loc
Definition: SemaObjC.cpp:754
This file declares semantic analysis for Objective-C.
static ImplicitConversionSequence::CompareKind CompareStandardConversionSequences(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareStandardConversionSequences - Compare two standard conversion sequences to determine whether o...
static bool sameFunctionParameterTypeLists(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2, bool IsFn1Reversed, bool IsFn2Reversed)
We're allowed to use constraints partial ordering only if the candidates have the same parameter type...
static bool isNullPointerConstantForConversion(Expr *Expr, bool InOverloadResolution, ASTContext &Context)
static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn)
static const FunctionType * getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv)
static bool functionHasPassObjectSizeParams(const FunctionDecl *FD)
static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, const FunctionDecl *Cand2)
Compares the enable_if attributes of two FunctionDecls, for the purposes of overload resolution.
static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr *ArgExpr)
CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, if any, found in visible typ...
FixedEnumPromotion
static void AddOverloadedCallCandidate(Sema &S, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading, bool KnownValid)
Add a single candidate to the overload set.
static void AddTemplateOverloadCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit, Sema::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction)
static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, OverloadCandidateSet *CandidateSet, OverloadCandidateSet::iterator *Best, OverloadingResult OverloadResult, bool AllowTypoCorrection)
FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns the completed call expre...
static bool isQualificationConversionStep(QualType FromType, QualType ToType, bool CStyle, bool IsTopLevel, bool &PreviousToQualsIncludeConst, bool &ObjCLifetimeConversion, const ASTContext &Ctx)
Perform a single iteration of the loop for checking if a qualification conversion is valid.
static ImplicitConversionSequence::CompareKind CompareQualificationConversions(Sema &S, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareQualificationConversions - Compares two standard conversion sequences to determine whether the...
static void dropPointerConversion(StandardConversionSequence &SCS)
dropPointerConversions - If the given standard conversion sequence involves any pointer conversions,...
static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand)
static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, unsigned NumFormalArgs, bool IsAddressOf=false)
General arity mismatch diagnosis over a candidate in a candidate set.
static const Expr * IgnoreNarrowingConversion(ASTContext &Ctx, const Expr *Converted)
Skip any implicit casts which could be either part of a narrowing conversion or after one in an impli...
static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1, const FunctionDecl *F2)
static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI)
static QualType BuildSimilarlyQualifiedPointerType(const Type *FromPtr, QualType ToPointee, QualType ToType, ASTContext &Context, bool StripObjCLifetime=false)
BuildSimilarlyQualifiedPointerType - In a pointer conversion from the pointer type FromPtr to a point...
static void forAllQualifierCombinations(QualifiersAndAtomic Quals, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static bool FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, QualType DeclType, SourceLocation DeclLoc, Expr *Init, QualType T2, bool AllowRvalues, bool AllowExplicit)
Look for a user-defined conversion to a value reference-compatible with DeclType.
static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static Expr * GetExplicitObjectExpr(Sema &S, Expr *Obj, const FunctionDecl *Fun)
static bool hasDeprecatedStringLiteralToCharPtrConversion(const ImplicitConversionSequence &ICS)
static void AddBuiltinAssignmentOperatorCandidates(Sema &S, QualType T, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
Helper function for AddBuiltinOperatorCandidates() that adds the volatile- and non-volatile-qualified...
static bool CheckConvertedConstantConversions(Sema &S, StandardConversionSequence &SCS)
Check that the specified conversion is permitted in a converted constant expression,...
static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, SourceLocation OpLoc, OverloadCandidate *Cand)
static ImplicitConversionSequence::CompareKind compareConversionFunctions(Sema &S, FunctionDecl *Function1, FunctionDecl *Function2)
Compare the user-defined conversion functions or constructors of two user-defined conversion sequence...
static void forAllQualifierCombinationsImpl(QualifiersAndAtomic Available, QualifiersAndAtomic Applied, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static const char * GetImplicitConversionName(ImplicitConversionKind Kind)
GetImplicitConversionName - Return the name of this kind of implicit conversion.
static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, bool Complain, bool InOverloadResolution, SourceLocation Loc)
Returns true if we can take the address of the function.
static ImplicitConversionSequence::CompareKind CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareDerivedToBaseConversions - Compares two standard conversion sequences to determine whether the...
static bool convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, ArrayRef< Expr * > Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, Expr *&ConvertedThis, SmallVectorImpl< Expr * > &ConvertedArgs)
static TemplateDecl * getDescribedTemplate(Decl *Templated)
static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, ArrayRef< Expr * > Args, OverloadCandidateSet::CandidateSetKind CSK)
CompleteNonViableCandidate - Normally, overload resolution only computes up to the first bad conversi...
static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs)
Adopt the given qualifiers for the given type.
static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, OverloadCandidate *Cand)
static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, unsigned NumArgs, bool IsAddressOf=false)
Additional arity mismatch diagnosis specific to a function overload candidates.
static ImplicitConversionSequence::CompareKind compareStandardConversionSubsets(ASTContext &Context, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
static bool hasDependentExplicit(FunctionTemplateDecl *FTD)
static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, ImplicitConversionKind &ElConv, Expr *From, bool InOverloadResolution, bool CStyle)
Determine whether the conversion from FromType to ToType is a valid vector conversion.
static ImplicitConversionSequence TryContextuallyConvertToObjCPointer(Sema &S, Expr *From)
TryContextuallyConvertToObjCPointer - Attempt to contextually convert the expression From to an Objec...
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static ExprResult CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base, bool HadMultipleCandidates, SourceLocation Loc=SourceLocation(), const DeclarationNameLoc &LocInfo=DeclarationNameLoc())
A convenience routine for creating a decayed reference to a function.
static std::optional< QualType > getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F)
Compute the type of the implicit object parameter for the given function, if any.
static bool checkPlaceholderForOverload(Sema &S, Expr *&E, UnbridgedCastsSet *unbridgedCasts=nullptr)
checkPlaceholderForOverload - Do any interesting placeholder-like preprocessing on the given expressi...
static FixedEnumPromotion getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS)
Returns kind of fixed enum promotion the SCS uses.
static bool isAllowableExplicitConversion(Sema &S, QualType ConvType, QualType ToType, bool AllowObjCPointerConversion)
Determine whether this is an allowable conversion from the result of an explicit conversion operator ...
static bool isNonViableMultiVersionOverload(FunctionDecl *FD)
static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X, const FunctionDecl *Y)
static ImplicitConversionSequence TryImplicitConversion(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion, bool AllowObjCConversionOnExplicit)
TryImplicitConversion - Attempt to perform an implicit conversion from the given expression (Expr) to...
static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest, APValue &PreNarrowingValue)
BuildConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static bool IsVectorElementConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, Expr *From)
static ImplicitConversionSequence TryListConversion(Sema &S, InitListExpr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion)
TryListConversion - Try to copy-initialize a value of type ToType from the initializer list From.
static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, bool UseOverrideRules=false)
static QualType withoutUnaligned(ASTContext &Ctx, QualType T)
static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand)
CUDA: diagnose an invalid call across targets.
static void MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef< OverloadCandidate > Cands)
static bool diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, UnresolvedSetImpl &ExplicitConversions)
static void AddMethodTemplateCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, OverloadCandidateParamOrder PO)
static void AddTemplateConversionCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion)
static ImplicitConversionSequence TryContextuallyConvertToBool(Sema &S, Expr *From)
TryContextuallyConvertToBool - Attempt to contextually convert the expression From to bool (C++0x [co...
static ImplicitConversionSequence TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, Expr::Classification FromClassification, CXXMethodDecl *Method, const CXXRecordDecl *ActingContext, bool InOverloadResolution=false, QualType ExplicitParameterType=QualType(), bool SuppressUserConversion=false)
TryObjectArgumentInitialization - Try to initialize the object parameter of the given member function...
static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, DeclAccessPair &Found)
static ImplicitConversionSequence::CompareKind CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, const ImplicitConversionSequence &ICS1, const ImplicitConversionSequence &ICS2)
CompareImplicitConversionSequences - Compare two implicit conversion sequences to determine whether o...
@ ft_different_class
@ ft_parameter_mismatch
@ ft_noexcept
@ ft_return_type
@ ft_parameter_arity
@ ft_default
@ ft_qualifer_mismatch
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)
static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, Expr *Arg)
Helper function for adjusting address spaces for the pointer or reference operands of builtin operato...
static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand)
static bool DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, CXXRecordDecl **FoundInClass=nullptr)
Attempt to recover from an ill-formed use of a non-dependent name in a template, where the non-depend...
static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
Determine whether one of the given reference bindings is better than the other based on what kind of ...
static bool canBeDeclaredInNamespace(const DeclarationName &Name)
Determine whether a declaration with the specified name could be moved into a different namespace.
static ExprResult finishContextualImplicitConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter)
static bool IsStandardConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle, bool AllowObjCWritebackConversion)
IsStandardConversion - Determines whether there is a standard conversion sequence (C++ [conv],...
static bool DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args)
Attempt to recover from ill-formed use of a non-dependent operator in a template, where the non-depen...
static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, Qualifiers ToQuals)
Determine whether the lifetime conversion between the two given qualifiers sets is nontrivial.
static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I, bool TakingCandidateAddress)
static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, bool Complain=true)
static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc, Expr *FirstOperand, FunctionDecl *EqFD)
static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, const FunctionDecl *FD)
static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method, Expr *Object, MultiExprArg &Args, SmallVectorImpl< Expr * > &NewArgs)
static OverloadingResult IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, CXXRecordDecl *To, UserDefinedConversionSequence &User, OverloadCandidateSet &CandidateSet, bool AllowExplicit)
static bool checkAddressOfCandidateIsAvailable(Sema &S, const FunctionDecl *FD)
static bool IsFloatingPointConversion(Sema &S, QualType FromType, QualType ToType)
Determine whether the conversion from FromType to ToType is a valid floating point conversion.
static bool isFirstArgumentCompatibleWithType(ASTContext &Context, CXXConstructorDecl *Constructor, QualType Type)
static Comparison isBetterMultiversionCandidate(const OverloadCandidate &Cand1, const OverloadCandidate &Cand2)
static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn)
static void collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, UnresolvedSetImpl &ViableConversions, OverloadCandidateSet &CandidateSet)
static ImplicitConversionSequence TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, SourceLocation DeclLoc, bool SuppressUserConversions, bool AllowExplicit)
Compute an implicit conversion sequence for reference initialization.
static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD)
Determine whether a given function template has a simple explicit specifier or a non-value-dependent ...
static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args, UnbridgedCastsSet &unbridged)
checkArgPlaceholdersForOverload - Check a set of call operands for placeholders.
static QualType makeQualifiedLValueReferenceType(QualType Base, QualifiersAndAtomic Quals, Sema &S)
static QualType chooseRecoveryType(OverloadCandidateSet &CS, OverloadCandidateSet::iterator *Best)
static void AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet, DeferredMethodTemplateOverloadCandidate &C)
static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand)
static ExprResult BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MutableArrayRef< Expr * > Args, SourceLocation RParenLoc, bool EmptyLookup, bool AllowTypoCorrection)
Attempts to recover from a call where no functions were found.
static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand)
static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, bool ArgDependent, SourceLocation Loc, CheckFn &&IsSuccessful)
static OverloadingResult IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, UserDefinedConversionSequence &User, OverloadCandidateSet &Conversions, AllowedExplicit AllowExplicit, bool AllowObjCConversionOnExplicit)
Determines whether there is a user-defined conversion sequence (C++ [over.ics.user]) that converts ex...
static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, FunctionDecl *Fn, ArrayRef< Expr * > Args)
IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is an acceptable non-member overloaded ...
static FunctionDecl * getMorePartialOrderingConstrained(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2, bool IsFn1Reversed, bool IsFn2Reversed)
static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, DeductionFailureInfo &DeductionFailure, unsigned NumArgs, bool TakingCandidateAddress)
Diagnose a failed template-argument deduction.
static bool IsTransparentUnionStandardConversion(Sema &S, Expr *From, QualType &ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static const FunctionProtoType * tryGetFunctionProtoType(QualType FromType)
Attempts to get the FunctionProtoType from a Type.
static bool PrepareArgumentsForCallToObjectOfClassType(Sema &S, SmallVectorImpl< Expr * > &MethodArgs, CXXMethodDecl *Method, MultiExprArg Args, SourceLocation LParenLoc)
static TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< TemplateArgument > Ps, ArrayRef< TemplateArgument > As, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool NumberOfArgumentsMustMatch, bool PartialOrdering, PackFold PackFold, bool *HasDeducedAnyParam)
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
__device__ __2f16 b
__device__ int
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:892
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
bool isAbsent() const
Definition: APValue.h:463
bool isFloat() const
Definition: APValue.h:468
bool isInt() const
Definition: APValue.h:467
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:956
APFloat & getFloat()
Definition: APValue.h:503
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:3056
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
Definition: ASTContext.h:1231
unsigned getIntWidth(QualType T) const
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
CanQualType Int128Ty
Definition: ASTContext.h:1231
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:744
CanQualType FloatTy
Definition: ASTContext.h:1234
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2851
bool mergeExtParameterInfo(const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, bool &CanUseFirst, bool &CanUseSecond, SmallVectorImpl< FunctionProtoType::ExtParameterInfo > &NewParamInfos)
This function merges the ExtParameterInfo lists of two functions.
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2867
CanQualType DoubleTy
Definition: ASTContext.h:1234
CanQualType LongDoubleTy
Definition: ASTContext.h:1234
CanQualType Char16Ty
Definition: ASTContext.h:1229
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 DependentTy
Definition: ASTContext.h:1250
CanQualType NullPtrTy
Definition: ASTContext.h:1249
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:742
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:894
QualType removePtrSizeAddrSpace(QualType T) const
Remove the existing address space on the type if it is a pointer size address space and return the ty...
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.
bool canBindObjCObjectType(QualType To, QualType From)
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
CanQualType Ibm128Ty
Definition: ASTContext.h:1234
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>.
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
Definition: ASTContext.h:2565
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
Definition: ASTContext.h:1223
const TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:860
CanQualType Float128Ty
Definition: ASTContext.h:1234
CanQualType UnsignedLongTy
Definition: ASTContext.h:1232
bool hasAnyFunctionEffects() const
Definition: ASTContext.h:3155
QualType getRestrictType(QualType T) const
Return the uniqued reference to the type for a restrict qualified type.
Definition: ASTContext.h:1441
CanQualType BoundMemberTy
Definition: ASTContext.h:1250
CanQualType CharTy
Definition: ASTContext.h:1224
CanQualType IntTy
Definition: ASTContext.h:1231
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2442
CanQualType SignedCharTy
Definition: ASTContext.h:1231
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
Definition: ASTContext.h:1250
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2333
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2898
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.
Definition: ASTContext.h:2625
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:1233
CanQualType BuiltinFnTy
Definition: ASTContext.h:1252
CanQualType VoidTy
Definition: ASTContext.h:1222
CanQualType UnsignedCharTy
Definition: ASTContext.h:1232
CanQualType UnsignedIntTy
Definition: ASTContext.h:1232
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
Definition: ASTContext.h:1450
CanQualType UnknownAnyTy
Definition: ASTContext.h:1251
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1233
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
CanQualType UnsignedShortTy
Definition: ASTContext.h:1232
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1750
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
CanQualType ShortTy
Definition: ASTContext.h:1231
bool hasSimilarType(QualType T1, QualType T2) const
Determine if two types are similar, according to the C++ rules.
CanQualType Char32Ty
Definition: ASTContext.h:1230
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.
Definition: ASTContext.h:2437
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:859
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
bool UnwrapSimilarTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
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
Definition: ASTContext.h:1231
CanQualType getCanonicalTagType(const TagDecl *TD) const
CanQualType WCharTy
Definition: ASTContext.h:1225
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
CanQualType Char8Ty
Definition: ASTContext.h:1228
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:3908
QualType getConstantArrayType(const ASTContext &Ctx) const
Definition: Type.cpp:279
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: TypeBase.h:3738
QualType getElementType() const
Definition: TypeBase.h:3750
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: TypeBase.h:8142
Attr - This represents one attribute.
Definition: Attr.h:44
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3974
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition: Expr.cpp:2175
StringRef getOpcodeStr() const
Definition: Expr.h:4040
bool isCompoundAssignmentOp() const
Definition: Expr.h:4118
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:4938
Pointer to a block type.
Definition: TypeBase.h:3558
This class is used for builtin types like 'int'.
Definition: TypeBase.h:3182
Kind getKind() const
Definition: TypeBase.h:3230
bool isDirectlyAddressable(unsigned ID) const
Determines whether this builtin can have its address taken with no special action required.
Definition: Builtins.h:341
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2604
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition: DeclCXX.cpp:3019
bool isConvertingConstructor(bool AllowExplicit) const
Whether this constructor is a converting constructor (C++ [class.conv.ctor]), which can be used for u...
Definition: DeclCXX.cpp:3056
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2937
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition: DeclCXX.h:2973
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2977
Represents a call to a member function that may be written either with member call syntax (e....
Definition: ExprCXX.h:179
static CXXMemberCallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RP, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0)
Definition: ExprCXX.cpp:692
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2129
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition: DeclCXX.cpp:2703
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition: DeclCXX.cpp:2710
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition: DeclCXX.cpp:2820
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2255
static CXXOperatorCallExpr * Create(const ASTContext &Ctx, OverloadedOperatorKind OpKind, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation OperatorLoc, FPOptionsOverride FPFeatures, ADLCallKind UsesADL=NotADL)
Definition: ExprCXX.cpp:624
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1018
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition: DeclCXX.cpp:1977
bool hasDefinition() const
Definition: DeclCXX.h:561
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1736
A rewritten comparison expression that was originally written using operator syntax.
Definition: ExprCXX.h:286
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:73
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:178
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:103
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2879
static CallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0, ADLCallKind UsesADL=NotADL)
Create a call expression.
Definition: Expr.cpp:1513
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3062
void setUsesMemberSyntax(bool V=true)
Definition: Expr.h:3043
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition: Expr.h:3261
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)
Builds a canonical type from a QualType.
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.
Definition: CanonicalType.h:84
const ComparisonCategoryInfo * lookupInfoForType(QualType Ty) const
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:3293
QualType getElementType() const
Definition: TypeBase.h:3303
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:4960
Represents the canonical version of C arrays with a specified constant size.
Definition: TypeBase.h:3776
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:346
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:37
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2109
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1879
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:2040
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1272
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:1465
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition: DeclBase.cpp:263
T * getAttr() const
Definition: DeclBase.h:573
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:524
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:593
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
Definition: DeclBase.cpp:1199
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:251
bool isInvalidDecl() const
Definition: DeclBase.h:588
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:559
SourceLocation getLocation() const
Definition: DeclBase.h:439
DeclContext * getDeclContext()
Definition: DeclBase.h:448
AccessSpecifier getAccess() const
Definition: DeclBase.h:507
specific_attr_iterator< T > specific_attr_end() const
Definition: DeclBase.h:569
specific_attr_iterator< T > specific_attr_begin() const
Definition: DeclBase.h:564
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:918
bool hasAttr() const
Definition: DeclBase.h:577
DeclarationNameLoc - Additional source/type location info for a declaration name.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
TemplateDecl * getCXXDeductionGuideTemplate() const
If this name is the name of a C++ deduction guide, return the template associated with that name.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:830
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:854
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition: Diagnostic.h:776
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition: Diagnostic.h:761
OverloadsShown getShowOverloads() const
Definition: Diagnostic.h:752
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition: Diagnostic.h:591
RAII object that enters a new expression evaluation context.
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4213
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: TypeBase.h:6522
EnumDecl * getOriginalDecl() const
Definition: TypeBase.h:6529
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1924
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition: DeclCXX.h:1948
ExplicitSpecKind getKind() const
Definition: DeclCXX.h:1932
const Expr * getExpr() const
Definition: DeclCXX.h:1933
static ExplicitSpecifier getFromDecl(FunctionDecl *Function)
Definition: DeclCXX.cpp:2354
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition: ExprCXX.cpp:1464
The return type of classify().
Definition: Expr.h:337
bool isLValue() const
Definition: Expr.h:387
bool isPRValue() const
Definition: Expr.h:390
bool isXValue() const
Definition: Expr.h:388
static Classification makeSimpleLValue()
Create a simple, modifiable lvalue.
Definition: Expr.h:395
bool isRValue() const
Definition: Expr.h:391
This represents one expression.
Definition: Expr.h:112
bool isIntegerConstantExpr(const ASTContext &Ctx) const
bool isGLValue() const
Definition: Expr.h:287
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3078
void setType(QualType t)
Definition: Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:444
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:194
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3069
bool isPRValue() const
Definition: Expr.h:285
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition: Expr.cpp:3293
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:4164
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:833
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:837
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:451
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition: Expr.h:813
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:4001
ConstantExprKind
Definition: Expr.h:751
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:273
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition: Expr.h:476
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition: Expr.h:412
QualType getType() const
Definition: Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:523
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:434
ExtVectorType - Extended vector type.
Definition: TypeBase.h:4283
Represents difference between two FPOptions values.
Definition: LangOptions.h:919
Represents a member of a struct/union/class.
Definition: Decl.h:3157
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:78
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:139
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:102
Represents a function declaration or definition.
Definition: Decl.h:1999
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2686
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2794
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4134
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3703
param_iterator param_end()
Definition: Decl.h:2784
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition: Decl.cpp:3607
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3806
QualType getReturnType() const
Definition: Decl.h:2842
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2771
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition: Decl.cpp:4205
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4254
param_iterator param_begin()
Definition: Decl.h:2783
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3125
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4270
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4198
unsigned getNumNonObjectParams() const
Definition: Decl.cpp:3810
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2469
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:4071
bool isConsteval() const
Definition: Decl.h:2481
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition: Decl.cpp:3651
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition: Decl.h:2859
bool isTargetMultiVersionDefault() const
True if this function is the default version of a multiversioned dispatch function as a part of the t...
Definition: Decl.cpp:3656
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3767
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2682
Represents a prototype with parameter type info, e.g.
Definition: TypeBase.h:5282
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: TypeBase.h:5786
unsigned getNumParams() const
Definition: TypeBase.h:5560
Qualifiers getMethodQuals() const
Definition: TypeBase.h:5708
QualType getParamType(unsigned i) const
Definition: TypeBase.h:5562
bool isVariadic() const
Whether this function prototype is variadic.
Definition: TypeBase.h:5686
ArrayRef< QualType > param_types() const
Definition: TypeBase.h:5722
Declaration of a template function.
Definition: DeclTemplate.h:952
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Definition: DeclTemplate.h:998
A class which abstracts out some details necessary for making a call.
Definition: TypeBase.h:4589
ExtInfo withNoReturn(bool noReturn) const
Definition: TypeBase.h:4660
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition: TypeBase.h:4517
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: TypeBase.h:4478
ExtInfo getExtInfo() const
Definition: TypeBase.h:4834
CallingConv getCallConv() const
Definition: TypeBase.h:4833
QualType getReturnType() const
Definition: TypeBase.h:4818
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition: TypeBase.h:4846
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:4560
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:3789
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2068
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:615
void dump() const
dump - Print this implicit conversion sequence to standard error.
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence.
Definition: Overload.h:666
void setBad(BadConversionSequence::FailureKind Failure, Expr *FromExpr, QualType ToType)
Sets this sequence as a bad conversion for an explicit argument.
Definition: Overload.h:763
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition: Overload.h:670
static ImplicitConversionSequence getNullptrToBool(QualType SourceType, QualType DestType, bool NeedLValToRVal)
Form an "implicit" conversion sequence from nullptr_t to bool, for a direct-initialization of a bool ...
Definition: Overload.h:820
AmbiguousConversionSequence Ambiguous
When ConversionKind == AmbiguousConversion, provides the details of the ambiguous conversion.
Definition: Overload.h:674
bool hasInitializerListContainerType() const
Definition: Overload.h:802
unsigned getKindRank() const
Return a ranking of the implicit conversion sequence kind, where smaller ranks represent better conve...
Definition: Overload.h:727
bool isInitializerListOfIncompleteArray() const
Definition: Overload.h:809
BadConversionSequence Bad
When ConversionKind == BadConversion, provides the details of the bad conversion.
Definition: Overload.h:678
QualType getInitializerListContainerType() const
Definition: Overload.h:812
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition: Expr.h:5235
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition: Expr.h:5350
unsigned getNumInits() const
Definition: Expr.h:5265
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:2491
const Expr * getInit(unsigned Init) const
Definition: Expr.h:5289
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:2509
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static InitializedEntity InitializeTemplateParameter(QualType T, NamedDecl *Param)
Create the initialization entity for a template parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:971
An lvalue reference type, per C++11 [dcl.ref].
Definition: TypeBase.h:3633
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:619
Represents the results of name lookup.
Definition: Lookup.h:147
void addAllDecls(const LookupResult &Other)
Add all the declarations from another set of lookup results.
Definition: Lookup.h:488
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:607
DeclClass * getAsSingle() const
Definition: Lookup.h:558
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:475
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Definition: SemaLookup.cpp:488
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:666
bool isAmbiguous() const
Definition: Lookup.h:324
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:275
void suppressAccessDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup due to access control violat...
Definition: Lookup.h:643
const UnresolvedSetImpl & asUnresolvedSet() const
Definition: Lookup.h:354
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:636
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:265
iterator end() const
Definition: Lookup.h:359
iterator begin() const
Definition: Lookup.h:358
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3300
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition: Expr.h:3489
NestedNameSpecifier getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition: Expr.h:3411
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3383
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition: Expr.h:3397
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition: Expr.h:3518
Expr * getBase() const
Definition: Expr.h:3377
void setBase(Expr *E)
Definition: Expr.h:3376
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1790
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:3495
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition: Expr.h:3387
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: TypeBase.h:3669
NestedNameSpecifier getQualifier() const
Definition: TypeBase.h:3701
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition: Type.cpp:5502
QualType getPointeeType() const
Definition: TypeBase.h:3687
Describes a module or submodule.
Definition: Module.h:144
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition: Module.cpp:239
This represents a decl that may have a name.
Definition: Decl.h:273
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:300
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:339
std::string getQualifiedNameAsString() const
Definition: Decl.cpp:1680
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1206
Represent a C++ namespace.
Definition: Decl.h:591
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Represents an ObjC class declaration.
Definition: DeclObjC.h:1154
Interfaces are the core concept in Objective-C for object oriented design.
Definition: TypeBase.h:7905
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition: TypeBase.h:7961
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition: TypeBase.h:8050
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition: TypeBase.h:8019
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: TypeBase.h:7973
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition: TypeBase.h:8013
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1840
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition: TypeBase.h:8025
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1180
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:1153
void clear(CandidateSetKind CSK)
Clear out all of the candidates.
void AddDeferredTemplateCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit, CallExpr::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction)
bool isNewCandidate(Decl *F, OverloadCandidateParamOrder PO=OverloadCandidateParamOrder::Normal)
Determine when this overload candidate will be new to the overload set.
Definition: Overload.h:1353
void AddDeferredConversionTemplateCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion)
void AddDeferredMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, OverloadCandidateParamOrder PO)
void DisableResolutionByPerfectCandidate()
Definition: Overload.h:1451
ConversionSequenceList allocateConversionSequences(unsigned NumConversions)
Allocate storage for conversion sequences for NumConversions conversions.
Definition: Overload.h:1385
llvm::MutableArrayRef< Expr * > getPersistentArgsArray(unsigned N)
Provide storage for any Expr* arg that must be preserved until deferred template candidates are deduc...
Definition: Overload.h:1401
OperatorRewriteInfo getRewriteInfo() const
Definition: Overload.h:1343
bool shouldDeferTemplateArgumentDeduction(const LangOptions &Opts) const
Definition: Overload.h:1542
@ CSK_AddressOfOverloadSet
C++ [over.match.call.general] Resolve a call through the address of an overload set.
Definition: Overload.h:1178
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition: Overload.h:1174
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition: Overload.h:1169
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1157
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition: Overload.h:1164
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1369
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
bool shouldDeferDiags(Sema &S, ArrayRef< Expr * > Args, SourceLocation OpLoc)
Whether diagnostics should be deferred.
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
void exclude(Decl *F)
Exclude a function from being considered by overload resolution.
Definition: Overload.h:1361
SourceLocation getLocation() const
Definition: Overload.h:1341
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions={})
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition: Overload.h:1416
void InjectNonDeducedTemplateCandidates(Sema &S)
CandidateSetKind getKind() const
Definition: Overload.h:1342
size_t nonDeferredCandidatesCount() const
Definition: Overload.h:1376
SmallVector< OverloadCandidate *, 32 > CompleteCandidates(Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, SourceLocation OpLoc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition: ExprCXX.h:3122
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition: ExprCXX.h:3274
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3183
NestedNameSpecifier getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition: ExprCXX.h:3238
SourceLocation getNameLoc() const
Gets the location of the name.
Definition: ExprCXX.h:3235
decls_iterator decls_begin() const
Definition: ExprCXX.h:3215
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition: ExprCXX.h:3226
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition: ExprCXX.h:3248
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition: ExprCXX.h:3244
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition: ExprCXX.h:3336
decls_iterator decls_end() const
Definition: ExprCXX.h:3218
DeclarationName getName() const
Gets the name looked up.
Definition: ExprCXX.h:3232
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:256
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2184
Represents a parameter to a function.
Definition: Decl.h:1789
bool isEquivalent(PointerAuthQualifier Other) const
Definition: TypeBase.h:301
std::string getAsString() const
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: TypeBase.h:3346
QualType getPointeeType() const
Definition: TypeBase.h:3356
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition: Expr.cpp:5032
A (possibly-)qualified type.
Definition: TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: TypeBase.h:8427
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: TypeBase.h:8421
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: TypeBase.h:8432
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3591
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: TypeBase.h:1225
void addConst()
Add the const type qualifier to this QualType.
Definition: TypeBase.h:1156
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: TypeBase.h:8343
LangAS getAddressSpace() const
Return the address space of this type.
Definition: TypeBase.h:8469
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: TypeBase.h:8383
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:8528
QualType getCanonicalType() const
Definition: TypeBase.h:8395
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: TypeBase.h:8437
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition: TypeBase.h:1089
bool isMoreQualifiedThan(QualType Other, const ASTContext &Ctx) const
Determine whether this type is more qualified than the other given type, requiring exact equality for...
Definition: TypeBase.h:8497
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: TypeBase.h:8416
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: TypeBase.h:8464
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: TypeBase.h:8389
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: TypeBase.h:1332
bool isAtLeastAsQualifiedAs(QualType Other, const ASTContext &Ctx) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition: TypeBase.h:8508
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: TypeBase.h:8375
A qualifier set is used to build a set of qualifiers.
Definition: TypeBase.h:8283
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: TypeBase.h:8290
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:4710
bool hasAtomic() const
Definition: TypeBase.h:841
bool hasRestrict() const
Definition: TypeBase.h:840
QualifiersAndAtomic withVolatile()
Definition: TypeBase.h:853
QualifiersAndAtomic withAtomic()
Definition: TypeBase.h:860
bool hasVolatile() const
Definition: TypeBase.h:838
The collection of all-type qualifiers we support.
Definition: TypeBase.h:331
unsigned getCVRQualifiers() const
Definition: TypeBase.h:488
GC getObjCGCAttr() const
Definition: TypeBase.h:519
bool hasOnlyConst() const
Definition: TypeBase.h:458
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: TypeBase.h:354
void removeObjCLifetime()
Definition: TypeBase.h:551
bool hasConst() const
Definition: TypeBase.h:457
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition: TypeBase.h:727
void addRestrict()
Definition: TypeBase.h:480
bool hasRestrict() const
Definition: TypeBase.h:477
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition: TypeBase.h:708
void removeObjCGCAttr()
Definition: TypeBase.h:523
void removeUnaligned()
Definition: TypeBase.h:515
void removeAddressSpace()
Definition: TypeBase.h:596
void setAddressSpace(LangAS space)
Definition: TypeBase.h:591
bool hasVolatile() const
Definition: TypeBase.h:467
PointerAuthQualifier getPointerAuth() const
Definition: TypeBase.h:603
bool hasObjCGCAttr() const
Definition: TypeBase.h:518
ObjCLifetime getObjCLifetime() const
Definition: TypeBase.h:545
void removeVolatile()
Definition: TypeBase.h:469
std::string getAsString() const
LangAS getAddressSpace() const
Definition: TypeBase.h:571
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition: TypeBase.h:750
void addVolatile()
Definition: TypeBase.h:470
An rvalue reference type, per C++11 [dcl.ref].
Definition: TypeBase.h:3651
Represents a struct/union/class.
Definition: Decl.h:4309
field_range fields() const
Definition: Decl.h:4512
RecordDecl * getDefinitionOrSelf() const
Definition: Decl.h:4497
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: TypeBase.h:6502
RecordDecl * getOriginalDecl() const
Definition: TypeBase.h:6509
Base for LValueReferenceType and RValueReferenceType.
Definition: TypeBase.h:3589
QualType getPointeeType() const
Definition: TypeBase.h:3607
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
Smart pointer class that efficiently represents Objective-C method names.
unsigned getNumArgs() const
bool areCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an SVE builtin and a VectorType that is a fixed-length representat...
Definition: SemaARM.cpp:1473
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
Definition: SemaARM.cpp:1517
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:61
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:33
bool IsAllowedCall(const FunctionDecl *Caller, const FunctionDecl *Callee)
Determines whether Caller may invoke Callee, based on their CUDA host/device attributes.
Definition: SemaCUDA.h:186
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:134
bool inferTargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose)
Given a implicit special member, infer its CUDA target from the calls it needs to make to underlying ...
Definition: SemaCUDA.cpp:371
static bool isImplicitHostDeviceFunction(const FunctionDecl *D)
Definition: SemaCUDA.cpp:312
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:318
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:225
bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
Determine whether this is an Objective-C writeback conversion, used for parameter passing when perfor...
Definition: SemaObjC.cpp:1314
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:10258
virtual SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy)=0
Emits a note for one of the candidate conversions.
virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic complaining that the expression does not have integral or enumeration type.
virtual SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy)=0
Emits a note for the explicit conversion function.
virtual SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy)=0
Emits a diagnostic when the only matching conversion function is explicit.
virtual SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy)=0
Emits a diagnostic when we picked a conversion function (for cases when we are not allowed to pick a ...
virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic when there are multiple possible conversion functions.
virtual bool match(QualType T)=0
Determine whether the specified type is a valid destination type for this conversion.
virtual SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic when the expression has incomplete class type.
For a defaulted function, the kind of defaulted function that it is.
Definition: Sema.h:6313
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:6342
RAII class to control scope of DeferDiags.
Definition: Sema.h:9992
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:12359
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12392
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:850
bool TryFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy) const
Same as IsFunctionConversion, but if this would return true, it sets ResultTy to ToType.
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
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.
bool IsBuildingRecoveryCallExpr
Flag indicating if Sema is building a recovery call expression.
Definition: Sema.h:10008
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:9281
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition: Sema.h:9293
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:9289
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr * > Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
bool IsStringInit(Expr *Init, const ArrayType *AT)
Definition: SemaInit.cpp:167
ExprResult 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:1438
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:10341
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition: Sema.h:10344
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition: Sema.h:10350
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition: Sema.h:10348
@ AR_dependent
Definition: Sema.h:1653
@ AR_accessible
Definition: Sema.h:1651
@ AR_inaccessible
Definition: Sema.h:1652
@ AR_delayed
Definition: Sema.h:1654
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.
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:2042
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.
Definition: SemaExpr.cpp:9764
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition: Sema.cpp:1647
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition: Sema.h:1276
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:915
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:1483
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...
ASTContext & getASTContext() const
Definition: Sema.h:918
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)
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:756
bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction, const FunctionDecl *NewFunction, unsigned *ArgPos=nullptr, bool Reversed=false)
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
ForRangeStatus
Definition: Sema.h:10728
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...
AllowedExplicit
Definition: Sema.h:10055
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:1184
bool IsComplexPromotion(QualType FromType, QualType ToType)
Determine if a conversion is a complex promotion.
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:12073
bool AddingCFIUncheckedCallee(QualType From, QualType To) const
Returns true if From is a function or pointer to a function without the cfi_unchecked_callee attribut...
void AddConversionCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true, bool StrictPackMatch=false)
AddConversionCandidate - Add a C++ conversion function as a candidate in the candidate set (C++ [over...
bool IsBlockPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
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...
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...
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:83
const LangOptions & getLangOpts() const
Definition: Sema.h:911
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.
Definition: SemaExpr.cpp:2513
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.
Definition: SemaExpr.cpp:6572
ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, FunctionDecl *DefaultedFn)
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:1274
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.
Definition: SemaExpr.cpp:6838
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
MemberPointerConversionDirection
Definition: Sema.h:10179
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)
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...
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add the overload candidates named by callee and/or found by argument dependent lookup to the given ov...
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:633
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3230
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:15324
void NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind=OverloadCandidateRewriteKind(), QualType DestType=QualType(), bool TakingAddress=false)
bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType)
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:1411
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.
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...
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:20356
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:21316
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:13791
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...
bool IsFunctionConversion(QualType FromType, QualType ToType, bool *DiscardingCFIUncheckedCallee=nullptr, bool *AddingCFIUncheckedCallee=nullptr) const
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
bool resolveAndFixAddressOfSingleOverloadCandidate(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false)
Given an overloaded function, tries to turn it into a non-overloaded function reference using resolve...
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:5564
bool anyAltivecTypes(QualType srcType, QualType destType)
Definition: SemaExpr.cpp:7653
bool isLaxVectorConversion(QualType srcType, QualType destType)
Is this a legal conversion between two types, one of which is known to be a vector type?
Definition: SemaExpr.cpp:7690
ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false)
BuildOverloadedCallExpr - Given the call expression that calls Fn (which eventually refers to the dec...
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:218
ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc)
BuildCallToObjectOfClassType - Build a call to an object of class type (C++ [over....
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:15279
bool CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity &Entity, InitListExpr *From)
Determine whether we can perform aggregate initialization for the purposes of overload resolution.
Definition: SemaInit.cpp:3515
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 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...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
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.
MemberPointerConversionResult
Definition: Sema.h:10171
SourceManager & SourceMgr
Definition: Sema.h:1279
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
Definition: SemaExpr.cpp:2454
DiagnosticsEngine & Diags
Definition: Sema.h:1278
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9874
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...
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21528
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(const NamedDecl *D1, ArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, ArrayRef< AssociatedConstraint > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, SourceLocation RangeLoc, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr)
Build a call to 'begin' or 'end' for a C++11 for-range statement.
ExprResult InitializeExplicitObjectArgument(Sema &S, Expr *Obj, FunctionDecl *Fun)
bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init)
Definition: SemaInit.cpp:9859
bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method, SourceLocation CallLoc)
Returns true if the explicit object parameter was invalid.
Definition: SemaLambda.cpp:413
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.
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:1418
void AddMemberOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, OverloadCandidateParamOrder PO={})
Add overload candidates for overloaded operators that are member functions.
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8599
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition: Overload.h:292
void dump() const
dump - Print this standard conversion sequence to standard error.
void setFromType(QualType T)
Definition: Overload.h:388
DeclAccessPair FoundCopyConstructor
Definition: Overload.h:386
unsigned BindsToRvalue
Whether we're binding to an rvalue.
Definition: Overload.h:351
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition: Overload.h:303
QualType getFromType() const
Definition: Overload.h:401
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition: Overload.h:297
unsigned BindsImplicitObjectArgumentWithoutRefQualifier
Whether this binds an implicit object argument to a non-static member function without a ref-qualifie...
Definition: Overload.h:356
unsigned ReferenceBinding
ReferenceBinding - True when this is a reference binding (C++ [over.ics.ref]).
Definition: Overload.h:333
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
unsigned DeprecatedStringLiteralToCharPtr
Whether this is the deprecated conversion of a string literal to a pointer to non-const character dat...
Definition: Overload.h:318
CXXConstructorDecl * CopyConstructor
CopyConstructor - The copy constructor that is used to perform this conversion, when the conversion i...
Definition: Overload.h:385
unsigned IncompatibleObjC
IncompatibleObjC - Whether this is an Objective-C conversion that we should warn about (if we actuall...
Definition: Overload.h:328
unsigned ObjCLifetimeConversionBinding
Whether this binds a reference to an object with a different Objective-C lifetime qualifier.
Definition: Overload.h:361
ImplicitConversionKind Third
Third - The third conversion can be a qualification conversion or a function conversion.
Definition: Overload.h:312
unsigned QualificationIncludesObjCLifetime
Whether the qualification conversion involves a change in the Objective-C lifetime (for automatic ref...
Definition: Overload.h:323
void setToType(unsigned Idx, QualType T)
Definition: Overload.h:390
bool isPointerConversionToBool() const
isPointerConversionToBool - Determines whether this conversion is a conversion of a pointer or pointe...
void * ToTypePtrs[3]
ToType - The types that this conversion is converting to in each step.
Definition: Overload.h:378
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
unsigned IsLvalueReference
Whether this is an lvalue reference binding (otherwise, it's an rvalue reference binding).
Definition: Overload.h:343
ImplicitConversionKind Dimension
Dimension - Between the second and third conversion a vector or matrix dimension conversion may occur...
Definition: Overload.h:308
unsigned BindsToFunctionLvalue
Whether we're binding to a function lvalue.
Definition: Overload.h:347
unsigned DirectBinding
DirectBinding - True when this is a reference binding that is a direct binding (C++ [dcl....
Definition: Overload.h:338
ImplicitConversionRank getRank() const
getRank - Retrieve the rank of this standard conversion sequence (C++ 13.3.3.1.1p3).
bool isPointerConversionToVoidPointer(ASTContext &Context) const
isPointerConversionToVoidPointer - Determines whether this conversion is a conversion of a pointer to...
void setAllToTypes(QualType T)
Definition: Overload.h:395
unsigned FromBracedInitList
Whether the source expression was originally a single element braced-init-list.
Definition: Overload.h:368
QualType getToType(unsigned Idx) const
Definition: Overload.h:405
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:358
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:346
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1801
StringRef getString() const
Definition: Expr.h:1869
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1288
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition: TargetInfo.h:673
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition: TargetInfo.h:727
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition: TargetInfo.h:712
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1360
A convenient class for passing around template argument information.
Definition: TemplateBase.h:634
A template argument list.
Definition: DeclTemplate.h:250
Represents a template argument.
Definition: TemplateBase.h:61
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.
Definition: TemplateBase.h:322
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:346
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:446
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:296
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:396
bool isTypeAlias() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:415
Represents a C++ template name within the type system.
Definition: TemplateName.h:222
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.
Definition: TemplateName.h:239
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.
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: TypeBase.h:7290
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Declaration of a template type parameter.
const Type * getTypeForDecl() const
Definition: Decl.h:3535
The base class of the type hierarchy.
Definition: TypeBase.h:1833
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition: TypeBase.h:2503
bool isBlockPointerType() const
Definition: TypeBase.h:8600
bool isVoidType() const
Definition: TypeBase.h:8936
bool isBooleanType() const
Definition: TypeBase.h:9066
bool isObjCBuiltinType() const
Definition: TypeBase.h:8800
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2229
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:1955
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:787
bool isIncompleteArrayType() const
Definition: TypeBase.h:8687
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2209
bool isFloat16Type() const
Definition: TypeBase.h:8945
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:724
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2119
bool isRValueReferenceType() const
Definition: TypeBase.h:8612
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:8683
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: TypeBase.h:9096
bool isArrayType() const
Definition: TypeBase.h:8679
bool isCharType() const
Definition: Type.cpp:2136
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition: TypeBase.h:9004
CXXRecordDecl * castAsCXXRecordDecl() const
Definition: Type.h:36
bool isArithmeticType() const
Definition: Type.cpp:2341
bool isPointerType() const
Definition: TypeBase.h:8580
bool isArrayParameterType() const
Definition: TypeBase.h:8695
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: TypeBase.h:8980
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2578
const T * castAs() const
Member-template castAs<specific type>.
Definition: TypeBase.h:9226
bool isReferenceType() const
Definition: TypeBase.h:8604
bool isEnumeralType() const
Definition: TypeBase.h:8711
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2107
bool isObjCQualifiedIdType() const
Definition: TypeBase.h:8770
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: TypeBase.h:9054
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2172
bool isObjCObjectOrInterfaceType() const
Definition: TypeBase.h:8757
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: TypeBase.h:2808
bool isLValueReferenceType() const
Definition: TypeBase.h:8608
bool isBitIntType() const
Definition: TypeBase.h:8845
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: TypeBase.h:2800
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2415
bool isAnyComplexType() const
Definition: TypeBase.h:8715
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: TypeBase.h:8992
bool isHalfType() const
Definition: TypeBase.h:8940
const BuiltinType * getAsPlaceholderType() const
Definition: TypeBase.h:8918
bool isQueueT() const
Definition: TypeBase.h:8826
bool isMemberPointerType() const
Definition: TypeBase.h:8661
bool isObjCIdType() const
Definition: TypeBase.h:8782
bool isMatrixType() const
Definition: TypeBase.h:8737
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: TypeBase.h:9072
bool isObjectType() const
Determine whether this type is an object type.
Definition: TypeBase.h:2528
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition: Type.h:53
bool isEventT() const
Definition: TypeBase.h:8818
bool isBFloat16Type() const
Definition: TypeBase.h:8957
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2440
bool isFunctionType() const
Definition: TypeBase.h:8576
bool isObjCObjectPointerType() const
Definition: TypeBase.h:8749
bool isVectorType() const
Definition: TypeBase.h:8719
bool isObjCClassType() const
Definition: TypeBase.h:8788
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2324
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2599
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition: TypeBase.h:2939
bool isHLSLAttributedResourceType() const
Definition: TypeBase.h:8893
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:2257
bool isAnyPointerType() const
Definition: TypeBase.h:8588
TypeClass getTypeClass() const
Definition: TypeBase.h:2403
bool isSamplerT() const
Definition: TypeBase.h:8814
const T * getAs() const
Member-template getAs<specific type>'.
Definition: TypeBase.h:9159
bool isNullPtrType() const
Definition: TypeBase.h:8973
bool isRecordType() const
Definition: TypeBase.h:8707
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2246
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition: Expr.cpp:1426
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4995
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition: Expr.cpp:1402
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3384
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition: ExprCXX.h:3453
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition: ExprCXX.cpp:432
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition: ExprCXX.h:4120
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition: ExprCXX.h:4228
QualType getBaseType() const
Definition: ExprCXX.h:4202
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition: ExprCXX.h:4212
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition: ExprCXX.h:4193
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.h:4238
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition: ExprCXX.h:4232
A set of unresolved declarations.
Definition: UnresolvedSet.h:62
unsigned size() const
ArrayRef< DeclAccessPair > pairs() const
Definition: UnresolvedSet.h:89
void addDecl(NamedDecl *D)
Definition: UnresolvedSet.h:91
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
A set of unresolved declarations.
A call to a literal operator (C++11 [over.literal]) written as a user-defined literal (C++11 [lit....
Definition: ExprCXX.h:640
static UserDefinedLiteral * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation LitEndLoc, SourceLocation SuffixLoc, FPOptionsOverride FPFeatures)
Definition: ExprCXX.cpp:966
QualType getType() const
Definition: Decl.h:722
unsigned getNumElements() const
Definition: TypeBase.h:4206
QualType getElementType() const
Definition: TypeBase.h:4205
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...
Definition: AttrIterator.h:36
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition: limits.h:64
Definition: SPIR.cpp:47
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
@ Warning
Present this diagnostic as a warning.
@ Error
Present this diagnostic as an error.
bool Ret(InterpState &S, CodePtr &PC)
Definition: Interp.h:312
void checkAssignmentLifetime(Sema &SemaRef, const AssignedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for assigning to the ent...
The JSON file list parser is used to communicate input to InstallAPI.
ImplicitConversionRank GetDimensionConversionRank(ImplicitConversionRank Base, ImplicitConversionKind Dimension)
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
@ NUM_OVERLOADED_OPERATORS
Definition: OperatorKinds.h:26
OverloadKind
Definition: Sema.h:809
@ NonFunction
This is not an overload because the lookup results contain a non-function.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus14
Definition: LangStandard.h:57
OverloadingResult
OverloadingResult - Capture the result of performing overload resolution.
Definition: Overload.h:50
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition: Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition: Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition: Overload.h:55
CUDAFunctionTarget
Definition: Cuda.h:60
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
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)
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
OverloadFailureKind
Definition: Overload.h:852
@ ovl_fail_final_conversion_not_exact
This conversion function template specialization candidate is not viable because the final conversion...
Definition: Overload.h:880
@ ovl_fail_enable_if
This candidate function was not viable because an enable_if attribute disabled it.
Definition: Overload.h:889
@ ovl_fail_illegal_constructor
This conversion candidate was not considered because it is an illegal instantiation of a constructor ...
Definition: Overload.h:872
@ ovl_fail_bad_final_conversion
This conversion candidate is not viable because its result type is not implicitly convertible to the ...
Definition: Overload.h:876
@ ovl_fail_module_mismatched
This candidate was not viable because it has internal linkage and is from a different module unit tha...
Definition: Overload.h:917
@ ovl_fail_too_few_arguments
Definition: Overload.h:854
@ ovl_fail_addr_not_available
This candidate was not viable because its address could not be taken.
Definition: Overload.h:896
@ ovl_fail_too_many_arguments
Definition: Overload.h:853
@ ovl_non_default_multiversion_function
This candidate was not viable because it is a non-default multiversioned function.
Definition: Overload.h:904
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition: Overload.h:913
@ ovl_fail_bad_conversion
Definition: Overload.h:855
@ ovl_fail_bad_target
(CUDA) This candidate was not viable because the callee was not accessible from the caller's target (...
Definition: Overload.h:885
@ ovl_fail_bad_deduction
Definition: Overload.h:856
@ ovl_fail_inhctor_slice
This inherited constructor is not viable because it would slice the argument.
Definition: Overload.h:900
@ ovl_fail_object_addrspace_mismatch
This constructor/conversion candidate fail due to an address space mismatch between the object being ...
Definition: Overload.h:909
@ ovl_fail_explicit
This candidate constructor or conversion function is explicit but the context doesn't permit explicit...
Definition: Overload.h:893
@ ovl_fail_trivial_conversion
This conversion candidate was not considered because it duplicates the work of a trivial or derived-t...
Definition: Overload.h:861
@ RQ_None
No ref-qualifier was provided.
Definition: TypeBase.h:1782
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition: TypeBase.h:1785
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: TypeBase.h:1788
ImplicitConversionRank
ImplicitConversionRank - The rank of an implicit conversion kind.
Definition: Overload.h:215
@ ICR_Conversion
Conversion.
Definition: Overload.h:229
@ ICR_Writeback_Conversion
ObjC ARC writeback conversion.
Definition: Overload.h:241
@ ICR_HLSL_Dimension_Reduction
HLSL Matching Dimension Reduction.
Definition: Overload.h:251
@ ICR_HLSL_Dimension_Reduction_Conversion
HLSL Dimension reduction with conversion.
Definition: Overload.h:257
@ ICR_HLSL_Scalar_Widening
HLSL Scalar Widening.
Definition: Overload.h:220
@ ICR_C_Conversion
Conversion only allowed in the C standard (e.g. void* to char*).
Definition: Overload.h:244
@ ICR_OCL_Scalar_Widening
OpenCL Scalar Widening.
Definition: Overload.h:232
@ ICR_Complex_Real_Conversion
Complex <-> Real conversion.
Definition: Overload.h:238
@ ICR_HLSL_Scalar_Widening_Conversion
HLSL Scalar Widening with conversion.
Definition: Overload.h:235
@ ICR_HLSL_Dimension_Reduction_Promotion
HLSL Dimension reduction with promotion.
Definition: Overload.h:254
@ ICR_Promotion
Promotion.
Definition: Overload.h:223
@ ICR_Exact_Match
Exact Match.
Definition: Overload.h:217
@ ICR_C_Conversion_Extension
Conversion not allowed by the C standard, but that we accept as an extension anyway.
Definition: Overload.h:248
@ ICR_HLSL_Scalar_Widening_Promotion
HLSL Scalar Widening with promotion.
Definition: Overload.h:226
OverloadCandidateDisplayKind
Definition: Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition: Overload.h:73
@ OCD_ViableCandidates
Requests that only viable candidates be shown.
Definition: Overload.h:70
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition: Overload.h:67
@ OK_ObjCProperty
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition: Specifiers.h:161
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:151
BinaryOperatorKind
OverloadCandidateParamOrder
The parameter ordering that will be used for the candidate.
Definition: Overload.h:84
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ AS_public
Definition: Specifiers.h:124
@ AS_none
Definition: Specifiers.h:127
OverloadsShown
Specifies which overload candidates to display when overload resolution fails.
@ Ovl_Best
Show just the "best" overload candidates.
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
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
@ Result
The result type of a method or function.
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition: Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition: Overload.h:139
@ ICK_Floating_Promotion
Floating point promotions (C++ [conv.fpprom])
Definition: Overload.h:127
@ ICK_Boolean_Conversion
Boolean conversions (C++ [conv.bool])
Definition: Overload.h:151
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition: Overload.h:133
@ ICK_HLSL_Vector_Splat
Definition: Overload.h:205
@ ICK_Fixed_Point_Conversion
Fixed point type conversions according to N1169.
Definition: Overload.h:196
@ ICK_Vector_Conversion
Vector conversions.
Definition: Overload.h:160
@ ICK_Block_Pointer_Conversion
Block Pointer conversions.
Definition: Overload.h:175
@ ICK_Pointer_Member
Pointer-to-member conversions (C++ [conv.mem])
Definition: Overload.h:148
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition: Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition: Overload.h:202
@ ICK_SVE_Vector_Conversion
Arm SVE Vector conversions.
Definition: Overload.h:163
@ ICK_HLSL_Vector_Truncation
HLSL vector truncation.
Definition: Overload.h:199
@ ICK_Incompatible_Pointer_Conversion
C-only conversion between pointers with incompatible types.
Definition: Overload.h:193
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition: Overload.h:112
@ ICK_RVV_Vector_Conversion
RISC-V RVV Vector conversions.
Definition: Overload.h:166
@ ICK_Complex_Promotion
Complex promotions (Clang extension)
Definition: Overload.h:130
@ ICK_Num_Conversion_Kinds
The number of conversion kinds.
Definition: Overload.h:208
@ ICK_Function_Conversion
Function pointer conversion (C++17 [conv.fctptr])
Definition: Overload.h:118
@ ICK_Vector_Splat
A vector splat from an arithmetic type.
Definition: Overload.h:169
@ ICK_Zero_Queue_Conversion
Zero constant to queue.
Definition: Overload.h:187
@ ICK_Identity
Identity conversion (no conversion)
Definition: Overload.h:106
@ ICK_Derived_To_Base
Derived-to-base (C++ [over.best.ics])
Definition: Overload.h:157
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition: Overload.h:109
@ ICK_Qualification
Qualification conversions (C++ [conv.qual])
Definition: Overload.h:121
@ ICK_Pointer_Conversion
Pointer conversions (C++ [conv.ptr])
Definition: Overload.h:145
@ ICK_TransparentUnionConversion
Transparent Union Conversions.
Definition: Overload.h:178
@ ICK_Integral_Promotion
Integral promotions (C++ [conv.prom])
Definition: Overload.h:124
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition: Overload.h:136
@ ICK_Compatible_Conversion
Conversions between compatible types in C99.
Definition: Overload.h:154
@ ICK_C_Only_Conversion
Conversions allowed in C, but not C++.
Definition: Overload.h:190
@ ICK_Writeback_Conversion
Objective-C ARC writeback conversion.
Definition: Overload.h:181
@ ICK_Zero_Event_Conversion
Zero constant to event (OpenCL1.2 6.12.10)
Definition: Overload.h:184
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition: Overload.h:172
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition: Overload.h:115
@ Template
We are parsing a template declaration.
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:687
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
@ CompatibleVoidPtrToNonVoidPtr
CompatibleVoidPtrToNonVoidPtr - The types are compatible in C because a void * can implicitly convert...
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
@ Compatible
Compatible - the types are compatible according to the standard.
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
UnaryOperatorKind
ActionResult< Expr * > ExprResult
Definition: Ownership.h:249
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.
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
Definition: DeclTemplate.h:66
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
CastKind
CastKind - The kind of operation required for a conversion.
AssignmentAction
Definition: Sema.h:213
CXXSpecialMemberKind
Kinds of C++ special members.
Definition: Sema.h:424
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
Definition: OperatorKinds.h:36
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:139
const FunctionProtoType * T
bool shouldEnforceArgLimit(bool PartialOverloading, FunctionDecl *Function)
NarrowingKind
NarrowingKind - The kind of narrowing conversion being performed by a standard conversion sequence ac...
Definition: Overload.h:268
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition: Overload.h:270
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition: Overload.h:276
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition: Overload.h:284
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition: Overload.h:273
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition: Overload.h:280
@ TPOC_Conversion
Partial ordering of function templates for a call to a conversion function.
Definition: Template.h:304
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition: Template.h:300
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1288
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:366
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
@ CUDATargetMismatch
CUDA Target attributes do not match.
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
@ Invalid
The declaration was invalid; do nothing.
@ Success
Template argument deduction was successful.
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
@ AlreadyDiagnosed
Some error which was already diagnosed.
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:278
const char * getOperatorSpelling(OverloadedOperatorKind Operator)
Retrieve the spelling of the given overloaded operator, without the preceding "operator" keyword.
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition: Overload.h:1512
@ None
The alignment was not explicit in code.
CCEKind
Contexts in which a converted constant expression is required.
Definition: Sema.h:824
@ TemplateArg
Value of a non-type template parameter.
@ Noexcept
Condition in a noexcept(bool) specifier.
@ ArrayBound
Array bound in array declarator or new-expression.
@ TempArgStrict
As above, but applies strict template checking rules.
@ ExplicitBool
Condition in an explicit(bool) specifier.
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.
@ EST_None
no exception specification
@ ForBuiltinOverloadedOp
A conversion for an operand of a builtin overloaded operator.
__DEVICE__ _Tp abs(const std::complex< _Tp > &__c)
Definition: complex_cmath.h:34
#define true
Definition: stdbool.h:25
#define false
Definition: stdbool.h:26
Represents an ambiguous user-defined conversion sequence.
Definition: Overload.h:515
ConversionSet::const_iterator const_iterator
Definition: Overload.h:551
ConversionSet & conversions()
Definition: Overload.h:534
void addConversion(NamedDecl *Found, FunctionDecl *D)
Definition: Overload.h:542
SmallVector< std::pair< NamedDecl *, FunctionDecl * >, 4 > ConversionSet
Definition: Overload.h:517
void copyFrom(const AmbiguousConversionSequence &)
const Expr * ConstraintExpr
Definition: Decl.h:87
UnsignedOrNone ArgPackSubstIndex
Definition: Decl.h:88
QualType getToType() const
Definition: Overload.h:600
QualType getFromType() const
Definition: Overload.h:599
OverloadFixItKind Kind
The type of fix applied.
unsigned NumConversionsFixed
The number of Conversions fixed.
void setConversionChecker(TypeComparisonFuncTy Foo)
Resets the default conversion checker method.
std::vector< FixItHint > Hints
The list of Hints generated so far.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
void setCXXOperatorNameRange(SourceRange R)
setCXXOperatorNameRange - Sets the range of the operator name (without the operator keyword).
const DeclarationNameLoc & getInfo() const
SourceLocation getCXXLiteralOperatorNameLoc() const
getCXXLiteralOperatorNameLoc - Returns the location of the literal operator name (not the operator ke...
A structure used to record information about a failed template argument deduction,...
void * Data
Opaque pointer containing additional data about this deduction failure.
const TemplateArgument * getSecondArg()
Return the second template argument this deduction failure refers to, if any.
unsigned Result
A Sema::TemplateDeductionResult.
PartialDiagnosticAt * getSFINAEDiagnostic()
Retrieve the diagnostic which caused this deduction failure, if any.
unsigned HasDiagnostic
Indicates whether a diagnostic is stored in Diagnostic.
TemplateDeductionResult getResult() const
void Destroy()
Free any memory associated with this deduction failure.
char Diagnostic[sizeof(PartialDiagnosticAt)]
A diagnostic indicating why deduction failed.
UnsignedOrNone getCallArgIndex()
Return the index of the call argument that this deduction failure refers to, if any.
TemplateParameter getTemplateParameter()
Retrieve the template parameter this deduction failure refers to, if any.
TemplateArgumentList * getTemplateArgumentList()
Retrieve the template argument list associated with this deduction failure, if any.
const TemplateArgument * getFirstArg()
Return the first template argument this deduction failure refers to, if any.
DeferredTemplateOverloadCandidate * Next
Definition: Overload.h:1095
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:645
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:647
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition: Expr.h:633
Extra information about a function prototype.
Definition: TypeBase.h:5367
const ExtParameterInfo * ExtParameterInfos
Definition: TypeBase.h:5372
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition: Overload.h:1188
bool shouldAddReversed(Sema &S, ArrayRef< Expr * > OriginalArgs, FunctionDecl *FD)
Determine whether we should add a rewritten candidate for FD with reversed parameter order.
bool allowsReversed(OverloadedOperatorKind Op)
Determine whether reversing parameter order is allowed for operator Op.
bool AllowRewrittenCandidates
Whether we should include rewritten candidates in the overload set.
Definition: Overload.h:1201
bool isReversible()
Determines whether this operator could be implemented by a function with reversed parameter order.
Definition: Overload.h:1237
bool isAcceptableCandidate(const FunctionDecl *FD)
Definition: Overload.h:1210
OverloadCandidateRewriteKind getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO)
Determine the kind of rewrite that should be performed for this candidate.
Definition: Overload.h:1227
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition: Overload.h:926
unsigned StrictPackMatch
Have we matched any packs on the parameter side, versus any non-packs on the argument side,...
Definition: Overload.h:991
unsigned IgnoreObjectArgument
IgnoreObjectArgument - True to indicate that the first argument's conversion, which for this function...
Definition: Overload.h:982
bool TryToFixBadConversion(unsigned Idx, Sema &S)
Definition: Overload.h:1056
bool NotValidBecauseConstraintExprHasError() const
bool isReversed() const
Definition: Overload.h:1030
unsigned IsADLCandidate
True if the candidate was found using ADL.
Definition: Overload.h:995
unsigned IsSurrogate
IsSurrogate - True to indicate that this candidate is a surrogate for a conversion to a function poin...
Definition: Overload.h:972
QualType BuiltinParamTypes[3]
BuiltinParamTypes - Provides the parameter types of a built-in overload candidate.
Definition: Overload.h:940
DeclAccessPair FoundDecl
FoundDecl - The original declaration that was looked up / invented / otherwise found,...
Definition: Overload.h:936
FunctionDecl * Function
Function - The actual function that this candidate represents.
Definition: Overload.h:931
unsigned RewriteKind
Whether this is a rewritten candidate, and if so, of what kind?
Definition: Overload.h:1003
ConversionFixItGenerator Fix
The FixIt hints which can be used to fix the Bad candidate.
Definition: Overload.h:952
unsigned Best
Whether this candidate is the best viable function, or tied for being the best viable function.
Definition: Overload.h:966
StandardConversionSequence FinalConversion
FinalConversion - For a conversion function (where Function is a CXXConversionDecl),...
Definition: Overload.h:1021
unsigned getNumParams() const
Definition: Overload.h:1069
unsigned HasFinalConversion
Whether FinalConversion has been set.
Definition: Overload.h:999
unsigned TookAddressOfOverload
Definition: Overload.h:985
unsigned FailureKind
FailureKind - The reason why this candidate is not viable.
Definition: Overload.h:1008
unsigned ExplicitCallArguments
The number of call arguments that were explicitly provided, to be used while performing partial order...
Definition: Overload.h:1012
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition: Overload.h:949
DeductionFailureInfo DeductionFailure
Definition: Overload.h:1015
unsigned Viable
Viable - True to indicate that this overload candidate is viable.
Definition: Overload.h:956
CXXConversionDecl * Surrogate
Surrogate - The conversion function for which this candidate is a surrogate, but only if IsSurrogate ...
Definition: Overload.h:944
OverloadCandidateRewriteKind getRewriteKind() const
Get RewriteKind value in OverloadCandidateRewriteKind type (This function is to workaround the spurio...
Definition: Overload.h:1026
bool SuppressUserConversions
Do not consider any user-defined conversions when constructing the initializing sequence.
Definition: Sema.h:10461
bool OnlyInitializeNonUserDefinedConversions
Before constructing the initializing sequence, we check whether the parameter type and argument type ...
Definition: Sema.h:10468
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:12953
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition: Sema.h:13041
ReferenceConversions
The conversions that would be performed on an lvalue of type T2 when binding a reference of type T1 t...
Definition: Sema.h:10358
Abstract class used to diagnose incomplete types.
Definition: Sema.h:8203
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition: TypeBase.h:870
const Type * Ty
The locally-unqualified type.
Definition: TypeBase.h:872
Qualifiers Quals
The local qualifiers.
Definition: TypeBase.h:875
TemplateSpecCandidate - This is a generalization of OverloadCandidate which keeps track of template a...
void NoteDeductionFailure(Sema &S, bool ForTakingAddress)
Diagnose a template argument deduction failure.
DeductionFailureInfo DeductionFailure
Template argument deduction info.
Decl * Specialization
Specialization - The actual specialization that this candidate represents.
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
UserDefinedConversionSequence - Represents a user-defined conversion sequence (C++ 13....
Definition: Overload.h:470
StandardConversionSequence Before
Represents the standard conversion that occurs before the actual user-defined conversion.
Definition: Overload.h:482
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition: Overload.h:504
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition: Overload.h:495
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition: Overload.h:499
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition: Overload.h:490
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition: Overload.h:509
void dump() const
dump - Print this user-defined conversion sequence to standard error.
Describes an entity that is being assigned.