clang 20.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/SemaCUDA.h"
34#include "clang/Sema/SemaObjC.h"
35#include "clang/Sema/Template.h"
37#include "llvm/ADT/DenseSet.h"
38#include "llvm/ADT/STLExtras.h"
39#include "llvm/ADT/STLForwardCompat.h"
40#include "llvm/ADT/ScopeExit.h"
41#include "llvm/ADT/SmallPtrSet.h"
42#include "llvm/ADT/SmallVector.h"
43#include <algorithm>
44#include <cassert>
45#include <cstddef>
46#include <cstdlib>
47#include <optional>
48
49using namespace clang;
50using namespace sema;
51
53
55 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
56 return P->hasAttr<PassObjectSizeAttr>();
57 });
58}
59
60/// A convenience routine for creating a decayed reference to a function.
62 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
63 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
64 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
65 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
66 return ExprError();
67 // If FoundDecl is different from Fn (such as if one is a template
68 // and the other a specialization), make sure DiagnoseUseOfDecl is
69 // called on both.
70 // FIXME: This would be more comprehensively addressed by modifying
71 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
72 // being used.
73 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
74 return ExprError();
75 DeclRefExpr *DRE = new (S.Context)
76 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
77 if (HadMultipleCandidates)
78 DRE->setHadMultipleCandidates(true);
79
81 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
82 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
84 DRE->setType(Fn->getType());
85 }
86 }
87 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
88 CK_FunctionToPointerDecay);
89}
90
91static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
92 bool InOverloadResolution,
94 bool CStyle,
95 bool AllowObjCWritebackConversion);
96
98 QualType &ToType,
99 bool InOverloadResolution,
101 bool CStyle);
103IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
105 OverloadCandidateSet& Conversions,
106 AllowedExplicit AllowExplicit,
107 bool AllowObjCConversionOnExplicit);
108
111 const StandardConversionSequence& SCS1,
112 const StandardConversionSequence& SCS2);
113
116 const StandardConversionSequence& SCS1,
117 const StandardConversionSequence& SCS2);
118
121 const StandardConversionSequence& SCS1,
122 const StandardConversionSequence& SCS2);
123
124/// GetConversionRank - Retrieve the implicit conversion rank
125/// corresponding to the given implicit conversion kind.
127 static const ImplicitConversionRank Rank[] = {
154 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
155 // it was omitted by the patch that added
156 // ICK_Zero_Event_Conversion
157 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
158 // it was omitted by the patch that added
159 // ICK_Zero_Queue_Conversion
166 };
167 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
168 return Rank[(int)Kind];
169}
170
173 ImplicitConversionKind Dimension) {
175 if (Rank == ICR_HLSL_Scalar_Widening) {
176 if (Base == ICR_Promotion)
178 if (Base == ICR_Conversion)
180 }
181 if (Rank == ICR_HLSL_Dimension_Reduction) {
182 if (Base == ICR_Promotion)
184 if (Base == ICR_Conversion)
186 }
187 return Rank;
188}
189
190/// GetImplicitConversionName - Return the name of this kind of
191/// implicit conversion.
193 static const char *const Name[] = {
194 "No conversion",
195 "Lvalue-to-rvalue",
196 "Array-to-pointer",
197 "Function-to-pointer",
198 "Function pointer conversion",
199 "Qualification",
200 "Integral promotion",
201 "Floating point promotion",
202 "Complex promotion",
203 "Integral conversion",
204 "Floating conversion",
205 "Complex conversion",
206 "Floating-integral conversion",
207 "Pointer conversion",
208 "Pointer-to-member conversion",
209 "Boolean conversion",
210 "Compatible-types conversion",
211 "Derived-to-base conversion",
212 "Vector conversion",
213 "SVE Vector conversion",
214 "RVV Vector conversion",
215 "Vector splat",
216 "Complex-real conversion",
217 "Block Pointer conversion",
218 "Transparent Union Conversion",
219 "Writeback conversion",
220 "OpenCL Zero Event Conversion",
221 "OpenCL Zero Queue Conversion",
222 "C specific type conversion",
223 "Incompatible pointer conversion",
224 "Fixed point conversion",
225 "HLSL vector truncation",
226 "Non-decaying array conversion",
227 "HLSL vector splat",
228 };
229 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
230 return Name[Kind];
231}
232
233/// StandardConversionSequence - Set the standard conversion
234/// sequence to the identity conversion.
242 ReferenceBinding = false;
243 DirectBinding = false;
244 IsLvalueReference = true;
245 BindsToFunctionLvalue = false;
246 BindsToRvalue = false;
249 CopyConstructor = nullptr;
250}
251
252/// getRank - Retrieve the rank of this standard conversion sequence
253/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
254/// implicit conversions.
257 if (GetConversionRank(First) > Rank)
258 Rank = GetConversionRank(First);
259 if (GetConversionRank(Second) > Rank)
261 if (GetDimensionConversionRank(Rank, Dimension) > Rank)
263 if (GetConversionRank(Third) > Rank)
264 Rank = GetConversionRank(Third);
265 return Rank;
266}
267
268/// isPointerConversionToBool - Determines whether this conversion is
269/// a conversion of a pointer or pointer-to-member to bool. This is
270/// used as part of the ranking of standard conversion sequences
271/// (C++ 13.3.3.2p4).
273 // Note that FromType has not necessarily been transformed by the
274 // array-to-pointer or function-to-pointer implicit conversions, so
275 // check for their presence as well as checking whether FromType is
276 // a pointer.
277 if (getToType(1)->isBooleanType() &&
278 (getFromType()->isPointerType() ||
279 getFromType()->isMemberPointerType() ||
280 getFromType()->isObjCObjectPointerType() ||
281 getFromType()->isBlockPointerType() ||
283 return true;
284
285 return false;
286}
287
288/// isPointerConversionToVoidPointer - Determines whether this
289/// conversion is a conversion of a pointer to a void pointer. This is
290/// used as part of the ranking of standard conversion sequences (C++
291/// 13.3.3.2p4).
292bool
295 QualType FromType = getFromType();
296 QualType ToType = getToType(1);
297
298 // Note that FromType has not necessarily been transformed by the
299 // array-to-pointer implicit conversion, so check for its presence
300 // and redo the conversion to get a pointer.
302 FromType = Context.getArrayDecayedType(FromType);
303
304 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
305 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
306 return ToPtrType->getPointeeType()->isVoidType();
307
308 return false;
309}
310
311/// Skip any implicit casts which could be either part of a narrowing conversion
312/// or after one in an implicit conversion.
314 const Expr *Converted) {
315 // We can have cleanups wrapping the converted expression; these need to be
316 // preserved so that destructors run if necessary.
317 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
318 Expr *Inner =
319 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
320 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
321 EWC->getObjects());
322 }
323
324 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
325 switch (ICE->getCastKind()) {
326 case CK_NoOp:
327 case CK_IntegralCast:
328 case CK_IntegralToBoolean:
329 case CK_IntegralToFloating:
330 case CK_BooleanToSignedIntegral:
331 case CK_FloatingToIntegral:
332 case CK_FloatingToBoolean:
333 case CK_FloatingCast:
334 Converted = ICE->getSubExpr();
335 continue;
336
337 default:
338 return Converted;
339 }
340 }
341
342 return Converted;
343}
344
345/// Check if this standard conversion sequence represents a narrowing
346/// conversion, according to C++11 [dcl.init.list]p7.
347///
348/// \param Ctx The AST context.
349/// \param Converted The result of applying this standard conversion sequence.
350/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
351/// value of the expression prior to the narrowing conversion.
352/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
353/// type of the expression prior to the narrowing conversion.
354/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
355/// from floating point types to integral types should be ignored.
357 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
358 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
359 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
360 "narrowing check outside C++");
361
362 // C++11 [dcl.init.list]p7:
363 // A narrowing conversion is an implicit conversion ...
364 QualType FromType = getToType(0);
365 QualType ToType = getToType(1);
366
367 // A conversion to an enumeration type is narrowing if the conversion to
368 // the underlying type is narrowing. This only arises for expressions of
369 // the form 'Enum{init}'.
370 if (auto *ET = ToType->getAs<EnumType>())
371 ToType = ET->getDecl()->getIntegerType();
372
373 switch (Second) {
374 // 'bool' is an integral type; dispatch to the right place to handle it.
376 if (FromType->isRealFloatingType())
377 goto FloatingIntegralConversion;
379 goto IntegralConversion;
380 // -- from a pointer type or pointer-to-member type to bool, or
381 return NK_Type_Narrowing;
382
383 // -- from a floating-point type to an integer type, or
384 //
385 // -- from an integer type or unscoped enumeration type to a floating-point
386 // type, except where the source is a constant expression and the actual
387 // value after conversion will fit into the target type and will produce
388 // the original value when converted back to the original type, or
390 FloatingIntegralConversion:
391 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
392 return NK_Type_Narrowing;
393 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
394 ToType->isRealFloatingType()) {
395 if (IgnoreFloatToIntegralConversion)
396 return NK_Not_Narrowing;
397 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
398 assert(Initializer && "Unknown conversion expression");
399
400 // If it's value-dependent, we can't tell whether it's narrowing.
401 if (Initializer->isValueDependent())
403
404 if (std::optional<llvm::APSInt> IntConstantValue =
405 Initializer->getIntegerConstantExpr(Ctx)) {
406 // Convert the integer to the floating type.
407 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
408 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
409 llvm::APFloat::rmNearestTiesToEven);
410 // And back.
411 llvm::APSInt ConvertedValue = *IntConstantValue;
412 bool ignored;
413 Result.convertToInteger(ConvertedValue,
414 llvm::APFloat::rmTowardZero, &ignored);
415 // If the resulting value is different, this was a narrowing conversion.
416 if (*IntConstantValue != ConvertedValue) {
417 ConstantValue = APValue(*IntConstantValue);
418 ConstantType = Initializer->getType();
420 }
421 } else {
422 // Variables are always narrowings.
424 }
425 }
426 return NK_Not_Narrowing;
427
428 // -- from long double to double or float, or from double to float, except
429 // where the source is a constant expression and the actual value after
430 // conversion is within the range of values that can be represented (even
431 // if it cannot be represented exactly), or
433 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
434 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
435 // FromType is larger than ToType.
436 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
437
438 // If it's value-dependent, we can't tell whether it's narrowing.
439 if (Initializer->isValueDependent())
441
443 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
444 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
445 // Constant!
446 if (Ctx.getLangOpts().C23)
447 ConstantValue = R.Val;
448 assert(ConstantValue.isFloat());
449 llvm::APFloat FloatVal = ConstantValue.getFloat();
450 // Convert the source value into the target type.
451 bool ignored;
452 llvm::APFloat Converted = FloatVal;
453 llvm::APFloat::opStatus ConvertStatus =
454 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
455 llvm::APFloat::rmNearestTiesToEven, &ignored);
456 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
457 llvm::APFloat::rmNearestTiesToEven, &ignored);
458 if (Ctx.getLangOpts().C23) {
459 if (FloatVal.isNaN() && Converted.isNaN() &&
460 !FloatVal.isSignaling() && !Converted.isSignaling()) {
461 // Quiet NaNs are considered the same value, regardless of
462 // payloads.
463 return NK_Not_Narrowing;
464 }
465 // For normal values, check exact equality.
466 if (!Converted.bitwiseIsEqual(FloatVal)) {
467 ConstantType = Initializer->getType();
469 }
470 } else {
471 // If there was no overflow, the source value is within the range of
472 // values that can be represented.
473 if (ConvertStatus & llvm::APFloat::opOverflow) {
474 ConstantType = Initializer->getType();
476 }
477 }
478 } else {
480 }
481 }
482 return NK_Not_Narrowing;
483
484 // -- from an integer type or unscoped enumeration type to an integer type
485 // that cannot represent all the values of the original type, except where
486 // (CWG2627) -- the source is a bit-field whose width w is less than that
487 // of its type (or, for an enumeration type, its underlying type) and the
488 // target type can represent all the values of a hypothetical extended
489 // integer type with width w and with the same signedness as the original
490 // type or
491 // -- the source is a constant expression and the actual value after
492 // conversion will fit into the target type and will produce the original
493 // value when converted back to the original type.
495 IntegralConversion: {
496 assert(FromType->isIntegralOrUnscopedEnumerationType());
497 assert(ToType->isIntegralOrUnscopedEnumerationType());
498 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
499 unsigned FromWidth = Ctx.getIntWidth(FromType);
500 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
501 const unsigned ToWidth = Ctx.getIntWidth(ToType);
502
503 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
504 bool ToSigned, unsigned ToWidth) {
505 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
506 !(FromSigned && !ToSigned);
507 };
508
509 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
510 return NK_Not_Narrowing;
511
512 // Not all values of FromType can be represented in ToType.
513 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
514
515 bool DependentBitField = false;
516 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
517 if (BitField->getBitWidth()->isValueDependent())
518 DependentBitField = true;
519 else if (unsigned BitFieldWidth = BitField->getBitWidthValue(Ctx);
520 BitFieldWidth < FromWidth) {
521 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
522 return NK_Not_Narrowing;
523
524 // The initializer will be truncated to the bit-field width
525 FromWidth = BitFieldWidth;
526 }
527 }
528
529 // If it's value-dependent, we can't tell whether it's narrowing.
530 if (Initializer->isValueDependent())
532
533 std::optional<llvm::APSInt> OptInitializerValue =
534 Initializer->getIntegerConstantExpr(Ctx);
535 if (!OptInitializerValue) {
536 // If the bit-field width was dependent, it might end up being small
537 // enough to fit in the target type (unless the target type is unsigned
538 // and the source type is signed, in which case it will never fit)
539 if (DependentBitField && !(FromSigned && !ToSigned))
541
542 // Otherwise, such a conversion is always narrowing
544 }
545 llvm::APSInt &InitializerValue = *OptInitializerValue;
546 bool Narrowing = false;
547 if (FromWidth < ToWidth) {
548 // Negative -> unsigned is narrowing. Otherwise, more bits is never
549 // narrowing.
550 if (InitializerValue.isSigned() && InitializerValue.isNegative())
551 Narrowing = true;
552 } else {
553 // Add a bit to the InitializerValue so we don't have to worry about
554 // signed vs. unsigned comparisons.
555 InitializerValue =
556 InitializerValue.extend(InitializerValue.getBitWidth() + 1);
557 // Convert the initializer to and from the target width and signed-ness.
558 llvm::APSInt ConvertedValue = InitializerValue;
559 ConvertedValue = ConvertedValue.trunc(ToWidth);
560 ConvertedValue.setIsSigned(ToSigned);
561 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
562 ConvertedValue.setIsSigned(InitializerValue.isSigned());
563 // If the result is different, this was a narrowing conversion.
564 if (ConvertedValue != InitializerValue)
565 Narrowing = true;
566 }
567 if (Narrowing) {
568 ConstantType = Initializer->getType();
569 ConstantValue = APValue(InitializerValue);
571 }
572
573 return NK_Not_Narrowing;
574 }
575 case ICK_Complex_Real:
576 if (FromType->isComplexType() && !ToType->isComplexType())
577 return NK_Type_Narrowing;
578 return NK_Not_Narrowing;
579
581 if (Ctx.getLangOpts().C23) {
582 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
584 if (Initializer->EvaluateAsRValue(R, Ctx)) {
585 ConstantValue = R.Val;
586 assert(ConstantValue.isFloat());
587 llvm::APFloat FloatVal = ConstantValue.getFloat();
588 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
589 // value, the unqualified versions of the type of the initializer and
590 // the corresponding real type of the object declared shall be
591 // compatible.
592 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
593 ConstantType = Initializer->getType();
595 }
596 }
597 }
598 return NK_Not_Narrowing;
599 default:
600 // Other kinds of conversions are not narrowings.
601 return NK_Not_Narrowing;
602 }
603}
604
605/// dump - Print this standard conversion sequence to standard
606/// error. Useful for debugging overloading issues.
607LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
608 raw_ostream &OS = llvm::errs();
609 bool PrintedSomething = false;
610 if (First != ICK_Identity) {
612 PrintedSomething = true;
613 }
614
615 if (Second != ICK_Identity) {
616 if (PrintedSomething) {
617 OS << " -> ";
618 }
620
621 if (CopyConstructor) {
622 OS << " (by copy constructor)";
623 } else if (DirectBinding) {
624 OS << " (direct reference binding)";
625 } else if (ReferenceBinding) {
626 OS << " (reference binding)";
627 }
628 PrintedSomething = true;
629 }
630
631 if (Third != ICK_Identity) {
632 if (PrintedSomething) {
633 OS << " -> ";
634 }
636 PrintedSomething = true;
637 }
638
639 if (!PrintedSomething) {
640 OS << "No conversions required";
641 }
642}
643
644/// dump - Print this user-defined conversion sequence to standard
645/// error. Useful for debugging overloading issues.
647 raw_ostream &OS = llvm::errs();
648 if (Before.First || Before.Second || Before.Third) {
649 Before.dump();
650 OS << " -> ";
651 }
653 OS << '\'' << *ConversionFunction << '\'';
654 else
655 OS << "aggregate initialization";
656 if (After.First || After.Second || After.Third) {
657 OS << " -> ";
658 After.dump();
659 }
660}
661
662/// dump - Print this implicit conversion sequence to standard
663/// error. Useful for debugging overloading issues.
665 raw_ostream &OS = llvm::errs();
667 OS << "Worst list element conversion: ";
668 switch (ConversionKind) {
670 OS << "Standard conversion: ";
671 Standard.dump();
672 break;
674 OS << "User-defined conversion: ";
676 break;
678 OS << "Ellipsis conversion";
679 break;
681 OS << "Ambiguous conversion";
682 break;
683 case BadConversion:
684 OS << "Bad conversion";
685 break;
686 }
687
688 OS << "\n";
689}
690
692 new (&conversions()) ConversionSet();
693}
694
696 conversions().~ConversionSet();
697}
698
699void
704}
705
706namespace {
707 // Structure used by DeductionFailureInfo to store
708 // template argument information.
709 struct DFIArguments {
710 TemplateArgument FirstArg;
711 TemplateArgument SecondArg;
712 };
713 // Structure used by DeductionFailureInfo to store
714 // template parameter and template argument information.
715 struct DFIParamWithArguments : DFIArguments {
716 TemplateParameter Param;
717 };
718 // Structure used by DeductionFailureInfo to store template argument
719 // information and the index of the problematic call argument.
720 struct DFIDeducedMismatchArgs : DFIArguments {
721 TemplateArgumentList *TemplateArgs;
722 unsigned CallArgIndex;
723 };
724 // Structure used by DeductionFailureInfo to store information about
725 // unsatisfied constraints.
726 struct CNSInfo {
727 TemplateArgumentList *TemplateArgs;
728 ConstraintSatisfaction Satisfaction;
729 };
730}
731
732/// Convert from Sema's representation of template deduction information
733/// to the form used in overload-candidate information.
737 TemplateDeductionInfo &Info) {
739 Result.Result = static_cast<unsigned>(TDK);
740 Result.HasDiagnostic = false;
741 switch (TDK) {
748 Result.Data = nullptr;
749 break;
750
753 Result.Data = Info.Param.getOpaqueValue();
754 break;
755
758 // FIXME: Should allocate from normal heap so that we can free this later.
759 auto *Saved = new (Context) DFIDeducedMismatchArgs;
760 Saved->FirstArg = Info.FirstArg;
761 Saved->SecondArg = Info.SecondArg;
762 Saved->TemplateArgs = Info.takeSugared();
763 Saved->CallArgIndex = Info.CallArgIndex;
764 Result.Data = Saved;
765 break;
766 }
767
769 // FIXME: Should allocate from normal heap so that we can free this later.
770 DFIArguments *Saved = new (Context) DFIArguments;
771 Saved->FirstArg = Info.FirstArg;
772 Saved->SecondArg = Info.SecondArg;
773 Result.Data = Saved;
774 break;
775 }
776
778 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
781 // FIXME: Should allocate from normal heap so that we can free this later.
782 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
783 Saved->Param = Info.Param;
784 Saved->FirstArg = Info.FirstArg;
785 Saved->SecondArg = Info.SecondArg;
786 Result.Data = Saved;
787 break;
788 }
789
791 Result.Data = Info.takeSugared();
792 if (Info.hasSFINAEDiagnostic()) {
796 Result.HasDiagnostic = true;
797 }
798 break;
799
801 CNSInfo *Saved = new (Context) CNSInfo;
802 Saved->TemplateArgs = Info.takeSugared();
803 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
804 Result.Data = Saved;
805 break;
806 }
807
811 llvm_unreachable("not a deduction failure");
812 }
813
814 return Result;
815}
816
818 switch (static_cast<TemplateDeductionResult>(Result)) {
828 break;
829
836 // FIXME: Destroy the data?
837 Data = nullptr;
838 break;
839
841 // FIXME: Destroy the template argument list?
842 Data = nullptr;
844 Diag->~PartialDiagnosticAt();
845 HasDiagnostic = false;
846 }
847 break;
848
850 // FIXME: Destroy the template argument list?
851 Data = nullptr;
853 Diag->~PartialDiagnosticAt();
854 HasDiagnostic = false;
855 }
856 break;
857
858 // Unhandled
861 break;
862 }
863}
864
866 if (HasDiagnostic)
867 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
868 return nullptr;
869}
870
872 switch (static_cast<TemplateDeductionResult>(Result)) {
885 return TemplateParameter();
886
889 return TemplateParameter::getFromOpaqueValue(Data);
890
894 return static_cast<DFIParamWithArguments*>(Data)->Param;
895
896 // Unhandled
899 break;
900 }
901
902 return TemplateParameter();
903}
904
906 switch (static_cast<TemplateDeductionResult>(Result)) {
920 return nullptr;
921
924 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
925
927 return static_cast<TemplateArgumentList*>(Data);
928
930 return static_cast<CNSInfo*>(Data)->TemplateArgs;
931
932 // Unhandled
935 break;
936 }
937
938 return nullptr;
939}
940
942 switch (static_cast<TemplateDeductionResult>(Result)) {
954 return nullptr;
955
962 return &static_cast<DFIArguments*>(Data)->FirstArg;
963
964 // Unhandled
967 break;
968 }
969
970 return nullptr;
971}
972
974 switch (static_cast<TemplateDeductionResult>(Result)) {
987 return nullptr;
988
994 return &static_cast<DFIArguments*>(Data)->SecondArg;
995
996 // Unhandled
999 break;
1000 }
1001
1002 return nullptr;
1003}
1004
1005std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
1006 switch (static_cast<TemplateDeductionResult>(Result)) {
1009 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1010
1011 default:
1012 return std::nullopt;
1013 }
1014}
1015
1017 const FunctionDecl *Y) {
1018 if (!X || !Y)
1019 return false;
1020 if (X->getNumParams() != Y->getNumParams())
1021 return false;
1022 // FIXME: when do rewritten comparison operators
1023 // with explicit object parameters correspond?
1024 // https://cplusplus.github.io/CWG/issues/2797.html
1025 for (unsigned I = 0; I < X->getNumParams(); ++I)
1026 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1027 Y->getParamDecl(I)->getType()))
1028 return false;
1029 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1030 auto *FTY = Y->getDescribedFunctionTemplate();
1031 if (!FTY)
1032 return false;
1033 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1034 FTY->getTemplateParameters()))
1035 return false;
1036 }
1037 return true;
1038}
1039
1041 Expr *FirstOperand, FunctionDecl *EqFD) {
1042 assert(EqFD->getOverloadedOperator() ==
1043 OverloadedOperatorKind::OO_EqualEqual);
1044 // C++2a [over.match.oper]p4:
1045 // A non-template function or function template F named operator== is a
1046 // rewrite target with first operand o unless a search for the name operator!=
1047 // in the scope S from the instantiation context of the operator expression
1048 // finds a function or function template that would correspond
1049 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1050 // scope of the class type of o if F is a class member, and the namespace
1051 // scope of which F is a member otherwise. A function template specialization
1052 // named operator== is a rewrite target if its function template is a rewrite
1053 // target.
1055 OverloadedOperatorKind::OO_ExclaimEqual);
1056 if (isa<CXXMethodDecl>(EqFD)) {
1057 // If F is a class member, search scope is class type of first operand.
1058 QualType RHS = FirstOperand->getType();
1059 auto *RHSRec = RHS->getAs<RecordType>();
1060 if (!RHSRec)
1061 return true;
1062 LookupResult Members(S, NotEqOp, OpLoc,
1064 S.LookupQualifiedName(Members, RHSRec->getDecl());
1065 Members.suppressAccessDiagnostics();
1066 for (NamedDecl *Op : Members)
1067 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1068 return false;
1069 return true;
1070 }
1071 // Otherwise the search scope is the namespace scope of which F is a member.
1072 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1073 auto *NotEqFD = Op->getAsFunction();
1074 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1075 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1076 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1078 cast<Decl>(Op->getLexicalDeclContext())))
1079 return false;
1080 }
1081 return true;
1082}
1083
1087 return false;
1088 return Op == OO_EqualEqual || Op == OO_Spaceship;
1089}
1090
1092 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
1093 auto Op = FD->getOverloadedOperator();
1094 if (!allowsReversed(Op))
1095 return false;
1096 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1097 assert(OriginalArgs.size() == 2);
1099 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1100 return false;
1101 }
1102 // Don't bother adding a reversed candidate that can never be a better
1103 // match than the non-reversed version.
1104 return FD->getNumNonObjectParams() != 2 ||
1106 FD->getParamDecl(1)->getType()) ||
1107 FD->hasAttr<EnableIfAttr>();
1108}
1109
1110void OverloadCandidateSet::destroyCandidates() {
1111 for (iterator i = begin(), e = end(); i != e; ++i) {
1112 for (auto &C : i->Conversions)
1113 C.~ImplicitConversionSequence();
1114 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1115 i->DeductionFailure.Destroy();
1116 }
1117}
1118
1120 destroyCandidates();
1121 SlabAllocator.Reset();
1122 NumInlineBytesUsed = 0;
1123 Candidates.clear();
1124 Functions.clear();
1125 Kind = CSK;
1126}
1127
1128namespace {
1129 class UnbridgedCastsSet {
1130 struct Entry {
1131 Expr **Addr;
1132 Expr *Saved;
1133 };
1134 SmallVector<Entry, 2> Entries;
1135
1136 public:
1137 void save(Sema &S, Expr *&E) {
1138 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1139 Entry entry = { &E, E };
1140 Entries.push_back(entry);
1142 }
1143
1144 void restore() {
1146 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1147 *i->Addr = i->Saved;
1148 }
1149 };
1150}
1151
1152/// checkPlaceholderForOverload - Do any interesting placeholder-like
1153/// preprocessing on the given expression.
1154///
1155/// \param unbridgedCasts a collection to which to add unbridged casts;
1156/// without this, they will be immediately diagnosed as errors
1157///
1158/// Return true on unrecoverable error.
1159static bool
1161 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1162 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1163 // We can't handle overloaded expressions here because overload
1164 // resolution might reasonably tweak them.
1165 if (placeholder->getKind() == BuiltinType::Overload) return false;
1166
1167 // If the context potentially accepts unbridged ARC casts, strip
1168 // the unbridged cast and add it to the collection for later restoration.
1169 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1170 unbridgedCasts) {
1171 unbridgedCasts->save(S, E);
1172 return false;
1173 }
1174
1175 // Go ahead and check everything else.
1176 ExprResult result = S.CheckPlaceholderExpr(E);
1177 if (result.isInvalid())
1178 return true;
1179
1180 E = result.get();
1181 return false;
1182 }
1183
1184 // Nothing to do.
1185 return false;
1186}
1187
1188/// checkArgPlaceholdersForOverload - Check a set of call operands for
1189/// placeholders.
1191 UnbridgedCastsSet &unbridged) {
1192 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1193 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1194 return true;
1195
1196 return false;
1197}
1198
1201 NamedDecl *&Match, bool NewIsUsingDecl) {
1202 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1203 I != E; ++I) {
1204 NamedDecl *OldD = *I;
1205
1206 bool OldIsUsingDecl = false;
1207 if (isa<UsingShadowDecl>(OldD)) {
1208 OldIsUsingDecl = true;
1209
1210 // We can always introduce two using declarations into the same
1211 // context, even if they have identical signatures.
1212 if (NewIsUsingDecl) continue;
1213
1214 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1215 }
1216
1217 // A using-declaration does not conflict with another declaration
1218 // if one of them is hidden.
1219 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1220 continue;
1221
1222 // If either declaration was introduced by a using declaration,
1223 // we'll need to use slightly different rules for matching.
1224 // Essentially, these rules are the normal rules, except that
1225 // function templates hide function templates with different
1226 // return types or template parameter lists.
1227 bool UseMemberUsingDeclRules =
1228 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1229 !New->getFriendObjectKind();
1230
1231 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1232 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1233 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1234 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1235 continue;
1236 }
1237
1238 if (!isa<FunctionTemplateDecl>(OldD) &&
1239 !shouldLinkPossiblyHiddenDecl(*I, New))
1240 continue;
1241
1242 Match = *I;
1243 return Ovl_Match;
1244 }
1245
1246 // Builtins that have custom typechecking or have a reference should
1247 // not be overloadable or redeclarable.
1248 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1249 Match = *I;
1250 return Ovl_NonFunction;
1251 }
1252 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1253 // We can overload with these, which can show up when doing
1254 // redeclaration checks for UsingDecls.
1255 assert(Old.getLookupKind() == LookupUsingDeclName);
1256 } else if (isa<TagDecl>(OldD)) {
1257 // We can always overload with tags by hiding them.
1258 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1259 // Optimistically assume that an unresolved using decl will
1260 // overload; if it doesn't, we'll have to diagnose during
1261 // template instantiation.
1262 //
1263 // Exception: if the scope is dependent and this is not a class
1264 // member, the using declaration can only introduce an enumerator.
1265 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1266 Match = *I;
1267 return Ovl_NonFunction;
1268 }
1269 } else {
1270 // (C++ 13p1):
1271 // Only function declarations can be overloaded; object and type
1272 // declarations cannot be overloaded.
1273 Match = *I;
1274 return Ovl_NonFunction;
1275 }
1276 }
1277
1278 // C++ [temp.friend]p1:
1279 // For a friend function declaration that is not a template declaration:
1280 // -- if the name of the friend is a qualified or unqualified template-id,
1281 // [...], otherwise
1282 // -- if the name of the friend is a qualified-id and a matching
1283 // non-template function is found in the specified class or namespace,
1284 // the friend declaration refers to that function, otherwise,
1285 // -- if the name of the friend is a qualified-id and a matching function
1286 // template is found in the specified class or namespace, the friend
1287 // declaration refers to the deduced specialization of that function
1288 // template, otherwise
1289 // -- the name shall be an unqualified-id [...]
1290 // If we get here for a qualified friend declaration, we've just reached the
1291 // third bullet. If the type of the friend is dependent, skip this lookup
1292 // until instantiation.
1293 if (New->getFriendObjectKind() && New->getQualifier() &&
1296 !New->getType()->isDependentType()) {
1297 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1298 TemplateSpecResult.addAllDecls(Old);
1299 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1300 /*QualifiedFriend*/true)) {
1301 New->setInvalidDecl();
1302 return Ovl_Overload;
1303 }
1304
1305 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1306 return Ovl_Match;
1307 }
1308
1309 return Ovl_Overload;
1310}
1311
1312static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1313 FunctionDecl *Old,
1314 bool UseMemberUsingDeclRules,
1315 bool ConsiderCudaAttrs,
1316 bool UseOverrideRules = false) {
1317 // C++ [basic.start.main]p2: This function shall not be overloaded.
1318 if (New->isMain())
1319 return false;
1320
1321 // MSVCRT user defined entry points cannot be overloaded.
1322 if (New->isMSVCRTEntryPoint())
1323 return false;
1324
1325 NamedDecl *OldDecl = Old;
1326 NamedDecl *NewDecl = New;
1329
1330 // C++ [temp.fct]p2:
1331 // A function template can be overloaded with other function templates
1332 // and with normal (non-template) functions.
1333 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1334 return true;
1335
1336 // Is the function New an overload of the function Old?
1337 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1338 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1339
1340 // Compare the signatures (C++ 1.3.10) of the two functions to
1341 // determine whether they are overloads. If we find any mismatch
1342 // in the signature, they are overloads.
1343
1344 // If either of these functions is a K&R-style function (no
1345 // prototype), then we consider them to have matching signatures.
1346 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1347 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1348 return false;
1349
1350 const auto *OldType = cast<FunctionProtoType>(OldQType);
1351 const auto *NewType = cast<FunctionProtoType>(NewQType);
1352
1353 // The signature of a function includes the types of its
1354 // parameters (C++ 1.3.10), which includes the presence or absence
1355 // of the ellipsis; see C++ DR 357).
1356 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1357 return true;
1358
1359 // For member-like friends, the enclosing class is part of the signature.
1360 if ((New->isMemberLikeConstrainedFriend() ||
1363 return true;
1364
1365 // Compare the parameter lists.
1366 // This can only be done once we have establish that friend functions
1367 // inhabit the same context, otherwise we might tried to instantiate
1368 // references to non-instantiated entities during constraint substitution.
1369 // GH78101.
1370 if (NewTemplate) {
1371 OldDecl = OldTemplate;
1372 NewDecl = NewTemplate;
1373 // C++ [temp.over.link]p4:
1374 // The signature of a function template consists of its function
1375 // signature, its return type and its template parameter list. The names
1376 // of the template parameters are significant only for establishing the
1377 // relationship between the template parameters and the rest of the
1378 // signature.
1379 //
1380 // We check the return type and template parameter lists for function
1381 // templates first; the remaining checks follow.
1382 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1383 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1384 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1385 bool SameReturnType = SemaRef.Context.hasSameType(
1387 // FIXME(GH58571): Match template parameter list even for non-constrained
1388 // template heads. This currently ensures that the code prior to C++20 is
1389 // not newly broken.
1390 bool ConstraintsInTemplateHead =
1393 // C++ [namespace.udecl]p11:
1394 // The set of declarations named by a using-declarator that inhabits a
1395 // class C does not include member functions and member function
1396 // templates of a base class that "correspond" to (and thus would
1397 // conflict with) a declaration of a function or function template in
1398 // C.
1399 // Comparing return types is not required for the "correspond" check to
1400 // decide whether a member introduced by a shadow declaration is hidden.
1401 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1402 !SameTemplateParameterList)
1403 return true;
1404 if (!UseMemberUsingDeclRules &&
1405 (!SameTemplateParameterList || !SameReturnType))
1406 return true;
1407 }
1408
1409 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1410 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1411
1412 int OldParamsOffset = 0;
1413 int NewParamsOffset = 0;
1414
1415 // When determining if a method is an overload from a base class, act as if
1416 // the implicit object parameter are of the same type.
1417
1418 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1420 auto ThisType = M->getFunctionObjectParameterReferenceType();
1421 if (ThisType.isConstQualified())
1422 Q.removeConst();
1423 return Q;
1424 }
1425
1426 // We do not allow overloading based off of '__restrict'.
1427 Q.removeRestrict();
1428
1429 // We may not have applied the implicit const for a constexpr member
1430 // function yet (because we haven't yet resolved whether this is a static
1431 // or non-static member function). Add it now, on the assumption that this
1432 // is a redeclaration of OldMethod.
1433 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1434 (M->isConstexpr() || M->isConsteval()) &&
1435 !isa<CXXConstructorDecl>(NewMethod))
1436 Q.addConst();
1437 return Q;
1438 };
1439
1440 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1441 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1442 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1443
1444 if (OldMethod->isExplicitObjectMemberFunction()) {
1445 BS.Quals.removeVolatile();
1446 DS.Quals.removeVolatile();
1447 }
1448
1449 return BS.Quals == DS.Quals;
1450 };
1451
1452 auto CompareType = [&](QualType Base, QualType D) {
1453 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1454 auto DS = D.getNonReferenceType().getCanonicalType().split();
1455
1456 if (!AreQualifiersEqual(BS, DS))
1457 return false;
1458
1459 if (OldMethod->isImplicitObjectMemberFunction() &&
1460 OldMethod->getParent() != NewMethod->getParent()) {
1461 QualType ParentType =
1462 SemaRef.Context.getTypeDeclType(OldMethod->getParent())
1463 .getCanonicalType();
1464 if (ParentType.getTypePtr() != BS.Ty)
1465 return false;
1466 BS.Ty = DS.Ty;
1467 }
1468
1469 // FIXME: should we ignore some type attributes here?
1470 if (BS.Ty != DS.Ty)
1471 return false;
1472
1473 if (Base->isLValueReferenceType())
1474 return D->isLValueReferenceType();
1475 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1476 };
1477
1478 // If the function is a class member, its signature includes the
1479 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1480 auto DiagnoseInconsistentRefQualifiers = [&]() {
1481 if (SemaRef.LangOpts.CPlusPlus23)
1482 return false;
1483 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1484 return false;
1485 if (OldMethod->isExplicitObjectMemberFunction() ||
1486 NewMethod->isExplicitObjectMemberFunction())
1487 return false;
1488 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1489 NewMethod->getRefQualifier() == RQ_None)) {
1490 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1491 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1492 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1493 return true;
1494 }
1495 return false;
1496 };
1497
1498 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1499 OldParamsOffset++;
1500 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1501 NewParamsOffset++;
1502
1503 if (OldType->getNumParams() - OldParamsOffset !=
1504 NewType->getNumParams() - NewParamsOffset ||
1506 {OldType->param_type_begin() + OldParamsOffset,
1507 OldType->param_type_end()},
1508 {NewType->param_type_begin() + NewParamsOffset,
1509 NewType->param_type_end()},
1510 nullptr)) {
1511 return true;
1512 }
1513
1514 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1515 !NewMethod->isStatic()) {
1516 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1517 const CXXMethodDecl *New) {
1518 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1519 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1520
1521 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1522 return F->getRefQualifier() == RQ_None &&
1523 !F->isExplicitObjectMemberFunction();
1524 };
1525
1526 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1527 CompareType(OldObjectType.getNonReferenceType(),
1528 NewObjectType.getNonReferenceType()))
1529 return true;
1530 return CompareType(OldObjectType, NewObjectType);
1531 }(OldMethod, NewMethod);
1532
1533 if (!HaveCorrespondingObjectParameters) {
1534 if (DiagnoseInconsistentRefQualifiers())
1535 return true;
1536 // CWG2554
1537 // and, if at least one is an explicit object member function, ignoring
1538 // object parameters
1539 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1540 !OldMethod->isExplicitObjectMemberFunction()))
1541 return true;
1542 }
1543 }
1544
1545 if (!UseOverrideRules &&
1547 Expr *NewRC = New->getTrailingRequiresClause(),
1548 *OldRC = Old->getTrailingRequiresClause();
1549 if ((NewRC != nullptr) != (OldRC != nullptr))
1550 return true;
1551 if (NewRC &&
1552 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC, NewDecl, NewRC))
1553 return true;
1554 }
1555
1556 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1557 NewMethod->isImplicitObjectMemberFunction()) {
1558 if (DiagnoseInconsistentRefQualifiers())
1559 return true;
1560 }
1561
1562 // Though pass_object_size is placed on parameters and takes an argument, we
1563 // consider it to be a function-level modifier for the sake of function
1564 // identity. Either the function has one or more parameters with
1565 // pass_object_size or it doesn't.
1568 return true;
1569
1570 // enable_if attributes are an order-sensitive part of the signature.
1572 NewI = New->specific_attr_begin<EnableIfAttr>(),
1573 NewE = New->specific_attr_end<EnableIfAttr>(),
1574 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1575 OldE = Old->specific_attr_end<EnableIfAttr>();
1576 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1577 if (NewI == NewE || OldI == OldE)
1578 return true;
1579 llvm::FoldingSetNodeID NewID, OldID;
1580 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1581 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1582 if (NewID != OldID)
1583 return true;
1584 }
1585
1586 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1587 // Don't allow overloading of destructors. (In theory we could, but it
1588 // would be a giant change to clang.)
1589 if (!isa<CXXDestructorDecl>(New)) {
1590 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1591 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1592 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1593 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1594 "Unexpected invalid target.");
1595
1596 // Allow overloading of functions with same signature and different CUDA
1597 // target attributes.
1598 if (NewTarget != OldTarget)
1599 return true;
1600 }
1601 }
1602 }
1603
1604 // The signatures match; this is not an overload.
1605 return false;
1606}
1607
1609 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1610 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1611 ConsiderCudaAttrs);
1612}
1613
1615 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1616 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1617 /*UseMemberUsingDeclRules=*/false,
1618 /*ConsiderCudaAttrs=*/true,
1619 /*UseOverrideRules=*/true);
1620}
1621
1622/// Tries a user-defined conversion from From to ToType.
1623///
1624/// Produces an implicit conversion sequence for when a standard conversion
1625/// is not an option. See TryImplicitConversion for more information.
1628 bool SuppressUserConversions,
1629 AllowedExplicit AllowExplicit,
1630 bool InOverloadResolution,
1631 bool CStyle,
1632 bool AllowObjCWritebackConversion,
1633 bool AllowObjCConversionOnExplicit) {
1635
1636 if (SuppressUserConversions) {
1637 // We're not in the case above, so there is no conversion that
1638 // we can perform.
1640 return ICS;
1641 }
1642
1643 // Attempt user-defined conversion.
1644 OverloadCandidateSet Conversions(From->getExprLoc(),
1646 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1647 Conversions, AllowExplicit,
1648 AllowObjCConversionOnExplicit)) {
1649 case OR_Success:
1650 case OR_Deleted:
1651 ICS.setUserDefined();
1652 // C++ [over.ics.user]p4:
1653 // A conversion of an expression of class type to the same class
1654 // type is given Exact Match rank, and a conversion of an
1655 // expression of class type to a base class of that type is
1656 // given Conversion rank, in spite of the fact that a copy
1657 // constructor (i.e., a user-defined conversion function) is
1658 // called for those cases.
1659 if (CXXConstructorDecl *Constructor
1660 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1661 QualType FromType;
1662 SourceLocation FromLoc;
1663 // C++11 [over.ics.list]p6, per DR2137:
1664 // C++17 [over.ics.list]p6:
1665 // If C is not an initializer-list constructor and the initializer list
1666 // has a single element of type cv U, where U is X or a class derived
1667 // from X, the implicit conversion sequence has Exact Match rank if U is
1668 // X, or Conversion rank if U is derived from X.
1669 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1670 InitList && InitList->getNumInits() == 1 &&
1671 !S.isInitListConstructor(Constructor)) {
1672 const Expr *SingleInit = InitList->getInit(0);
1673 FromType = SingleInit->getType();
1674 FromLoc = SingleInit->getBeginLoc();
1675 } else {
1676 FromType = From->getType();
1677 FromLoc = From->getBeginLoc();
1678 }
1679 QualType FromCanon =
1681 QualType ToCanon
1683 if ((FromCanon == ToCanon ||
1684 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1685 // Turn this into a "standard" conversion sequence, so that it
1686 // gets ranked with standard conversion sequences.
1688 ICS.setStandard();
1690 ICS.Standard.setFromType(FromType);
1691 ICS.Standard.setAllToTypes(ToType);
1692 ICS.Standard.CopyConstructor = Constructor;
1694 if (ToCanon != FromCanon)
1696 }
1697 }
1698 break;
1699
1700 case OR_Ambiguous:
1701 ICS.setAmbiguous();
1702 ICS.Ambiguous.setFromType(From->getType());
1703 ICS.Ambiguous.setToType(ToType);
1704 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1705 Cand != Conversions.end(); ++Cand)
1706 if (Cand->Best)
1707 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1708 break;
1709
1710 // Fall through.
1713 break;
1714 }
1715
1716 return ICS;
1717}
1718
1719/// TryImplicitConversion - Attempt to perform an implicit conversion
1720/// from the given expression (Expr) to the given type (ToType). This
1721/// function returns an implicit conversion sequence that can be used
1722/// to perform the initialization. Given
1723///
1724/// void f(float f);
1725/// void g(int i) { f(i); }
1726///
1727/// this routine would produce an implicit conversion sequence to
1728/// describe the initialization of f from i, which will be a standard
1729/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1730/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1731//
1732/// Note that this routine only determines how the conversion can be
1733/// performed; it does not actually perform the conversion. As such,
1734/// it will not produce any diagnostics if no conversion is available,
1735/// but will instead return an implicit conversion sequence of kind
1736/// "BadConversion".
1737///
1738/// If @p SuppressUserConversions, then user-defined conversions are
1739/// not permitted.
1740/// If @p AllowExplicit, then explicit user-defined conversions are
1741/// permitted.
1742///
1743/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1744/// writeback conversion, which allows __autoreleasing id* parameters to
1745/// be initialized with __strong id* or __weak id* arguments.
1748 bool SuppressUserConversions,
1749 AllowedExplicit AllowExplicit,
1750 bool InOverloadResolution,
1751 bool CStyle,
1752 bool AllowObjCWritebackConversion,
1753 bool AllowObjCConversionOnExplicit) {
1755 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1756 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1757 ICS.setStandard();
1758 return ICS;
1759 }
1760
1761 if (!S.getLangOpts().CPlusPlus) {
1763 return ICS;
1764 }
1765
1766 // C++ [over.ics.user]p4:
1767 // A conversion of an expression of class type to the same class
1768 // type is given Exact Match rank, and a conversion of an
1769 // expression of class type to a base class of that type is
1770 // given Conversion rank, in spite of the fact that a copy/move
1771 // constructor (i.e., a user-defined conversion function) is
1772 // called for those cases.
1773 QualType FromType = From->getType();
1774 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1775 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1776 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1777 ICS.setStandard();
1779 ICS.Standard.setFromType(FromType);
1780 ICS.Standard.setAllToTypes(ToType);
1781
1782 // We don't actually check at this point whether there is a valid
1783 // copy/move constructor, since overloading just assumes that it
1784 // exists. When we actually perform initialization, we'll find the
1785 // appropriate constructor to copy the returned object, if needed.
1786 ICS.Standard.CopyConstructor = nullptr;
1787
1788 // Determine whether this is considered a derived-to-base conversion.
1789 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1791
1792 return ICS;
1793 }
1794
1795 if (S.getLangOpts().HLSL && ToType->isHLSLAttributedResourceType() &&
1796 FromType->isHLSLAttributedResourceType()) {
1797 auto *ToResType = cast<HLSLAttributedResourceType>(ToType);
1798 auto *FromResType = cast<HLSLAttributedResourceType>(FromType);
1799 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1800 FromResType->getWrappedType()) &&
1801 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1802 FromResType->getContainedType()) &&
1803 ToResType->getAttrs() == FromResType->getAttrs()) {
1804 ICS.setStandard();
1806 ICS.Standard.setFromType(FromType);
1807 ICS.Standard.setAllToTypes(ToType);
1808 return ICS;
1809 }
1810 }
1811
1812 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1813 AllowExplicit, InOverloadResolution, CStyle,
1814 AllowObjCWritebackConversion,
1815 AllowObjCConversionOnExplicit);
1816}
1817
1820 bool SuppressUserConversions,
1821 AllowedExplicit AllowExplicit,
1822 bool InOverloadResolution,
1823 bool CStyle,
1824 bool AllowObjCWritebackConversion) {
1825 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1826 AllowExplicit, InOverloadResolution, CStyle,
1827 AllowObjCWritebackConversion,
1828 /*AllowObjCConversionOnExplicit=*/false);
1829}
1830
1832 AssignmentAction Action,
1833 bool AllowExplicit) {
1834 if (checkPlaceholderForOverload(*this, From))
1835 return ExprError();
1836
1837 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1838 bool AllowObjCWritebackConversion =
1839 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1840 Action == AssignmentAction::Sending);
1841 if (getLangOpts().ObjC)
1842 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1843 From->getType(), From);
1845 *this, From, ToType,
1846 /*SuppressUserConversions=*/false,
1847 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1848 /*InOverloadResolution=*/false,
1849 /*CStyle=*/false, AllowObjCWritebackConversion,
1850 /*AllowObjCConversionOnExplicit=*/false);
1851 return PerformImplicitConversion(From, ToType, ICS, Action);
1852}
1853
1855 QualType &ResultTy) {
1856 if (Context.hasSameUnqualifiedType(FromType, ToType))
1857 return false;
1858
1859 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1860 // or F(t noexcept) -> F(t)
1861 // where F adds one of the following at most once:
1862 // - a pointer
1863 // - a member pointer
1864 // - a block pointer
1865 // Changes here need matching changes in FindCompositePointerType.
1866 CanQualType CanTo = Context.getCanonicalType(ToType);
1867 CanQualType CanFrom = Context.getCanonicalType(FromType);
1868 Type::TypeClass TyClass = CanTo->getTypeClass();
1869 if (TyClass != CanFrom->getTypeClass()) return false;
1870 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1871 if (TyClass == Type::Pointer) {
1872 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1873 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1874 } else if (TyClass == Type::BlockPointer) {
1875 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1876 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1877 } else if (TyClass == Type::MemberPointer) {
1878 auto ToMPT = CanTo.castAs<MemberPointerType>();
1879 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1880 // A function pointer conversion cannot change the class of the function.
1881 if (ToMPT->getClass() != FromMPT->getClass())
1882 return false;
1883 CanTo = ToMPT->getPointeeType();
1884 CanFrom = FromMPT->getPointeeType();
1885 } else {
1886 return false;
1887 }
1888
1889 TyClass = CanTo->getTypeClass();
1890 if (TyClass != CanFrom->getTypeClass()) return false;
1891 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1892 return false;
1893 }
1894
1895 const auto *FromFn = cast<FunctionType>(CanFrom);
1896 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1897
1898 const auto *ToFn = cast<FunctionType>(CanTo);
1899 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1900
1901 bool Changed = false;
1902
1903 // Drop 'noreturn' if not present in target type.
1904 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1905 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1906 Changed = true;
1907 }
1908
1909 // Drop 'noexcept' if not present in target type.
1910 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1911 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1912 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1913 FromFn = cast<FunctionType>(
1914 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1915 EST_None)
1916 .getTypePtr());
1917 Changed = true;
1918 }
1919
1920 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1921 // only if the ExtParameterInfo lists of the two function prototypes can be
1922 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1924 bool CanUseToFPT, CanUseFromFPT;
1925 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1926 CanUseFromFPT, NewParamInfos) &&
1927 CanUseToFPT && !CanUseFromFPT) {
1928 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1929 ExtInfo.ExtParameterInfos =
1930 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1931 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1932 FromFPT->getParamTypes(), ExtInfo);
1933 FromFn = QT->getAs<FunctionType>();
1934 Changed = true;
1935 }
1936
1937 // For C, when called from checkPointerTypesForAssignment,
1938 // we need to not alter FromFn, or else even an innocuous cast
1939 // like dropping effects will fail. In C++ however we do want to
1940 // alter FromFn (because of the way PerformImplicitConversion works).
1941 if (Context.hasAnyFunctionEffects() && getLangOpts().CPlusPlus) {
1942 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
1943
1944 // Transparently add/drop effects; here we are concerned with
1945 // language rules/canonicalization. Adding/dropping effects is a warning.
1946 const auto FromFX = FromFPT->getFunctionEffects();
1947 const auto ToFX = ToFPT->getFunctionEffects();
1948 if (FromFX != ToFX) {
1949 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1950 ExtInfo.FunctionEffects = ToFX;
1951 QualType QT = Context.getFunctionType(
1952 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
1953 FromFn = QT->getAs<FunctionType>();
1954 Changed = true;
1955 }
1956 }
1957 }
1958
1959 if (!Changed)
1960 return false;
1961
1962 assert(QualType(FromFn, 0).isCanonical());
1963 if (QualType(FromFn, 0) != CanTo) return false;
1964
1965 ResultTy = ToType;
1966 return true;
1967}
1968
1969/// Determine whether the conversion from FromType to ToType is a valid
1970/// floating point conversion.
1971///
1972static bool IsFloatingPointConversion(Sema &S, QualType FromType,
1973 QualType ToType) {
1974 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
1975 return false;
1976 // FIXME: disable conversions between long double, __ibm128 and __float128
1977 // if their representation is different until there is back end support
1978 // We of course allow this conversion if long double is really double.
1979
1980 // Conversions between bfloat16 and float16 are currently not supported.
1981 if ((FromType->isBFloat16Type() &&
1982 (ToType->isFloat16Type() || ToType->isHalfType())) ||
1983 (ToType->isBFloat16Type() &&
1984 (FromType->isFloat16Type() || FromType->isHalfType())))
1985 return false;
1986
1987 // Conversions between IEEE-quad and IBM-extended semantics are not
1988 // permitted.
1989 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
1990 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
1991 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
1992 &ToSem == &llvm::APFloat::IEEEquad()) ||
1993 (&FromSem == &llvm::APFloat::IEEEquad() &&
1994 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
1995 return false;
1996 return true;
1997}
1998
1999static bool IsVectorElementConversion(Sema &S, QualType FromType,
2000 QualType ToType,
2001 ImplicitConversionKind &ICK, Expr *From) {
2002 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2003 return true;
2004
2005 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2007 return true;
2008 }
2009
2010 if (IsFloatingPointConversion(S, FromType, ToType)) {
2012 return true;
2013 }
2014
2015 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2017 return true;
2018 }
2019
2020 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2022 ToType->isRealFloatingType())) {
2024 return true;
2025 }
2026
2027 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2029 return true;
2030 }
2031
2032 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2033 ToType->isIntegralType(S.Context)) {
2035 return true;
2036 }
2037
2038 return false;
2039}
2040
2041/// Determine whether the conversion from FromType to ToType is a valid
2042/// vector conversion.
2043///
2044/// \param ICK Will be set to the vector conversion kind, if this is a vector
2045/// conversion.
2046static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2048 ImplicitConversionKind &ElConv, Expr *From,
2049 bool InOverloadResolution, bool CStyle) {
2050 // We need at least one of these types to be a vector type to have a vector
2051 // conversion.
2052 if (!ToType->isVectorType() && !FromType->isVectorType())
2053 return false;
2054
2055 // Identical types require no conversions.
2056 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2057 return false;
2058
2059 // HLSL allows implicit truncation of vector types.
2060 if (S.getLangOpts().HLSL) {
2061 auto *ToExtType = ToType->getAs<ExtVectorType>();
2062 auto *FromExtType = FromType->getAs<ExtVectorType>();
2063
2064 // If both arguments are vectors, handle possible vector truncation and
2065 // element conversion.
2066 if (ToExtType && FromExtType) {
2067 unsigned FromElts = FromExtType->getNumElements();
2068 unsigned ToElts = ToExtType->getNumElements();
2069 if (FromElts < ToElts)
2070 return false;
2071 if (FromElts == ToElts)
2072 ElConv = ICK_Identity;
2073 else
2075
2076 QualType FromElTy = FromExtType->getElementType();
2077 QualType ToElTy = ToExtType->getElementType();
2078 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2079 return true;
2080 return IsVectorElementConversion(S, FromElTy, ToElTy, ICK, From);
2081 }
2082 if (FromExtType && !ToExtType) {
2084 QualType FromElTy = FromExtType->getElementType();
2085 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2086 return true;
2087 return IsVectorElementConversion(S, FromElTy, ToType, ICK, From);
2088 }
2089 // Fallthrough for the case where ToType is a vector and FromType is not.
2090 }
2091
2092 // There are no conversions between extended vector types, only identity.
2093 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2094 if (FromType->getAs<ExtVectorType>()) {
2095 // There are no conversions between extended vector types other than the
2096 // identity conversion.
2097 return false;
2098 }
2099
2100 // Vector splat from any arithmetic type to a vector.
2101 if (FromType->isArithmeticType()) {
2102 if (S.getLangOpts().HLSL) {
2103 ElConv = ICK_HLSL_Vector_Splat;
2104 QualType ToElTy = ToExtType->getElementType();
2105 return IsVectorElementConversion(S, FromType, ToElTy, ICK, From);
2106 }
2107 ICK = ICK_Vector_Splat;
2108 return true;
2109 }
2110 }
2111
2112 if (ToType->isSVESizelessBuiltinType() ||
2113 FromType->isSVESizelessBuiltinType())
2114 if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
2115 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
2117 return true;
2118 }
2119
2120 if (ToType->isRVVSizelessBuiltinType() ||
2121 FromType->isRVVSizelessBuiltinType())
2122 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2123 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2125 return true;
2126 }
2127
2128 // We can perform the conversion between vector types in the following cases:
2129 // 1)vector types are equivalent AltiVec and GCC vector types
2130 // 2)lax vector conversions are permitted and the vector types are of the
2131 // same size
2132 // 3)the destination type does not have the ARM MVE strict-polymorphism
2133 // attribute, which inhibits lax vector conversion for overload resolution
2134 // only
2135 if (ToType->isVectorType() && FromType->isVectorType()) {
2136 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2137 (S.isLaxVectorConversion(FromType, ToType) &&
2138 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2139 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2140 S.isLaxVectorConversion(FromType, ToType) &&
2141 S.anyAltivecTypes(FromType, ToType) &&
2142 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2143 !InOverloadResolution && !CStyle) {
2144 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2145 << FromType << ToType;
2146 }
2148 return true;
2149 }
2150 }
2151
2152 return false;
2153}
2154
2155static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2156 bool InOverloadResolution,
2158 bool CStyle);
2159
2160/// IsStandardConversion - Determines whether there is a standard
2161/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2162/// expression From to the type ToType. Standard conversion sequences
2163/// only consider non-class types; for conversions that involve class
2164/// types, use TryImplicitConversion. If a conversion exists, SCS will
2165/// contain the standard conversion sequence required to perform this
2166/// conversion and this routine will return true. Otherwise, this
2167/// routine will return false and the value of SCS is unspecified.
2168static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2169 bool InOverloadResolution,
2171 bool CStyle,
2172 bool AllowObjCWritebackConversion) {
2173 QualType FromType = From->getType();
2174
2175 // Standard conversions (C++ [conv])
2177 SCS.IncompatibleObjC = false;
2178 SCS.setFromType(FromType);
2179 SCS.CopyConstructor = nullptr;
2180
2181 // There are no standard conversions for class types in C++, so
2182 // abort early. When overloading in C, however, we do permit them.
2183 if (S.getLangOpts().CPlusPlus &&
2184 (FromType->isRecordType() || ToType->isRecordType()))
2185 return false;
2186
2187 // The first conversion can be an lvalue-to-rvalue conversion,
2188 // array-to-pointer conversion, or function-to-pointer conversion
2189 // (C++ 4p1).
2190
2191 if (FromType == S.Context.OverloadTy) {
2192 DeclAccessPair AccessPair;
2193 if (FunctionDecl *Fn
2194 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2195 AccessPair)) {
2196 // We were able to resolve the address of the overloaded function,
2197 // so we can convert to the type of that function.
2198 FromType = Fn->getType();
2199 SCS.setFromType(FromType);
2200
2201 // we can sometimes resolve &foo<int> regardless of ToType, so check
2202 // if the type matches (identity) or we are converting to bool
2204 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2205 QualType resultTy;
2206 // if the function type matches except for [[noreturn]], it's ok
2207 if (!S.IsFunctionConversion(FromType,
2208 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
2209 // otherwise, only a boolean conversion is standard
2210 if (!ToType->isBooleanType())
2211 return false;
2212 }
2213
2214 // Check if the "from" expression is taking the address of an overloaded
2215 // function and recompute the FromType accordingly. Take advantage of the
2216 // fact that non-static member functions *must* have such an address-of
2217 // expression.
2218 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2219 if (Method && !Method->isStatic() &&
2220 !Method->isExplicitObjectMemberFunction()) {
2221 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2222 "Non-unary operator on non-static member address");
2223 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2224 == UO_AddrOf &&
2225 "Non-address-of operator on non-static member address");
2226 const Type *ClassType
2228 FromType = S.Context.getMemberPointerType(FromType, ClassType);
2229 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2230 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2231 UO_AddrOf &&
2232 "Non-address-of operator for overloaded function expression");
2233 FromType = S.Context.getPointerType(FromType);
2234 }
2235 } else {
2236 return false;
2237 }
2238 }
2239
2240 bool argIsLValue = From->isGLValue();
2241 // To handle conversion from ArrayParameterType to ConstantArrayType
2242 // this block must be above the one below because Array parameters
2243 // do not decay and when handling HLSLOutArgExprs and
2244 // the From expression is an LValue.
2245 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2246 ToType->isConstantArrayType()) {
2247 // HLSL constant array parameters do not decay, so if the argument is a
2248 // constant array and the parameter is an ArrayParameterType we have special
2249 // handling here.
2250 if (ToType->isArrayParameterType()) {
2251 FromType = S.Context.getArrayParameterType(FromType);
2253 } else if (FromType->isArrayParameterType()) {
2254 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2255 FromType = APT->getConstantArrayType(S.Context);
2257 } else {
2258 SCS.First = ICK_Identity;
2259 }
2260
2261 if (S.Context.getCanonicalType(FromType) !=
2262 S.Context.getCanonicalType(ToType))
2263 return false;
2264
2265 SCS.setAllToTypes(ToType);
2266 return true;
2267 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2268 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2269 // Lvalue-to-rvalue conversion (C++11 4.1):
2270 // A glvalue (3.10) of a non-function, non-array type T can
2271 // be converted to a prvalue.
2272
2274
2275 // C11 6.3.2.1p2:
2276 // ... if the lvalue has atomic type, the value has the non-atomic version
2277 // of the type of the lvalue ...
2278 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2279 FromType = Atomic->getValueType();
2280
2281 // If T is a non-class type, the type of the rvalue is the
2282 // cv-unqualified version of T. Otherwise, the type of the rvalue
2283 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2284 // just strip the qualifiers because they don't matter.
2285 FromType = FromType.getUnqualifiedType();
2286 } else if (FromType->isArrayType()) {
2287 // Array-to-pointer conversion (C++ 4.2)
2289
2290 // An lvalue or rvalue of type "array of N T" or "array of unknown
2291 // bound of T" can be converted to an rvalue of type "pointer to
2292 // T" (C++ 4.2p1).
2293 FromType = S.Context.getArrayDecayedType(FromType);
2294
2295 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2296 // This conversion is deprecated in C++03 (D.4)
2298
2299 // For the purpose of ranking in overload resolution
2300 // (13.3.3.1.1), this conversion is considered an
2301 // array-to-pointer conversion followed by a qualification
2302 // conversion (4.4). (C++ 4.2p2)
2303 SCS.Second = ICK_Identity;
2306 SCS.setAllToTypes(FromType);
2307 return true;
2308 }
2309 } else if (FromType->isFunctionType() && argIsLValue) {
2310 // Function-to-pointer conversion (C++ 4.3).
2312
2313 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2314 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2316 return false;
2317
2318 // An lvalue of function type T can be converted to an rvalue of
2319 // type "pointer to T." The result is a pointer to the
2320 // function. (C++ 4.3p1).
2321 FromType = S.Context.getPointerType(FromType);
2322 } else {
2323 // We don't require any conversions for the first step.
2324 SCS.First = ICK_Identity;
2325 }
2326 SCS.setToType(0, FromType);
2327
2328 // The second conversion can be an integral promotion, floating
2329 // point promotion, integral conversion, floating point conversion,
2330 // floating-integral conversion, pointer conversion,
2331 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2332 // For overloading in C, this can also be a "compatible-type"
2333 // conversion.
2334 bool IncompatibleObjC = false;
2336 ImplicitConversionKind DimensionICK = ICK_Identity;
2337 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2338 // The unqualified versions of the types are the same: there's no
2339 // conversion to do.
2340 SCS.Second = ICK_Identity;
2341 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2342 // Integral promotion (C++ 4.5).
2344 FromType = ToType.getUnqualifiedType();
2345 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2346 // Floating point promotion (C++ 4.6).
2348 FromType = ToType.getUnqualifiedType();
2349 } else if (S.IsComplexPromotion(FromType, ToType)) {
2350 // Complex promotion (Clang extension)
2352 FromType = ToType.getUnqualifiedType();
2353 } else if (ToType->isBooleanType() &&
2354 (FromType->isArithmeticType() ||
2355 FromType->isAnyPointerType() ||
2356 FromType->isBlockPointerType() ||
2357 FromType->isMemberPointerType())) {
2358 // Boolean conversions (C++ 4.12).
2360 FromType = S.Context.BoolTy;
2361 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2362 ToType->isIntegralType(S.Context)) {
2363 // Integral conversions (C++ 4.7).
2365 FromType = ToType.getUnqualifiedType();
2366 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2367 // Complex conversions (C99 6.3.1.6)
2369 FromType = ToType.getUnqualifiedType();
2370 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2371 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2372 // Complex-real conversions (C99 6.3.1.7)
2374 FromType = ToType.getUnqualifiedType();
2375 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2376 // Floating point conversions (C++ 4.8).
2378 FromType = ToType.getUnqualifiedType();
2379 } else if ((FromType->isRealFloatingType() &&
2380 ToType->isIntegralType(S.Context)) ||
2382 ToType->isRealFloatingType())) {
2383
2384 // Floating-integral conversions (C++ 4.9).
2386 FromType = ToType.getUnqualifiedType();
2387 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2389 } else if (AllowObjCWritebackConversion &&
2390 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2392 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2393 FromType, IncompatibleObjC)) {
2394 // Pointer conversions (C++ 4.10).
2396 SCS.IncompatibleObjC = IncompatibleObjC;
2397 FromType = FromType.getUnqualifiedType();
2398 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2399 InOverloadResolution, FromType)) {
2400 // Pointer to member conversions (4.11).
2402 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2403 From, InOverloadResolution, CStyle)) {
2404 SCS.Second = SecondICK;
2405 SCS.Dimension = DimensionICK;
2406 FromType = ToType.getUnqualifiedType();
2407 } else if (!S.getLangOpts().CPlusPlus &&
2408 S.Context.typesAreCompatible(ToType, FromType)) {
2409 // Compatible conversions (Clang extension for C function overloading)
2411 FromType = ToType.getUnqualifiedType();
2413 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2415 FromType = ToType;
2416 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2417 CStyle)) {
2418 // tryAtomicConversion has updated the standard conversion sequence
2419 // appropriately.
2420 return true;
2421 } else if (ToType->isEventT() &&
2423 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2425 FromType = ToType;
2426 } else if (ToType->isQueueT() &&
2428 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2430 FromType = ToType;
2431 } else if (ToType->isSamplerT() &&
2434 FromType = ToType;
2435 } else if ((ToType->isFixedPointType() &&
2436 FromType->isConvertibleToFixedPointType()) ||
2437 (FromType->isFixedPointType() &&
2438 ToType->isConvertibleToFixedPointType())) {
2440 FromType = ToType;
2441 } else {
2442 // No second conversion required.
2443 SCS.Second = ICK_Identity;
2444 }
2445 SCS.setToType(1, FromType);
2446
2447 // The third conversion can be a function pointer conversion or a
2448 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2449 bool ObjCLifetimeConversion;
2450 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
2451 // Function pointer conversions (removing 'noexcept') including removal of
2452 // 'noreturn' (Clang extension).
2454 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2455 ObjCLifetimeConversion)) {
2457 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2458 FromType = ToType;
2459 } else {
2460 // No conversion required
2461 SCS.Third = ICK_Identity;
2462 }
2463
2464 // C++ [over.best.ics]p6:
2465 // [...] Any difference in top-level cv-qualification is
2466 // subsumed by the initialization itself and does not constitute
2467 // a conversion. [...]
2468 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2469 QualType CanonTo = S.Context.getCanonicalType(ToType);
2470 if (CanonFrom.getLocalUnqualifiedType()
2471 == CanonTo.getLocalUnqualifiedType() &&
2472 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2473 FromType = ToType;
2474 CanonFrom = CanonTo;
2475 }
2476
2477 SCS.setToType(2, FromType);
2478
2479 if (CanonFrom == CanonTo)
2480 return true;
2481
2482 // If we have not converted the argument type to the parameter type,
2483 // this is a bad conversion sequence, unless we're resolving an overload in C.
2484 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2485 return false;
2486
2487 ExprResult ER = ExprResult{From};
2490 /*Diagnose=*/false,
2491 /*DiagnoseCFAudited=*/false,
2492 /*ConvertRHS=*/false);
2493 ImplicitConversionKind SecondConv;
2494 switch (Conv) {
2495 case Sema::Compatible:
2496 SecondConv = ICK_C_Only_Conversion;
2497 break;
2498 // For our purposes, discarding qualifiers is just as bad as using an
2499 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2500 // qualifiers, as well.
2505 break;
2506 default:
2507 return false;
2508 }
2509
2510 // First can only be an lvalue conversion, so we pretend that this was the
2511 // second conversion. First should already be valid from earlier in the
2512 // function.
2513 SCS.Second = SecondConv;
2514 SCS.setToType(1, ToType);
2515
2516 // Third is Identity, because Second should rank us worse than any other
2517 // conversion. This could also be ICK_Qualification, but it's simpler to just
2518 // lump everything in with the second conversion, and we don't gain anything
2519 // from making this ICK_Qualification.
2520 SCS.Third = ICK_Identity;
2521 SCS.setToType(2, ToType);
2522 return true;
2523}
2524
2525static bool
2527 QualType &ToType,
2528 bool InOverloadResolution,
2530 bool CStyle) {
2531
2532 const RecordType *UT = ToType->getAsUnionType();
2533 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2534 return false;
2535 // The field to initialize within the transparent union.
2536 RecordDecl *UD = UT->getDecl();
2537 // It's compatible if the expression matches any of the fields.
2538 for (const auto *it : UD->fields()) {
2539 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2540 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2541 ToType = it->getType();
2542 return true;
2543 }
2544 }
2545 return false;
2546}
2547
2548bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2549 const BuiltinType *To = ToType->getAs<BuiltinType>();
2550 // All integers are built-in.
2551 if (!To) {
2552 return false;
2553 }
2554
2555 // An rvalue of type char, signed char, unsigned char, short int, or
2556 // unsigned short int can be converted to an rvalue of type int if
2557 // int can represent all the values of the source type; otherwise,
2558 // the source rvalue can be converted to an rvalue of type unsigned
2559 // int (C++ 4.5p1).
2560 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2561 !FromType->isEnumeralType()) {
2562 if ( // We can promote any signed, promotable integer type to an int
2563 (FromType->isSignedIntegerType() ||
2564 // We can promote any unsigned integer type whose size is
2565 // less than int to an int.
2566 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2567 return To->getKind() == BuiltinType::Int;
2568 }
2569
2570 return To->getKind() == BuiltinType::UInt;
2571 }
2572
2573 // C++11 [conv.prom]p3:
2574 // A prvalue of an unscoped enumeration type whose underlying type is not
2575 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2576 // following types that can represent all the values of the enumeration
2577 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2578 // unsigned int, long int, unsigned long int, long long int, or unsigned
2579 // long long int. If none of the types in that list can represent all the
2580 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2581 // type can be converted to an rvalue a prvalue of the extended integer type
2582 // with lowest integer conversion rank (4.13) greater than the rank of long
2583 // long in which all the values of the enumeration can be represented. If
2584 // there are two such extended types, the signed one is chosen.
2585 // C++11 [conv.prom]p4:
2586 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2587 // can be converted to a prvalue of its underlying type. Moreover, if
2588 // integral promotion can be applied to its underlying type, a prvalue of an
2589 // unscoped enumeration type whose underlying type is fixed can also be
2590 // converted to a prvalue of the promoted underlying type.
2591 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2592 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2593 // provided for a scoped enumeration.
2594 if (FromEnumType->getDecl()->isScoped())
2595 return false;
2596
2597 // We can perform an integral promotion to the underlying type of the enum,
2598 // even if that's not the promoted type. Note that the check for promoting
2599 // the underlying type is based on the type alone, and does not consider
2600 // the bitfield-ness of the actual source expression.
2601 if (FromEnumType->getDecl()->isFixed()) {
2602 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2603 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2604 IsIntegralPromotion(nullptr, Underlying, ToType);
2605 }
2606
2607 // We have already pre-calculated the promotion type, so this is trivial.
2608 if (ToType->isIntegerType() &&
2609 isCompleteType(From->getBeginLoc(), FromType))
2610 return Context.hasSameUnqualifiedType(
2611 ToType, FromEnumType->getDecl()->getPromotionType());
2612
2613 // C++ [conv.prom]p5:
2614 // If the bit-field has an enumerated type, it is treated as any other
2615 // value of that type for promotion purposes.
2616 //
2617 // ... so do not fall through into the bit-field checks below in C++.
2618 if (getLangOpts().CPlusPlus)
2619 return false;
2620 }
2621
2622 // C++0x [conv.prom]p2:
2623 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2624 // to an rvalue a prvalue of the first of the following types that can
2625 // represent all the values of its underlying type: int, unsigned int,
2626 // long int, unsigned long int, long long int, or unsigned long long int.
2627 // If none of the types in that list can represent all the values of its
2628 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2629 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2630 // type.
2631 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2632 ToType->isIntegerType()) {
2633 // Determine whether the type we're converting from is signed or
2634 // unsigned.
2635 bool FromIsSigned = FromType->isSignedIntegerType();
2636 uint64_t FromSize = Context.getTypeSize(FromType);
2637
2638 // The types we'll try to promote to, in the appropriate
2639 // order. Try each of these types.
2640 QualType PromoteTypes[6] = {
2641 Context.IntTy, Context.UnsignedIntTy,
2642 Context.LongTy, Context.UnsignedLongTy ,
2643 Context.LongLongTy, Context.UnsignedLongLongTy
2644 };
2645 for (int Idx = 0; Idx < 6; ++Idx) {
2646 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2647 if (FromSize < ToSize ||
2648 (FromSize == ToSize &&
2649 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2650 // We found the type that we can promote to. If this is the
2651 // type we wanted, we have a promotion. Otherwise, no
2652 // promotion.
2653 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2654 }
2655 }
2656 }
2657
2658 // An rvalue for an integral bit-field (9.6) can be converted to an
2659 // rvalue of type int if int can represent all the values of the
2660 // bit-field; otherwise, it can be converted to unsigned int if
2661 // unsigned int can represent all the values of the bit-field. If
2662 // the bit-field is larger yet, no integral promotion applies to
2663 // it. If the bit-field has an enumerated type, it is treated as any
2664 // other value of that type for promotion purposes (C++ 4.5p3).
2665 // FIXME: We should delay checking of bit-fields until we actually perform the
2666 // conversion.
2667 //
2668 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2669 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2670 // bit-fields and those whose underlying type is larger than int) for GCC
2671 // compatibility.
2672 if (From) {
2673 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2674 std::optional<llvm::APSInt> BitWidth;
2675 if (FromType->isIntegralType(Context) &&
2676 (BitWidth =
2677 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2678 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2679 ToSize = Context.getTypeSize(ToType);
2680
2681 // Are we promoting to an int from a bitfield that fits in an int?
2682 if (*BitWidth < ToSize ||
2683 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2684 return To->getKind() == BuiltinType::Int;
2685 }
2686
2687 // Are we promoting to an unsigned int from an unsigned bitfield
2688 // that fits into an unsigned int?
2689 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2690 return To->getKind() == BuiltinType::UInt;
2691 }
2692
2693 return false;
2694 }
2695 }
2696 }
2697
2698 // An rvalue of type bool can be converted to an rvalue of type int,
2699 // with false becoming zero and true becoming one (C++ 4.5p4).
2700 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2701 return true;
2702 }
2703
2704 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2705 // integral type.
2706 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2707 ToType->isIntegerType())
2708 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2709
2710 return false;
2711}
2712
2714 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2715 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2716 /// An rvalue of type float can be converted to an rvalue of type
2717 /// double. (C++ 4.6p1).
2718 if (FromBuiltin->getKind() == BuiltinType::Float &&
2719 ToBuiltin->getKind() == BuiltinType::Double)
2720 return true;
2721
2722 // C99 6.3.1.5p1:
2723 // When a float is promoted to double or long double, or a
2724 // double is promoted to long double [...].
2725 if (!getLangOpts().CPlusPlus &&
2726 (FromBuiltin->getKind() == BuiltinType::Float ||
2727 FromBuiltin->getKind() == BuiltinType::Double) &&
2728 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2729 ToBuiltin->getKind() == BuiltinType::Float128 ||
2730 ToBuiltin->getKind() == BuiltinType::Ibm128))
2731 return true;
2732
2733 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2734 // or not native half types are enabled.
2735 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2736 (ToBuiltin->getKind() == BuiltinType::Float ||
2737 ToBuiltin->getKind() == BuiltinType::Double))
2738 return true;
2739
2740 // Half can be promoted to float.
2741 if (!getLangOpts().NativeHalfType &&
2742 FromBuiltin->getKind() == BuiltinType::Half &&
2743 ToBuiltin->getKind() == BuiltinType::Float)
2744 return true;
2745 }
2746
2747 return false;
2748}
2749
2751 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2752 if (!FromComplex)
2753 return false;
2754
2755 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2756 if (!ToComplex)
2757 return false;
2758
2759 return IsFloatingPointPromotion(FromComplex->getElementType(),
2760 ToComplex->getElementType()) ||
2761 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2762 ToComplex->getElementType());
2763}
2764
2765/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2766/// the pointer type FromPtr to a pointer to type ToPointee, with the
2767/// same type qualifiers as FromPtr has on its pointee type. ToType,
2768/// if non-empty, will be a pointer to ToType that may or may not have
2769/// the right set of qualifiers on its pointee.
2770///
2771static QualType
2773 QualType ToPointee, QualType ToType,
2774 ASTContext &Context,
2775 bool StripObjCLifetime = false) {
2776 assert((FromPtr->getTypeClass() == Type::Pointer ||
2777 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2778 "Invalid similarly-qualified pointer type");
2779
2780 /// Conversions to 'id' subsume cv-qualifier conversions.
2781 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2782 return ToType.getUnqualifiedType();
2783
2784 QualType CanonFromPointee
2785 = Context.getCanonicalType(FromPtr->getPointeeType());
2786 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2787 Qualifiers Quals = CanonFromPointee.getQualifiers();
2788
2789 if (StripObjCLifetime)
2790 Quals.removeObjCLifetime();
2791
2792 // Exact qualifier match -> return the pointer type we're converting to.
2793 if (CanonToPointee.getLocalQualifiers() == Quals) {
2794 // ToType is exactly what we need. Return it.
2795 if (!ToType.isNull())
2796 return ToType.getUnqualifiedType();
2797
2798 // Build a pointer to ToPointee. It has the right qualifiers
2799 // already.
2800 if (isa<ObjCObjectPointerType>(ToType))
2801 return Context.getObjCObjectPointerType(ToPointee);
2802 return Context.getPointerType(ToPointee);
2803 }
2804
2805 // Just build a canonical type that has the right qualifiers.
2806 QualType QualifiedCanonToPointee
2807 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2808
2809 if (isa<ObjCObjectPointerType>(ToType))
2810 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2811 return Context.getPointerType(QualifiedCanonToPointee);
2812}
2813
2815 bool InOverloadResolution,
2816 ASTContext &Context) {
2817 // Handle value-dependent integral null pointer constants correctly.
2818 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2819 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2821 return !InOverloadResolution;
2822
2823 return Expr->isNullPointerConstant(Context,
2824 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2826}
2827
2829 bool InOverloadResolution,
2830 QualType& ConvertedType,
2831 bool &IncompatibleObjC) {
2832 IncompatibleObjC = false;
2833 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2834 IncompatibleObjC))
2835 return true;
2836
2837 // Conversion from a null pointer constant to any Objective-C pointer type.
2838 if (ToType->isObjCObjectPointerType() &&
2839 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2840 ConvertedType = ToType;
2841 return true;
2842 }
2843
2844 // Blocks: Block pointers can be converted to void*.
2845 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2846 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2847 ConvertedType = ToType;
2848 return true;
2849 }
2850 // Blocks: A null pointer constant can be converted to a block
2851 // pointer type.
2852 if (ToType->isBlockPointerType() &&
2853 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2854 ConvertedType = ToType;
2855 return true;
2856 }
2857
2858 // If the left-hand-side is nullptr_t, the right side can be a null
2859 // pointer constant.
2860 if (ToType->isNullPtrType() &&
2861 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2862 ConvertedType = ToType;
2863 return true;
2864 }
2865
2866 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2867 if (!ToTypePtr)
2868 return false;
2869
2870 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2871 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2872 ConvertedType = ToType;
2873 return true;
2874 }
2875
2876 // Beyond this point, both types need to be pointers
2877 // , including objective-c pointers.
2878 QualType ToPointeeType = ToTypePtr->getPointeeType();
2879 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2880 !getLangOpts().ObjCAutoRefCount) {
2881 ConvertedType = BuildSimilarlyQualifiedPointerType(
2882 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2883 Context);
2884 return true;
2885 }
2886 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2887 if (!FromTypePtr)
2888 return false;
2889
2890 QualType FromPointeeType = FromTypePtr->getPointeeType();
2891
2892 // If the unqualified pointee types are the same, this can't be a
2893 // pointer conversion, so don't do all of the work below.
2894 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2895 return false;
2896
2897 // An rvalue of type "pointer to cv T," where T is an object type,
2898 // can be converted to an rvalue of type "pointer to cv void" (C++
2899 // 4.10p2).
2900 if (FromPointeeType->isIncompleteOrObjectType() &&
2901 ToPointeeType->isVoidType()) {
2902 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2903 ToPointeeType,
2904 ToType, Context,
2905 /*StripObjCLifetime=*/true);
2906 return true;
2907 }
2908
2909 // MSVC allows implicit function to void* type conversion.
2910 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2911 ToPointeeType->isVoidType()) {
2912 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2913 ToPointeeType,
2914 ToType, Context);
2915 return true;
2916 }
2917
2918 // When we're overloading in C, we allow a special kind of pointer
2919 // conversion for compatible-but-not-identical pointee types.
2920 if (!getLangOpts().CPlusPlus &&
2921 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2922 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2923 ToPointeeType,
2924 ToType, Context);
2925 return true;
2926 }
2927
2928 // C++ [conv.ptr]p3:
2929 //
2930 // An rvalue of type "pointer to cv D," where D is a class type,
2931 // can be converted to an rvalue of type "pointer to cv B," where
2932 // B is a base class (clause 10) of D. If B is an inaccessible
2933 // (clause 11) or ambiguous (10.2) base class of D, a program that
2934 // necessitates this conversion is ill-formed. The result of the
2935 // conversion is a pointer to the base class sub-object of the
2936 // derived class object. The null pointer value is converted to
2937 // the null pointer value of the destination type.
2938 //
2939 // Note that we do not check for ambiguity or inaccessibility
2940 // here. That is handled by CheckPointerConversion.
2941 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2942 ToPointeeType->isRecordType() &&
2943 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2944 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2945 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2946 ToPointeeType,
2947 ToType, Context);
2948 return true;
2949 }
2950
2951 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2952 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2953 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2954 ToPointeeType,
2955 ToType, Context);
2956 return true;
2957 }
2958
2959 return false;
2960}
2961
2962/// Adopt the given qualifiers for the given type.
2964 Qualifiers TQs = T.getQualifiers();
2965
2966 // Check whether qualifiers already match.
2967 if (TQs == Qs)
2968 return T;
2969
2970 if (Qs.compatiblyIncludes(TQs, Context))
2971 return Context.getQualifiedType(T, Qs);
2972
2973 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2974}
2975
2977 QualType& ConvertedType,
2978 bool &IncompatibleObjC) {
2979 if (!getLangOpts().ObjC)
2980 return false;
2981
2982 // The set of qualifiers on the type we're converting from.
2983 Qualifiers FromQualifiers = FromType.getQualifiers();
2984
2985 // First, we handle all conversions on ObjC object pointer types.
2986 const ObjCObjectPointerType* ToObjCPtr =
2987 ToType->getAs<ObjCObjectPointerType>();
2988 const ObjCObjectPointerType *FromObjCPtr =
2989 FromType->getAs<ObjCObjectPointerType>();
2990
2991 if (ToObjCPtr && FromObjCPtr) {
2992 // If the pointee types are the same (ignoring qualifications),
2993 // then this is not a pointer conversion.
2994 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2995 FromObjCPtr->getPointeeType()))
2996 return false;
2997
2998 // Conversion between Objective-C pointers.
2999 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3000 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3001 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3002 if (getLangOpts().CPlusPlus && LHS && RHS &&
3004 FromObjCPtr->getPointeeType(), getASTContext()))
3005 return false;
3006 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3007 ToObjCPtr->getPointeeType(),
3008 ToType, Context);
3009 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3010 return true;
3011 }
3012
3013 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3014 // Okay: this is some kind of implicit downcast of Objective-C
3015 // interfaces, which is permitted. However, we're going to
3016 // complain about it.
3017 IncompatibleObjC = true;
3018 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3019 ToObjCPtr->getPointeeType(),
3020 ToType, Context);
3021 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3022 return true;
3023 }
3024 }
3025 // Beyond this point, both types need to be C pointers or block pointers.
3026 QualType ToPointeeType;
3027 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3028 ToPointeeType = ToCPtr->getPointeeType();
3029 else if (const BlockPointerType *ToBlockPtr =
3030 ToType->getAs<BlockPointerType>()) {
3031 // Objective C++: We're able to convert from a pointer to any object
3032 // to a block pointer type.
3033 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3034 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3035 return true;
3036 }
3037 ToPointeeType = ToBlockPtr->getPointeeType();
3038 }
3039 else if (FromType->getAs<BlockPointerType>() &&
3040 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3041 // Objective C++: We're able to convert from a block pointer type to a
3042 // pointer to any object.
3043 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3044 return true;
3045 }
3046 else
3047 return false;
3048
3049 QualType FromPointeeType;
3050 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3051 FromPointeeType = FromCPtr->getPointeeType();
3052 else if (const BlockPointerType *FromBlockPtr =
3053 FromType->getAs<BlockPointerType>())
3054 FromPointeeType = FromBlockPtr->getPointeeType();
3055 else
3056 return false;
3057
3058 // If we have pointers to pointers, recursively check whether this
3059 // is an Objective-C conversion.
3060 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3061 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3062 IncompatibleObjC)) {
3063 // We always complain about this conversion.
3064 IncompatibleObjC = true;
3065 ConvertedType = Context.getPointerType(ConvertedType);
3066 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3067 return true;
3068 }
3069 // Allow conversion of pointee being objective-c pointer to another one;
3070 // as in I* to id.
3071 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3072 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3073 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3074 IncompatibleObjC)) {
3075
3076 ConvertedType = Context.getPointerType(ConvertedType);
3077 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3078 return true;
3079 }
3080
3081 // If we have pointers to functions or blocks, check whether the only
3082 // differences in the argument and result types are in Objective-C
3083 // pointer conversions. If so, we permit the conversion (but
3084 // complain about it).
3085 const FunctionProtoType *FromFunctionType
3086 = FromPointeeType->getAs<FunctionProtoType>();
3087 const FunctionProtoType *ToFunctionType
3088 = ToPointeeType->getAs<FunctionProtoType>();
3089 if (FromFunctionType && ToFunctionType) {
3090 // If the function types are exactly the same, this isn't an
3091 // Objective-C pointer conversion.
3092 if (Context.getCanonicalType(FromPointeeType)
3093 == Context.getCanonicalType(ToPointeeType))
3094 return false;
3095
3096 // Perform the quick checks that will tell us whether these
3097 // function types are obviously different.
3098 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3099 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3100 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3101 return false;
3102
3103 bool HasObjCConversion = false;
3104 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3105 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3106 // Okay, the types match exactly. Nothing to do.
3107 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3108 ToFunctionType->getReturnType(),
3109 ConvertedType, IncompatibleObjC)) {
3110 // Okay, we have an Objective-C pointer conversion.
3111 HasObjCConversion = true;
3112 } else {
3113 // Function types are too different. Abort.
3114 return false;
3115 }
3116
3117 // Check argument types.
3118 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3119 ArgIdx != NumArgs; ++ArgIdx) {
3120 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3121 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3122 if (Context.getCanonicalType(FromArgType)
3123 == Context.getCanonicalType(ToArgType)) {
3124 // Okay, the types match exactly. Nothing to do.
3125 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3126 ConvertedType, IncompatibleObjC)) {
3127 // Okay, we have an Objective-C pointer conversion.
3128 HasObjCConversion = true;
3129 } else {
3130 // Argument types are too different. Abort.
3131 return false;
3132 }
3133 }
3134
3135 if (HasObjCConversion) {
3136 // We had an Objective-C conversion. Allow this pointer
3137 // conversion, but complain about it.
3138 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3139 IncompatibleObjC = true;
3140 return true;
3141 }
3142 }
3143
3144 return false;
3145}
3146
3148 QualType& ConvertedType) {
3149 QualType ToPointeeType;
3150 if (const BlockPointerType *ToBlockPtr =
3151 ToType->getAs<BlockPointerType>())
3152 ToPointeeType = ToBlockPtr->getPointeeType();
3153 else
3154 return false;
3155
3156 QualType FromPointeeType;
3157 if (const BlockPointerType *FromBlockPtr =
3158 FromType->getAs<BlockPointerType>())
3159 FromPointeeType = FromBlockPtr->getPointeeType();
3160 else
3161 return false;
3162 // We have pointer to blocks, check whether the only
3163 // differences in the argument and result types are in Objective-C
3164 // pointer conversions. If so, we permit the conversion.
3165
3166 const FunctionProtoType *FromFunctionType
3167 = FromPointeeType->getAs<FunctionProtoType>();
3168 const FunctionProtoType *ToFunctionType
3169 = ToPointeeType->getAs<FunctionProtoType>();
3170
3171 if (!FromFunctionType || !ToFunctionType)
3172 return false;
3173
3174 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3175 return true;
3176
3177 // Perform the quick checks that will tell us whether these
3178 // function types are obviously different.
3179 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3180 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3181 return false;
3182
3183 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3184 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3185 if (FromEInfo != ToEInfo)
3186 return false;
3187
3188 bool IncompatibleObjC = false;
3189 if (Context.hasSameType(FromFunctionType->getReturnType(),
3190 ToFunctionType->getReturnType())) {
3191 // Okay, the types match exactly. Nothing to do.
3192 } else {
3193 QualType RHS = FromFunctionType->getReturnType();
3194 QualType LHS = ToFunctionType->getReturnType();
3195 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3196 !RHS.hasQualifiers() && LHS.hasQualifiers())
3197 LHS = LHS.getUnqualifiedType();
3198
3199 if (Context.hasSameType(RHS,LHS)) {
3200 // OK exact match.
3201 } else if (isObjCPointerConversion(RHS, LHS,
3202 ConvertedType, IncompatibleObjC)) {
3203 if (IncompatibleObjC)
3204 return false;
3205 // Okay, we have an Objective-C pointer conversion.
3206 }
3207 else
3208 return false;
3209 }
3210
3211 // Check argument types.
3212 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3213 ArgIdx != NumArgs; ++ArgIdx) {
3214 IncompatibleObjC = false;
3215 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3216 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3217 if (Context.hasSameType(FromArgType, ToArgType)) {
3218 // Okay, the types match exactly. Nothing to do.
3219 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3220 ConvertedType, IncompatibleObjC)) {
3221 if (IncompatibleObjC)
3222 return false;
3223 // Okay, we have an Objective-C pointer conversion.
3224 } else
3225 // Argument types are too different. Abort.
3226 return false;
3227 }
3228
3230 bool CanUseToFPT, CanUseFromFPT;
3231 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3232 CanUseToFPT, CanUseFromFPT,
3233 NewParamInfos))
3234 return false;
3235
3236 ConvertedType = ToType;
3237 return true;
3238}
3239
3240enum {
3249
3250/// Attempts to get the FunctionProtoType from a Type. Handles
3251/// MemberFunctionPointers properly.
3253 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3254 return FPT;
3255
3256 if (auto *MPT = FromType->getAs<MemberPointerType>())
3257 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3258
3259 return nullptr;
3260}
3261
3263 QualType FromType, QualType ToType) {
3264 // If either type is not valid, include no extra info.
3265 if (FromType.isNull() || ToType.isNull()) {
3266 PDiag << ft_default;
3267 return;
3268 }
3269
3270 // Get the function type from the pointers.
3271 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3272 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3273 *ToMember = ToType->castAs<MemberPointerType>();
3274 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
3275 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
3276 << QualType(FromMember->getClass(), 0);
3277 return;
3278 }
3279 FromType = FromMember->getPointeeType();
3280 ToType = ToMember->getPointeeType();
3281 }
3282
3283 if (FromType->isPointerType())
3284 FromType = FromType->getPointeeType();
3285 if (ToType->isPointerType())
3286 ToType = ToType->getPointeeType();
3287
3288 // Remove references.
3289 FromType = FromType.getNonReferenceType();
3290 ToType = ToType.getNonReferenceType();
3291
3292 // Don't print extra info for non-specialized template functions.
3293 if (FromType->isInstantiationDependentType() &&
3294 !FromType->getAs<TemplateSpecializationType>()) {
3295 PDiag << ft_default;
3296 return;
3297 }
3298
3299 // No extra info for same types.
3300 if (Context.hasSameType(FromType, ToType)) {
3301 PDiag << ft_default;
3302 return;
3303 }
3304
3305 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3306 *ToFunction = tryGetFunctionProtoType(ToType);
3307
3308 // Both types need to be function types.
3309 if (!FromFunction || !ToFunction) {
3310 PDiag << ft_default;
3311 return;
3312 }
3313
3314 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3315 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3316 << FromFunction->getNumParams();
3317 return;
3318 }
3319
3320 // Handle different parameter types.
3321 unsigned ArgPos;
3322 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3323 PDiag << ft_parameter_mismatch << ArgPos + 1
3324 << ToFunction->getParamType(ArgPos)
3325 << FromFunction->getParamType(ArgPos);
3326 return;
3327 }
3328
3329 // Handle different return type.
3330 if (!Context.hasSameType(FromFunction->getReturnType(),
3331 ToFunction->getReturnType())) {
3332 PDiag << ft_return_type << ToFunction->getReturnType()
3333 << FromFunction->getReturnType();
3334 return;
3335 }
3336
3337 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3338 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3339 << FromFunction->getMethodQuals();
3340 return;
3341 }
3342
3343 // Handle exception specification differences on canonical type (in C++17
3344 // onwards).
3345 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
3346 ->isNothrow() !=
3347 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3348 ->isNothrow()) {
3349 PDiag << ft_noexcept;
3350 return;
3351 }
3352
3353 // Unable to find a difference, so add no extra info.
3354 PDiag << ft_default;
3355}
3356
3358 ArrayRef<QualType> New, unsigned *ArgPos,
3359 bool Reversed) {
3360 assert(llvm::size(Old) == llvm::size(New) &&
3361 "Can't compare parameters of functions with different number of "
3362 "parameters!");
3363
3364 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3365 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3366 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3367
3368 // Ignore address spaces in pointee type. This is to disallow overloading
3369 // on __ptr32/__ptr64 address spaces.
3370 QualType OldType =
3371 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3372 QualType NewType =
3373 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3374
3375 if (!Context.hasSameType(OldType, NewType)) {
3376 if (ArgPos)
3377 *ArgPos = Idx;
3378 return false;
3379 }
3380 }
3381 return true;
3382}
3383
3385 const FunctionProtoType *NewType,
3386 unsigned *ArgPos, bool Reversed) {
3387 return FunctionParamTypesAreEqual(OldType->param_types(),
3388 NewType->param_types(), ArgPos, Reversed);
3389}
3390
3392 const FunctionDecl *NewFunction,
3393 unsigned *ArgPos,
3394 bool Reversed) {
3395
3396 if (OldFunction->getNumNonObjectParams() !=
3397 NewFunction->getNumNonObjectParams())
3398 return false;
3399
3400 unsigned OldIgnore =
3402 unsigned NewIgnore =
3404
3405 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3406 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3407
3408 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3409 NewPT->param_types().slice(NewIgnore),
3410 ArgPos, Reversed);
3411}
3412
3414 CastKind &Kind,
3415 CXXCastPath& BasePath,
3416 bool IgnoreBaseAccess,
3417 bool Diagnose) {
3418 QualType FromType = From->getType();
3419 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3420
3421 Kind = CK_BitCast;
3422
3423 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3426 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3427 DiagRuntimeBehavior(From->getExprLoc(), From,
3428 PDiag(diag::warn_impcast_bool_to_null_pointer)
3429 << ToType << From->getSourceRange());
3430 else if (!isUnevaluatedContext())
3431 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3432 << ToType << From->getSourceRange();
3433 }
3434 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3435 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3436 QualType FromPointeeType = FromPtrType->getPointeeType(),
3437 ToPointeeType = ToPtrType->getPointeeType();
3438
3439 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3440 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3441 // We must have a derived-to-base conversion. Check an
3442 // ambiguous or inaccessible conversion.
3443 unsigned InaccessibleID = 0;
3444 unsigned AmbiguousID = 0;
3445 if (Diagnose) {
3446 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3447 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3448 }
3449 if (CheckDerivedToBaseConversion(
3450 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3451 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3452 &BasePath, IgnoreBaseAccess))
3453 return true;
3454
3455 // The conversion was successful.
3456 Kind = CK_DerivedToBase;
3457 }
3458
3459 if (Diagnose && !IsCStyleOrFunctionalCast &&
3460 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3461 assert(getLangOpts().MSVCCompat &&
3462 "this should only be possible with MSVCCompat!");
3463 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3464 << From->getSourceRange();
3465 }
3466 }
3467 } else if (const ObjCObjectPointerType *ToPtrType =
3468 ToType->getAs<ObjCObjectPointerType>()) {
3469 if (const ObjCObjectPointerType *FromPtrType =
3470 FromType->getAs<ObjCObjectPointerType>()) {
3471 // Objective-C++ conversions are always okay.
3472 // FIXME: We should have a different class of conversions for the
3473 // Objective-C++ implicit conversions.
3474 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3475 return false;
3476 } else if (FromType->isBlockPointerType()) {
3477 Kind = CK_BlockPointerToObjCPointerCast;
3478 } else {
3479 Kind = CK_CPointerToObjCPointerCast;
3480 }
3481 } else if (ToType->isBlockPointerType()) {
3482 if (!FromType->isBlockPointerType())
3483 Kind = CK_AnyPointerToBlockPointerCast;
3484 }
3485
3486 // We shouldn't fall into this case unless it's valid for other
3487 // reasons.
3489 Kind = CK_NullToPointer;
3490
3491 return false;
3492}
3493
3495 QualType ToType,
3496 bool InOverloadResolution,
3497 QualType &ConvertedType) {
3498 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3499 if (!ToTypePtr)
3500 return false;
3501
3502 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3503 if (From->isNullPointerConstant(Context,
3504 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3506 ConvertedType = ToType;
3507 return true;
3508 }
3509
3510 // Otherwise, both types have to be member pointers.
3511 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3512 if (!FromTypePtr)
3513 return false;
3514
3515 // A pointer to member of B can be converted to a pointer to member of D,
3516 // where D is derived from B (C++ 4.11p2).
3517 QualType FromClass(FromTypePtr->getClass(), 0);
3518 QualType ToClass(ToTypePtr->getClass(), 0);
3519
3520 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3521 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3522 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3523 ToClass.getTypePtr());
3524 return true;
3525 }
3526
3527 return false;
3528}
3529
3531 CastKind &Kind,
3532 CXXCastPath &BasePath,
3533 bool IgnoreBaseAccess) {
3534 QualType FromType = From->getType();
3535 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3536 if (!FromPtrType) {
3537 // This must be a null pointer to member pointer conversion
3538 assert(From->isNullPointerConstant(Context,
3540 "Expr must be null pointer constant!");
3541 Kind = CK_NullToMemberPointer;
3542 return false;
3543 }
3544
3545 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3546 assert(ToPtrType && "No member pointer cast has a target type "
3547 "that is not a member pointer.");
3548
3549 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3550 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3551
3552 // FIXME: What about dependent types?
3553 assert(FromClass->isRecordType() && "Pointer into non-class.");
3554 assert(ToClass->isRecordType() && "Pointer into non-class.");
3555
3556 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3557 /*DetectVirtual=*/true);
3558 bool DerivationOkay =
3559 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3560 assert(DerivationOkay &&
3561 "Should not have been called if derivation isn't OK.");
3562 (void)DerivationOkay;
3563
3564 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3565 getUnqualifiedType())) {
3566 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3567 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3568 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3569 return true;
3570 }
3571
3572 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3573 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3574 << FromClass << ToClass << QualType(VBase, 0)
3575 << From->getSourceRange();
3576 return true;
3577 }
3578
3579 if (!IgnoreBaseAccess)
3580 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3581 Paths.front(),
3582 diag::err_downcast_from_inaccessible_base);
3583
3584 // Must be a base to derived member conversion.
3585 BuildBasePathArray(Paths, BasePath);
3586 Kind = CK_BaseToDerivedMemberPointer;
3587 return false;
3588}
3589
3590/// Determine whether the lifetime conversion between the two given
3591/// qualifiers sets is nontrivial.
3593 Qualifiers ToQuals) {
3594 // Converting anything to const __unsafe_unretained is trivial.
3595 if (ToQuals.hasConst() &&
3597 return false;
3598
3599 return true;
3600}
3601
3602/// Perform a single iteration of the loop for checking if a qualification
3603/// conversion is valid.
3604///
3605/// Specifically, check whether any change between the qualifiers of \p
3606/// FromType and \p ToType is permissible, given knowledge about whether every
3607/// outer layer is const-qualified.
3609 bool CStyle, bool IsTopLevel,
3610 bool &PreviousToQualsIncludeConst,
3611 bool &ObjCLifetimeConversion,
3612 const ASTContext &Ctx) {
3613 Qualifiers FromQuals = FromType.getQualifiers();
3614 Qualifiers ToQuals = ToType.getQualifiers();
3615
3616 // Ignore __unaligned qualifier.
3617 FromQuals.removeUnaligned();
3618
3619 // Objective-C ARC:
3620 // Check Objective-C lifetime conversions.
3621 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3622 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3623 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3624 ObjCLifetimeConversion = true;
3625 FromQuals.removeObjCLifetime();
3626 ToQuals.removeObjCLifetime();
3627 } else {
3628 // Qualification conversions cannot cast between different
3629 // Objective-C lifetime qualifiers.
3630 return false;
3631 }
3632 }
3633
3634 // Allow addition/removal of GC attributes but not changing GC attributes.
3635 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3636 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3637 FromQuals.removeObjCGCAttr();
3638 ToQuals.removeObjCGCAttr();
3639 }
3640
3641 // -- for every j > 0, if const is in cv 1,j then const is in cv
3642 // 2,j, and similarly for volatile.
3643 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3644 return false;
3645
3646 // If address spaces mismatch:
3647 // - in top level it is only valid to convert to addr space that is a
3648 // superset in all cases apart from C-style casts where we allow
3649 // conversions between overlapping address spaces.
3650 // - in non-top levels it is not a valid conversion.
3651 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3652 (!IsTopLevel ||
3653 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
3654 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
3655 return false;
3656
3657 // -- if the cv 1,j and cv 2,j are different, then const is in
3658 // every cv for 0 < k < j.
3659 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3660 !PreviousToQualsIncludeConst)
3661 return false;
3662
3663 // The following wording is from C++20, where the result of the conversion
3664 // is T3, not T2.
3665 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3666 // "array of unknown bound of"
3667 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3668 return false;
3669
3670 // -- if the resulting P3,i is different from P1,i [...], then const is
3671 // added to every cv 3_k for 0 < k < i.
3672 if (!CStyle && FromType->isConstantArrayType() &&
3673 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3674 return false;
3675
3676 // Keep track of whether all prior cv-qualifiers in the "to" type
3677 // include const.
3678 PreviousToQualsIncludeConst =
3679 PreviousToQualsIncludeConst && ToQuals.hasConst();
3680 return true;
3681}
3682
3683bool
3685 bool CStyle, bool &ObjCLifetimeConversion) {
3686 FromType = Context.getCanonicalType(FromType);
3687 ToType = Context.getCanonicalType(ToType);
3688 ObjCLifetimeConversion = false;
3689
3690 // If FromType and ToType are the same type, this is not a
3691 // qualification conversion.
3692 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3693 return false;
3694
3695 // (C++ 4.4p4):
3696 // A conversion can add cv-qualifiers at levels other than the first
3697 // in multi-level pointers, subject to the following rules: [...]
3698 bool PreviousToQualsIncludeConst = true;
3699 bool UnwrappedAnyPointer = false;
3700 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3701 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3702 !UnwrappedAnyPointer,
3703 PreviousToQualsIncludeConst,
3704 ObjCLifetimeConversion, getASTContext()))
3705 return false;
3706 UnwrappedAnyPointer = true;
3707 }
3708
3709 // We are left with FromType and ToType being the pointee types
3710 // after unwrapping the original FromType and ToType the same number
3711 // of times. If we unwrapped any pointers, and if FromType and
3712 // ToType have the same unqualified type (since we checked
3713 // qualifiers above), then this is a qualification conversion.
3714 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3715}
3716
3717/// - Determine whether this is a conversion from a scalar type to an
3718/// atomic type.
3719///
3720/// If successful, updates \c SCS's second and third steps in the conversion
3721/// sequence to finish the conversion.
3722static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3723 bool InOverloadResolution,
3725 bool CStyle) {
3726 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3727 if (!ToAtomic)
3728 return false;
3729
3731 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3732 InOverloadResolution, InnerSCS,
3733 CStyle, /*AllowObjCWritebackConversion=*/false))
3734 return false;
3735
3736 SCS.Second = InnerSCS.Second;
3737 SCS.setToType(1, InnerSCS.getToType(1));
3738 SCS.Third = InnerSCS.Third;
3741 SCS.setToType(2, InnerSCS.getToType(2));
3742 return true;
3743}
3744
3746 CXXConstructorDecl *Constructor,
3747 QualType Type) {
3748 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3749 if (CtorType->getNumParams() > 0) {
3750 QualType FirstArg = CtorType->getParamType(0);
3751 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3752 return true;
3753 }
3754 return false;
3755}
3756
3757static OverloadingResult
3759 CXXRecordDecl *To,
3761 OverloadCandidateSet &CandidateSet,
3762 bool AllowExplicit) {
3764 for (auto *D : S.LookupConstructors(To)) {
3765 auto Info = getConstructorInfo(D);
3766 if (!Info)
3767 continue;
3768
3769 bool Usable = !Info.Constructor->isInvalidDecl() &&
3770 S.isInitListConstructor(Info.Constructor);
3771 if (Usable) {
3772 bool SuppressUserConversions = false;
3773 if (Info.ConstructorTmpl)
3774 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3775 /*ExplicitArgs*/ nullptr, From,
3776 CandidateSet, SuppressUserConversions,
3777 /*PartialOverloading*/ false,
3778 AllowExplicit);
3779 else
3780 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3781 CandidateSet, SuppressUserConversions,
3782 /*PartialOverloading*/ false, AllowExplicit);
3783 }
3784 }
3785
3786 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3787
3789 switch (auto Result =
3790 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3791 case OR_Deleted:
3792 case OR_Success: {
3793 // Record the standard conversion we used and the conversion function.
3794 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3795 QualType ThisType = Constructor->getFunctionObjectParameterType();
3796 // Initializer lists don't have conversions as such.
3798 User.HadMultipleCandidates = HadMultipleCandidates;
3799 User.ConversionFunction = Constructor;
3800 User.FoundConversionFunction = Best->FoundDecl;
3802 User.After.setFromType(ThisType);
3803 User.After.setAllToTypes(ToType);
3804 return Result;
3805 }
3806
3808 return OR_No_Viable_Function;
3809 case OR_Ambiguous:
3810 return OR_Ambiguous;
3811 }
3812
3813 llvm_unreachable("Invalid OverloadResult!");
3814}
3815
3816/// Determines whether there is a user-defined conversion sequence
3817/// (C++ [over.ics.user]) that converts expression From to the type
3818/// ToType. If such a conversion exists, User will contain the
3819/// user-defined conversion sequence that performs such a conversion
3820/// and this routine will return true. Otherwise, this routine returns
3821/// false and User is unspecified.
3822///
3823/// \param AllowExplicit true if the conversion should consider C++0x
3824/// "explicit" conversion functions as well as non-explicit conversion
3825/// functions (C++0x [class.conv.fct]p2).
3826///
3827/// \param AllowObjCConversionOnExplicit true if the conversion should
3828/// allow an extra Objective-C pointer conversion on uses of explicit
3829/// constructors. Requires \c AllowExplicit to also be set.
3830static OverloadingResult
3833 OverloadCandidateSet &CandidateSet,
3834 AllowedExplicit AllowExplicit,
3835 bool AllowObjCConversionOnExplicit) {
3836 assert(AllowExplicit != AllowedExplicit::None ||
3837 !AllowObjCConversionOnExplicit);
3839
3840 // Whether we will only visit constructors.
3841 bool ConstructorsOnly = false;
3842
3843 // If the type we are conversion to is a class type, enumerate its
3844 // constructors.
3845 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3846 // C++ [over.match.ctor]p1:
3847 // When objects of class type are direct-initialized (8.5), or
3848 // copy-initialized from an expression of the same or a
3849 // derived class type (8.5), overload resolution selects the
3850 // constructor. [...] For copy-initialization, the candidate
3851 // functions are all the converting constructors (12.3.1) of
3852 // that class. The argument list is the expression-list within
3853 // the parentheses of the initializer.
3854 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3855 (From->getType()->getAs<RecordType>() &&
3856 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3857 ConstructorsOnly = true;
3858
3859 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3860 // We're not going to find any constructors.
3861 } else if (CXXRecordDecl *ToRecordDecl
3862 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3863
3864 Expr **Args = &From;
3865 unsigned NumArgs = 1;
3866 bool ListInitializing = false;
3867 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3868 // But first, see if there is an init-list-constructor that will work.
3870 S, From, ToType, ToRecordDecl, User, CandidateSet,
3871 AllowExplicit == AllowedExplicit::All);
3873 return Result;
3874 // Never mind.
3875 CandidateSet.clear(
3877
3878 // If we're list-initializing, we pass the individual elements as
3879 // arguments, not the entire list.
3880 Args = InitList->getInits();
3881 NumArgs = InitList->getNumInits();
3882 ListInitializing = true;
3883 }
3884
3885 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3886 auto Info = getConstructorInfo(D);
3887 if (!Info)
3888 continue;
3889
3890 bool Usable = !Info.Constructor->isInvalidDecl();
3891 if (!ListInitializing)
3892 Usable = Usable && Info.Constructor->isConvertingConstructor(
3893 /*AllowExplicit*/ true);
3894 if (Usable) {
3895 bool SuppressUserConversions = !ConstructorsOnly;
3896 // C++20 [over.best.ics.general]/4.5:
3897 // if the target is the first parameter of a constructor [of class
3898 // X] and the constructor [...] is a candidate by [...] the second
3899 // phase of [over.match.list] when the initializer list has exactly
3900 // one element that is itself an initializer list, [...] and the
3901 // conversion is to X or reference to cv X, user-defined conversion
3902 // sequences are not cnosidered.
3903 if (SuppressUserConversions && ListInitializing) {
3904 SuppressUserConversions =
3905 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3906 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3907 ToType);
3908 }
3909 if (Info.ConstructorTmpl)
3911 Info.ConstructorTmpl, Info.FoundDecl,
3912 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
3913 CandidateSet, SuppressUserConversions,
3914 /*PartialOverloading*/ false,
3915 AllowExplicit == AllowedExplicit::All);
3916 else
3917 // Allow one user-defined conversion when user specifies a
3918 // From->ToType conversion via an static cast (c-style, etc).
3919 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3920 llvm::ArrayRef(Args, NumArgs), CandidateSet,
3921 SuppressUserConversions,
3922 /*PartialOverloading*/ false,
3923 AllowExplicit == AllowedExplicit::All);
3924 }
3925 }
3926 }
3927 }
3928
3929 // Enumerate conversion functions, if we're allowed to.
3930 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3931 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3932 // No conversion functions from incomplete types.
3933 } else if (const RecordType *FromRecordType =
3934 From->getType()->getAs<RecordType>()) {
3935 if (CXXRecordDecl *FromRecordDecl
3936 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3937 // Add all of the conversion functions as candidates.
3938 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3939 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3940 DeclAccessPair FoundDecl = I.getPair();
3941 NamedDecl *D = FoundDecl.getDecl();
3942 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3943 if (isa<UsingShadowDecl>(D))
3944 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3945
3946 CXXConversionDecl *Conv;
3947 FunctionTemplateDecl *ConvTemplate;
3948 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3949 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3950 else
3951 Conv = cast<CXXConversionDecl>(D);
3952
3953 if (ConvTemplate)
3955 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3956 CandidateSet, AllowObjCConversionOnExplicit,
3957 AllowExplicit != AllowedExplicit::None);
3958 else
3959 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3960 CandidateSet, AllowObjCConversionOnExplicit,
3961 AllowExplicit != AllowedExplicit::None);
3962 }
3963 }
3964 }
3965
3966 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3967
3969 switch (auto Result =
3970 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3971 case OR_Success:
3972 case OR_Deleted:
3973 // Record the standard conversion we used and the conversion function.
3974 if (CXXConstructorDecl *Constructor
3975 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3976 // C++ [over.ics.user]p1:
3977 // If the user-defined conversion is specified by a
3978 // constructor (12.3.1), the initial standard conversion
3979 // sequence converts the source type to the type required by
3980 // the argument of the constructor.
3981 //
3982 if (isa<InitListExpr>(From)) {
3983 // Initializer lists don't have conversions as such.
3985 } else {
3986 if (Best->Conversions[0].isEllipsis())
3987 User.EllipsisConversion = true;
3988 else {
3989 User.Before = Best->Conversions[0].Standard;
3990 User.EllipsisConversion = false;
3991 }
3992 }
3993 User.HadMultipleCandidates = HadMultipleCandidates;
3994 User.ConversionFunction = Constructor;
3995 User.FoundConversionFunction = Best->FoundDecl;
3997 User.After.setFromType(Constructor->getFunctionObjectParameterType());
3998 User.After.setAllToTypes(ToType);
3999 return Result;
4000 }
4001 if (CXXConversionDecl *Conversion
4002 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4003 // C++ [over.ics.user]p1:
4004 //
4005 // [...] If the user-defined conversion is specified by a
4006 // conversion function (12.3.2), the initial standard
4007 // conversion sequence converts the source type to the
4008 // implicit object parameter of the conversion function.
4009 User.Before = Best->Conversions[0].Standard;
4010 User.HadMultipleCandidates = HadMultipleCandidates;
4011 User.ConversionFunction = Conversion;
4012 User.FoundConversionFunction = Best->FoundDecl;
4013 User.EllipsisConversion = false;
4014
4015 // C++ [over.ics.user]p2:
4016 // The second standard conversion sequence converts the
4017 // result of the user-defined conversion to the target type
4018 // for the sequence. Since an implicit conversion sequence
4019 // is an initialization, the special rules for
4020 // initialization by user-defined conversion apply when
4021 // selecting the best user-defined conversion for a
4022 // user-defined conversion sequence (see 13.3.3 and
4023 // 13.3.3.1).
4024 User.After = Best->FinalConversion;
4025 return Result;
4026 }
4027 llvm_unreachable("Not a constructor or conversion function?");
4028
4030 return OR_No_Viable_Function;
4031
4032 case OR_Ambiguous:
4033 return OR_Ambiguous;
4034 }
4035
4036 llvm_unreachable("Invalid OverloadResult!");
4037}
4038
4039bool
4042 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4044 OverloadingResult OvResult =
4045 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4046 CandidateSet, AllowedExplicit::None, false);
4047
4048 if (!(OvResult == OR_Ambiguous ||
4049 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4050 return false;
4051
4052 auto Cands = CandidateSet.CompleteCandidates(
4053 *this,
4055 From);
4056 if (OvResult == OR_Ambiguous)
4057 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4058 << From->getType() << ToType << From->getSourceRange();
4059 else { // OR_No_Viable_Function && !CandidateSet.empty()
4060 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4061 diag::err_typecheck_nonviable_condition_incomplete,
4062 From->getType(), From->getSourceRange()))
4063 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4064 << false << From->getType() << From->getSourceRange() << ToType;
4065 }
4066
4067 CandidateSet.NoteCandidates(
4068 *this, From, Cands);
4069 return true;
4070}
4071
4072// Helper for compareConversionFunctions that gets the FunctionType that the
4073// conversion-operator return value 'points' to, or nullptr.
4074static const FunctionType *
4076 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4077 const PointerType *RetPtrTy =
4078 ConvFuncTy->getReturnType()->getAs<PointerType>();
4079
4080 if (!RetPtrTy)
4081 return nullptr;
4082
4083 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4084}
4085
4086/// Compare the user-defined conversion functions or constructors
4087/// of two user-defined conversion sequences to determine whether any ordering
4088/// is possible.
4091 FunctionDecl *Function2) {
4092 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4093 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4094 if (!Conv1 || !Conv2)
4096
4097 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4099
4100 // Objective-C++:
4101 // If both conversion functions are implicitly-declared conversions from
4102 // a lambda closure type to a function pointer and a block pointer,
4103 // respectively, always prefer the conversion to a function pointer,
4104 // because the function pointer is more lightweight and is more likely
4105 // to keep code working.
4106 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4107 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4108 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4109 if (Block1 != Block2)
4110 return Block1 ? ImplicitConversionSequence::Worse
4112 }
4113
4114 // In order to support multiple calling conventions for the lambda conversion
4115 // operator (such as when the free and member function calling convention is
4116 // different), prefer the 'free' mechanism, followed by the calling-convention
4117 // of operator(). The latter is in place to support the MSVC-like solution of
4118 // defining ALL of the possible conversions in regards to calling-convention.
4119 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4120 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4121
4122 if (Conv1FuncRet && Conv2FuncRet &&
4123 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4124 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4125 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4126
4127 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4128 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4129
4130 CallingConv CallOpCC =
4131 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4133 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4135 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4136
4137 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4138 for (CallingConv CC : PrefOrder) {
4139 if (Conv1CC == CC)
4141 if (Conv2CC == CC)
4143 }
4144 }
4145
4147}
4148
4150 const ImplicitConversionSequence &ICS) {
4152 (ICS.isUserDefined() &&
4154}
4155
4156/// CompareImplicitConversionSequences - Compare two implicit
4157/// conversion sequences to determine whether one is better than the
4158/// other or if they are indistinguishable (C++ 13.3.3.2).
4161 const ImplicitConversionSequence& ICS1,
4162 const ImplicitConversionSequence& ICS2)
4163{
4164 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4165 // conversion sequences (as defined in 13.3.3.1)
4166 // -- a standard conversion sequence (13.3.3.1.1) is a better
4167 // conversion sequence than a user-defined conversion sequence or
4168 // an ellipsis conversion sequence, and
4169 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4170 // conversion sequence than an ellipsis conversion sequence
4171 // (13.3.3.1.3).
4172 //
4173 // C++0x [over.best.ics]p10:
4174 // For the purpose of ranking implicit conversion sequences as
4175 // described in 13.3.3.2, the ambiguous conversion sequence is
4176 // treated as a user-defined sequence that is indistinguishable
4177 // from any other user-defined conversion sequence.
4178
4179 // String literal to 'char *' conversion has been deprecated in C++03. It has
4180 // been removed from C++11. We still accept this conversion, if it happens at
4181 // the best viable function. Otherwise, this conversion is considered worse
4182 // than ellipsis conversion. Consider this as an extension; this is not in the
4183 // standard. For example:
4184 //
4185 // int &f(...); // #1
4186 // void f(char*); // #2
4187 // void g() { int &r = f("foo"); }
4188 //
4189 // In C++03, we pick #2 as the best viable function.
4190 // In C++11, we pick #1 as the best viable function, because ellipsis
4191 // conversion is better than string-literal to char* conversion (since there
4192 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4193 // convert arguments, #2 would be the best viable function in C++11.
4194 // If the best viable function has this conversion, a warning will be issued
4195 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4196
4197 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4200 // Ill-formedness must not differ
4201 ICS1.isBad() == ICS2.isBad())
4205
4206 if (ICS1.getKindRank() < ICS2.getKindRank())
4208 if (ICS2.getKindRank() < ICS1.getKindRank())
4210
4211 // The following checks require both conversion sequences to be of
4212 // the same kind.
4213 if (ICS1.getKind() != ICS2.getKind())
4215
4218
4219 // Two implicit conversion sequences of the same form are
4220 // indistinguishable conversion sequences unless one of the
4221 // following rules apply: (C++ 13.3.3.2p3):
4222
4223 // List-initialization sequence L1 is a better conversion sequence than
4224 // list-initialization sequence L2 if:
4225 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4226 // if not that,
4227 // — L1 and L2 convert to arrays of the same element type, and either the
4228 // number of elements n_1 initialized by L1 is less than the number of
4229 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4230 // an array of unknown bound and L1 does not,
4231 // even if one of the other rules in this paragraph would otherwise apply.
4232 if (!ICS1.isBad()) {
4233 bool StdInit1 = false, StdInit2 = false;
4236 nullptr);
4239 nullptr);
4240 if (StdInit1 != StdInit2)
4241 return StdInit1 ? ImplicitConversionSequence::Better
4243
4246 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4248 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4250 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4251 CAT2->getElementType())) {
4252 // Both to arrays of the same element type
4253 if (CAT1->getSize() != CAT2->getSize())
4254 // Different sized, the smaller wins
4255 return CAT1->getSize().ult(CAT2->getSize())
4260 // One is incomplete, it loses
4264 }
4265 }
4266 }
4267
4268 if (ICS1.isStandard())
4269 // Standard conversion sequence S1 is a better conversion sequence than
4270 // standard conversion sequence S2 if [...]
4272 ICS1.Standard, ICS2.Standard);
4273 else if (ICS1.isUserDefined()) {
4274 // User-defined conversion sequence U1 is a better conversion
4275 // sequence than another user-defined conversion sequence U2 if
4276 // they contain the same user-defined conversion function or
4277 // constructor and if the second standard conversion sequence of
4278 // U1 is better than the second standard conversion sequence of
4279 // U2 (C++ 13.3.3.2p3).
4283 ICS1.UserDefined.After,
4284 ICS2.UserDefined.After);
4285 else
4289 }
4290
4291 return Result;
4292}
4293
4294// Per 13.3.3.2p3, compare the given standard conversion sequences to
4295// determine if one is a proper subset of the other.
4298 const StandardConversionSequence& SCS1,
4299 const StandardConversionSequence& SCS2) {
4302
4303 // the identity conversion sequence is considered to be a subsequence of
4304 // any non-identity conversion sequence
4305 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4307 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4309
4310 if (SCS1.Second != SCS2.Second) {
4311 if (SCS1.Second == ICK_Identity)
4313 else if (SCS2.Second == ICK_Identity)
4315 else
4317 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4319
4320 if (SCS1.Third == SCS2.Third) {
4321 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4323 }
4324
4325 if (SCS1.Third == ICK_Identity)
4329
4330 if (SCS2.Third == ICK_Identity)
4334
4336}
4337
4338/// Determine whether one of the given reference bindings is better
4339/// than the other based on what kind of bindings they are.
4340static bool
4342 const StandardConversionSequence &SCS2) {
4343 // C++0x [over.ics.rank]p3b4:
4344 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4345 // implicit object parameter of a non-static member function declared
4346 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4347 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4348 // lvalue reference to a function lvalue and S2 binds an rvalue
4349 // reference*.
4350 //
4351 // FIXME: Rvalue references. We're going rogue with the above edits,
4352 // because the semantics in the current C++0x working paper (N3225 at the
4353 // time of this writing) break the standard definition of std::forward
4354 // and std::reference_wrapper when dealing with references to functions.
4355 // Proposed wording changes submitted to CWG for consideration.
4358 return false;
4359
4360 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4361 SCS2.IsLvalueReference) ||
4364}
4365
4367 None,
4370};
4371
4372/// Returns kind of fixed enum promotion the \a SCS uses.
4373static FixedEnumPromotion
4375
4376 if (SCS.Second != ICK_Integral_Promotion)
4377 return FixedEnumPromotion::None;
4378
4379 QualType FromType = SCS.getFromType();
4380 if (!FromType->isEnumeralType())
4381 return FixedEnumPromotion::None;
4382
4383 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
4384 if (!Enum->isFixed())
4385 return FixedEnumPromotion::None;
4386
4387 QualType UnderlyingType = Enum->getIntegerType();
4388 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4389 return FixedEnumPromotion::ToUnderlyingType;
4390
4391 return FixedEnumPromotion::ToPromotedUnderlyingType;
4392}
4393
4394/// CompareStandardConversionSequences - Compare two standard
4395/// conversion sequences to determine whether one is better than the
4396/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4399 const StandardConversionSequence& SCS1,
4400 const StandardConversionSequence& SCS2)
4401{
4402 // Standard conversion sequence S1 is a better conversion sequence
4403 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4404
4405 // -- S1 is a proper subsequence of S2 (comparing the conversion
4406 // sequences in the canonical form defined by 13.3.3.1.1,
4407 // excluding any Lvalue Transformation; the identity conversion
4408 // sequence is considered to be a subsequence of any
4409 // non-identity conversion sequence) or, if not that,
4412 return CK;
4413
4414 // -- the rank of S1 is better than the rank of S2 (by the rules
4415 // defined below), or, if not that,
4416 ImplicitConversionRank Rank1 = SCS1.getRank();
4417 ImplicitConversionRank Rank2 = SCS2.getRank();
4418 if (Rank1 < Rank2)
4420 else if (Rank2 < Rank1)
4422
4423 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4424 // are indistinguishable unless one of the following rules
4425 // applies:
4426
4427 // A conversion that is not a conversion of a pointer, or
4428 // pointer to member, to bool is better than another conversion
4429 // that is such a conversion.
4431 return SCS2.isPointerConversionToBool()
4434
4435 // C++14 [over.ics.rank]p4b2:
4436 // This is retroactively applied to C++11 by CWG 1601.
4437 //
4438 // A conversion that promotes an enumeration whose underlying type is fixed
4439 // to its underlying type is better than one that promotes to the promoted
4440 // underlying type, if the two are different.
4443 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4444 FEP1 != FEP2)
4445 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4448
4449 // C++ [over.ics.rank]p4b2:
4450 //
4451 // If class B is derived directly or indirectly from class A,
4452 // conversion of B* to A* is better than conversion of B* to
4453 // void*, and conversion of A* to void* is better than conversion
4454 // of B* to void*.
4455 bool SCS1ConvertsToVoid
4457 bool SCS2ConvertsToVoid
4459 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4460 // Exactly one of the conversion sequences is a conversion to
4461 // a void pointer; it's the worse conversion.
4462 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4464 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4465 // Neither conversion sequence converts to a void pointer; compare
4466 // their derived-to-base conversions.
4468 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4469 return DerivedCK;
4470 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4471 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4472 // Both conversion sequences are conversions to void
4473 // pointers. Compare the source types to determine if there's an
4474 // inheritance relationship in their sources.
4475 QualType FromType1 = SCS1.getFromType();
4476 QualType FromType2 = SCS2.getFromType();
4477
4478 // Adjust the types we're converting from via the array-to-pointer
4479 // conversion, if we need to.
4480 if (SCS1.First == ICK_Array_To_Pointer)
4481 FromType1 = S.Context.getArrayDecayedType(FromType1);
4482 if (SCS2.First == ICK_Array_To_Pointer)
4483 FromType2 = S.Context.getArrayDecayedType(FromType2);
4484
4485 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4486 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4487
4488 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4490 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4492
4493 // Objective-C++: If one interface is more specific than the
4494 // other, it is the better one.
4495 const ObjCObjectPointerType* FromObjCPtr1
4496 = FromType1->getAs<ObjCObjectPointerType>();
4497 const ObjCObjectPointerType* FromObjCPtr2
4498 = FromType2->getAs<ObjCObjectPointerType>();
4499 if (FromObjCPtr1 && FromObjCPtr2) {
4500 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4501 FromObjCPtr2);
4502 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4503 FromObjCPtr1);
4504 if (AssignLeft != AssignRight) {
4505 return AssignLeft? ImplicitConversionSequence::Better
4507 }
4508 }
4509 }
4510
4511 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4512 // Check for a better reference binding based on the kind of bindings.
4513 if (isBetterReferenceBindingKind(SCS1, SCS2))
4515 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4517 }
4518
4519 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4520 // bullet 3).
4522 = CompareQualificationConversions(S, SCS1, SCS2))
4523 return QualCK;
4524
4525 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4526 // C++ [over.ics.rank]p3b4:
4527 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4528 // which the references refer are the same type except for
4529 // top-level cv-qualifiers, and the type to which the reference
4530 // initialized by S2 refers is more cv-qualified than the type
4531 // to which the reference initialized by S1 refers.
4532 QualType T1 = SCS1.getToType(2);
4533 QualType T2 = SCS2.getToType(2);
4534 T1 = S.Context.getCanonicalType(T1);
4535 T2 = S.Context.getCanonicalType(T2);
4536 Qualifiers T1Quals, T2Quals;
4537 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4538 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4539 if (UnqualT1 == UnqualT2) {
4540 // Objective-C++ ARC: If the references refer to objects with different
4541 // lifetimes, prefer bindings that don't change lifetime.
4547 }
4548
4549 // If the type is an array type, promote the element qualifiers to the
4550 // type for comparison.
4551 if (isa<ArrayType>(T1) && T1Quals)
4552 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4553 if (isa<ArrayType>(T2) && T2Quals)
4554 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4555 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4557 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4559 }
4560 }
4561
4562 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4563 // floating-to-integral conversion if the integral conversion
4564 // is between types of the same size.
4565 // For example:
4566 // void f(float);
4567 // void f(int);
4568 // int main {
4569 // long a;
4570 // f(a);
4571 // }
4572 // Here, MSVC will call f(int) instead of generating a compile error
4573 // as clang will do in standard mode.
4574 if (S.getLangOpts().MSVCCompat &&
4577 SCS2.Second == ICK_Floating_Integral &&
4578 S.Context.getTypeSize(SCS1.getFromType()) ==
4579 S.Context.getTypeSize(SCS1.getToType(2)))
4581
4582 // Prefer a compatible vector conversion over a lax vector conversion
4583 // For example:
4584 //
4585 // typedef float __v4sf __attribute__((__vector_size__(16)));
4586 // void f(vector float);
4587 // void f(vector signed int);
4588 // int main() {
4589 // __v4sf a;
4590 // f(a);
4591 // }
4592 // Here, we'd like to choose f(vector float) and not
4593 // report an ambiguous call error
4594 if (SCS1.Second == ICK_Vector_Conversion &&
4595 SCS2.Second == ICK_Vector_Conversion) {
4596 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4597 SCS1.getFromType(), SCS1.getToType(2));
4598 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4599 SCS2.getFromType(), SCS2.getToType(2));
4600
4601 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4602 return SCS1IsCompatibleVectorConversion
4605 }
4606
4607 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4609 bool SCS1IsCompatibleSVEVectorConversion =
4611 bool SCS2IsCompatibleSVEVectorConversion =
4613
4614 if (SCS1IsCompatibleSVEVectorConversion !=
4615 SCS2IsCompatibleSVEVectorConversion)
4616 return SCS1IsCompatibleSVEVectorConversion
4619 }
4620
4621 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4623 bool SCS1IsCompatibleRVVVectorConversion =
4625 bool SCS2IsCompatibleRVVVectorConversion =
4627
4628 if (SCS1IsCompatibleRVVVectorConversion !=
4629 SCS2IsCompatibleRVVVectorConversion)
4630 return SCS1IsCompatibleRVVVectorConversion
4633 }
4635}
4636
4637/// CompareQualificationConversions - Compares two standard conversion
4638/// sequences to determine whether they can be ranked based on their
4639/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4642 const StandardConversionSequence& SCS1,
4643 const StandardConversionSequence& SCS2) {
4644 // C++ [over.ics.rank]p3:
4645 // -- S1 and S2 differ only in their qualification conversion and
4646 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4647 // [C++98]
4648 // [...] and the cv-qualification signature of type T1 is a proper subset
4649 // of the cv-qualification signature of type T2, and S1 is not the
4650 // deprecated string literal array-to-pointer conversion (4.2).
4651 // [C++2a]
4652 // [...] where T1 can be converted to T2 by a qualification conversion.
4653 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4654 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4656
4657 // FIXME: the example in the standard doesn't use a qualification
4658 // conversion (!)
4659 QualType T1 = SCS1.getToType(2);
4660 QualType T2 = SCS2.getToType(2);
4661 T1 = S.Context.getCanonicalType(T1);
4662 T2 = S.Context.getCanonicalType(T2);
4663 assert(!T1->isReferenceType() && !T2->isReferenceType());
4664 Qualifiers T1Quals, T2Quals;
4665 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4666 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4667
4668 // If the types are the same, we won't learn anything by unwrapping
4669 // them.
4670 if (UnqualT1 == UnqualT2)
4672
4673 // Don't ever prefer a standard conversion sequence that uses the deprecated
4674 // string literal array to pointer conversion.
4675 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4676 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4677
4678 // Objective-C++ ARC:
4679 // Prefer qualification conversions not involving a change in lifetime
4680 // to qualification conversions that do change lifetime.
4683 CanPick1 = false;
4686 CanPick2 = false;
4687
4688 bool ObjCLifetimeConversion;
4689 if (CanPick1 &&
4690 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4691 CanPick1 = false;
4692 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4693 // directions, so we can't short-cut this second check in general.
4694 if (CanPick2 &&
4695 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4696 CanPick2 = false;
4697
4698 if (CanPick1 != CanPick2)
4699 return CanPick1 ? ImplicitConversionSequence::Better
4702}
4703
4704/// CompareDerivedToBaseConversions - Compares two standard conversion
4705/// sequences to determine whether they can be ranked based on their
4706/// various kinds of derived-to-base conversions (C++
4707/// [over.ics.rank]p4b3). As part of these checks, we also look at
4708/// conversions between Objective-C interface types.
4711 const StandardConversionSequence& SCS1,
4712 const StandardConversionSequence& SCS2) {
4713 QualType FromType1 = SCS1.getFromType();
4714 QualType ToType1 = SCS1.getToType(1);
4715 QualType FromType2 = SCS2.getFromType();
4716 QualType ToType2 = SCS2.getToType(1);
4717
4718 // Adjust the types we're converting from via the array-to-pointer
4719 // conversion, if we need to.
4720 if (SCS1.First == ICK_Array_To_Pointer)
4721 FromType1 = S.Context.getArrayDecayedType(FromType1);
4722 if (SCS2.First == ICK_Array_To_Pointer)
4723 FromType2 = S.Context.getArrayDecayedType(FromType2);
4724
4725 // Canonicalize all of the types.
4726 FromType1 = S.Context.getCanonicalType(FromType1);
4727 ToType1 = S.Context.getCanonicalType(ToType1);
4728 FromType2 = S.Context.getCanonicalType(FromType2);
4729 ToType2 = S.Context.getCanonicalType(ToType2);
4730
4731 // C++ [over.ics.rank]p4b3:
4732 //
4733 // If class B is derived directly or indirectly from class A and
4734 // class C is derived directly or indirectly from B,
4735 //
4736 // Compare based on pointer conversions.
4737 if (SCS1.Second == ICK_Pointer_Conversion &&
4739 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4740 FromType1->isPointerType() && FromType2->isPointerType() &&
4741 ToType1->isPointerType() && ToType2->isPointerType()) {
4742 QualType FromPointee1 =
4744 QualType ToPointee1 =
4746 QualType FromPointee2 =
4748 QualType ToPointee2 =
4750
4751 // -- conversion of C* to B* is better than conversion of C* to A*,
4752 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4753 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4755 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4757 }
4758
4759 // -- conversion of B* to A* is better than conversion of C* to A*,
4760 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4761 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4763 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4765 }
4766 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4768 const ObjCObjectPointerType *FromPtr1
4769 = FromType1->getAs<ObjCObjectPointerType>();
4770 const ObjCObjectPointerType *FromPtr2
4771 = FromType2->getAs<ObjCObjectPointerType>();
4772 const ObjCObjectPointerType *ToPtr1
4773 = ToType1->getAs<ObjCObjectPointerType>();
4774 const ObjCObjectPointerType *ToPtr2
4775 = ToType2->getAs<ObjCObjectPointerType>();
4776
4777 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4778 // Apply the same conversion ranking rules for Objective-C pointer types
4779 // that we do for C++ pointers to class types. However, we employ the
4780 // Objective-C pseudo-subtyping relationship used for assignment of
4781 // Objective-C pointer types.
4782 bool FromAssignLeft
4783 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4784 bool FromAssignRight
4785 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4786 bool ToAssignLeft
4787 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4788 bool ToAssignRight
4789 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4790
4791 // A conversion to an a non-id object pointer type or qualified 'id'
4792 // type is better than a conversion to 'id'.
4793 if (ToPtr1->isObjCIdType() &&
4794 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4796 if (ToPtr2->isObjCIdType() &&
4797 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4799
4800 // A conversion to a non-id object pointer type is better than a
4801 // conversion to a qualified 'id' type
4802 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4804 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4806
4807 // A conversion to an a non-Class object pointer type or qualified 'Class'
4808 // type is better than a conversion to 'Class'.
4809 if (ToPtr1->isObjCClassType() &&
4810 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4812 if (ToPtr2->isObjCClassType() &&
4813 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4815
4816 // A conversion to a non-Class object pointer type is better than a
4817 // conversion to a qualified 'Class' type.
4818 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4820 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4822
4823 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4824 if (S.Context.hasSameType(FromType1, FromType2) &&
4825 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4826 (ToAssignLeft != ToAssignRight)) {
4827 if (FromPtr1->isSpecialized()) {
4828 // "conversion of B<A> * to B * is better than conversion of B * to
4829 // C *.
4830 bool IsFirstSame =
4831 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4832 bool IsSecondSame =
4833 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4834 if (IsFirstSame) {
4835 if (!IsSecondSame)
4837 } else if (IsSecondSame)
4839 }
4840 return ToAssignLeft? ImplicitConversionSequence::Worse
4842 }
4843
4844 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4845 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4846 (FromAssignLeft != FromAssignRight))
4847 return FromAssignLeft? ImplicitConversionSequence::Better
4849 }
4850 }
4851
4852 // Ranking of member-pointer types.
4853 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4854 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4855 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4856 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4857 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4858 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4859 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4860 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4861 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4862 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4863 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4864 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4865 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4866 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4867 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4868 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4869 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4870 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4872 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4874 }
4875 // conversion of B::* to C::* is better than conversion of A::* to C::*
4876 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4877 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4879 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4881 }
4882 }
4883
4884 if (SCS1.Second == ICK_Derived_To_Base) {
4885 // -- conversion of C to B is better than conversion of C to A,
4886 // -- binding of an expression of type C to a reference of type
4887 // B& is better than binding an expression of type C to a
4888 // reference of type A&,
4889 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4890 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4891 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4893 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4895 }
4896
4897 // -- conversion of B to A is better than conversion of C to A.
4898 // -- binding of an expression of type B to a reference of type
4899 // A& is better than binding an expression of type C to a
4900 // reference of type A&,
4901 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4902 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4903 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4905 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4907 }
4908 }
4909
4911}
4912
4914 if (!T.getQualifiers().hasUnaligned())
4915 return T;
4916
4917 Qualifiers Q;
4918 T = Ctx.getUnqualifiedArrayType(T, Q);
4919 Q.removeUnaligned();
4920 return Ctx.getQualifiedType(T, Q);
4921}
4922
4925 QualType OrigT1, QualType OrigT2,
4926 ReferenceConversions *ConvOut) {
4927 assert(!OrigT1->isReferenceType() &&
4928 "T1 must be the pointee type of the reference type");
4929 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4930
4931 QualType T1 = Context.getCanonicalType(OrigT1);
4932 QualType T2 = Context.getCanonicalType(OrigT2);
4933 Qualifiers T1Quals, T2Quals;
4934 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4935 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4936
4937 ReferenceConversions ConvTmp;
4938 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4939 Conv = ReferenceConversions();
4940
4941 // C++2a [dcl.init.ref]p4:
4942 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4943 // reference-related to "cv2 T2" if T1 is similar to T2, or
4944 // T1 is a base class of T2.
4945 // "cv1 T1" is reference-compatible with "cv2 T2" if
4946 // a prvalue of type "pointer to cv2 T2" can be converted to the type
4947 // "pointer to cv1 T1" via a standard conversion sequence.
4948
4949 // Check for standard conversions we can apply to pointers: derived-to-base
4950 // conversions, ObjC pointer conversions, and function pointer conversions.
4951 // (Qualification conversions are checked last.)
4952 QualType ConvertedT2;
4953 if (UnqualT1 == UnqualT2) {
4954 // Nothing to do.
4955 } else if (isCompleteType(Loc, OrigT2) &&
4956 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4957 Conv |= ReferenceConversions::DerivedToBase;
4958 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4959 UnqualT2->isObjCObjectOrInterfaceType() &&
4960 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4961 Conv |= ReferenceConversions::ObjC;
4962 else if (UnqualT2->isFunctionType() &&
4963 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4964 Conv |= ReferenceConversions::Function;
4965 // No need to check qualifiers; function types don't have them.
4966 return Ref_Compatible;
4967 }
4968 bool ConvertedReferent = Conv != 0;
4969
4970 // We can have a qualification conversion. Compute whether the types are
4971 // similar at the same time.
4972 bool PreviousToQualsIncludeConst = true;
4973 bool TopLevel = true;
4974 do {
4975 if (T1 == T2)
4976 break;
4977
4978 // We will need a qualification conversion.
4979 Conv |= ReferenceConversions::Qualification;
4980
4981 // Track whether we performed a qualification conversion anywhere other
4982 // than the top level. This matters for ranking reference bindings in
4983 // overload resolution.
4984 if (!TopLevel)
4985 Conv |= ReferenceConversions::NestedQualification;
4986
4987 // MS compiler ignores __unaligned qualifier for references; do the same.
4988 T1 = withoutUnaligned(Context, T1);
4989 T2 = withoutUnaligned(Context, T2);
4990
4991 // If we find a qualifier mismatch, the types are not reference-compatible,
4992 // but are still be reference-related if they're similar.
4993 bool ObjCLifetimeConversion = false;
4994 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4995 PreviousToQualsIncludeConst,
4996 ObjCLifetimeConversion, getASTContext()))
4997 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4998 ? Ref_Related
4999 : Ref_Incompatible;
5000
5001 // FIXME: Should we track this for any level other than the first?
5002 if (ObjCLifetimeConversion)
5003 Conv |= ReferenceConversions::ObjCLifetime;
5004
5005 TopLevel = false;
5006 } while (Context.UnwrapSimilarTypes(T1, T2));
5007
5008 // At this point, if the types are reference-related, we must either have the
5009 // same inner type (ignoring qualifiers), or must have already worked out how
5010 // to convert the referent.
5011 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5012 ? Ref_Compatible
5013 : Ref_Incompatible;
5014}
5015
5016/// Look for a user-defined conversion to a value reference-compatible
5017/// with DeclType. Return true if something definite is found.
5018static bool
5020 QualType DeclType, SourceLocation DeclLoc,
5021 Expr *Init, QualType T2, bool AllowRvalues,
5022 bool AllowExplicit) {
5023 assert(T2->isRecordType() && "Can only find conversions of record types.");
5024 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
5025
5026 OverloadCandidateSet CandidateSet(
5028 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5029 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5030 NamedDecl *D = *I;
5031 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5032 if (isa<UsingShadowDecl>(D))
5033 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5034
5035 FunctionTemplateDecl *ConvTemplate
5036 = dyn_cast<FunctionTemplateDecl>(D);
5037 CXXConversionDecl *Conv;
5038 if (ConvTemplate)
5039 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5040 else
5041 Conv = cast<CXXConversionDecl>(D);
5042
5043 if (AllowRvalues) {
5044 // If we are initializing an rvalue reference, don't permit conversion
5045 // functions that return lvalues.
5046 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5047 const ReferenceType *RefType
5049 if (RefType && !RefType->getPointeeType()->isFunctionType())
5050 continue;
5051 }
5052
5053 if (!ConvTemplate &&
5055 DeclLoc,
5056 Conv->getConversionType()
5061 continue;
5062 } else {
5063 // If the conversion function doesn't return a reference type,
5064 // it can't be considered for this conversion. An rvalue reference
5065 // is only acceptable if its referencee is a function type.
5066
5067 const ReferenceType *RefType =
5069 if (!RefType ||
5070 (!RefType->isLValueReferenceType() &&
5071 !RefType->getPointeeType()->isFunctionType()))
5072 continue;
5073 }
5074
5075 if (ConvTemplate)
5077 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5078 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5079 else
5081 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5082 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5083 }
5084
5085 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5086
5088 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5089 case OR_Success:
5090 // C++ [over.ics.ref]p1:
5091 //
5092 // [...] If the parameter binds directly to the result of
5093 // applying a conversion function to the argument
5094 // expression, the implicit conversion sequence is a
5095 // user-defined conversion sequence (13.3.3.1.2), with the
5096 // second standard conversion sequence either an identity
5097 // conversion or, if the conversion function returns an
5098 // entity of a type that is a derived class of the parameter
5099 // type, a derived-to-base Conversion.
5100 if (!Best->FinalConversion.DirectBinding)
5101 return false;
5102
5103 ICS.setUserDefined();
5104 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5105 ICS.UserDefined.After = Best->FinalConversion;
5106 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5107 ICS.UserDefined.ConversionFunction = Best->Function;
5108 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5109 ICS.UserDefined.EllipsisConversion = false;
5110 assert(ICS.UserDefined.After.ReferenceBinding &&
5112 "Expected a direct reference binding!");
5113 return true;
5114
5115 case OR_Ambiguous:
5116 ICS.setAmbiguous();
5117 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5118 Cand != CandidateSet.end(); ++Cand)
5119 if (Cand->Best)
5120 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5121 return true;
5122
5124 case OR_Deleted:
5125 // There was no suitable conversion, or we found a deleted
5126 // conversion; continue with other checks.
5127 return false;
5128 }
5129
5130 llvm_unreachable("Invalid OverloadResult!");
5131}
5132
5133/// Compute an implicit conversion sequence for reference
5134/// initialization.
5137 SourceLocation DeclLoc,
5138 bool SuppressUserConversions,
5139 bool AllowExplicit) {
5140 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5141
5142 // Most paths end in a failed conversion.
5145
5146 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5147 QualType T2 = Init->getType();
5148
5149 // If the initializer is the address of an overloaded function, try
5150 // to resolve the overloaded function. If all goes well, T2 is the
5151 // type of the resulting function.
5152 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5155 false, Found))
5156 T2 = Fn->getType();
5157 }
5158
5159 // Compute some basic properties of the types and the initializer.
5160 bool isRValRef = DeclType->isRValueReferenceType();
5161 Expr::Classification InitCategory = Init->Classify(S.Context);
5162
5164 Sema::ReferenceCompareResult RefRelationship =
5165 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5166
5167 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5168 ICS.setStandard();
5170 // FIXME: A reference binding can be a function conversion too. We should
5171 // consider that when ordering reference-to-function bindings.
5172 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5174 : (RefConv & Sema::ReferenceConversions::ObjC)
5176 : ICK_Identity;
5178 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5179 // a reference binding that performs a non-top-level qualification
5180 // conversion as a qualification conversion, not as an identity conversion.
5181 ICS.Standard.Third = (RefConv &
5182 Sema::ReferenceConversions::NestedQualification)
5184 : ICK_Identity;
5185 ICS.Standard.setFromType(T2);
5186 ICS.Standard.setToType(0, T2);
5187 ICS.Standard.setToType(1, T1);
5188 ICS.Standard.setToType(2, T1);
5189 ICS.Standard.ReferenceBinding = true;
5190 ICS.Standard.DirectBinding = BindsDirectly;
5191 ICS.Standard.IsLvalueReference = !isRValRef;
5193 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5196 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5197 ICS.Standard.CopyConstructor = nullptr;
5199 };
5200
5201 // C++0x [dcl.init.ref]p5:
5202 // A reference to type "cv1 T1" is initialized by an expression
5203 // of type "cv2 T2" as follows:
5204
5205 // -- If reference is an lvalue reference and the initializer expression
5206 if (!isRValRef) {
5207 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5208 // reference-compatible with "cv2 T2," or
5209 //
5210 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5211 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5212 // C++ [over.ics.ref]p1:
5213 // When a parameter of reference type binds directly (8.5.3)
5214 // to an argument expression, the implicit conversion sequence
5215 // is the identity conversion, unless the argument expression
5216 // has a type that is a derived class of the parameter type,
5217 // in which case the implicit conversion sequence is a
5218 // derived-to-base Conversion (13.3.3.1).
5219 SetAsReferenceBinding(/*BindsDirectly=*/true);
5220
5221 // Nothing more to do: the inaccessibility/ambiguity check for
5222 // derived-to-base conversions is suppressed when we're
5223 // computing the implicit conversion sequence (C++
5224 // [over.best.ics]p2).
5225 return ICS;
5226 }
5227
5228 // -- has a class type (i.e., T2 is a class type), where T1 is
5229 // not reference-related to T2, and can be implicitly
5230 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5231 // is reference-compatible with "cv3 T3" 92) (this
5232 // conversion is selected by enumerating the applicable
5233 // conversion functions (13.3.1.6) and choosing the best
5234 // one through overload resolution (13.3)),
5235 if (!SuppressUserConversions && T2->isRecordType() &&
5236 S.isCompleteType(DeclLoc, T2) &&
5237 RefRelationship == Sema::Ref_Incompatible) {
5238 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5239 Init, T2, /*AllowRvalues=*/false,
5240 AllowExplicit))
5241 return ICS;
5242 }
5243 }
5244
5245 // -- Otherwise, the reference shall be an lvalue reference to a
5246 // non-volatile const type (i.e., cv1 shall be const), or the reference
5247 // shall be an rvalue reference.
5248 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5249 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5251 return ICS;
5252 }
5253
5254 // -- If the initializer expression
5255 //
5256 // -- is an xvalue, class prvalue, array prvalue or function
5257 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5258 if (RefRelationship == Sema::Ref_Compatible &&
5259 (InitCategory.isXValue() ||
5260 (InitCategory.isPRValue() &&
5261 (T2->isRecordType() || T2->isArrayType())) ||
5262 (InitCategory.isLValue() && T2->isFunctionType()))) {
5263 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5264 // binding unless we're binding to a class prvalue.
5265 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5266 // allow the use of rvalue references in C++98/03 for the benefit of
5267 // standard library implementors; therefore, we need the xvalue check here.
5268 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5269 !(InitCategory.isPRValue() || T2->isRecordType()));
5270 return ICS;
5271 }
5272
5273 // -- has a class type (i.e., T2 is a class type), where T1 is not
5274 // reference-related to T2, and can be implicitly converted to
5275 // an xvalue, class prvalue, or function lvalue of type
5276 // "cv3 T3", where "cv1 T1" is reference-compatible with
5277 // "cv3 T3",
5278 //
5279 // then the reference is bound to the value of the initializer
5280 // expression in the first case and to the result of the conversion
5281 // in the second case (or, in either case, to an appropriate base
5282 // class subobject).
5283 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5284 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5285 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5286 Init, T2, /*AllowRvalues=*/true,
5287 AllowExplicit)) {
5288 // In the second case, if the reference is an rvalue reference
5289 // and the second standard conversion sequence of the
5290 // user-defined conversion sequence includes an lvalue-to-rvalue
5291 // conversion, the program is ill-formed.
5292 if (ICS.isUserDefined() && isRValRef &&
5295
5296 return ICS;
5297 }
5298
5299 // A temporary of function type cannot be created; don't even try.
5300 if (T1->isFunctionType())
5301 return ICS;
5302
5303 // -- Otherwise, a temporary of type "cv1 T1" is created and
5304 // initialized from the initializer expression using the
5305 // rules for a non-reference copy initialization (8.5). The
5306 // reference is then bound to the temporary. If T1 is
5307 // reference-related to T2, cv1 must be the same
5308 // cv-qualification as, or greater cv-qualification than,
5309 // cv2; otherwise, the program is ill-formed.
5310 if (RefRelationship == Sema::Ref_Related) {
5311 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5312 // we would be reference-compatible or reference-compatible with
5313 // added qualification. But that wasn't the case, so the reference
5314 // initialization fails.
5315 //
5316 // Note that we only want to check address spaces and cvr-qualifiers here.
5317 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5318 Qualifiers T1Quals = T1.getQualifiers();
5319 Qualifiers T2Quals = T2.getQualifiers();
5320 T1Quals.removeObjCGCAttr();
5321 T1Quals.removeObjCLifetime();
5322 T2Quals.removeObjCGCAttr();
5323 T2Quals.removeObjCLifetime();
5324 // MS compiler ignores __unaligned qualifier for references; do the same.
5325 T1Quals.removeUnaligned();
5326 T2Quals.removeUnaligned();
5327 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5328 return ICS;
5329 }
5330
5331 // If at least one of the types is a class type, the types are not
5332 // related, and we aren't allowed any user conversions, the
5333 // reference binding fails. This case is important for breaking
5334 // recursion, since TryImplicitConversion below will attempt to
5335 // create a temporary through the use of a copy constructor.
5336 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5337 (T1->isRecordType() || T2->isRecordType()))
5338 return ICS;
5339
5340 // If T1 is reference-related to T2 and the reference is an rvalue
5341 // reference, the initializer expression shall not be an lvalue.
5342 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5343 Init->Classify(S.Context).isLValue()) {
5345 return ICS;
5346 }
5347
5348 // C++ [over.ics.ref]p2:
5349 // When a parameter of reference type is not bound directly to
5350 // an argument expression, the conversion sequence is the one
5351 // required to convert the argument expression to the
5352 // underlying type of the reference according to
5353 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5354 // to copy-initializing a temporary of the underlying type with
5355 // the argument expression. Any difference in top-level
5356 // cv-qualification is subsumed by the initialization itself
5357 // and does not constitute a conversion.
5358 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5359 AllowedExplicit::None,
5360 /*InOverloadResolution=*/false,
5361 /*CStyle=*/false,
5362 /*AllowObjCWritebackConversion=*/false,
5363 /*AllowObjCConversionOnExplicit=*/false);
5364
5365 // Of course, that's still a reference binding.
5366 if (ICS.isStandard()) {
5367 ICS.Standard.ReferenceBinding = true;
5368 ICS.Standard.IsLvalueReference = !isRValRef;
5369 ICS.Standard.BindsToFunctionLvalue = false;
5370 ICS.Standard.BindsToRvalue = true;
5373 } else if (ICS.isUserDefined()) {
5374 const ReferenceType *LValRefType =
5377
5378 // C++ [over.ics.ref]p3:
5379 // Except for an implicit object parameter, for which see 13.3.1, a
5380 // standard conversion sequence cannot be formed if it requires [...]
5381 // binding an rvalue reference to an lvalue other than a function
5382 // lvalue.
5383 // Note that the function case is not possible here.
5384 if (isRValRef && LValRefType) {
5386 return ICS;
5387 }
5388
5390 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5392 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5395 }
5396
5397 return ICS;
5398}
5399
5401TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5402 bool SuppressUserConversions,
5403 bool InOverloadResolution,
5404 bool AllowObjCWritebackConversion,
5405 bool AllowExplicit = false);
5406
5407/// TryListConversion - Try to copy-initialize a value of type ToType from the
5408/// initializer list From.
5411 bool SuppressUserConversions,
5412 bool InOverloadResolution,
5413 bool AllowObjCWritebackConversion) {
5414 // C++11 [over.ics.list]p1:
5415 // When an argument is an initializer list, it is not an expression and
5416 // special rules apply for converting it to a parameter type.
5417
5419 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5420
5421 // We need a complete type for what follows. With one C++20 exception,
5422 // incomplete types can never be initialized from init lists.
5423 QualType InitTy = ToType;
5424 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5425 if (AT && S.getLangOpts().CPlusPlus20)
5426 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5427 // C++20 allows list initialization of an incomplete array type.
5428 InitTy = IAT->getElementType();
5429 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5430 return Result;
5431
5432 // C++20 [over.ics.list]/2:
5433 // If the initializer list is a designated-initializer-list, a conversion
5434 // is only possible if the parameter has an aggregate type
5435 //
5436 // FIXME: The exception for reference initialization here is not part of the
5437 // language rules, but follow other compilers in adding it as a tentative DR
5438 // resolution.
5439 bool IsDesignatedInit = From->hasDesignatedInit();
5440 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5441 IsDesignatedInit)
5442 return Result;
5443
5444 // Per DR1467 and DR2137:
5445 // If the parameter type is an aggregate class X and the initializer list
5446 // has a single element of type cv U, where U is X or a class derived from
5447 // X, the implicit conversion sequence is the one required to convert the
5448 // element to the parameter type.
5449 //
5450 // Otherwise, if the parameter type is a character array [... ]
5451 // and the initializer list has a single element that is an
5452 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5453 // implicit conversion sequence is the identity conversion.
5454 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5455 if (ToType->isRecordType() && ToType->isAggregateType()) {
5456 QualType InitType = From->getInit(0)->getType();
5457 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5458 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5459 return TryCopyInitialization(S, From->getInit(0), ToType,
5460 SuppressUserConversions,
5461 InOverloadResolution,
5462 AllowObjCWritebackConversion);
5463 }
5464
5465 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5466 InitializedEntity Entity =
5468 /*Consumed=*/false);
5469 if (S.CanPerformCopyInitialization(Entity, From)) {
5470 Result.setStandard();
5471 Result.Standard.setAsIdentityConversion();
5472 Result.Standard.setFromType(ToType);
5473 Result.Standard.setAllToTypes(ToType);
5474 return Result;
5475 }
5476 }
5477 }
5478
5479 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5480 // C++11 [over.ics.list]p2:
5481 // If the parameter type is std::initializer_list<X> or "array of X" and
5482 // all the elements can be implicitly converted to X, the implicit
5483 // conversion sequence is the worst conversion necessary to convert an
5484 // element of the list to X.
5485 //
5486 // C++14 [over.ics.list]p3:
5487 // Otherwise, if the parameter type is "array of N X", if the initializer
5488 // list has exactly N elements or if it has fewer than N elements and X is
5489 // default-constructible, and if all the elements of the initializer list
5490 // can be implicitly converted to X, the implicit conversion sequence is
5491 // the worst conversion necessary to convert an element of the list to X.
5492 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5493 unsigned e = From->getNumInits();
5496 QualType());
5497 QualType ContTy = ToType;
5498 bool IsUnbounded = false;
5499 if (AT) {
5500 InitTy = AT->getElementType();
5501 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5502 if (CT->getSize().ult(e)) {
5503 // Too many inits, fatally bad
5505 ToType);
5506 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5507 return Result;
5508 }
5509 if (CT->getSize().ugt(e)) {
5510 // Need an init from empty {}, is there one?
5511 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5512 From->getEndLoc());
5513 EmptyList.setType(S.Context.VoidTy);
5514 DfltElt = TryListConversion(
5515 S, &EmptyList, InitTy, SuppressUserConversions,
5516 InOverloadResolution, AllowObjCWritebackConversion);
5517 if (DfltElt.isBad()) {
5518 // No {} init, fatally bad
5520 ToType);
5521 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5522 return Result;
5523 }
5524 }
5525 } else {
5526 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5527 IsUnbounded = true;
5528 if (!e) {
5529 // Cannot convert to zero-sized.
5531 ToType);
5532 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5533 return Result;
5534 }
5535 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5536 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5538 }
5539 }
5540
5541 Result.setStandard();
5542 Result.Standard.setAsIdentityConversion();
5543 Result.Standard.setFromType(InitTy);
5544 Result.Standard.setAllToTypes(InitTy);
5545 for (unsigned i = 0; i < e; ++i) {
5546 Expr *Init = From->getInit(i);
5548 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5549 AllowObjCWritebackConversion);
5550
5551 // Keep the worse conversion seen so far.
5552 // FIXME: Sequences are not totally ordered, so 'worse' can be
5553 // ambiguous. CWG has been informed.
5555 Result) ==
5557 Result = ICS;
5558 // Bail as soon as we find something unconvertible.
5559 if (Result.isBad()) {
5560 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5561 return Result;
5562 }
5563 }
5564 }
5565
5566 // If we needed any implicit {} initialization, compare that now.
5567 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5568 // has been informed that this might not be the best thing.
5569 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5570 S, From->getEndLoc(), DfltElt, Result) ==
5572 Result = DfltElt;
5573 // Record the type being initialized so that we may compare sequences
5574 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5575 return Result;
5576 }
5577
5578 // C++14 [over.ics.list]p4:
5579 // C++11 [over.ics.list]p3:
5580 // Otherwise, if the parameter is a non-aggregate class X and overload
5581 // resolution chooses a single best constructor [...] the implicit
5582 // conversion sequence is a user-defined conversion sequence. If multiple
5583 // constructors are viable but none is better than the others, the
5584 // implicit conversion sequence is a user-defined conversion sequence.
5585 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5586 // This function can deal with initializer lists.
5587 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5588 AllowedExplicit::None,
5589 InOverloadResolution, /*CStyle=*/false,
5590 AllowObjCWritebackConversion,
5591 /*AllowObjCConversionOnExplicit=*/false);
5592 }
5593
5594 // C++14 [over.ics.list]p5:
5595 // C++11 [over.ics.list]p4:
5596 // Otherwise, if the parameter has an aggregate type which can be
5597 // initialized from the initializer list [...] the implicit conversion
5598 // sequence is a user-defined conversion sequence.
5599 if (ToType->isAggregateType()) {
5600 // Type is an aggregate, argument is an init list. At this point it comes
5601 // down to checking whether the initialization works.
5602 // FIXME: Find out whether this parameter is consumed or not.
5603 InitializedEntity Entity =
5605 /*Consumed=*/false);
5607 From)) {
5608 Result.setUserDefined();
5609 Result.UserDefined.Before.setAsIdentityConversion();
5610 // Initializer lists don't have a type.
5611 Result.UserDefined.Before.setFromType(QualType());
5612 Result.UserDefined.Before.setAllToTypes(QualType());
5613
5614 Result.UserDefined.After.setAsIdentityConversion();
5615 Result.UserDefined.After.setFromType(ToType);
5616 Result.UserDefined.After.setAllToTypes(ToType);
5617 Result.UserDefined.ConversionFunction = nullptr;
5618 }
5619 return Result;
5620 }
5621
5622 // C++14 [over.ics.list]p6:
5623 // C++11 [over.ics.list]p5:
5624 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5625 if (ToType->isReferenceType()) {
5626 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5627 // mention initializer lists in any way. So we go by what list-
5628 // initialization would do and try to extrapolate from that.
5629
5630 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5631
5632 // If the initializer list has a single element that is reference-related
5633 // to the parameter type, we initialize the reference from that.
5634 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5635 Expr *Init = From->getInit(0);
5636
5637 QualType T2 = Init->getType();
5638
5639 // If the initializer is the address of an overloaded function, try
5640 // to resolve the overloaded function. If all goes well, T2 is the
5641 // type of the resulting function.
5642 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5645 Init, ToType, false, Found))
5646 T2 = Fn->getType();
5647 }
5648
5649 // Compute some basic properties of the types and the initializer.
5650 Sema::ReferenceCompareResult RefRelationship =
5651 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5652
5653 if (RefRelationship >= Sema::Ref_Related) {
5654 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5655 SuppressUserConversions,
5656 /*AllowExplicit=*/false);
5657 }
5658 }
5659
5660 // Otherwise, we bind the reference to a temporary created from the
5661 // initializer list.
5662 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5663 InOverloadResolution,
5664 AllowObjCWritebackConversion);
5665 if (Result.isFailure())
5666 return Result;
5667 assert(!Result.isEllipsis() &&
5668 "Sub-initialization cannot result in ellipsis conversion.");
5669
5670 // Can we even bind to a temporary?
5671 if (ToType->isRValueReferenceType() ||
5672 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5673 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5674 Result.UserDefined.After;
5675 SCS.ReferenceBinding = true;
5677 SCS.BindsToRvalue = true;
5678 SCS.BindsToFunctionLvalue = false;
5681 } else
5683 From, ToType);
5684 return Result;
5685 }
5686
5687 // C++14 [over.ics.list]p7:
5688 // C++11 [over.ics.list]p6:
5689 // Otherwise, if the parameter type is not a class:
5690 if (!ToType->isRecordType()) {
5691 // - if the initializer list has one element that is not itself an
5692 // initializer list, the implicit conversion sequence is the one
5693 // required to convert the element to the parameter type.
5694 unsigned NumInits = From->getNumInits();
5695 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5696 Result = TryCopyInitialization(S, From->getInit(0), ToType,
5697 SuppressUserConversions,
5698 InOverloadResolution,
5699 AllowObjCWritebackConversion);
5700 // - if the initializer list has no elements, the implicit conversion
5701 // sequence is the identity conversion.
5702 else if (NumInits == 0) {
5703 Result.setStandard();
5704 Result.Standard.setAsIdentityConversion();
5705 Result.Standard.setFromType(ToType);
5706 Result.Standard.setAllToTypes(ToType);
5707 }
5708 return Result;
5709 }
5710
5711 // C++14 [over.ics.list]p8:
5712 // C++11 [over.ics.list]p7:
5713 // In all cases other than those enumerated above, no conversion is possible
5714 return Result;
5715}
5716
5717/// TryCopyInitialization - Try to copy-initialize a value of type
5718/// ToType from the expression From. Return the implicit conversion
5719/// sequence required to pass this argument, which may be a bad
5720/// conversion sequence (meaning that the argument cannot be passed to
5721/// a parameter of this type). If @p SuppressUserConversions, then we
5722/// do not permit any user-defined conversion sequences.
5725 bool SuppressUserConversions,
5726 bool InOverloadResolution,
5727 bool AllowObjCWritebackConversion,
5728 bool AllowExplicit) {
5729 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5730 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5731 InOverloadResolution,AllowObjCWritebackConversion);
5732
5733 if (ToType->isReferenceType())
5734 return TryReferenceInit(S, From, ToType,
5735 /*FIXME:*/ From->getBeginLoc(),
5736 SuppressUserConversions, AllowExplicit);
5737
5738 return TryImplicitConversion(S, From, ToType,
5739 SuppressUserConversions,
5740 AllowedExplicit::None,
5741 InOverloadResolution,
5742 /*CStyle=*/false,
5743 AllowObjCWritebackConversion,
5744 /*AllowObjCConversionOnExplicit=*/false);
5745}
5746
5747static bool TryCopyInitialization(const CanQualType FromQTy,
5748 const CanQualType ToQTy,
5749 Sema &S,
5750 SourceLocation Loc,
5751 ExprValueKind FromVK) {
5752 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5754 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5755
5756 return !ICS.isBad();
5757}
5758
5759/// TryObjectArgumentInitialization - Try to initialize the object
5760/// parameter of the given member function (@c Method) from the
5761/// expression @p From.
5763 Sema &S, SourceLocation Loc, QualType FromType,
5764 Expr::Classification FromClassification, CXXMethodDecl *Method,
5765 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5766 QualType ExplicitParameterType = QualType(),
5767 bool SuppressUserConversion = false) {
5768
5769 // We need to have an object of class type.
5770 if (const auto *PT = FromType->getAs<PointerType>()) {
5771 FromType = PT->getPointeeType();
5772
5773 // When we had a pointer, it's implicitly dereferenced, so we
5774 // better have an lvalue.
5775 assert(FromClassification.isLValue());
5776 }
5777
5778 auto ValueKindFromClassification = [](Expr::Classification C) {
5779 if (C.isPRValue())
5780 return clang::VK_PRValue;
5781 if (C.isXValue())
5782 return VK_XValue;
5783 return clang::VK_LValue;
5784 };
5785
5786 if (Method->isExplicitObjectMemberFunction()) {
5787 if (ExplicitParameterType.isNull())
5788 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
5789 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
5790 ValueKindFromClassification(FromClassification));
5792 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
5793 /*InOverloadResolution=*/true, false);
5794 if (ICS.isBad())
5795 ICS.Bad.FromExpr = nullptr;
5796 return ICS;
5797 }
5798
5799 assert(FromType->isRecordType());
5800
5801 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5802 // C++98 [class.dtor]p2:
5803 // A destructor can be invoked for a const, volatile or const volatile
5804 // object.
5805 // C++98 [over.match.funcs]p4:
5806 // For static member functions, the implicit object parameter is considered
5807 // to match any object (since if the function is selected, the object is
5808 // discarded).
5809 Qualifiers Quals = Method->getMethodQualifiers();
5810 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
5811 Quals.addConst();
5812 Quals.addVolatile();
5813 }
5814
5815 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5816
5817 // Set up the conversion sequence as a "bad" conversion, to allow us
5818 // to exit early.
5820
5821 // C++0x [over.match.funcs]p4:
5822 // For non-static member functions, the type of the implicit object
5823 // parameter is
5824 //
5825 // - "lvalue reference to cv X" for functions declared without a
5826 // ref-qualifier or with the & ref-qualifier
5827 // - "rvalue reference to cv X" for functions declared with the &&
5828 // ref-qualifier
5829 //
5830 // where X is the class of which the function is a member and cv is the
5831 // cv-qualification on the member function declaration.
5832 //
5833 // However, when finding an implicit conversion sequence for the argument, we
5834 // are not allowed to perform user-defined conversions
5835 // (C++ [over.match.funcs]p5). We perform a simplified version of
5836 // reference binding here, that allows class rvalues to bind to
5837 // non-constant references.
5838
5839 // First check the qualifiers.
5840 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5841 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
5842 if (ImplicitParamType.getCVRQualifiers() !=
5843 FromTypeCanon.getLocalCVRQualifiers() &&
5844 !ImplicitParamType.isAtLeastAsQualifiedAs(
5845 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
5847 FromType, ImplicitParamType);
5848 return ICS;
5849 }
5850
5851 if (FromTypeCanon.hasAddressSpace()) {
5852 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5853 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5854 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
5855 S.getASTContext())) {
5857 FromType, ImplicitParamType);
5858 return ICS;
5859 }
5860 }
5861
5862 // Check that we have either the same type or a derived type. It
5863 // affects the conversion rank.
5864 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5865 ImplicitConversionKind SecondKind;
5866 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5867 SecondKind = ICK_Identity;
5868 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
5869 SecondKind = ICK_Derived_To_Base;
5870 } else if (!Method->isExplicitObjectMemberFunction()) {
5872 FromType, ImplicitParamType);
5873 return ICS;
5874 }
5875
5876 // Check the ref-qualifier.
5877 switch (Method->getRefQualifier()) {
5878 case RQ_None:
5879 // Do nothing; we don't care about lvalueness or rvalueness.
5880 break;
5881
5882 case RQ_LValue:
5883 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5884 // non-const lvalue reference cannot bind to an rvalue
5886 ImplicitParamType);
5887 return ICS;
5888 }
5889 break;
5890
5891 case RQ_RValue:
5892 if (!FromClassification.isRValue()) {
5893 // rvalue reference cannot bind to an lvalue
5895 ImplicitParamType);
5896 return ICS;
5897 }
5898 break;
5899 }
5900
5901 // Success. Mark this as a reference binding.
5902 ICS.setStandard();
5904 ICS.Standard.Second = SecondKind;
5905 ICS.Standard.setFromType(FromType);
5906 ICS.Standard.setAllToTypes(ImplicitParamType);
5907 ICS.Standard.ReferenceBinding = true;
5908 ICS.Standard.DirectBinding = true;
5910 ICS.Standard.BindsToFunctionLvalue = false;
5911 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5913 = (Method->getRefQualifier() == RQ_None);
5914 return ICS;
5915}
5916
5917/// PerformObjectArgumentInitialization - Perform initialization of
5918/// the implicit object parameter for the given Method with the given
5919/// expression.
5921 Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl,
5922 CXXMethodDecl *Method) {
5923 QualType FromRecordType, DestType;
5924 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
5925
5926 Expr::Classification FromClassification;
5927 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5928 FromRecordType = PT->getPointeeType();
5929 DestType = Method->getThisType();
5930 FromClassification = Expr::Classification::makeSimpleLValue();
5931 } else {
5932 FromRecordType = From->getType();
5933 DestType = ImplicitParamRecordType;
5934 FromClassification = From->Classify(Context);
5935
5936 // CWG2813 [expr.call]p6:
5937 // If the function is an implicit object member function, the object
5938 // expression of the class member access shall be a glvalue [...]
5939 if (From->isPRValue()) {
5940 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5941 Method->getRefQualifier() !=
5943 }
5944 }
5945
5946 // Note that we always use the true parent context when performing
5947 // the actual argument initialization.
5949 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5950 Method->getParent());
5951 if (ICS.isBad()) {
5952 switch (ICS.Bad.Kind) {
5954 Qualifiers FromQs = FromRecordType.getQualifiers();
5955 Qualifiers ToQs = DestType.getQualifiers();
5956 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5957 if (CVR) {
5958 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5959 << Method->getDeclName() << FromRecordType << (CVR - 1)
5960 << From->getSourceRange();
5961 Diag(Method->getLocation(), diag::note_previous_decl)
5962 << Method->getDeclName();
5963 return ExprError();
5964 }
5965 break;
5966 }
5967
5970 bool IsRValueQualified =
5972 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5973 << Method->getDeclName() << FromClassification.isRValue()
5974 << IsRValueQualified;
5975 Diag(Method->getLocation(), diag::note_previous_decl)
5976 << Method->getDeclName();
5977 return ExprError();
5978 }
5979
5982 break;
5983
5986 llvm_unreachable("Lists are not objects");
5987 }
5988
5989 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5990 << ImplicitParamRecordType << FromRecordType
5991 << From->getSourceRange();
5992 }
5993
5994 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5995 ExprResult FromRes =
5996 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5997 if (FromRes.isInvalid())
5998 return ExprError();
5999 From = FromRes.get();
6000 }
6001
6002 if (!Context.hasSameType(From->getType(), DestType)) {
6003 CastKind CK;
6004 QualType PteeTy = DestType->getPointeeType();
6005 LangAS DestAS =
6006 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6007 if (FromRecordType.getAddressSpace() != DestAS)
6008 CK = CK_AddressSpaceConversion;
6009 else
6010 CK = CK_NoOp;
6011 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6012 }
6013 return From;
6014}
6015
6016/// TryContextuallyConvertToBool - Attempt to contextually convert the
6017/// expression From to bool (C++0x [conv]p3).
6020 // C++ [dcl.init]/17.8:
6021 // - Otherwise, if the initialization is direct-initialization, the source
6022 // type is std::nullptr_t, and the destination type is bool, the initial
6023 // value of the object being initialized is false.
6024 if (From->getType()->isNullPtrType())
6026 S.Context.BoolTy,
6027 From->isGLValue());
6028
6029 // All other direct-initialization of bool is equivalent to an implicit
6030 // conversion to bool in which explicit conversions are permitted.
6031 return TryImplicitConversion(S, From, S.Context.BoolTy,
6032 /*SuppressUserConversions=*/false,
6033 AllowedExplicit::Conversions,
6034 /*InOverloadResolution=*/false,
6035 /*CStyle=*/false,
6036 /*AllowObjCWritebackConversion=*/false,
6037 /*AllowObjCConversionOnExplicit=*/false);
6038}
6039
6041 if (checkPlaceholderForOverload(*this, From))
6042 return ExprError();
6043
6045 if (!ICS.isBad())
6046 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6048
6049 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
6050 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6051 << From->getType() << From->getSourceRange();
6052 return ExprError();
6053}
6054
6055/// Check that the specified conversion is permitted in a converted constant
6056/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6057/// is acceptable.
6060 // Since we know that the target type is an integral or unscoped enumeration
6061 // type, most conversion kinds are impossible. All possible First and Third
6062 // conversions are fine.
6063 switch (SCS.Second) {
6064 case ICK_Identity:
6066 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6068 return true;
6069
6071 // Conversion from an integral or unscoped enumeration type to bool is
6072 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6073 // conversion, so we allow it in a converted constant expression.
6074 //
6075 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6076 // a lot of popular code. We should at least add a warning for this
6077 // (non-conforming) extension.
6079 SCS.getToType(2)->isBooleanType();
6080
6082 case ICK_Pointer_Member:
6083 // C++1z: null pointer conversions and null member pointer conversions are
6084 // only permitted if the source type is std::nullptr_t.
6085 return SCS.getFromType()->isNullPtrType();
6086
6098 case ICK_Vector_Splat:
6099 case ICK_Complex_Real:
6108 return false;
6109
6114 llvm_unreachable("found a first conversion kind in Second");
6115
6117 case ICK_Qualification:
6118 llvm_unreachable("found a third conversion kind in Second");
6119
6121 break;
6122 }
6123
6124 llvm_unreachable("unknown conversion kind");
6125}
6126
6127/// BuildConvertedConstantExpression - Check that the expression From is a
6128/// converted constant expression of type T, perform the conversion but
6129/// does not evaluate the expression
6131 QualType T,
6132 Sema::CCEKind CCE,
6133 NamedDecl *Dest,
6134 APValue &PreNarrowingValue) {
6135 assert(S.getLangOpts().CPlusPlus11 &&
6136 "converted constant expression outside C++11");
6137
6138 if (checkPlaceholderForOverload(S, From))
6139 return ExprError();
6140
6141 // C++1z [expr.const]p3:
6142 // A converted constant expression of type T is an expression,
6143 // implicitly converted to type T, where the converted
6144 // expression is a constant expression and the implicit conversion
6145 // sequence contains only [... list of conversions ...].
6149 : TryCopyInitialization(S, From, T,
6150 /*SuppressUserConversions=*/false,
6151 /*InOverloadResolution=*/false,
6152 /*AllowObjCWritebackConversion=*/false,
6153 /*AllowExplicit=*/false);
6154 StandardConversionSequence *SCS = nullptr;
6155 switch (ICS.getKind()) {
6157 SCS = &ICS.Standard;
6158 break;
6160 if (T->isRecordType())
6161 SCS = &ICS.UserDefined.Before;
6162 else
6163 SCS = &ICS.UserDefined.After;
6164 break;
6168 return S.Diag(From->getBeginLoc(),
6169 diag::err_typecheck_converted_constant_expression)
6170 << From->getType() << From->getSourceRange() << T;
6171 return ExprError();
6172
6175 llvm_unreachable("bad conversion in converted constant expression");
6176 }
6177
6178 // Check that we would only use permitted conversions.
6179 if (!CheckConvertedConstantConversions(S, *SCS)) {
6180 return S.Diag(From->getBeginLoc(),
6181 diag::err_typecheck_converted_constant_expression_disallowed)
6182 << From->getType() << From->getSourceRange() << T;
6183 }
6184 // [...] and where the reference binding (if any) binds directly.
6185 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6186 return S.Diag(From->getBeginLoc(),
6187 diag::err_typecheck_converted_constant_expression_indirect)
6188 << From->getType() << From->getSourceRange() << T;
6189 }
6190 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6191 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6192 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6193 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6194 // case explicitly.
6195 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6196 return S.Diag(From->getBeginLoc(),
6197 diag::err_reference_bind_to_bitfield_in_cce)
6198 << From->getSourceRange();
6199 }
6200
6201 // Usually we can simply apply the ImplicitConversionSequence we formed
6202 // earlier, but that's not guaranteed to work when initializing an object of
6203 // class type.
6205 if (T->isRecordType()) {
6206 assert(CCE == Sema::CCEK_TemplateArg &&
6207 "unexpected class type converted constant expr");
6210 T, cast<NonTypeTemplateParmDecl>(Dest)),
6211 SourceLocation(), From);
6212 } else {
6213 Result =
6215 }
6216 if (Result.isInvalid())
6217 return Result;
6218
6219 // C++2a [intro.execution]p5:
6220 // A full-expression is [...] a constant-expression [...]
6221 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6222 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6224 if (Result.isInvalid())
6225 return Result;
6226
6227 // Check for a narrowing implicit conversion.
6228 bool ReturnPreNarrowingValue = false;
6229 QualType PreNarrowingType;
6230 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6231 PreNarrowingType)) {
6233 // Implicit conversion to a narrower type, but the expression is
6234 // value-dependent so we can't tell whether it's actually narrowing.
6236 // Implicit conversion to a narrower type, and the value is not a constant
6237 // expression. We'll diagnose this in a moment.
6238 case NK_Not_Narrowing:
6239 break;
6240
6242 if (CCE == Sema::CCEK_ArrayBound &&
6243 PreNarrowingType->isIntegralOrEnumerationType() &&
6244 PreNarrowingValue.isInt()) {
6245 // Don't diagnose array bound narrowing here; we produce more precise
6246 // errors by allowing the un-narrowed value through.
6247 ReturnPreNarrowingValue = true;
6248 break;
6249 }
6250 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6251 << CCE << /*Constant*/ 1
6252 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6253 break;
6254
6255 case NK_Type_Narrowing:
6256 // FIXME: It would be better to diagnose that the expression is not a
6257 // constant expression.
6258 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6259 << CCE << /*Constant*/ 0 << From->getType() << T;
6260 break;
6261 }
6262 if (!ReturnPreNarrowingValue)
6263 PreNarrowingValue = {};
6264
6265 return Result;
6266}
6267
6268/// CheckConvertedConstantExpression - Check that the expression From is a
6269/// converted constant expression of type T, perform the conversion and produce
6270/// the converted expression, per C++11 [expr.const]p3.
6273 Sema::CCEKind CCE,
6274 bool RequireInt,
6275 NamedDecl *Dest) {
6276
6277 APValue PreNarrowingValue;
6279 PreNarrowingValue);
6280 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6281 Value = APValue();
6282 return Result;
6283 }
6284 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6285 RequireInt, PreNarrowingValue);
6286}
6287
6289 CCEKind CCE,
6290 NamedDecl *Dest) {
6291 APValue PreNarrowingValue;
6292 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6293 PreNarrowingValue);
6294}
6295
6297 APValue &Value, CCEKind CCE,
6298 NamedDecl *Dest) {
6299 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6300 Dest);
6301}
6302
6304 llvm::APSInt &Value,
6305 CCEKind CCE) {
6306 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6307
6308 APValue V;
6309 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6310 /*Dest=*/nullptr);
6311 if (!R.isInvalid() && !R.get()->isValueDependent())
6312 Value = V.getInt();
6313 return R;
6314}
6315
6318 Sema::CCEKind CCE, bool RequireInt,
6319 const APValue &PreNarrowingValue) {
6320
6322 // Check the expression is a constant expression.
6324 Expr::EvalResult Eval;
6325 Eval.Diag = &Notes;
6326
6327 ConstantExprKind Kind;
6328 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
6329 Kind = ConstantExprKind::ClassTemplateArgument;
6330 else if (CCE == Sema::CCEK_TemplateArg)
6331 Kind = ConstantExprKind::NonClassTemplateArgument;
6332 else
6333 Kind = ConstantExprKind::Normal;
6334
6335 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6336 (RequireInt && !Eval.Val.isInt())) {
6337 // The expression can't be folded, so we can't keep it at this position in
6338 // the AST.
6339 Result = ExprError();
6340 } else {
6341 Value = Eval.Val;
6342
6343 if (Notes.empty()) {
6344 // It's a constant expression.
6345 Expr *E = Result.get();
6346 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6347 // We expect a ConstantExpr to have a value associated with it
6348 // by this point.
6349 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6350 "ConstantExpr has no value associated with it");
6351 (void)CE;
6352 } else {
6353 E = ConstantExpr::Create(Context, Result.get(), Value);
6354 }
6355 if (!PreNarrowingValue.isAbsent())
6356 Value = std::move(PreNarrowingValue);
6357 return E;
6358 }
6359 }
6360
6361 // It's not a constant expression. Produce an appropriate diagnostic.
6362 if (Notes.size() == 1 &&
6363 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6364 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6365 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6366 diag::note_constexpr_invalid_template_arg) {
6367 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6368 for (unsigned I = 0; I < Notes.size(); ++I)
6369 Diag(Notes[I].first, Notes[I].second);
6370 } else {
6371 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6372 << CCE << E->getSourceRange();
6373 for (unsigned I = 0; I < Notes.size(); ++I)
6374 Diag(Notes[I].first, Notes[I].second);
6375 }
6376 return ExprError();
6377}
6378
6379/// dropPointerConversions - If the given standard conversion sequence
6380/// involves any pointer conversions, remove them. This may change
6381/// the result type of the conversion sequence.
6383 if (SCS.Second == ICK_Pointer_Conversion) {
6384 SCS.Second = ICK_Identity;
6385 SCS.Dimension = ICK_Identity;
6386 SCS.Third = ICK_Identity;
6387 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6388 }
6389}
6390
6391/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6392/// convert the expression From to an Objective-C pointer type.
6395 // Do an implicit conversion to 'id'.
6398 = TryImplicitConversion(S, From, Ty,
6399 // FIXME: Are these flags correct?
6400 /*SuppressUserConversions=*/false,
6401 AllowedExplicit::Conversions,
6402 /*InOverloadResolution=*/false,
6403 /*CStyle=*/false,
6404 /*AllowObjCWritebackConversion=*/false,
6405 /*AllowObjCConversionOnExplicit=*/true);
6406
6407 // Strip off any final conversions to 'id'.
6408 switch (ICS.getKind()) {
6413 break;
6414
6417 break;
6418
6421 break;
6422 }
6423
6424 return ICS;
6425}
6426
6428 if (checkPlaceholderForOverload(*this, From))
6429 return ExprError();
6430
6431 QualType Ty = Context.getObjCIdType();
6434 if (!ICS.isBad())
6435 return PerformImplicitConversion(From, Ty, ICS,
6437 return ExprResult();
6438}
6439
6440static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6441 const Expr *Base = nullptr;
6442 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6443 "expected a member expression");
6444
6445 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6446 M && !M->isImplicitAccess())
6447 Base = M->getBase();
6448 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6449 M && !M->isImplicitAccess())
6450 Base = M->getBase();
6451
6452 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6453
6454 if (T->isPointerType())
6455 T = T->getPointeeType();
6456
6457 return T;
6458}
6459
6461 const FunctionDecl *Fun) {
6462 QualType ObjType = Obj->getType();
6463 if (ObjType->isPointerType()) {
6464 ObjType = ObjType->getPointeeType();
6465 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6467 /*CanOverflow=*/false, FPOptionsOverride());
6468 }
6469 return Obj;
6470}
6471
6473 FunctionDecl *Fun) {
6474 Obj = GetExplicitObjectExpr(S, Obj, Fun);
6477 Obj->getExprLoc(), Obj);
6478}
6479
6481 Expr *Object, MultiExprArg &Args,
6482 SmallVectorImpl<Expr *> &NewArgs) {
6483 assert(Method->isExplicitObjectMemberFunction() &&
6484 "Method is not an explicit member function");
6485 assert(NewArgs.empty() && "NewArgs should be empty");
6486
6487 NewArgs.reserve(Args.size() + 1);
6488 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6489 NewArgs.push_back(This);
6490 NewArgs.append(Args.begin(), Args.end());
6491 Args = NewArgs;
6493 Method, Object->getBeginLoc());
6494}
6495
6496/// Determine whether the provided type is an integral type, or an enumeration
6497/// type of a permitted flavor.
6499 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6501}
6502
6503static ExprResult
6506 QualType T, UnresolvedSetImpl &ViableConversions) {
6507
6508 if (Converter.Suppress)
6509 return ExprError();
6510
6511 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6512 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6513 CXXConversionDecl *Conv =
6514 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6516 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6517 }
6518 return From;
6519}
6520
6521static bool
6524 QualType T, bool HadMultipleCandidates,
6525 UnresolvedSetImpl &ExplicitConversions) {
6526 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6527 DeclAccessPair Found = ExplicitConversions[0];
6528 CXXConversionDecl *Conversion =
6529 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6530
6531 // The user probably meant to invoke the given explicit
6532 // conversion; use it.
6533 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6534 std::string TypeStr;
6535 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6536
6537 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6539 "static_cast<" + TypeStr + ">(")
6541 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6542 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6543
6544 // If we aren't in a SFINAE context, build a call to the
6545 // explicit conversion function.
6546 if (SemaRef.isSFINAEContext())
6547 return true;
6548
6549 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6550 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6551 HadMultipleCandidates);
6552 if (Result.isInvalid())
6553 return true;
6554
6555 // Replace the conversion with a RecoveryExpr, so we don't try to
6556 // instantiate it later, but can further diagnose here.
6557 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6558 From, Result.get()->getType());
6559 if (Result.isInvalid())
6560 return true;
6561 From = Result.get();
6562 }
6563 return false;
6564}
6565
6566static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6568 QualType T, bool HadMultipleCandidates,
6570 CXXConversionDecl *Conversion =
6571 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6572 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6573
6574 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6575 if (!Converter.SuppressConversion) {
6576 if (SemaRef.isSFINAEContext())
6577 return true;
6578
6579 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6580 << From->getSourceRange();
6581 }
6582
6583 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6584 HadMultipleCandidates);
6585 if (Result.isInvalid())
6586 return true;
6587 // Record usage of conversion in an implicit cast.
6588 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6589 CK_UserDefinedConversion, Result.get(),
6590 nullptr, Result.get()->getValueKind(),
6591 SemaRef.CurFPFeatureOverrides());
6592 return false;
6593}
6594
6596 Sema &SemaRef, SourceLocation Loc, Expr *From,
6598 if (!Converter.match(From->getType()) && !Converter.Suppress)
6599 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6600 << From->getSourceRange();
6601
6602 return SemaRef.DefaultLvalueConversion(From);
6603}
6604
6605static void
6607 UnresolvedSetImpl &ViableConversions,
6608 OverloadCandidateSet &CandidateSet) {
6609 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6610 NamedDecl *D = FoundDecl.getDecl();
6611 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6612 if (isa<UsingShadowDecl>(D))
6613 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6614
6615 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
6617 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6618 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6619 continue;
6620 }
6621 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6622 SemaRef.AddConversionCandidate(
6623 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
6624 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6625 }
6626}
6627
6628/// Attempt to convert the given expression to a type which is accepted
6629/// by the given converter.
6630///
6631/// This routine will attempt to convert an expression of class type to a
6632/// type accepted by the specified converter. In C++11 and before, the class
6633/// must have a single non-explicit conversion function converting to a matching
6634/// type. In C++1y, there can be multiple such conversion functions, but only
6635/// one target type.
6636///
6637/// \param Loc The source location of the construct that requires the
6638/// conversion.
6639///
6640/// \param From The expression we're converting from.
6641///
6642/// \param Converter Used to control and diagnose the conversion process.
6643///
6644/// \returns The expression, converted to an integral or enumeration type if
6645/// successful.
6647 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6648 // We can't perform any more checking for type-dependent expressions.
6649 if (From->isTypeDependent())
6650 return From;
6651
6652 // Process placeholders immediately.
6653 if (From->hasPlaceholderType()) {
6654 ExprResult result = CheckPlaceholderExpr(From);
6655 if (result.isInvalid())
6656 return result;
6657 From = result.get();
6658 }
6659
6660 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6661 ExprResult Converted = DefaultLvalueConversion(From);
6662 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6663 // If the expression already has a matching type, we're golden.
6664 if (Converter.match(T))
6665 return Converted;
6666
6667 // FIXME: Check for missing '()' if T is a function type?
6668
6669 // We can only perform contextual implicit conversions on objects of class
6670 // type.
6671 const RecordType *RecordTy = T->getAs<RecordType>();
6672 if (!RecordTy || !getLangOpts().CPlusPlus) {
6673 if (!Converter.Suppress)
6674 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6675 return From;
6676 }
6677
6678 // We must have a complete class type.
6679 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6680 ContextualImplicitConverter &Converter;
6681 Expr *From;
6682
6683 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6684 : Converter(Converter), From(From) {}
6685
6686 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6687 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6688 }
6689 } IncompleteDiagnoser(Converter, From);
6690
6691 if (Converter.Suppress ? !isCompleteType(Loc, T)
6692 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6693 return From;
6694
6695 // Look for a conversion to an integral or enumeration type.
6697 ViableConversions; // These are *potentially* viable in C++1y.
6698 UnresolvedSet<4> ExplicitConversions;
6699 const auto &Conversions =
6700 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6701
6702 bool HadMultipleCandidates =
6703 (std::distance(Conversions.begin(), Conversions.end()) > 1);
6704
6705 // To check that there is only one target type, in C++1y:
6706 QualType ToType;
6707 bool HasUniqueTargetType = true;
6708
6709 // Collect explicit or viable (potentially in C++1y) conversions.
6710 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6711 NamedDecl *D = (*I)->getUnderlyingDecl();
6712 CXXConversionDecl *Conversion;
6713 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6714 if (ConvTemplate) {
6715 if (getLangOpts().CPlusPlus14)
6716 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6717 else
6718 continue; // C++11 does not consider conversion operator templates(?).
6719 } else
6720 Conversion = cast<CXXConversionDecl>(D);
6721
6722 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6723 "Conversion operator templates are considered potentially "
6724 "viable in C++1y");
6725
6726 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6727 if (Converter.match(CurToType) || ConvTemplate) {
6728
6729 if (Conversion->isExplicit()) {
6730 // FIXME: For C++1y, do we need this restriction?
6731 // cf. diagnoseNoViableConversion()
6732 if (!ConvTemplate)
6733 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6734 } else {
6735 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6736 if (ToType.isNull())
6737 ToType = CurToType.getUnqualifiedType();
6738 else if (HasUniqueTargetType &&
6739 (CurToType.getUnqualifiedType() != ToType))
6740 HasUniqueTargetType = false;
6741 }
6742 ViableConversions.addDecl(I.getDecl(), I.getAccess());
6743 }
6744 }
6745 }
6746
6747 if (getLangOpts().CPlusPlus14) {
6748 // C++1y [conv]p6:
6749 // ... An expression e of class type E appearing in such a context
6750 // is said to be contextually implicitly converted to a specified
6751 // type T and is well-formed if and only if e can be implicitly
6752 // converted to a type T that is determined as follows: E is searched
6753 // for conversion functions whose return type is cv T or reference to
6754 // cv T such that T is allowed by the context. There shall be
6755 // exactly one such T.
6756
6757 // If no unique T is found:
6758 if (ToType.isNull()) {
6759 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6760 HadMultipleCandidates,
6761 ExplicitConversions))
6762 return ExprError();
6763 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6764 }
6765
6766 // If more than one unique Ts are found:
6767 if (!HasUniqueTargetType)
6768 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6769 ViableConversions);
6770
6771 // If one unique T is found:
6772 // First, build a candidate set from the previously recorded
6773 // potentially viable conversions.
6775 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6776 CandidateSet);
6777
6778 // Then, perform overload resolution over the candidate set.
6780 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6781 case OR_Success: {
6782 // Apply this conversion.
6784 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6785 if (recordConversion(*this, Loc, From, Converter, T,
6786 HadMultipleCandidates, Found))
6787 return ExprError();
6788 break;
6789 }
6790 case OR_Ambiguous:
6791 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6792 ViableConversions);
6794 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6795 HadMultipleCandidates,
6796 ExplicitConversions))
6797 return ExprError();
6798 [[fallthrough]];
6799 case OR_Deleted:
6800 // We'll complain below about a non-integral condition type.
6801 break;
6802 }
6803 } else {
6804 switch (ViableConversions.size()) {
6805 case 0: {
6806 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6807 HadMultipleCandidates,
6808 ExplicitConversions))
6809 return ExprError();
6810
6811 // We'll complain below about a non-integral condition type.
6812 break;
6813 }
6814 case 1: {
6815 // Apply this conversion.
6816 DeclAccessPair Found = ViableConversions[0];
6817 if (recordConversion(*this, Loc, From, Converter, T,
6818 HadMultipleCandidates, Found))
6819 return ExprError();
6820 break;
6821 }
6822 default:
6823 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6824 ViableConversions);
6825 }
6826 }
6827
6828 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6829}
6830
6831/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6832/// an acceptable non-member overloaded operator for a call whose
6833/// arguments have types T1 (and, if non-empty, T2). This routine
6834/// implements the check in C++ [over.match.oper]p3b2 concerning
6835/// enumeration types.
6837 FunctionDecl *Fn,
6838 ArrayRef<Expr *> Args) {
6839 QualType T1 = Args[0]->getType();
6840 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6841
6842 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6843 return true;
6844
6845 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6846 return true;
6847
6848 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6849 if (Proto->getNumParams() < 1)
6850 return false;
6851
6852 if (T1->isEnumeralType()) {
6853 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6854 if (Context.hasSameUnqualifiedType(T1, ArgType))
6855 return true;
6856 }
6857
6858 if (Proto->getNumParams() < 2)
6859 return false;
6860
6861 if (!T2.isNull() && T2->isEnumeralType()) {
6862 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6863 if (Context.hasSameUnqualifiedType(T2, ArgType))
6864 return true;
6865 }
6866
6867 return false;
6868}
6869
6872 return false;
6873
6874 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
6875 return FD->isTargetMultiVersion();
6876
6877 if (!FD->isMultiVersion())
6878 return false;
6879
6880 // Among multiple target versions consider either the default,
6881 // or the first non-default in the absence of default version.
6882 unsigned SeenAt = 0;
6883 unsigned I = 0;
6884 bool HasDefault = false;
6886 FD, [&](const FunctionDecl *CurFD) {
6887 if (FD == CurFD)
6888 SeenAt = I;
6889 else if (CurFD->isTargetMultiVersionDefault())
6890 HasDefault = true;
6891 ++I;
6892 });
6893 return HasDefault || SeenAt != 0;
6894}
6895
6898 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6899 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6900 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6901 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
6902 const FunctionProtoType *Proto
6903 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6904 assert(Proto && "Functions without a prototype cannot be overloaded");
6905 assert(!Function->getDescribedFunctionTemplate() &&
6906 "Use AddTemplateOverloadCandidate for function templates");
6907
6908 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6909 if (!isa<CXXConstructorDecl>(Method)) {
6910 // If we get here, it's because we're calling a member function
6911 // that is named without a member access expression (e.g.,
6912 // "this->f") that was either written explicitly or created
6913 // implicitly. This can happen with a qualified call to a member
6914 // function, e.g., X::f(). We use an empty type for the implied
6915 // object argument (C++ [over.call.func]p3), and the acting context
6916 // is irrelevant.
6917 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6919 CandidateSet, SuppressUserConversions,
6920 PartialOverloading, EarlyConversions, PO);
6921 return;
6922 }
6923 // We treat a constructor like a non-member function, since its object
6924 // argument doesn't participate in overload resolution.
6925 }
6926
6927 if (!CandidateSet.isNewCandidate(Function, PO))
6928 return;
6929
6930 // C++11 [class.copy]p11: [DR1402]
6931 // A defaulted move constructor that is defined as deleted is ignored by
6932 // overload resolution.
6933 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6934 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6935 Constructor->isMoveConstructor())
6936 return;
6937
6938 // Overload resolution is always an unevaluated context.
6941
6942 // C++ [over.match.oper]p3:
6943 // if no operand has a class type, only those non-member functions in the
6944 // lookup set that have a first parameter of type T1 or "reference to
6945 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6946 // is a right operand) a second parameter of type T2 or "reference to
6947 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
6948 // candidate functions.
6949 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6951 return;
6952
6953 // Add this candidate
6954 OverloadCandidate &Candidate =
6955 CandidateSet.addCandidate(Args.size(), EarlyConversions);
6956 Candidate.FoundDecl = FoundDecl;
6957 Candidate.Function = Function;
6958 Candidate.Viable = true;
6959 Candidate.RewriteKind =
6960 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6961 Candidate.IsADLCandidate = IsADLCandidate;
6962 Candidate.ExplicitCallArguments = Args.size();
6963
6964 // Explicit functions are not actually candidates at all if we're not
6965 // allowing them in this context, but keep them around so we can point
6966 // to them in diagnostics.
6967 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6968 Candidate.Viable = false;
6969 Candidate.FailureKind = ovl_fail_explicit;
6970 return;
6971 }
6972
6973 // Functions with internal linkage are only viable in the same module unit.
6974 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
6975 /// FIXME: Currently, the semantics of linkage in clang is slightly
6976 /// different from the semantics in C++ spec. In C++ spec, only names
6977 /// have linkage. So that all entities of the same should share one
6978 /// linkage. But in clang, different entities of the same could have
6979 /// different linkage.
6980 NamedDecl *ND = Function;
6981 if (auto *SpecInfo = Function->getTemplateSpecializationInfo())
6982 ND = SpecInfo->getTemplate();
6983
6984 if (ND->getFormalLinkage() == Linkage::Internal) {
6985 Candidate.Viable = false;
6987 return;
6988 }
6989 }
6990
6992 Candidate.Viable = false;
6994 return;
6995 }
6996
6997 if (Constructor) {
6998 // C++ [class.copy]p3:
6999 // A member function template is never instantiated to perform the copy
7000 // of a class object to an object of its class type.
7001 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
7002 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7003 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7004 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7005 ClassType))) {
7006 Candidate.Viable = false;
7008 return;
7009 }
7010
7011 // C++ [over.match.funcs]p8: (proposed DR resolution)
7012 // A constructor inherited from class type C that has a first parameter
7013 // of type "reference to P" (including such a constructor instantiated
7014 // from a template) is excluded from the set of candidate functions when
7015 // constructing an object of type cv D if the argument list has exactly
7016 // one argument and D is reference-related to P and P is reference-related
7017 // to C.
7018 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7019 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7020 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7021 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7022 QualType C = Context.getRecordType(Constructor->getParent());
7023 QualType D = Context.getRecordType(Shadow->getParent());
7024 SourceLocation Loc = Args.front()->getExprLoc();
7025 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7026 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7027 Candidate.Viable = false;
7029 return;
7030 }
7031 }
7032
7033 // Check that the constructor is capable of constructing an object in the
7034 // destination address space.
7036 Constructor->getMethodQualifiers().getAddressSpace(),
7037 CandidateSet.getDestAS(), getASTContext())) {
7038 Candidate.Viable = false;
7040 }
7041 }
7042
7043 unsigned NumParams = Proto->getNumParams();
7044
7045 // (C++ 13.3.2p2): A candidate function having fewer than m
7046 // parameters is viable only if it has an ellipsis in its parameter
7047 // list (8.3.5).
7048 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7049 !Proto->isVariadic() &&
7050 shouldEnforceArgLimit(PartialOverloading, Function)) {
7051 Candidate.Viable = false;
7053 return;
7054 }
7055
7056 // (C++ 13.3.2p2): A candidate function having more than m parameters
7057 // is viable only if the (m+1)st parameter has a default argument
7058 // (8.3.6). For the purposes of overload resolution, the
7059 // parameter list is truncated on the right, so that there are
7060 // exactly m parameters.
7061 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7062 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7063 !PartialOverloading) {
7064 // Not enough arguments.
7065 Candidate.Viable = false;
7067 return;
7068 }
7069
7070 // (CUDA B.1): Check for invalid calls between targets.
7071 if (getLangOpts().CUDA) {
7072 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7073 // Skip the check for callers that are implicit members, because in this
7074 // case we may not yet know what the member's target is; the target is
7075 // inferred for the member automatically, based on the bases and fields of
7076 // the class.
7077 if (!(Caller && Caller->isImplicit()) &&
7078 !CUDA().IsAllowedCall(Caller, Function)) {
7079 Candidate.Viable = false;
7080 Candidate.FailureKind = ovl_fail_bad_target;
7081 return;
7082 }
7083 }
7084
7085 if (Function->getTrailingRequiresClause()) {
7086 ConstraintSatisfaction Satisfaction;
7087 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7088 /*ForOverloadResolution*/ true) ||
7089 !Satisfaction.IsSatisfied) {
7090 Candidate.Viable = false;
7092 return;
7093 }
7094 }
7095
7096 // Determine the implicit conversion sequences for each of the
7097 // arguments.
7098 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7099 unsigned ConvIdx =
7100 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7101 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7102 // We already formed a conversion sequence for this parameter during
7103 // template argument deduction.
7104 } else if (ArgIdx < NumParams) {
7105 // (C++ 13.3.2p3): for F to be a viable function, there shall
7106 // exist for each argument an implicit conversion sequence
7107 // (13.3.3.1) that converts that argument to the corresponding
7108 // parameter of F.
7109 QualType ParamType = Proto->getParamType(ArgIdx);
7110 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7111 if (ParamABI == ParameterABI::HLSLOut ||
7112 ParamABI == ParameterABI::HLSLInOut)
7113 ParamType = ParamType.getNonReferenceType();
7114 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7115 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7116 /*InOverloadResolution=*/true,
7117 /*AllowObjCWritebackConversion=*/
7118 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7119 if (Candidate.Conversions[ConvIdx].isBad()) {
7120 Candidate.Viable = false;
7122 return;
7123 }
7124 } else {
7125 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7126 // argument for which there is no corresponding parameter is
7127 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7128 Candidate.Conversions[ConvIdx].setEllipsis();
7129 }
7130 }
7131
7132 if (EnableIfAttr *FailedAttr =
7133 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7134 Candidate.Viable = false;
7135 Candidate.FailureKind = ovl_fail_enable_if;
7136 Candidate.DeductionFailure.Data = FailedAttr;
7137 return;
7138 }
7139}
7140
7144 if (Methods.size() <= 1)
7145 return nullptr;
7146
7147 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7148 bool Match = true;
7149 ObjCMethodDecl *Method = Methods[b];
7150 unsigned NumNamedArgs = Sel.getNumArgs();
7151 // Method might have more arguments than selector indicates. This is due
7152 // to addition of c-style arguments in method.
7153 if (Method->param_size() > NumNamedArgs)
7154 NumNamedArgs = Method->param_size();
7155 if (Args.size() < NumNamedArgs)
7156 continue;
7157
7158 for (unsigned i = 0; i < NumNamedArgs; i++) {
7159 // We can't do any type-checking on a type-dependent argument.
7160 if (Args[i]->isTypeDependent()) {
7161 Match = false;
7162 break;
7163 }
7164
7165 ParmVarDecl *param = Method->parameters()[i];
7166 Expr *argExpr = Args[i];
7167 assert(argExpr && "SelectBestMethod(): missing expression");
7168
7169 // Strip the unbridged-cast placeholder expression off unless it's
7170 // a consumed argument.
7171 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7172 !param->hasAttr<CFConsumedAttr>())
7173 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7174
7175 // If the parameter is __unknown_anytype, move on to the next method.
7176 if (param->getType() == Context.UnknownAnyTy) {
7177 Match = false;
7178 break;
7179 }
7180
7181 ImplicitConversionSequence ConversionState
7182 = TryCopyInitialization(*this, argExpr, param->getType(),
7183 /*SuppressUserConversions*/false,
7184 /*InOverloadResolution=*/true,
7185 /*AllowObjCWritebackConversion=*/
7186 getLangOpts().ObjCAutoRefCount,
7187 /*AllowExplicit*/false);
7188 // This function looks for a reasonably-exact match, so we consider
7189 // incompatible pointer conversions to be a failure here.
7190 if (ConversionState.isBad() ||
7191 (ConversionState.isStandard() &&
7192 ConversionState.Standard.Second ==
7194 Match = false;
7195 break;
7196 }
7197 }
7198 // Promote additional arguments to variadic methods.
7199 if (Match && Method->isVariadic()) {
7200 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7201 if (Args[i]->isTypeDependent()) {
7202 Match = false;
7203 break;
7204 }
7205 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
7206 nullptr);
7207 if (Arg.isInvalid()) {
7208 Match = false;
7209 break;
7210 }
7211 }
7212 } else {
7213 // Check for extra arguments to non-variadic methods.
7214 if (Args.size() != NumNamedArgs)
7215 Match = false;
7216 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7217 // Special case when selectors have no argument. In this case, select
7218 // one with the most general result type of 'id'.
7219 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7220 QualType ReturnT = Methods[b]->getReturnType();
7221 if (ReturnT->isObjCIdType())
7222 return Methods[b];
7223 }
7224 }
7225 }
7226
7227 if (Match)
7228 return Method;
7229 }
7230 return nullptr;
7231}
7232
7234 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7235 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7236 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7237 if (ThisArg) {
7238 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7239 assert(!isa<CXXConstructorDecl>(Method) &&
7240 "Shouldn't have `this` for ctors!");
7241 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7243 ThisArg, /*Qualifier=*/nullptr, Method, Method);
7244 if (R.isInvalid())
7245 return false;
7246 ConvertedThis = R.get();
7247 } else {
7248 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7249 (void)MD;
7250 assert((MissingImplicitThis || MD->isStatic() ||
7251 isa<CXXConstructorDecl>(MD)) &&
7252 "Expected `this` for non-ctor instance methods");
7253 }
7254 ConvertedThis = nullptr;
7255 }
7256
7257 // Ignore any variadic arguments. Converting them is pointless, since the
7258 // user can't refer to them in the function condition.
7259 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7260
7261 // Convert the arguments.
7262 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7263 ExprResult R;
7265 S.Context, Function->getParamDecl(I)),
7266 SourceLocation(), Args[I]);
7267
7268 if (R.isInvalid())
7269 return false;
7270
7271 ConvertedArgs.push_back(R.get());
7272 }
7273
7274 if (Trap.hasErrorOccurred())
7275 return false;
7276
7277 // Push default arguments if needed.
7278 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7279 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7280 ParmVarDecl *P = Function->getParamDecl(i);
7281 if (!P->hasDefaultArg())
7282 return false;
7284 if (R.isInvalid())
7285 return false;
7286 ConvertedArgs.push_back(R.get());
7287 }
7288
7289 if (Trap.hasErrorOccurred())
7290 return false;
7291 }
7292 return true;
7293}
7294
7296 SourceLocation CallLoc,
7297 ArrayRef<Expr *> Args,
7298 bool MissingImplicitThis) {
7299 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7300 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7301 return nullptr;
7302
7303 SFINAETrap Trap(*this);
7304 SmallVector<Expr *, 16> ConvertedArgs;
7305 // FIXME: We should look into making enable_if late-parsed.
7306 Expr *DiscardedThis;
7308 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7309 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7310 return *EnableIfAttrs.begin();
7311
7312 for (auto *EIA : EnableIfAttrs) {
7314 // FIXME: This doesn't consider value-dependent cases, because doing so is
7315 // very difficult. Ideally, we should handle them more gracefully.
7316 if (EIA->getCond()->isValueDependent() ||
7317 !EIA->getCond()->EvaluateWithSubstitution(
7318 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7319 return EIA;
7320
7321 if (!Result.isInt() || !Result.getInt().getBoolValue())
7322 return EIA;
7323 }
7324 return nullptr;
7325}
7326
7327template <typename CheckFn>
7329 bool ArgDependent, SourceLocation Loc,
7330 CheckFn &&IsSuccessful) {
7332 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7333 if (ArgDependent == DIA->getArgDependent())
7334 Attrs.push_back(DIA);
7335 }
7336
7337 // Common case: No diagnose_if attributes, so we can quit early.
7338 if (Attrs.empty())
7339 return false;
7340
7341 auto WarningBegin = std::stable_partition(
7342 Attrs.begin(), Attrs.end(),
7343 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
7344
7345 // Note that diagnose_if attributes are late-parsed, so they appear in the
7346 // correct order (unlike enable_if attributes).
7347 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7348 IsSuccessful);
7349 if (ErrAttr != WarningBegin) {
7350 const DiagnoseIfAttr *DIA = *ErrAttr;
7351 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7352 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7353 << DIA->getParent() << DIA->getCond()->getSourceRange();
7354 return true;
7355 }
7356
7357 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7358 if (IsSuccessful(DIA)) {
7359 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7360 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7361 << DIA->getParent() << DIA->getCond()->getSourceRange();
7362 }
7363
7364 return false;
7365}
7366
7368 const Expr *ThisArg,
7370 SourceLocation Loc) {
7372 *this, Function, /*ArgDependent=*/true, Loc,
7373 [&](const DiagnoseIfAttr *DIA) {
7375 // It's sane to use the same Args for any redecl of this function, since
7376 // EvaluateWithSubstitution only cares about the position of each
7377 // argument in the arg list, not the ParmVarDecl* it maps to.
7378 if (!DIA->getCond()->EvaluateWithSubstitution(
7379 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7380 return false;
7381 return Result.isInt() && Result.getInt().getBoolValue();
7382 });
7383}
7384
7386 SourceLocation Loc) {
7388 *this, ND, /*ArgDependent=*/false, Loc,
7389 [&](const DiagnoseIfAttr *DIA) {
7390 bool Result;
7391 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7392 Result;
7393 });
7394}
7395
7397 ArrayRef<Expr *> Args,
7398 OverloadCandidateSet &CandidateSet,
7399 TemplateArgumentListInfo *ExplicitTemplateArgs,
7400 bool SuppressUserConversions,
7401 bool PartialOverloading,
7402 bool FirstArgumentIsBase) {
7403 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7404 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7405 ArrayRef<Expr *> FunctionArgs = Args;
7406
7407 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7408 FunctionDecl *FD =
7409 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7410
7411 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7412 QualType ObjectType;
7413 Expr::Classification ObjectClassification;
7414 if (Args.size() > 0) {
7415 if (Expr *E = Args[0]) {
7416 // Use the explicit base to restrict the lookup:
7417 ObjectType = E->getType();
7418 // Pointers in the object arguments are implicitly dereferenced, so we
7419 // always classify them as l-values.
7420 if (!ObjectType.isNull() && ObjectType->isPointerType())
7421 ObjectClassification = Expr::Classification::makeSimpleLValue();
7422 else
7423 ObjectClassification = E->Classify(Context);
7424 } // .. else there is an implicit base.
7425 FunctionArgs = Args.slice(1);
7426 }
7427 if (FunTmpl) {
7428 AddMethodTemplateCandidate(
7429 FunTmpl, F.getPair(),
7430 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
7431 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7432 FunctionArgs, CandidateSet, SuppressUserConversions,
7433 PartialOverloading);
7434 } else {
7435 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7436 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7437 ObjectClassification, FunctionArgs, CandidateSet,
7438 SuppressUserConversions, PartialOverloading);
7439 }
7440 } else {
7441 // This branch handles both standalone functions and static methods.
7442
7443 // Slice the first argument (which is the base) when we access
7444 // static method as non-static.
7445 if (Args.size() > 0 &&
7446 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7447 !isa<CXXConstructorDecl>(FD)))) {
7448 assert(cast<CXXMethodDecl>(FD)->isStatic());
7449 FunctionArgs = Args.slice(1);
7450 }
7451 if (FunTmpl) {
7452 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7453 ExplicitTemplateArgs, FunctionArgs,
7454 CandidateSet, SuppressUserConversions,
7455 PartialOverloading);
7456 } else {
7457 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7458 SuppressUserConversions, PartialOverloading);
7459 }
7460 }
7461 }
7462}
7463
7465 Expr::Classification ObjectClassification,
7466 ArrayRef<Expr *> Args,
7467 OverloadCandidateSet &CandidateSet,
7468 bool SuppressUserConversions,
7470 NamedDecl *Decl = FoundDecl.getDecl();
7471 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
7472
7473 if (isa<UsingShadowDecl>(Decl))
7474 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7475
7476 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7477 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7478 "Expected a member function template");
7479 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7480 /*ExplicitArgs*/ nullptr, ObjectType,
7481 ObjectClassification, Args, CandidateSet,
7482 SuppressUserConversions, false, PO);
7483 } else {
7484 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7485 ObjectType, ObjectClassification, Args, CandidateSet,
7486 SuppressUserConversions, false, {}, PO);
7487 }
7488}
7489
7490void
7492 CXXRecordDecl *ActingContext, QualType ObjectType,
7493 Expr::Classification ObjectClassification,
7494 ArrayRef<Expr *> Args,
7495 OverloadCandidateSet &CandidateSet,
7496 bool SuppressUserConversions,
7497 bool PartialOverloading,
7498 ConversionSequenceList EarlyConversions,
7500 const FunctionProtoType *Proto
7501 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7502 assert(Proto && "Methods without a prototype cannot be overloaded");
7503 assert(!isa<CXXConstructorDecl>(Method) &&
7504 "Use AddOverloadCandidate for constructors");
7505
7506 if (!CandidateSet.isNewCandidate(Method, PO))
7507 return;
7508
7509 // C++11 [class.copy]p23: [DR1402]
7510 // A defaulted move assignment operator that is defined as deleted is
7511 // ignored by overload resolution.
7512 if (Method->isDefaulted() && Method->isDeleted() &&
7513 Method->isMoveAssignmentOperator())
7514 return;
7515
7516 // Overload resolution is always an unevaluated context.
7519
7520 // Add this candidate
7521 OverloadCandidate &Candidate =
7522 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
7523 Candidate.FoundDecl = FoundDecl;
7524 Candidate.Function = Method;
7525 Candidate.RewriteKind =
7526 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7527 Candidate.TookAddressOfOverload =
7529 Candidate.ExplicitCallArguments = Args.size();
7530
7531 bool IgnoreExplicitObject =
7532 (Method->isExplicitObjectMemberFunction() &&
7533 CandidateSet.getKind() ==
7535 bool ImplicitObjectMethodTreatedAsStatic =
7536 CandidateSet.getKind() ==
7539
7540 unsigned ExplicitOffset =
7541 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7542
7543 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7544 int(ImplicitObjectMethodTreatedAsStatic);
7545
7546 // (C++ 13.3.2p2): A candidate function having fewer than m
7547 // parameters is viable only if it has an ellipsis in its parameter
7548 // list (8.3.5).
7549 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7550 !Proto->isVariadic() &&
7551 shouldEnforceArgLimit(PartialOverloading, Method)) {
7552 Candidate.Viable = false;
7554 return;
7555 }
7556
7557 // (C++ 13.3.2p2): A candidate function having more than m parameters
7558 // is viable only if the (m+1)st parameter has a default argument
7559 // (8.3.6). For the purposes of overload resolution, the
7560 // parameter list is truncated on the right, so that there are
7561 // exactly m parameters.
7562 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7563 ExplicitOffset +
7564 int(ImplicitObjectMethodTreatedAsStatic);
7565
7566 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7567 // Not enough arguments.
7568 Candidate.Viable = false;
7570 return;
7571 }
7572
7573 Candidate.Viable = true;
7574
7575 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7576 if (ObjectType.isNull())
7577 Candidate.IgnoreObjectArgument = true;
7578 else if (Method->isStatic()) {
7579 // [over.best.ics.general]p8
7580 // When the parameter is the implicit object parameter of a static member
7581 // function, the implicit conversion sequence is a standard conversion
7582 // sequence that is neither better nor worse than any other standard
7583 // conversion sequence.
7584 //
7585 // This is a rule that was introduced in C++23 to support static lambdas. We
7586 // apply it retroactively because we want to support static lambdas as an
7587 // extension and it doesn't hurt previous code.
7588 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7589 } else {
7590 // Determine the implicit conversion sequence for the object
7591 // parameter.
7592 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7593 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7594 Method, ActingContext, /*InOverloadResolution=*/true);
7595 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7596 Candidate.Viable = false;
7598 return;
7599 }
7600 }
7601
7602 // (CUDA B.1): Check for invalid calls between targets.
7603 if (getLangOpts().CUDA)
7604 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
7605 Method)) {
7606 Candidate.Viable = false;
7607 Candidate.FailureKind = ovl_fail_bad_target;
7608 return;
7609 }
7610
7611 if (Method->getTrailingRequiresClause()) {
7612 ConstraintSatisfaction Satisfaction;
7613 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7614 /*ForOverloadResolution*/ true) ||
7615 !Satisfaction.IsSatisfied) {
7616 Candidate.Viable = false;
7618 return;
7619 }
7620 }
7621
7622 // Determine the implicit conversion sequences for each of the
7623 // arguments.
7624 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7625 unsigned ConvIdx =
7626 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7627 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7628 // We already formed a conversion sequence for this parameter during
7629 // template argument deduction.
7630 } else if (ArgIdx < NumParams) {
7631 // (C++ 13.3.2p3): for F to be a viable function, there shall
7632 // exist for each argument an implicit conversion sequence
7633 // (13.3.3.1) that converts that argument to the corresponding
7634 // parameter of F.
7635 QualType ParamType;
7636 if (ImplicitObjectMethodTreatedAsStatic) {
7637 ParamType = ArgIdx == 0
7639 : Proto->getParamType(ArgIdx - 1);
7640 } else {
7641 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
7642 }
7643 Candidate.Conversions[ConvIdx]
7644 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7645 SuppressUserConversions,
7646 /*InOverloadResolution=*/true,
7647 /*AllowObjCWritebackConversion=*/
7648 getLangOpts().ObjCAutoRefCount);
7649 if (Candidate.Conversions[ConvIdx].isBad()) {
7650 Candidate.Viable = false;
7652 return;
7653 }
7654 } else {
7655 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7656 // argument for which there is no corresponding parameter is
7657 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7658 Candidate.Conversions[ConvIdx].setEllipsis();
7659 }
7660 }
7661
7662 if (EnableIfAttr *FailedAttr =
7663 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7664 Candidate.Viable = false;
7665 Candidate.FailureKind = ovl_fail_enable_if;
7666 Candidate.DeductionFailure.Data = FailedAttr;
7667 return;
7668 }
7669
7670 if (isNonViableMultiVersionOverload(Method)) {
7671 Candidate.Viable = false;
7673 }
7674}
7675
7677 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7678 CXXRecordDecl *ActingContext,
7679 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7680 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7681 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7682 bool PartialOverloading, OverloadCandidateParamOrder PO) {
7683 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7684 return;
7685
7686 // C++ [over.match.funcs]p7:
7687 // In each case where a candidate is a function template, candidate
7688 // function template specializations are generated using template argument
7689 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7690 // candidate functions in the usual way.113) A given name can refer to one
7691 // or more function templates and also to a set of overloaded non-template
7692 // functions. In such a case, the candidate functions generated from each
7693 // function template are combined with the set of non-template candidate
7694 // functions.
7695 TemplateDeductionInfo Info(CandidateSet.getLocation());
7696 FunctionDecl *Specialization = nullptr;
7697 ConversionSequenceList Conversions;
7699 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7700 PartialOverloading, /*AggregateDeductionCandidate=*/false, ObjectType,
7701 ObjectClassification,
7702 [&](ArrayRef<QualType> ParamTypes) {
7703 return CheckNonDependentConversions(
7704 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7705 SuppressUserConversions, ActingContext, ObjectType,
7706 ObjectClassification, PO);
7707 });
7709 OverloadCandidate &Candidate =
7710 CandidateSet.addCandidate(Conversions.size(), Conversions);
7711 Candidate.FoundDecl = FoundDecl;
7712 Candidate.Function = MethodTmpl->getTemplatedDecl();
7713 Candidate.Viable = false;
7714 Candidate.RewriteKind =
7715 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7716 Candidate.IsSurrogate = false;
7717 Candidate.IgnoreObjectArgument =
7718 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7719 ObjectType.isNull();
7720 Candidate.ExplicitCallArguments = Args.size();
7723 else {
7726 Info);
7727 }
7728 return;
7729 }
7730
7731 // Add the function template specialization produced by template argument
7732 // deduction as a candidate.
7733 assert(Specialization && "Missing member function template specialization?");
7734 assert(isa<CXXMethodDecl>(Specialization) &&
7735 "Specialization is not a member function?");
7736 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7737 ActingContext, ObjectType, ObjectClassification, Args,
7738 CandidateSet, SuppressUserConversions, PartialOverloading,
7739 Conversions, PO);
7740}
7741
7742/// Determine whether a given function template has a simple explicit specifier
7743/// or a non-value-dependent explicit-specification that evaluates to true.
7746}
7747
7749 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7750 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7751 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7752 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7753 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
7754 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7755 return;
7756
7757 // If the function template has a non-dependent explicit specification,
7758 // exclude it now if appropriate; we are not permitted to perform deduction
7759 // and substitution in this case.
7760 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7761 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7762 Candidate.FoundDecl = FoundDecl;
7763 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7764 Candidate.Viable = false;
7765 Candidate.FailureKind = ovl_fail_explicit;
7766 return;
7767 }
7768
7769 // C++ [over.match.funcs]p7:
7770 // In each case where a candidate is a function template, candidate
7771 // function template specializations are generated using template argument
7772 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7773 // candidate functions in the usual way.113) A given name can refer to one
7774 // or more function templates and also to a set of overloaded non-template
7775 // functions. In such a case, the candidate functions generated from each
7776 // function template are combined with the set of non-template candidate
7777 // functions.
7778 TemplateDeductionInfo Info(CandidateSet.getLocation(),
7779 FunctionTemplate->getTemplateDepth());
7780 FunctionDecl *Specialization = nullptr;
7781 ConversionSequenceList Conversions;
7783 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7784 PartialOverloading, AggregateCandidateDeduction,
7785 /*ObjectType=*/QualType(),
7786 /*ObjectClassification=*/Expr::Classification(),
7787 [&](ArrayRef<QualType> ParamTypes) {
7788 return CheckNonDependentConversions(
7789 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7790 SuppressUserConversions, nullptr, QualType(), {}, PO);
7791 });
7793 OverloadCandidate &Candidate =
7794 CandidateSet.addCandidate(Conversions.size(), Conversions);
7795 Candidate.FoundDecl = FoundDecl;
7796 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7797 Candidate.Viable = false;
7798 Candidate.RewriteKind =
7799 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7800 Candidate.IsSurrogate = false;
7801 Candidate.IsADLCandidate = IsADLCandidate;
7802 // Ignore the object argument if there is one, since we don't have an object
7803 // type.
7804 Candidate.IgnoreObjectArgument =
7805 isa<CXXMethodDecl>(Candidate.Function) &&
7806 !isa<CXXConstructorDecl>(Candidate.Function);
7807 Candidate.ExplicitCallArguments = Args.size();
7810 else {
7813 Info);
7814 }
7815 return;
7816 }
7817
7818 // Add the function template specialization produced by template argument
7819 // deduction as a candidate.
7820 assert(Specialization && "Missing function template specialization?");
7821 AddOverloadCandidate(
7822 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7823 PartialOverloading, AllowExplicit,
7824 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
7826}
7827
7829 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7830 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7831 ConversionSequenceList &Conversions, bool SuppressUserConversions,
7832 CXXRecordDecl *ActingContext, QualType ObjectType,
7833 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7834 // FIXME: The cases in which we allow explicit conversions for constructor
7835 // arguments never consider calling a constructor template. It's not clear
7836 // that is correct.
7837 const bool AllowExplicit = false;
7838
7839 auto *FD = FunctionTemplate->getTemplatedDecl();
7840 auto *Method = dyn_cast<CXXMethodDecl>(FD);
7841 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7842 unsigned ThisConversions = HasThisConversion ? 1 : 0;
7843
7844 Conversions =
7845 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7846
7847 // Overload resolution is always an unevaluated context.
7850
7851 // For a method call, check the 'this' conversion here too. DR1391 doesn't
7852 // require that, but this check should never result in a hard error, and
7853 // overload resolution is permitted to sidestep instantiations.
7854 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7855 !ObjectType.isNull()) {
7856 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7857 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
7858 !ParamTypes[0]->isDependentType()) {
7859 Conversions[ConvIdx] = TryObjectArgumentInitialization(
7860 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7861 Method, ActingContext, /*InOverloadResolution=*/true,
7862 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
7863 : QualType());
7864 if (Conversions[ConvIdx].isBad())
7865 return true;
7866 }
7867 }
7868
7869 unsigned Offset =
7870 Method && Method->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
7871
7872 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
7873 I != N; ++I) {
7874 QualType ParamType = ParamTypes[I + Offset];
7875 if (!ParamType->isDependentType()) {
7876 unsigned ConvIdx;
7878 ConvIdx = Args.size() - 1 - I;
7879 assert(Args.size() + ThisConversions == 2 &&
7880 "number of args (including 'this') must be exactly 2 for "
7881 "reversed order");
7882 // For members, there would be only one arg 'Args[0]' whose ConvIdx
7883 // would also be 0. 'this' got ConvIdx = 1 previously.
7884 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
7885 } else {
7886 // For members, 'this' got ConvIdx = 0 previously.
7887 ConvIdx = ThisConversions + I;
7888 }
7889 Conversions[ConvIdx]
7890 = TryCopyInitialization(*this, Args[I], ParamType,
7891 SuppressUserConversions,
7892 /*InOverloadResolution=*/true,
7893 /*AllowObjCWritebackConversion=*/
7894 getLangOpts().ObjCAutoRefCount,
7895 AllowExplicit);
7896 if (Conversions[ConvIdx].isBad())
7897 return true;
7898 }
7899 }
7900
7901 return false;
7902}
7903
7904/// Determine whether this is an allowable conversion from the result
7905/// of an explicit conversion operator to the expected type, per C++
7906/// [over.match.conv]p1 and [over.match.ref]p1.
7907///
7908/// \param ConvType The return type of the conversion function.
7909///
7910/// \param ToType The type we are converting to.
7911///
7912/// \param AllowObjCPointerConversion Allow a conversion from one
7913/// Objective-C pointer to another.
7914///
7915/// \returns true if the conversion is allowable, false otherwise.
7917 QualType ConvType, QualType ToType,
7918 bool AllowObjCPointerConversion) {
7919 QualType ToNonRefType = ToType.getNonReferenceType();
7920
7921 // Easy case: the types are the same.
7922 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7923 return true;
7924
7925 // Allow qualification conversions.
7926 bool ObjCLifetimeConversion;
7927 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7928 ObjCLifetimeConversion))
7929 return true;
7930
7931 // If we're not allowed to consider Objective-C pointer conversions,
7932 // we're done.
7933 if (!AllowObjCPointerConversion)
7934 return false;
7935
7936 // Is this an Objective-C pointer conversion?
7937 bool IncompatibleObjC = false;
7938 QualType ConvertedType;
7939 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7940 IncompatibleObjC);
7941}
7942
7944 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7945 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7946 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7947 bool AllowExplicit, bool AllowResultConversion) {
7948 assert(!Conversion->getDescribedFunctionTemplate() &&
7949 "Conversion function templates use AddTemplateConversionCandidate");
7950 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7951 if (!CandidateSet.isNewCandidate(Conversion))
7952 return;
7953
7954 // If the conversion function has an undeduced return type, trigger its
7955 // deduction now.
7956 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7957 if (DeduceReturnType(Conversion, From->getExprLoc()))
7958 return;
7959 ConvType = Conversion->getConversionType().getNonReferenceType();
7960 }
7961
7962 // If we don't allow any conversion of the result type, ignore conversion
7963 // functions that don't convert to exactly (possibly cv-qualified) T.
7964 if (!AllowResultConversion &&
7965 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7966 return;
7967
7968 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7969 // operator is only a candidate if its return type is the target type or
7970 // can be converted to the target type with a qualification conversion.
7971 //
7972 // FIXME: Include such functions in the candidate list and explain why we
7973 // can't select them.
7974 if (Conversion->isExplicit() &&
7975 !isAllowableExplicitConversion(*this, ConvType, ToType,
7976 AllowObjCConversionOnExplicit))
7977 return;
7978
7979 // Overload resolution is always an unevaluated context.
7982
7983 // Add this candidate
7984 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7985 Candidate.FoundDecl = FoundDecl;
7986 Candidate.Function = Conversion;
7988 Candidate.FinalConversion.setFromType(ConvType);
7989 Candidate.FinalConversion.setAllToTypes(ToType);
7990 Candidate.Viable = true;
7991 Candidate.ExplicitCallArguments = 1;
7992
7993 // Explicit functions are not actually candidates at all if we're not
7994 // allowing them in this context, but keep them around so we can point
7995 // to them in diagnostics.
7996 if (!AllowExplicit && Conversion->isExplicit()) {
7997 Candidate.Viable = false;
7998 Candidate.FailureKind = ovl_fail_explicit;
7999 return;
8000 }
8001
8002 // C++ [over.match.funcs]p4:
8003 // For conversion functions, the function is considered to be a member of
8004 // the class of the implicit implied object argument for the purpose of
8005 // defining the type of the implicit object parameter.
8006 //
8007 // Determine the implicit conversion sequence for the implicit
8008 // object parameter.
8009 QualType ObjectType = From->getType();
8010 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8011 ObjectType = FromPtrType->getPointeeType();
8012 const auto *ConversionContext =
8013 cast<CXXRecordDecl>(ObjectType->castAs<RecordType>()->getDecl());
8014
8015 // C++23 [over.best.ics.general]
8016 // However, if the target is [...]
8017 // - the object parameter of a user-defined conversion function
8018 // [...] user-defined conversion sequences are not considered.
8020 *this, CandidateSet.getLocation(), From->getType(),
8021 From->Classify(Context), Conversion, ConversionContext,
8022 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8023 /*SuppressUserConversion*/ true);
8024
8025 if (Candidate.Conversions[0].isBad()) {
8026 Candidate.Viable = false;
8028 return;
8029 }
8030
8031 if (Conversion->getTrailingRequiresClause()) {
8032 ConstraintSatisfaction Satisfaction;
8033 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8034 !Satisfaction.IsSatisfied) {
8035 Candidate.Viable = false;
8037 return;
8038 }
8039 }
8040
8041 // We won't go through a user-defined type conversion function to convert a
8042 // derived to base as such conversions are given Conversion Rank. They only
8043 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8044 QualType FromCanon
8045 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8046 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8047 if (FromCanon == ToCanon ||
8048 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8049 Candidate.Viable = false;
8051 return;
8052 }
8053
8054 // To determine what the conversion from the result of calling the
8055 // conversion function to the type we're eventually trying to
8056 // convert to (ToType), we need to synthesize a call to the
8057 // conversion function and attempt copy initialization from it. This
8058 // makes sure that we get the right semantics with respect to
8059 // lvalues/rvalues and the type. Fortunately, we can allocate this
8060 // call on the stack and we don't need its arguments to be
8061 // well-formed.
8062 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8063 VK_LValue, From->getBeginLoc());
8065 Context.getPointerType(Conversion->getType()),
8066 CK_FunctionToPointerDecay, &ConversionRef,
8068
8069 QualType ConversionType = Conversion->getConversionType();
8070 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8071 Candidate.Viable = false;
8073 return;
8074 }
8075
8076 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8077
8078 // Note that it is safe to allocate CallExpr on the stack here because
8079 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
8080 // allocator).
8081 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8082
8083 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
8084 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
8085 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
8086
8088 TryCopyInitialization(*this, TheTemporaryCall, ToType,
8089 /*SuppressUserConversions=*/true,
8090 /*InOverloadResolution=*/false,
8091 /*AllowObjCWritebackConversion=*/false);
8092
8093 switch (ICS.getKind()) {
8095 Candidate.FinalConversion = ICS.Standard;
8096
8097 // C++ [over.ics.user]p3:
8098 // If the user-defined conversion is specified by a specialization of a
8099 // conversion function template, the second standard conversion sequence
8100 // shall have exact match rank.
8101 if (Conversion->getPrimaryTemplate() &&
8103 Candidate.Viable = false;
8105 return;
8106 }
8107
8108 // C++0x [dcl.init.ref]p5:
8109 // In the second case, if the reference is an rvalue reference and
8110 // the second standard conversion sequence of the user-defined
8111 // conversion sequence includes an lvalue-to-rvalue conversion, the
8112 // program is ill-formed.
8113 if (ToType->isRValueReferenceType() &&
8115 Candidate.Viable = false;
8117 return;
8118 }
8119 break;
8120
8122 Candidate.Viable = false;
8124 return;
8125
8126 default:
8127 llvm_unreachable(
8128 "Can only end up with a standard conversion sequence or failure");
8129 }
8130
8131 if (EnableIfAttr *FailedAttr =
8132 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8133 Candidate.Viable = false;
8134 Candidate.FailureKind = ovl_fail_enable_if;
8135 Candidate.DeductionFailure.Data = FailedAttr;
8136 return;
8137 }
8138
8139 if (isNonViableMultiVersionOverload(Conversion)) {
8140 Candidate.Viable = false;
8142 }
8143}
8144
8146 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8147 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8148 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8149 bool AllowExplicit, bool AllowResultConversion) {
8150 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8151 "Only conversion function templates permitted here");
8152
8153 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8154 return;
8155
8156 // If the function template has a non-dependent explicit specification,
8157 // exclude it now if appropriate; we are not permitted to perform deduction
8158 // and substitution in this case.
8159 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8160 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8161 Candidate.FoundDecl = FoundDecl;
8162 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8163 Candidate.Viable = false;
8164 Candidate.FailureKind = ovl_fail_explicit;
8165 return;
8166 }
8167
8168 QualType ObjectType = From->getType();
8169 Expr::Classification ObjectClassification = From->Classify(getASTContext());
8170
8171 TemplateDeductionInfo Info(CandidateSet.getLocation());
8174 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8175 Specialization, Info);
8177 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8178 Candidate.FoundDecl = FoundDecl;
8179 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8180 Candidate.Viable = false;
8182 Candidate.ExplicitCallArguments = 1;
8184 Info);
8185 return;
8186 }
8187
8188 // Add the conversion function template specialization produced by
8189 // template argument deduction as a candidate.
8190 assert(Specialization && "Missing function template specialization?");
8191 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
8192 CandidateSet, AllowObjCConversionOnExplicit,
8193 AllowExplicit, AllowResultConversion);
8194}
8195
8197 DeclAccessPair FoundDecl,
8198 CXXRecordDecl *ActingContext,
8199 const FunctionProtoType *Proto,
8200 Expr *Object,
8201 ArrayRef<Expr *> Args,
8202 OverloadCandidateSet& CandidateSet) {
8203 if (!CandidateSet.isNewCandidate(Conversion))
8204 return;
8205
8206 // Overload resolution is always an unevaluated context.
8209
8210 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8211 Candidate.FoundDecl = FoundDecl;
8212 Candidate.Function = nullptr;
8213 Candidate.Surrogate = Conversion;
8214 Candidate.IsSurrogate = true;
8215 Candidate.Viable = true;
8216 Candidate.ExplicitCallArguments = Args.size();
8217
8218 // Determine the implicit conversion sequence for the implicit
8219 // object parameter.
8220 ImplicitConversionSequence ObjectInit;
8221 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8222 ObjectInit = TryCopyInitialization(*this, Object,
8223 Conversion->getParamDecl(0)->getType(),
8224 /*SuppressUserConversions=*/false,
8225 /*InOverloadResolution=*/true, false);
8226 } else {
8228 *this, CandidateSet.getLocation(), Object->getType(),
8229 Object->Classify(Context), Conversion, ActingContext);
8230 }
8231
8232 if (ObjectInit.isBad()) {
8233 Candidate.Viable = false;
8235 Candidate.Conversions[0] = ObjectInit;
8236 return;
8237 }
8238
8239 // The first conversion is actually a user-defined conversion whose
8240 // first conversion is ObjectInit's standard conversion (which is
8241 // effectively a reference binding). Record it as such.
8242 Candidate.Conversions[0].setUserDefined();
8243 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8244 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8245 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8246 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8247 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8248 Candidate.Conversions[0].UserDefined.After
8249 = Candidate.Conversions[0].UserDefined.Before;
8250 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8251
8252 // Find the
8253 unsigned NumParams = Proto->getNumParams();
8254
8255 // (C++ 13.3.2p2): A candidate function having fewer than m
8256 // parameters is viable only if it has an ellipsis in its parameter
8257 // list (8.3.5).
8258 if (Args.size() > NumParams && !Proto->isVariadic()) {
8259 Candidate.Viable = false;
8261 return;
8262 }
8263
8264 // Function types don't have any default arguments, so just check if
8265 // we have enough arguments.
8266 if (Args.size() < NumParams) {
8267 // Not enough arguments.
8268 Candidate.Viable = false;
8270 return;
8271 }
8272
8273 // Determine the implicit conversion sequences for each of the
8274 // arguments.
8275 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8276 if (ArgIdx < NumParams) {
8277 // (C++ 13.3.2p3): for F to be a viable function, there shall
8278 // exist for each argument an implicit conversion sequence
8279 // (13.3.3.1) that converts that argument to the corresponding
8280 // parameter of F.
8281 QualType ParamType = Proto->getParamType(ArgIdx);
8282 Candidate.Conversions[ArgIdx + 1]
8283 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8284 /*SuppressUserConversions=*/false,
8285 /*InOverloadResolution=*/false,
8286 /*AllowObjCWritebackConversion=*/
8287 getLangOpts().ObjCAutoRefCount);
8288 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8289 Candidate.Viable = false;
8291 return;
8292 }
8293 } else {
8294 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8295 // argument for which there is no corresponding parameter is
8296 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8297 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8298 }
8299 }
8300
8301 if (Conversion->getTrailingRequiresClause()) {
8302 ConstraintSatisfaction Satisfaction;
8303 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8304 /*ForOverloadResolution*/ true) ||
8305 !Satisfaction.IsSatisfied) {
8306 Candidate.Viable = false;
8308 return;
8309 }
8310 }
8311
8312 if (EnableIfAttr *FailedAttr =
8313 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8314 Candidate.Viable = false;
8315 Candidate.FailureKind = ovl_fail_enable_if;
8316 Candidate.DeductionFailure.Data = FailedAttr;
8317 return;
8318 }
8319}
8320
8322 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8323 OverloadCandidateSet &CandidateSet,
8324 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8325 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8326 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8327 ArrayRef<Expr *> FunctionArgs = Args;
8328
8329 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8330 FunctionDecl *FD =
8331 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8332
8333 // Don't consider rewritten functions if we're not rewriting.
8334 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8335 continue;
8336
8337 assert(!isa<CXXMethodDecl>(FD) &&
8338 "unqualified operator lookup found a member function");
8339
8340 if (FunTmpl) {
8341 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8342 FunctionArgs, CandidateSet);
8343 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8344 AddTemplateOverloadCandidate(
8345 FunTmpl, F.getPair(), ExplicitTemplateArgs,
8346 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
8347 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
8348 } else {
8349 if (ExplicitTemplateArgs)
8350 continue;
8351 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8352 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8353 AddOverloadCandidate(FD, F.getPair(),
8354 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8355 false, false, true, false, ADLCallKind::NotADL, {},
8357 }
8358 }
8359}
8360
8362 SourceLocation OpLoc,
8363 ArrayRef<Expr *> Args,
8364 OverloadCandidateSet &CandidateSet,
8367
8368 // C++ [over.match.oper]p3:
8369 // For a unary operator @ with an operand of a type whose
8370 // cv-unqualified version is T1, and for a binary operator @ with
8371 // a left operand of a type whose cv-unqualified version is T1 and
8372 // a right operand of a type whose cv-unqualified version is T2,
8373 // three sets of candidate functions, designated member
8374 // candidates, non-member candidates and built-in candidates, are
8375 // constructed as follows:
8376 QualType T1 = Args[0]->getType();
8377
8378 // -- If T1 is a complete class type or a class currently being
8379 // defined, the set of member candidates is the result of the
8380 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8381 // the set of member candidates is empty.
8382 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
8383 // Complete the type if it can be completed.
8384 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
8385 return;
8386 // If the type is neither complete nor being defined, bail out now.
8387 if (!T1Rec->getDecl()->getDefinition())
8388 return;
8389
8390 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8391 LookupQualifiedName(Operators, T1Rec->getDecl());
8392 Operators.suppressAccessDiagnostics();
8393
8394 for (LookupResult::iterator Oper = Operators.begin(),
8395 OperEnd = Operators.end();
8396 Oper != OperEnd; ++Oper) {
8397 if (Oper->getAsFunction() &&
8399 !CandidateSet.getRewriteInfo().shouldAddReversed(
8400 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8401 continue;
8402 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8403 Args[0]->Classify(Context), Args.slice(1),
8404 CandidateSet, /*SuppressUserConversion=*/false, PO);
8405 }
8406 }
8407}
8408
8410 OverloadCandidateSet& CandidateSet,
8411 bool IsAssignmentOperator,
8412 unsigned NumContextualBoolArguments) {
8413 // Overload resolution is always an unevaluated context.
8416
8417 // Add this candidate
8418 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8419 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8420 Candidate.Function = nullptr;
8421 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8422
8423 // Determine the implicit conversion sequences for each of the
8424 // arguments.
8425 Candidate.Viable = true;
8426 Candidate.ExplicitCallArguments = Args.size();
8427 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8428 // C++ [over.match.oper]p4:
8429 // For the built-in assignment operators, conversions of the
8430 // left operand are restricted as follows:
8431 // -- no temporaries are introduced to hold the left operand, and
8432 // -- no user-defined conversions are applied to the left
8433 // operand to achieve a type match with the left-most
8434 // parameter of a built-in candidate.
8435 //
8436 // We block these conversions by turning off user-defined
8437 // conversions, since that is the only way that initialization of
8438 // a reference to a non-class type can occur from something that
8439 // is not of the same type.
8440 if (ArgIdx < NumContextualBoolArguments) {
8441 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8442 "Contextual conversion to bool requires bool type");
8443 Candidate.Conversions[ArgIdx]
8444 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
8445 } else {
8446 Candidate.Conversions[ArgIdx]
8447 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
8448 ArgIdx == 0 && IsAssignmentOperator,
8449 /*InOverloadResolution=*/false,
8450 /*AllowObjCWritebackConversion=*/
8451 getLangOpts().ObjCAutoRefCount);
8452 }
8453 if (Candidate.Conversions[ArgIdx].isBad()) {
8454 Candidate.Viable = false;
8456 break;
8457 }
8458 }
8459}
8460
8461namespace {
8462
8463/// BuiltinCandidateTypeSet - A set of types that will be used for the
8464/// candidate operator functions for built-in operators (C++
8465/// [over.built]). The types are separated into pointer types and
8466/// enumeration types.
8467class BuiltinCandidateTypeSet {
8468 /// TypeSet - A set of types.
8469 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8470
8471 /// PointerTypes - The set of pointer types that will be used in the
8472 /// built-in candidates.
8473 TypeSet PointerTypes;
8474
8475 /// MemberPointerTypes - The set of member pointer types that will be
8476 /// used in the built-in candidates.
8477 TypeSet MemberPointerTypes;
8478
8479 /// EnumerationTypes - The set of enumeration types that will be
8480 /// used in the built-in candidates.
8481 TypeSet EnumerationTypes;
8482
8483 /// The set of vector types that will be used in the built-in
8484 /// candidates.
8485 TypeSet VectorTypes;
8486
8487 /// The set of matrix types that will be used in the built-in
8488 /// candidates.
8489 TypeSet MatrixTypes;
8490
8491 /// The set of _BitInt types that will be used in the built-in candidates.
8492 TypeSet BitIntTypes;
8493
8494 /// A flag indicating non-record types are viable candidates
8495 bool HasNonRecordTypes;
8496
8497 /// A flag indicating whether either arithmetic or enumeration types
8498 /// were present in the candidate set.
8499 bool HasArithmeticOrEnumeralTypes;
8500
8501 /// A flag indicating whether the nullptr type was present in the
8502 /// candidate set.
8503 bool HasNullPtrType;
8504
8505 /// Sema - The semantic analysis instance where we are building the
8506 /// candidate type set.
8507 Sema &SemaRef;
8508
8509 /// Context - The AST context in which we will build the type sets.
8510 ASTContext &Context;
8511
8512 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8513 const Qualifiers &VisibleQuals);
8514 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8515
8516public:
8517 /// iterator - Iterates through the types that are part of the set.
8518 typedef TypeSet::iterator iterator;
8519
8520 BuiltinCandidateTypeSet(Sema &SemaRef)
8521 : HasNonRecordTypes(false),
8522 HasArithmeticOrEnumeralTypes(false),
8523 HasNullPtrType(false),
8524 SemaRef(SemaRef),
8525 Context(SemaRef.Context) { }
8526
8527 void AddTypesConvertedFrom(QualType Ty,
8529 bool AllowUserConversions,
8530 bool AllowExplicitConversions,
8531 const Qualifiers &VisibleTypeConversionsQuals);
8532
8533 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8534 llvm::iterator_range<iterator> member_pointer_types() {
8535 return MemberPointerTypes;
8536 }
8537 llvm::iterator_range<iterator> enumeration_types() {
8538 return EnumerationTypes;
8539 }
8540 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8541 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8542 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8543
8544 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
8545 bool hasNonRecordTypes() { return HasNonRecordTypes; }
8546 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8547 bool hasNullPtrType() const { return HasNullPtrType; }
8548};
8549
8550} // end anonymous namespace
8551
8552/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8553/// the set of pointer types along with any more-qualified variants of
8554/// that type. For example, if @p Ty is "int const *", this routine
8555/// will add "int const *", "int const volatile *", "int const
8556/// restrict *", and "int const volatile restrict *" to the set of
8557/// pointer types. Returns true if the add of @p Ty itself succeeded,
8558/// false otherwise.
8559///
8560/// FIXME: what to do about extended qualifiers?
8561bool
8562BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8563 const Qualifiers &VisibleQuals) {
8564
8565 // Insert this type.
8566 if (!PointerTypes.insert(Ty))
8567 return false;
8568
8569 QualType PointeeTy;
8570 const PointerType *PointerTy = Ty->getAs<PointerType>();
8571 bool buildObjCPtr = false;
8572 if (!PointerTy) {
8574 PointeeTy = PTy->getPointeeType();
8575 buildObjCPtr = true;
8576 } else {
8577 PointeeTy = PointerTy->getPointeeType();
8578 }
8579
8580 // Don't add qualified variants of arrays. For one, they're not allowed
8581 // (the qualifier would sink to the element type), and for another, the
8582 // only overload situation where it matters is subscript or pointer +- int,
8583 // and those shouldn't have qualifier variants anyway.
8584 if (PointeeTy->isArrayType())
8585 return true;
8586
8587 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8588 bool hasVolatile = VisibleQuals.hasVolatile();
8589 bool hasRestrict = VisibleQuals.hasRestrict();
8590
8591 // Iterate through all strict supersets of BaseCVR.
8592 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8593 if ((CVR | BaseCVR) != CVR) continue;
8594 // Skip over volatile if no volatile found anywhere in the types.
8595 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8596
8597 // Skip over restrict if no restrict found anywhere in the types, or if
8598 // the type cannot be restrict-qualified.
8599 if ((CVR & Qualifiers::Restrict) &&
8600 (!hasRestrict ||
8601 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8602 continue;
8603
8604 // Build qualified pointee type.
8605 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8606
8607 // Build qualified pointer type.
8608 QualType QPointerTy;
8609 if (!buildObjCPtr)
8610 QPointerTy = Context.getPointerType(QPointeeTy);
8611 else
8612 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8613
8614 // Insert qualified pointer type.
8615 PointerTypes.insert(QPointerTy);
8616 }
8617
8618 return true;
8619}
8620
8621/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8622/// to the set of pointer types along with any more-qualified variants of
8623/// that type. For example, if @p Ty is "int const *", this routine
8624/// will add "int const *", "int const volatile *", "int const
8625/// restrict *", and "int const volatile restrict *" to the set of
8626/// pointer types. Returns true if the add of @p Ty itself succeeded,
8627/// false otherwise.
8628///
8629/// FIXME: what to do about extended qualifiers?
8630bool
8631BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8632 QualType Ty) {
8633 // Insert this type.
8634 if (!MemberPointerTypes.insert(Ty))
8635 return false;
8636
8637 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8638 assert(PointerTy && "type was not a member pointer type!");
8639
8640 QualType PointeeTy = PointerTy->getPointeeType();
8641 // Don't add qualified variants of arrays. For one, they're not allowed
8642 // (the qualifier would sink to the element type), and for another, the
8643 // only overload situation where it matters is subscript or pointer +- int,
8644 // and those shouldn't have qualifier variants anyway.
8645 if (PointeeTy->isArrayType())
8646 return true;
8647 const Type *ClassTy = PointerTy->getClass();
8648
8649 // Iterate through all strict supersets of the pointee type's CVR
8650 // qualifiers.
8651 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8652 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8653 if ((CVR | BaseCVR) != CVR) continue;
8654
8655 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8656 MemberPointerTypes.insert(
8657 Context.getMemberPointerType(QPointeeTy, ClassTy));
8658 }
8659
8660 return true;
8661}
8662
8663/// AddTypesConvertedFrom - Add each of the types to which the type @p
8664/// Ty can be implicit converted to the given set of @p Types. We're
8665/// primarily interested in pointer types and enumeration types. We also
8666/// take member pointer types, for the conditional operator.
8667/// AllowUserConversions is true if we should look at the conversion
8668/// functions of a class type, and AllowExplicitConversions if we
8669/// should also include the explicit conversion functions of a class
8670/// type.
8671void
8672BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
8673 SourceLocation Loc,
8674 bool AllowUserConversions,
8675 bool AllowExplicitConversions,
8676 const Qualifiers &VisibleQuals) {
8677 // Only deal with canonical types.
8678 Ty = Context.getCanonicalType(Ty);
8679
8680 // Look through reference types; they aren't part of the type of an
8681 // expression for the purposes of conversions.
8682 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8683 Ty = RefTy->getPointeeType();
8684
8685 // If we're dealing with an array type, decay to the pointer.
8686 if (Ty->isArrayType())
8687 Ty = SemaRef.Context.getArrayDecayedType(Ty);
8688
8689 // Otherwise, we don't care about qualifiers on the type.
8690 Ty = Ty.getLocalUnqualifiedType();
8691
8692 // Flag if we ever add a non-record type.
8693 const RecordType *TyRec = Ty->getAs<RecordType>();
8694 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8695
8696 // Flag if we encounter an arithmetic type.
8697 HasArithmeticOrEnumeralTypes =
8698 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8699
8700 if (Ty->isObjCIdType() || Ty->isObjCClassType())
8701 PointerTypes.insert(Ty);
8702 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8703 // Insert our type, and its more-qualified variants, into the set
8704 // of types.
8705 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8706 return;
8707 } else if (Ty->isMemberPointerType()) {
8708 // Member pointers are far easier, since the pointee can't be converted.
8709 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8710 return;
8711 } else if (Ty->isEnumeralType()) {
8712 HasArithmeticOrEnumeralTypes = true;
8713 EnumerationTypes.insert(Ty);
8714 } else if (Ty->isBitIntType()) {
8715 HasArithmeticOrEnumeralTypes = true;
8716 BitIntTypes.insert(Ty);
8717 } else if (Ty->isVectorType()) {
8718 // We treat vector types as arithmetic types in many contexts as an
8719 // extension.
8720 HasArithmeticOrEnumeralTypes = true;
8721 VectorTypes.insert(Ty);
8722 } else if (Ty->isMatrixType()) {
8723 // Similar to vector types, we treat vector types as arithmetic types in
8724 // many contexts as an extension.
8725 HasArithmeticOrEnumeralTypes = true;
8726 MatrixTypes.insert(Ty);
8727 } else if (Ty->isNullPtrType()) {
8728 HasNullPtrType = true;
8729 } else if (AllowUserConversions && TyRec) {
8730 // No conversion functions in incomplete types.
8731 if (!SemaRef.isCompleteType(Loc, Ty))
8732 return;
8733
8734 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8735 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8736 if (isa<UsingShadowDecl>(D))
8737 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8738
8739 // Skip conversion function templates; they don't tell us anything
8740 // about which builtin types we can convert to.
8741 if (isa<FunctionTemplateDecl>(D))
8742 continue;
8743
8744 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8745 if (AllowExplicitConversions || !Conv->isExplicit()) {
8746 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8747 VisibleQuals);
8748 }
8749 }
8750 }
8751}
8752/// Helper function for adjusting address spaces for the pointer or reference
8753/// operands of builtin operators depending on the argument.
8755 Expr *Arg) {
8757}
8758
8759/// Helper function for AddBuiltinOperatorCandidates() that adds
8760/// the volatile- and non-volatile-qualified assignment operators for the
8761/// given type to the candidate set.
8763 QualType T,
8764 ArrayRef<Expr *> Args,
8765 OverloadCandidateSet &CandidateSet) {
8766 QualType ParamTypes[2];
8767
8768 // T& operator=(T&, T)
8769 ParamTypes[0] = S.Context.getLValueReferenceType(
8771 ParamTypes[1] = T;
8772 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8773 /*IsAssignmentOperator=*/true);
8774
8776 // volatile T& operator=(volatile T&, T)
8777 ParamTypes[0] = S.Context.getLValueReferenceType(
8779 Args[0]));
8780 ParamTypes[1] = T;
8781 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8782 /*IsAssignmentOperator=*/true);
8783 }
8784}
8785
8786/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8787/// if any, found in visible type conversion functions found in ArgExpr's type.
8788static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8789 Qualifiers VRQuals;
8790 const RecordType *TyRec;
8791 if (const MemberPointerType *RHSMPType =
8792 ArgExpr->getType()->getAs<MemberPointerType>())
8793 TyRec = RHSMPType->getClass()->getAs<RecordType>();
8794 else
8795 TyRec = ArgExpr->getType()->getAs<RecordType>();
8796 if (!TyRec) {
8797 // Just to be safe, assume the worst case.
8798 VRQuals.addVolatile();
8799 VRQuals.addRestrict();
8800 return VRQuals;
8801 }
8802
8803 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8804 if (!ClassDecl->hasDefinition())
8805 return VRQuals;
8806
8807 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8808 if (isa<UsingShadowDecl>(D))
8809 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8810 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8811 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8812 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8813 CanTy = ResTypeRef->getPointeeType();
8814 // Need to go down the pointer/mempointer chain and add qualifiers
8815 // as see them.
8816 bool done = false;
8817 while (!done) {
8818 if (CanTy.isRestrictQualified())
8819 VRQuals.addRestrict();
8820 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8821 CanTy = ResTypePtr->getPointeeType();
8822 else if (const MemberPointerType *ResTypeMPtr =
8823 CanTy->getAs<MemberPointerType>())
8824 CanTy = ResTypeMPtr->getPointeeType();
8825 else
8826 done = true;
8827 if (CanTy.isVolatileQualified())
8828 VRQuals.addVolatile();
8829 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8830 return VRQuals;
8831 }
8832 }
8833 }
8834 return VRQuals;
8835}
8836
8837// Note: We're currently only handling qualifiers that are meaningful for the
8838// LHS of compound assignment overloading.
8840 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
8841 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8842 // _Atomic
8843 if (Available.hasAtomic()) {
8844 Available.removeAtomic();
8845 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
8846 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8847 return;
8848 }
8849
8850 // volatile
8851 if (Available.hasVolatile()) {
8852 Available.removeVolatile();
8853 assert(!Applied.hasVolatile());
8854 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
8855 Callback);
8856 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8857 return;
8858 }
8859
8860 Callback(Applied);
8861}
8862
8864 QualifiersAndAtomic Quals,
8865 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8867 Callback);
8868}
8869
8871 QualifiersAndAtomic Quals,
8872 Sema &S) {
8873 if (Quals.hasAtomic())
8875 if (Quals.hasVolatile())
8878}
8879
8880namespace {
8881
8882/// Helper class to manage the addition of builtin operator overload
8883/// candidates. It provides shared state and utility methods used throughout
8884/// the process, as well as a helper method to add each group of builtin
8885/// operator overloads from the standard to a candidate set.
8886class BuiltinOperatorOverloadBuilder {
8887 // Common instance state available to all overload candidate addition methods.
8888 Sema &S;
8889 ArrayRef<Expr *> Args;
8890 QualifiersAndAtomic VisibleTypeConversionsQuals;
8891 bool HasArithmeticOrEnumeralCandidateType;
8893 OverloadCandidateSet &CandidateSet;
8894
8895 static constexpr int ArithmeticTypesCap = 26;
8897
8898 // Define some indices used to iterate over the arithmetic types in
8899 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
8900 // types are that preserved by promotion (C++ [over.built]p2).
8901 unsigned FirstIntegralType,
8902 LastIntegralType;
8903 unsigned FirstPromotedIntegralType,
8904 LastPromotedIntegralType;
8905 unsigned FirstPromotedArithmeticType,
8906 LastPromotedArithmeticType;
8907 unsigned NumArithmeticTypes;
8908
8909 void InitArithmeticTypes() {
8910 // Start of promoted types.
8911 FirstPromotedArithmeticType = 0;
8912 ArithmeticTypes.push_back(S.Context.FloatTy);
8913 ArithmeticTypes.push_back(S.Context.DoubleTy);
8914 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8916 ArithmeticTypes.push_back(S.Context.Float128Ty);
8918 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
8919
8920 // Start of integral types.
8921 FirstIntegralType = ArithmeticTypes.size();
8922 FirstPromotedIntegralType = ArithmeticTypes.size();
8923 ArithmeticTypes.push_back(S.Context.IntTy);
8924 ArithmeticTypes.push_back(S.Context.LongTy);
8925 ArithmeticTypes.push_back(S.Context.LongLongTy);
8929 ArithmeticTypes.push_back(S.Context.Int128Ty);
8930 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8931 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8932 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8936 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8937
8938 /// We add candidates for the unique, unqualified _BitInt types present in
8939 /// the candidate type set. The candidate set already handled ensuring the
8940 /// type is unqualified and canonical, but because we're adding from N
8941 /// different sets, we need to do some extra work to unique things. Insert
8942 /// the candidates into a unique set, then move from that set into the list
8943 /// of arithmetic types.
8944 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
8945 llvm::for_each(CandidateTypes, [&BitIntCandidates](
8946 BuiltinCandidateTypeSet &Candidate) {
8947 for (QualType BitTy : Candidate.bitint_types())
8948 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
8949 });
8950 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
8951 LastPromotedIntegralType = ArithmeticTypes.size();
8952 LastPromotedArithmeticType = ArithmeticTypes.size();
8953 // End of promoted types.
8954
8955 ArithmeticTypes.push_back(S.Context.BoolTy);
8956 ArithmeticTypes.push_back(S.Context.CharTy);
8957 ArithmeticTypes.push_back(S.Context.WCharTy);
8958 if (S.Context.getLangOpts().Char8)
8959 ArithmeticTypes.push_back(S.Context.Char8Ty);
8960 ArithmeticTypes.push_back(S.Context.Char16Ty);
8961 ArithmeticTypes.push_back(S.Context.Char32Ty);
8962 ArithmeticTypes.push_back(S.Context.SignedCharTy);
8963 ArithmeticTypes.push_back(S.Context.ShortTy);
8964 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8965 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8966 LastIntegralType = ArithmeticTypes.size();
8967 NumArithmeticTypes = ArithmeticTypes.size();
8968 // End of integral types.
8969 // FIXME: What about complex? What about half?
8970
8971 // We don't know for sure how many bit-precise candidates were involved, so
8972 // we subtract those from the total when testing whether we're under the
8973 // cap or not.
8974 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
8975 ArithmeticTypesCap &&
8976 "Enough inline storage for all arithmetic types.");
8977 }
8978
8979 /// Helper method to factor out the common pattern of adding overloads
8980 /// for '++' and '--' builtin operators.
8981 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8982 bool HasVolatile,
8983 bool HasRestrict) {
8984 QualType ParamTypes[2] = {
8985 S.Context.getLValueReferenceType(CandidateTy),
8986 S.Context.IntTy
8987 };
8988
8989 // Non-volatile version.
8990 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8991
8992 // Use a heuristic to reduce number of builtin candidates in the set:
8993 // add volatile version only if there are conversions to a volatile type.
8994 if (HasVolatile) {
8995 ParamTypes[0] =
8997 S.Context.getVolatileType(CandidateTy));
8998 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8999 }
9000
9001 // Add restrict version only if there are conversions to a restrict type
9002 // and our candidate type is a non-restrict-qualified pointer.
9003 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9004 !CandidateTy.isRestrictQualified()) {
9005 ParamTypes[0]
9008 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9009
9010 if (HasVolatile) {
9011 ParamTypes[0]
9013 S.Context.getCVRQualifiedType(CandidateTy,
9016 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9017 }
9018 }
9019
9020 }
9021
9022 /// Helper to add an overload candidate for a binary builtin with types \p L
9023 /// and \p R.
9024 void AddCandidate(QualType L, QualType R) {
9025 QualType LandR[2] = {L, R};
9026 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9027 }
9028
9029public:
9030 BuiltinOperatorOverloadBuilder(
9031 Sema &S, ArrayRef<Expr *> Args,
9032 QualifiersAndAtomic VisibleTypeConversionsQuals,
9033 bool HasArithmeticOrEnumeralCandidateType,
9035 OverloadCandidateSet &CandidateSet)
9036 : S(S), Args(Args),
9037 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9038 HasArithmeticOrEnumeralCandidateType(
9039 HasArithmeticOrEnumeralCandidateType),
9040 CandidateTypes(CandidateTypes),
9041 CandidateSet(CandidateSet) {
9042
9043 InitArithmeticTypes();
9044 }
9045
9046 // Increment is deprecated for bool since C++17.
9047 //
9048 // C++ [over.built]p3:
9049 //
9050 // For every pair (T, VQ), where T is an arithmetic type other
9051 // than bool, and VQ is either volatile or empty, there exist
9052 // candidate operator functions of the form
9053 //
9054 // VQ T& operator++(VQ T&);
9055 // T operator++(VQ T&, int);
9056 //
9057 // C++ [over.built]p4:
9058 //
9059 // For every pair (T, VQ), where T is an arithmetic type other
9060 // than bool, and VQ is either volatile or empty, there exist
9061 // candidate operator functions of the form
9062 //
9063 // VQ T& operator--(VQ T&);
9064 // T operator--(VQ T&, int);
9065 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9066 if (!HasArithmeticOrEnumeralCandidateType)
9067 return;
9068
9069 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9070 const auto TypeOfT = ArithmeticTypes[Arith];
9071 if (TypeOfT == S.Context.BoolTy) {
9072 if (Op == OO_MinusMinus)
9073 continue;
9074 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9075 continue;
9076 }
9077 addPlusPlusMinusMinusStyleOverloads(
9078 TypeOfT,
9079 VisibleTypeConversionsQuals.hasVolatile(),
9080 VisibleTypeConversionsQuals.hasRestrict());
9081 }
9082 }
9083
9084 // C++ [over.built]p5:
9085 //
9086 // For every pair (T, VQ), where T is a cv-qualified or
9087 // cv-unqualified object type, and VQ is either volatile or
9088 // empty, there exist candidate operator functions of the form
9089 //
9090 // T*VQ& operator++(T*VQ&);
9091 // T*VQ& operator--(T*VQ&);
9092 // T* operator++(T*VQ&, int);
9093 // T* operator--(T*VQ&, int);
9094 void addPlusPlusMinusMinusPointerOverloads() {
9095 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9096 // Skip pointer types that aren't pointers to object types.
9097 if (!PtrTy->getPointeeType()->isObjectType())
9098 continue;
9099
9100 addPlusPlusMinusMinusStyleOverloads(
9101 PtrTy,
9102 (!PtrTy.isVolatileQualified() &&
9103 VisibleTypeConversionsQuals.hasVolatile()),
9104 (!PtrTy.isRestrictQualified() &&
9105 VisibleTypeConversionsQuals.hasRestrict()));
9106 }
9107 }
9108
9109 // C++ [over.built]p6:
9110 // For every cv-qualified or cv-unqualified object type T, there
9111 // exist candidate operator functions of the form
9112 //
9113 // T& operator*(T*);
9114 //
9115 // C++ [over.built]p7:
9116 // For every function type T that does not have cv-qualifiers or a
9117 // ref-qualifier, there exist candidate operator functions of the form
9118 // T& operator*(T*);
9119 void addUnaryStarPointerOverloads() {
9120 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9121 QualType PointeeTy = ParamTy->getPointeeType();
9122 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9123 continue;
9124
9125 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9126 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9127 continue;
9128
9129 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9130 }
9131 }
9132
9133 // C++ [over.built]p9:
9134 // For every promoted arithmetic type T, there exist candidate
9135 // operator functions of the form
9136 //
9137 // T operator+(T);
9138 // T operator-(T);
9139 void addUnaryPlusOrMinusArithmeticOverloads() {
9140 if (!HasArithmeticOrEnumeralCandidateType)
9141 return;
9142
9143 for (unsigned Arith = FirstPromotedArithmeticType;
9144 Arith < LastPromotedArithmeticType; ++Arith) {
9145 QualType ArithTy = ArithmeticTypes[Arith];
9146 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9147 }
9148
9149 // Extension: We also add these operators for vector types.
9150 for (QualType VecTy : CandidateTypes[0].vector_types())
9151 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9152 }
9153
9154 // C++ [over.built]p8:
9155 // For every type T, there exist candidate operator functions of
9156 // the form
9157 //
9158 // T* operator+(T*);
9159 void addUnaryPlusPointerOverloads() {
9160 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9161 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9162 }
9163
9164 // C++ [over.built]p10:
9165 // For every promoted integral type T, there exist candidate
9166 // operator functions of the form
9167 //
9168 // T operator~(T);
9169 void addUnaryTildePromotedIntegralOverloads() {
9170 if (!HasArithmeticOrEnumeralCandidateType)
9171 return;
9172
9173 for (unsigned Int = FirstPromotedIntegralType;
9174 Int < LastPromotedIntegralType; ++Int) {
9175 QualType IntTy = ArithmeticTypes[Int];
9176 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9177 }
9178
9179 // Extension: We also add this operator for vector types.
9180 for (QualType VecTy : CandidateTypes[0].vector_types())
9181 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9182 }
9183
9184 // C++ [over.match.oper]p16:
9185 // For every pointer to member type T or type std::nullptr_t, there
9186 // exist candidate operator functions of the form
9187 //
9188 // bool operator==(T,T);
9189 // bool operator!=(T,T);
9190 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9191 /// Set of (canonical) types that we've already handled.
9193
9194 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9195 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9196 // Don't add the same builtin candidate twice.
9197 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9198 continue;
9199
9200 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9201 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9202 }
9203
9204 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9206 if (AddedTypes.insert(NullPtrTy).second) {
9207 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9208 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9209 }
9210 }
9211 }
9212 }
9213
9214 // C++ [over.built]p15:
9215 //
9216 // For every T, where T is an enumeration type or a pointer type,
9217 // there exist candidate operator functions of the form
9218 //
9219 // bool operator<(T, T);
9220 // bool operator>(T, T);
9221 // bool operator<=(T, T);
9222 // bool operator>=(T, T);
9223 // bool operator==(T, T);
9224 // bool operator!=(T, T);
9225 // R operator<=>(T, T)
9226 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9227 // C++ [over.match.oper]p3:
9228 // [...]the built-in candidates include all of the candidate operator
9229 // functions defined in 13.6 that, compared to the given operator, [...]
9230 // do not have the same parameter-type-list as any non-template non-member
9231 // candidate.
9232 //
9233 // Note that in practice, this only affects enumeration types because there
9234 // aren't any built-in candidates of record type, and a user-defined operator
9235 // must have an operand of record or enumeration type. Also, the only other
9236 // overloaded operator with enumeration arguments, operator=,
9237 // cannot be overloaded for enumeration types, so this is the only place
9238 // where we must suppress candidates like this.
9239 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9240 UserDefinedBinaryOperators;
9241
9242 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9243 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9244 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9245 CEnd = CandidateSet.end();
9246 C != CEnd; ++C) {
9247 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9248 continue;
9249
9250 if (C->Function->isFunctionTemplateSpecialization())
9251 continue;
9252
9253 // We interpret "same parameter-type-list" as applying to the
9254 // "synthesized candidate, with the order of the two parameters
9255 // reversed", not to the original function.
9256 bool Reversed = C->isReversed();
9257 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9258 ->getType()
9259 .getUnqualifiedType();
9260 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9261 ->getType()
9262 .getUnqualifiedType();
9263
9264 // Skip if either parameter isn't of enumeral type.
9265 if (!FirstParamType->isEnumeralType() ||
9266 !SecondParamType->isEnumeralType())
9267 continue;
9268
9269 // Add this operator to the set of known user-defined operators.
9270 UserDefinedBinaryOperators.insert(
9271 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9272 S.Context.getCanonicalType(SecondParamType)));
9273 }
9274 }
9275 }
9276
9277 /// Set of (canonical) types that we've already handled.
9279
9280 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9281 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9282 // Don't add the same builtin candidate twice.
9283 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9284 continue;
9285 if (IsSpaceship && PtrTy->isFunctionPointerType())
9286 continue;
9287
9288 QualType ParamTypes[2] = {PtrTy, PtrTy};
9289 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9290 }
9291 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9292 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9293
9294 // Don't add the same builtin candidate twice, or if a user defined
9295 // candidate exists.
9296 if (!AddedTypes.insert(CanonType).second ||
9297 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9298 CanonType)))
9299 continue;
9300 QualType ParamTypes[2] = {EnumTy, EnumTy};
9301 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9302 }
9303 }
9304 }
9305
9306 // C++ [over.built]p13:
9307 //
9308 // For every cv-qualified or cv-unqualified object type T
9309 // there exist candidate operator functions of the form
9310 //
9311 // T* operator+(T*, ptrdiff_t);
9312 // T& operator[](T*, ptrdiff_t); [BELOW]
9313 // T* operator-(T*, ptrdiff_t);
9314 // T* operator+(ptrdiff_t, T*);
9315 // T& operator[](ptrdiff_t, T*); [BELOW]
9316 //
9317 // C++ [over.built]p14:
9318 //
9319 // For every T, where T is a pointer to object type, there
9320 // exist candidate operator functions of the form
9321 //
9322 // ptrdiff_t operator-(T, T);
9323 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9324 /// Set of (canonical) types that we've already handled.
9326
9327 for (int Arg = 0; Arg < 2; ++Arg) {
9328 QualType AsymmetricParamTypes[2] = {
9331 };
9332 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9333 QualType PointeeTy = PtrTy->getPointeeType();
9334 if (!PointeeTy->isObjectType())
9335 continue;
9336
9337 AsymmetricParamTypes[Arg] = PtrTy;
9338 if (Arg == 0 || Op == OO_Plus) {
9339 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9340 // T* operator+(ptrdiff_t, T*);
9341 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9342 }
9343 if (Op == OO_Minus) {
9344 // ptrdiff_t operator-(T, T);
9345 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9346 continue;
9347
9348 QualType ParamTypes[2] = {PtrTy, PtrTy};
9349 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9350 }
9351 }
9352 }
9353 }
9354
9355 // C++ [over.built]p12:
9356 //
9357 // For every pair of promoted arithmetic types L and R, there
9358 // exist candidate operator functions of the form
9359 //
9360 // LR operator*(L, R);
9361 // LR operator/(L, R);
9362 // LR operator+(L, R);
9363 // LR operator-(L, R);
9364 // bool operator<(L, R);
9365 // bool operator>(L, R);
9366 // bool operator<=(L, R);
9367 // bool operator>=(L, R);
9368 // bool operator==(L, R);
9369 // bool operator!=(L, R);
9370 //
9371 // where LR is the result of the usual arithmetic conversions
9372 // between types L and R.
9373 //
9374 // C++ [over.built]p24:
9375 //
9376 // For every pair of promoted arithmetic types L and R, there exist
9377 // candidate operator functions of the form
9378 //
9379 // LR operator?(bool, L, R);
9380 //
9381 // where LR is the result of the usual arithmetic conversions
9382 // between types L and R.
9383 // Our candidates ignore the first parameter.
9384 void addGenericBinaryArithmeticOverloads() {
9385 if (!HasArithmeticOrEnumeralCandidateType)
9386 return;
9387
9388 for (unsigned Left = FirstPromotedArithmeticType;
9389 Left < LastPromotedArithmeticType; ++Left) {
9390 for (unsigned Right = FirstPromotedArithmeticType;
9391 Right < LastPromotedArithmeticType; ++Right) {
9392 QualType LandR[2] = { ArithmeticTypes[Left],
9393 ArithmeticTypes[Right] };
9394 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9395 }
9396 }
9397
9398 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9399 // conditional operator for vector types.
9400 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9401 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9402 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9403 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9404 }
9405 }
9406
9407 /// Add binary operator overloads for each candidate matrix type M1, M2:
9408 /// * (M1, M1) -> M1
9409 /// * (M1, M1.getElementType()) -> M1
9410 /// * (M2.getElementType(), M2) -> M2
9411 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9412 void addMatrixBinaryArithmeticOverloads() {
9413 if (!HasArithmeticOrEnumeralCandidateType)
9414 return;
9415
9416 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9417 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9418 AddCandidate(M1, M1);
9419 }
9420
9421 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9422 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9423 if (!CandidateTypes[0].containsMatrixType(M2))
9424 AddCandidate(M2, M2);
9425 }
9426 }
9427
9428 // C++2a [over.built]p14:
9429 //
9430 // For every integral type T there exists a candidate operator function
9431 // of the form
9432 //
9433 // std::strong_ordering operator<=>(T, T)
9434 //
9435 // C++2a [over.built]p15:
9436 //
9437 // For every pair of floating-point types L and R, there exists a candidate
9438 // operator function of the form
9439 //
9440 // std::partial_ordering operator<=>(L, R);
9441 //
9442 // FIXME: The current specification for integral types doesn't play nice with
9443 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9444 // comparisons. Under the current spec this can lead to ambiguity during
9445 // overload resolution. For example:
9446 //
9447 // enum A : int {a};
9448 // auto x = (a <=> (long)42);
9449 //
9450 // error: call is ambiguous for arguments 'A' and 'long'.
9451 // note: candidate operator<=>(int, int)
9452 // note: candidate operator<=>(long, long)
9453 //
9454 // To avoid this error, this function deviates from the specification and adds
9455 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9456 // arithmetic types (the same as the generic relational overloads).
9457 //
9458 // For now this function acts as a placeholder.
9459 void addThreeWayArithmeticOverloads() {
9460 addGenericBinaryArithmeticOverloads();
9461 }
9462
9463 // C++ [over.built]p17:
9464 //
9465 // For every pair of promoted integral types L and R, there
9466 // exist candidate operator functions of the form
9467 //
9468 // LR operator%(L, R);
9469 // LR operator&(L, R);
9470 // LR operator^(L, R);
9471 // LR operator|(L, R);
9472 // L operator<<(L, R);
9473 // L operator>>(L, R);
9474 //
9475 // where LR is the result of the usual arithmetic conversions
9476 // between types L and R.
9477 void addBinaryBitwiseArithmeticOverloads() {
9478 if (!HasArithmeticOrEnumeralCandidateType)
9479 return;
9480
9481 for (unsigned Left = FirstPromotedIntegralType;
9482 Left < LastPromotedIntegralType; ++Left) {
9483 for (unsigned Right = FirstPromotedIntegralType;
9484 Right < LastPromotedIntegralType; ++Right) {
9485 QualType LandR[2] = { ArithmeticTypes[Left],
9486 ArithmeticTypes[Right] };
9487 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9488 }
9489 }
9490 }
9491
9492 // C++ [over.built]p20:
9493 //
9494 // For every pair (T, VQ), where T is an enumeration or
9495 // pointer to member type and VQ is either volatile or
9496 // empty, there exist candidate operator functions of the form
9497 //
9498 // VQ T& operator=(VQ T&, T);
9499 void addAssignmentMemberPointerOrEnumeralOverloads() {
9500 /// Set of (canonical) types that we've already handled.
9502
9503 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9504 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9505 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9506 continue;
9507
9508 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9509 }
9510
9511 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9512 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9513 continue;
9514
9515 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9516 }
9517 }
9518 }
9519
9520 // C++ [over.built]p19:
9521 //
9522 // For every pair (T, VQ), where T is any type and VQ is either
9523 // volatile or empty, there exist candidate operator functions
9524 // of the form
9525 //
9526 // T*VQ& operator=(T*VQ&, T*);
9527 //
9528 // C++ [over.built]p21:
9529 //
9530 // For every pair (T, VQ), where T is a cv-qualified or
9531 // cv-unqualified object type and VQ is either volatile or
9532 // empty, there exist candidate operator functions of the form
9533 //
9534 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9535 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9536 void addAssignmentPointerOverloads(bool isEqualOp) {
9537 /// Set of (canonical) types that we've already handled.
9539
9540 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9541 // If this is operator=, keep track of the builtin candidates we added.
9542 if (isEqualOp)
9543 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9544 else if (!PtrTy->getPointeeType()->isObjectType())
9545 continue;
9546
9547 // non-volatile version
9548 QualType ParamTypes[2] = {
9550 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9551 };
9552 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9553 /*IsAssignmentOperator=*/ isEqualOp);
9554
9555 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9556 VisibleTypeConversionsQuals.hasVolatile();
9557 if (NeedVolatile) {
9558 // volatile version
9559 ParamTypes[0] =
9561 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9562 /*IsAssignmentOperator=*/isEqualOp);
9563 }
9564
9565 if (!PtrTy.isRestrictQualified() &&
9566 VisibleTypeConversionsQuals.hasRestrict()) {
9567 // restrict version
9568 ParamTypes[0] =
9570 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9571 /*IsAssignmentOperator=*/isEqualOp);
9572
9573 if (NeedVolatile) {
9574 // volatile restrict version
9575 ParamTypes[0] =
9578 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9579 /*IsAssignmentOperator=*/isEqualOp);
9580 }
9581 }
9582 }
9583
9584 if (isEqualOp) {
9585 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9586 // Make sure we don't add the same candidate twice.
9587 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9588 continue;
9589
9590 QualType ParamTypes[2] = {
9592 PtrTy,
9593 };
9594
9595 // non-volatile version
9596 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9597 /*IsAssignmentOperator=*/true);
9598
9599 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9600 VisibleTypeConversionsQuals.hasVolatile();
9601 if (NeedVolatile) {
9602 // volatile version
9603 ParamTypes[0] = S.Context.getLValueReferenceType(
9604 S.Context.getVolatileType(PtrTy));
9605 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9606 /*IsAssignmentOperator=*/true);
9607 }
9608
9609 if (!PtrTy.isRestrictQualified() &&
9610 VisibleTypeConversionsQuals.hasRestrict()) {
9611 // restrict version
9612 ParamTypes[0] = S.Context.getLValueReferenceType(
9613 S.Context.getRestrictType(PtrTy));
9614 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9615 /*IsAssignmentOperator=*/true);
9616
9617 if (NeedVolatile) {
9618 // volatile restrict version
9619 ParamTypes[0] =
9622 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9623 /*IsAssignmentOperator=*/true);
9624 }
9625 }
9626 }
9627 }
9628 }
9629
9630 // C++ [over.built]p18:
9631 //
9632 // For every triple (L, VQ, R), where L is an arithmetic type,
9633 // VQ is either volatile or empty, and R is a promoted
9634 // arithmetic type, there exist candidate operator functions of
9635 // the form
9636 //
9637 // VQ L& operator=(VQ L&, R);
9638 // VQ L& operator*=(VQ L&, R);
9639 // VQ L& operator/=(VQ L&, R);
9640 // VQ L& operator+=(VQ L&, R);
9641 // VQ L& operator-=(VQ L&, R);
9642 void addAssignmentArithmeticOverloads(bool isEqualOp) {
9643 if (!HasArithmeticOrEnumeralCandidateType)
9644 return;
9645
9646 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9647 for (unsigned Right = FirstPromotedArithmeticType;
9648 Right < LastPromotedArithmeticType; ++Right) {
9649 QualType ParamTypes[2];
9650 ParamTypes[1] = ArithmeticTypes[Right];
9652 S, ArithmeticTypes[Left], Args[0]);
9653
9655 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9656 ParamTypes[0] =
9657 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9658 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9659 /*IsAssignmentOperator=*/isEqualOp);
9660 });
9661 }
9662 }
9663
9664 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
9665 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9666 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
9667 QualType ParamTypes[2];
9668 ParamTypes[1] = Vec2Ty;
9669 // Add this built-in operator as a candidate (VQ is empty).
9670 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
9671 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9672 /*IsAssignmentOperator=*/isEqualOp);
9673
9674 // Add this built-in operator as a candidate (VQ is 'volatile').
9675 if (VisibleTypeConversionsQuals.hasVolatile()) {
9676 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
9677 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
9678 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9679 /*IsAssignmentOperator=*/isEqualOp);
9680 }
9681 }
9682 }
9683
9684 // C++ [over.built]p22:
9685 //
9686 // For every triple (L, VQ, R), where L is an integral type, VQ
9687 // is either volatile or empty, and R is a promoted integral
9688 // type, there exist candidate operator functions of the form
9689 //
9690 // VQ L& operator%=(VQ L&, R);
9691 // VQ L& operator<<=(VQ L&, R);
9692 // VQ L& operator>>=(VQ L&, R);
9693 // VQ L& operator&=(VQ L&, R);
9694 // VQ L& operator^=(VQ L&, R);
9695 // VQ L& operator|=(VQ L&, R);
9696 void addAssignmentIntegralOverloads() {
9697 if (!HasArithmeticOrEnumeralCandidateType)
9698 return;
9699
9700 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
9701 for (unsigned Right = FirstPromotedIntegralType;
9702 Right < LastPromotedIntegralType; ++Right) {
9703 QualType ParamTypes[2];
9704 ParamTypes[1] = ArithmeticTypes[Right];
9706 S, ArithmeticTypes[Left], Args[0]);
9707
9709 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9710 ParamTypes[0] =
9711 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9712 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9713 });
9714 }
9715 }
9716 }
9717
9718 // C++ [over.operator]p23:
9719 //
9720 // There also exist candidate operator functions of the form
9721 //
9722 // bool operator!(bool);
9723 // bool operator&&(bool, bool);
9724 // bool operator||(bool, bool);
9725 void addExclaimOverload() {
9726 QualType ParamTy = S.Context.BoolTy;
9727 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
9728 /*IsAssignmentOperator=*/false,
9729 /*NumContextualBoolArguments=*/1);
9730 }
9731 void addAmpAmpOrPipePipeOverload() {
9732 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
9733 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9734 /*IsAssignmentOperator=*/false,
9735 /*NumContextualBoolArguments=*/2);
9736 }
9737
9738 // C++ [over.built]p13:
9739 //
9740 // For every cv-qualified or cv-unqualified object type T there
9741 // exist candidate operator functions of the form
9742 //
9743 // T* operator+(T*, ptrdiff_t); [ABOVE]
9744 // T& operator[](T*, ptrdiff_t);
9745 // T* operator-(T*, ptrdiff_t); [ABOVE]
9746 // T* operator+(ptrdiff_t, T*); [ABOVE]
9747 // T& operator[](ptrdiff_t, T*);
9748 void addSubscriptOverloads() {
9749 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9750 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9751 QualType PointeeType = PtrTy->getPointeeType();
9752 if (!PointeeType->isObjectType())
9753 continue;
9754
9755 // T& operator[](T*, ptrdiff_t)
9756 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9757 }
9758
9759 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9760 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9761 QualType PointeeType = PtrTy->getPointeeType();
9762 if (!PointeeType->isObjectType())
9763 continue;
9764
9765 // T& operator[](ptrdiff_t, T*)
9766 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9767 }
9768 }
9769
9770 // C++ [over.built]p11:
9771 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9772 // C1 is the same type as C2 or is a derived class of C2, T is an object
9773 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9774 // there exist candidate operator functions of the form
9775 //
9776 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9777 //
9778 // where CV12 is the union of CV1 and CV2.
9779 void addArrowStarOverloads() {
9780 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9781 QualType C1Ty = PtrTy;
9782 QualType C1;
9784 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9785 if (!isa<RecordType>(C1))
9786 continue;
9787 // heuristic to reduce number of builtin candidates in the set.
9788 // Add volatile/restrict version only if there are conversions to a
9789 // volatile/restrict type.
9790 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9791 continue;
9792 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9793 continue;
9794 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9795 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
9796 QualType C2 = QualType(mptr->getClass(), 0);
9797 C2 = C2.getUnqualifiedType();
9798 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9799 break;
9800 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9801 // build CV12 T&
9802 QualType T = mptr->getPointeeType();
9803 if (!VisibleTypeConversionsQuals.hasVolatile() &&
9804 T.isVolatileQualified())
9805 continue;
9806 if (!VisibleTypeConversionsQuals.hasRestrict() &&
9807 T.isRestrictQualified())
9808 continue;
9809 T = Q1.apply(S.Context, T);
9810 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9811 }
9812 }
9813 }
9814
9815 // Note that we don't consider the first argument, since it has been
9816 // contextually converted to bool long ago. The candidates below are
9817 // therefore added as binary.
9818 //
9819 // C++ [over.built]p25:
9820 // For every type T, where T is a pointer, pointer-to-member, or scoped
9821 // enumeration type, there exist candidate operator functions of the form
9822 //
9823 // T operator?(bool, T, T);
9824 //
9825 void addConditionalOperatorOverloads() {
9826 /// Set of (canonical) types that we've already handled.
9828
9829 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9830 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9831 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9832 continue;
9833
9834 QualType ParamTypes[2] = {PtrTy, PtrTy};
9835 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9836 }
9837
9838 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9839 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9840 continue;
9841
9842 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9843 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9844 }
9845
9846 if (S.getLangOpts().CPlusPlus11) {
9847 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9848 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9849 continue;
9850
9851 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9852 continue;
9853
9854 QualType ParamTypes[2] = {EnumTy, EnumTy};
9855 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9856 }
9857 }
9858 }
9859 }
9860};
9861
9862} // end anonymous namespace
9863
9865 SourceLocation OpLoc,
9866 ArrayRef<Expr *> Args,
9867 OverloadCandidateSet &CandidateSet) {
9868 // Find all of the types that the arguments can convert to, but only
9869 // if the operator we're looking at has built-in operator candidates
9870 // that make use of these types. Also record whether we encounter non-record
9871 // candidate types or either arithmetic or enumeral candidate types.
9872 QualifiersAndAtomic VisibleTypeConversionsQuals;
9873 VisibleTypeConversionsQuals.addConst();
9874 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9875 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9876 if (Args[ArgIdx]->getType()->isAtomicType())
9877 VisibleTypeConversionsQuals.addAtomic();
9878 }
9879
9880 bool HasNonRecordCandidateType = false;
9881 bool HasArithmeticOrEnumeralCandidateType = false;
9883 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9884 CandidateTypes.emplace_back(*this);
9885 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9886 OpLoc,
9887 true,
9888 (Op == OO_Exclaim ||
9889 Op == OO_AmpAmp ||
9890 Op == OO_PipePipe),
9891 VisibleTypeConversionsQuals);
9892 HasNonRecordCandidateType = HasNonRecordCandidateType ||
9893 CandidateTypes[ArgIdx].hasNonRecordTypes();
9894 HasArithmeticOrEnumeralCandidateType =
9895 HasArithmeticOrEnumeralCandidateType ||
9896 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9897 }
9898
9899 // Exit early when no non-record types have been added to the candidate set
9900 // for any of the arguments to the operator.
9901 //
9902 // We can't exit early for !, ||, or &&, since there we have always have
9903 // 'bool' overloads.
9904 if (!HasNonRecordCandidateType &&
9905 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9906 return;
9907
9908 // Setup an object to manage the common state for building overloads.
9909 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9910 VisibleTypeConversionsQuals,
9911 HasArithmeticOrEnumeralCandidateType,
9912 CandidateTypes, CandidateSet);
9913
9914 // Dispatch over the operation to add in only those overloads which apply.
9915 switch (Op) {
9916 case OO_None:
9918 llvm_unreachable("Expected an overloaded operator");
9919
9920 case OO_New:
9921 case OO_Delete:
9922 case OO_Array_New:
9923 case OO_Array_Delete:
9924 case OO_Call:
9925 llvm_unreachable(
9926 "Special operators don't use AddBuiltinOperatorCandidates");
9927
9928 case OO_Comma:
9929 case OO_Arrow:
9930 case OO_Coawait:
9931 // C++ [over.match.oper]p3:
9932 // -- For the operator ',', the unary operator '&', the
9933 // operator '->', or the operator 'co_await', the
9934 // built-in candidates set is empty.
9935 break;
9936
9937 case OO_Plus: // '+' is either unary or binary
9938 if (Args.size() == 1)
9939 OpBuilder.addUnaryPlusPointerOverloads();
9940 [[fallthrough]];
9941
9942 case OO_Minus: // '-' is either unary or binary
9943 if (Args.size() == 1) {
9944 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9945 } else {
9946 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9947 OpBuilder.addGenericBinaryArithmeticOverloads();
9948 OpBuilder.addMatrixBinaryArithmeticOverloads();
9949 }
9950 break;
9951
9952 case OO_Star: // '*' is either unary or binary
9953 if (Args.size() == 1)
9954 OpBuilder.addUnaryStarPointerOverloads();
9955 else {
9956 OpBuilder.addGenericBinaryArithmeticOverloads();
9957 OpBuilder.addMatrixBinaryArithmeticOverloads();
9958 }
9959 break;
9960
9961 case OO_Slash:
9962 OpBuilder.addGenericBinaryArithmeticOverloads();
9963 break;
9964
9965 case OO_PlusPlus:
9966 case OO_MinusMinus:
9967 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9968 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9969 break;
9970
9971 case OO_EqualEqual:
9972 case OO_ExclaimEqual:
9973 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9974 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9975 OpBuilder.addGenericBinaryArithmeticOverloads();
9976 break;
9977
9978 case OO_Less:
9979 case OO_Greater:
9980 case OO_LessEqual:
9981 case OO_GreaterEqual:
9982 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9983 OpBuilder.addGenericBinaryArithmeticOverloads();
9984 break;
9985
9986 case OO_Spaceship:
9987 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
9988 OpBuilder.addThreeWayArithmeticOverloads();
9989 break;
9990
9991 case OO_Percent:
9992 case OO_Caret:
9993 case OO_Pipe:
9994 case OO_LessLess:
9995 case OO_GreaterGreater:
9996 OpBuilder.addBinaryBitwiseArithmeticOverloads();
9997 break;
9998
9999 case OO_Amp: // '&' is either unary or binary
10000 if (Args.size() == 1)
10001 // C++ [over.match.oper]p3:
10002 // -- For the operator ',', the unary operator '&', or the
10003 // operator '->', the built-in candidates set is empty.
10004 break;
10005
10006 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10007 break;
10008
10009 case OO_Tilde:
10010 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10011 break;
10012
10013 case OO_Equal:
10014 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10015 [[fallthrough]];
10016
10017 case OO_PlusEqual:
10018 case OO_MinusEqual:
10019 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10020 [[fallthrough]];
10021
10022 case OO_StarEqual:
10023 case OO_SlashEqual:
10024 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10025 break;
10026
10027 case OO_PercentEqual:
10028 case OO_LessLessEqual:
10029 case OO_GreaterGreaterEqual:
10030 case OO_AmpEqual:
10031 case OO_CaretEqual:
10032 case OO_PipeEqual:
10033 OpBuilder.addAssignmentIntegralOverloads();
10034 break;
10035
10036 case OO_Exclaim:
10037 OpBuilder.addExclaimOverload();
10038 break;
10039
10040 case OO_AmpAmp:
10041 case OO_PipePipe:
10042 OpBuilder.addAmpAmpOrPipePipeOverload();
10043 break;
10044
10045 case OO_Subscript:
10046 if (Args.size() == 2)
10047 OpBuilder.addSubscriptOverloads();
10048 break;
10049
10050 case OO_ArrowStar:
10051 OpBuilder.addArrowStarOverloads();
10052 break;
10053
10054 case OO_Conditional:
10055 OpBuilder.addConditionalOperatorOverloads();
10056 OpBuilder.addGenericBinaryArithmeticOverloads();
10057 break;
10058 }
10059}
10060
10061void
10063 SourceLocation Loc,
10064 ArrayRef<Expr *> Args,
10065 TemplateArgumentListInfo *ExplicitTemplateArgs,
10066 OverloadCandidateSet& CandidateSet,
10067 bool PartialOverloading) {
10068 ADLResult Fns;
10069
10070 // FIXME: This approach for uniquing ADL results (and removing
10071 // redundant candidates from the set) relies on pointer-equality,
10072 // which means we need to key off the canonical decl. However,
10073 // always going back to the canonical decl might not get us the
10074 // right set of default arguments. What default arguments are
10075 // we supposed to consider on ADL candidates, anyway?
10076
10077 // FIXME: Pass in the explicit template arguments?
10078 ArgumentDependentLookup(Name, Loc, Args, Fns);
10079
10080 // Erase all of the candidates we already knew about.
10081 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10082 CandEnd = CandidateSet.end();
10083 Cand != CandEnd; ++Cand)
10084 if (Cand->Function) {
10085 FunctionDecl *Fn = Cand->Function;
10086 Fns.erase(Fn);
10087 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10088 Fns.erase(FunTmpl);
10089 }
10090
10091 // For each of the ADL candidates we found, add it to the overload
10092 // set.
10093 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10095
10096 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10097 if (ExplicitTemplateArgs)
10098 continue;
10099
10100 AddOverloadCandidate(
10101 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10102 PartialOverloading, /*AllowExplicit=*/true,
10103 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10104 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10105 AddOverloadCandidate(
10106 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10107 /*SuppressUserConversions=*/false, PartialOverloading,
10108 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10109 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10110 }
10111 } else {
10112 auto *FTD = cast<FunctionTemplateDecl>(*I);
10113 AddTemplateOverloadCandidate(
10114 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10115 /*SuppressUserConversions=*/false, PartialOverloading,
10116 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10117 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10118 *this, Args, FTD->getTemplatedDecl())) {
10119 AddTemplateOverloadCandidate(
10120 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
10121 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
10122 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10124 }
10125 }
10126 }
10127}
10128
10129namespace {
10130enum class Comparison { Equal, Better, Worse };
10131}
10132
10133/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10134/// overload resolution.
10135///
10136/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10137/// Cand1's first N enable_if attributes have precisely the same conditions as
10138/// Cand2's first N enable_if attributes (where N = the number of enable_if
10139/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10140///
10141/// Note that you can have a pair of candidates such that Cand1's enable_if
10142/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10143/// worse than Cand1's.
10144static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10145 const FunctionDecl *Cand2) {
10146 // Common case: One (or both) decls don't have enable_if attrs.
10147 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10148 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10149 if (!Cand1Attr || !Cand2Attr) {
10150 if (Cand1Attr == Cand2Attr)
10151 return Comparison::Equal;
10152 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10153 }
10154
10155 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10156 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10157
10158 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10159 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10160 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10161 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10162
10163 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10164 // has fewer enable_if attributes than Cand2, and vice versa.
10165 if (!Cand1A)
10166 return Comparison::Worse;
10167 if (!Cand2A)
10168 return Comparison::Better;
10169
10170 Cand1ID.clear();
10171 Cand2ID.clear();
10172
10173 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10174 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10175 if (Cand1ID != Cand2ID)
10176 return Comparison::Worse;
10177 }
10178
10179 return Comparison::Equal;
10180}
10181
10182static Comparison
10184 const OverloadCandidate &Cand2) {
10185 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10186 !Cand2.Function->isMultiVersion())
10187 return Comparison::Equal;
10188
10189 // If both are invalid, they are equal. If one of them is invalid, the other
10190 // is better.
10191 if (Cand1.Function->isInvalidDecl()) {
10192 if (Cand2.Function->isInvalidDecl())
10193 return Comparison::Equal;
10194 return Comparison::Worse;
10195 }
10196 if (Cand2.Function->isInvalidDecl())
10197 return Comparison::Better;
10198
10199 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10200 // cpu_dispatch, else arbitrarily based on the identifiers.
10201 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10202 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10203 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10204 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10205
10206 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10207 return Comparison::Equal;
10208
10209 if (Cand1CPUDisp && !Cand2CPUDisp)
10210 return Comparison::Better;
10211 if (Cand2CPUDisp && !Cand1CPUDisp)
10212 return Comparison::Worse;
10213
10214 if (Cand1CPUSpec && Cand2CPUSpec) {
10215 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10216 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10217 ? Comparison::Better
10218 : Comparison::Worse;
10219
10220 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10221 FirstDiff = std::mismatch(
10222 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10223 Cand2CPUSpec->cpus_begin(),
10224 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10225 return LHS->getName() == RHS->getName();
10226 });
10227
10228 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10229 "Two different cpu-specific versions should not have the same "
10230 "identifier list, otherwise they'd be the same decl!");
10231 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10232 ? Comparison::Better
10233 : Comparison::Worse;
10234 }
10235 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10236}
10237
10238/// Compute the type of the implicit object parameter for the given function,
10239/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10240/// null QualType if there is a 'matches anything' implicit object parameter.
10241static std::optional<QualType>
10243 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
10244 return std::nullopt;
10245
10246 auto *M = cast<CXXMethodDecl>(F);
10247 // Static member functions' object parameters match all types.
10248 if (M->isStatic())
10249 return QualType();
10250 return M->getFunctionObjectParameterReferenceType();
10251}
10252
10253// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10254// represent the same entity.
10255static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10256 const FunctionDecl *F2) {
10257 if (declaresSameEntity(F1, F2))
10258 return true;
10259 auto PT1 = F1->getPrimaryTemplate();
10260 auto PT2 = F2->getPrimaryTemplate();
10261 if (PT1 && PT2) {
10262 if (declaresSameEntity(PT1, PT2) ||
10263 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10264 PT2->getInstantiatedFromMemberTemplate()))
10265 return true;
10266 }
10267 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10268 // different functions with same params). Consider removing this (as no test
10269 // fail w/o it).
10270 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10271 if (First) {
10272 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10273 return *T;
10274 }
10275 assert(I < F->getNumParams());
10276 return F->getParamDecl(I++)->getType();
10277 };
10278
10279 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10280 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10281
10282 if (F1NumParams != F2NumParams)
10283 return false;
10284
10285 unsigned I1 = 0, I2 = 0;
10286 for (unsigned I = 0; I != F1NumParams; ++I) {
10287 QualType T1 = NextParam(F1, I1, I == 0);
10288 QualType T2 = NextParam(F2, I2, I == 0);
10289 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10290 if (!Context.hasSameUnqualifiedType(T1, T2))
10291 return false;
10292 }
10293 return true;
10294}
10295
10296/// We're allowed to use constraints partial ordering only if the candidates
10297/// have the same parameter types:
10298/// [over.match.best.general]p2.6
10299/// F1 and F2 are non-template functions with the same
10300/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10302 const OverloadCandidate &Cand1,
10303 const OverloadCandidate &Cand2) {
10304 if (!Cand1.Function || !Cand2.Function)
10305 return false;
10306
10307 FunctionDecl *Fn1 = Cand1.Function;
10308 FunctionDecl *Fn2 = Cand2.Function;
10309
10310 if (Fn1->isVariadic() != Fn2->isVariadic())
10311 return false;
10312
10314 Fn1, Fn2, nullptr, Cand1.isReversed() ^ Cand2.isReversed()))
10315 return false;
10316
10317 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10318 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10319 if (Mem1 && Mem2) {
10320 // if they are member functions, both are direct members of the same class,
10321 // and
10322 if (Mem1->getParent() != Mem2->getParent())
10323 return false;
10324 // if both are non-static member functions, they have the same types for
10325 // their object parameters
10326 if (Mem1->isInstance() && Mem2->isInstance() &&
10328 Mem1->getFunctionObjectParameterReferenceType(),
10329 Mem1->getFunctionObjectParameterReferenceType()))
10330 return false;
10331 }
10332 return true;
10333}
10334
10335/// isBetterOverloadCandidate - Determines whether the first overload
10336/// candidate is a better candidate than the second (C++ 13.3.3p1).
10338 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10340 // Define viable functions to be better candidates than non-viable
10341 // functions.
10342 if (!Cand2.Viable)
10343 return Cand1.Viable;
10344 else if (!Cand1.Viable)
10345 return false;
10346
10347 // [CUDA] A function with 'never' preference is marked not viable, therefore
10348 // is never shown up here. The worst preference shown up here is 'wrong side',
10349 // e.g. an H function called by a HD function in device compilation. This is
10350 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10351 // function which is called only by an H function. A deferred diagnostic will
10352 // be triggered if it is emitted. However a wrong-sided function is still
10353 // a viable candidate here.
10354 //
10355 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10356 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10357 // can be emitted, Cand1 is not better than Cand2. This rule should have
10358 // precedence over other rules.
10359 //
10360 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10361 // other rules should be used to determine which is better. This is because
10362 // host/device based overloading resolution is mostly for determining
10363 // viability of a function. If two functions are both viable, other factors
10364 // should take precedence in preference, e.g. the standard-defined preferences
10365 // like argument conversion ranks or enable_if partial-ordering. The
10366 // preference for pass-object-size parameters is probably most similar to a
10367 // type-based-overloading decision and so should take priority.
10368 //
10369 // If other rules cannot determine which is better, CUDA preference will be
10370 // used again to determine which is better.
10371 //
10372 // TODO: Currently IdentifyPreference does not return correct values
10373 // for functions called in global variable initializers due to missing
10374 // correct context about device/host. Therefore we can only enforce this
10375 // rule when there is a caller. We should enforce this rule for functions
10376 // in global variable initializers once proper context is added.
10377 //
10378 // TODO: We can only enable the hostness based overloading resolution when
10379 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10380 // overloading resolution diagnostics.
10381 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10382 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10383 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10384 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
10385 bool IsCand1ImplicitHD =
10387 bool IsCand2ImplicitHD =
10389 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
10390 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10391 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10392 // The implicit HD function may be a function in a system header which
10393 // is forced by pragma. In device compilation, if we prefer HD candidates
10394 // over wrong-sided candidates, overloading resolution may change, which
10395 // may result in non-deferrable diagnostics. As a workaround, we let
10396 // implicit HD candidates take equal preference as wrong-sided candidates.
10397 // This will preserve the overloading resolution.
10398 // TODO: We still need special handling of implicit HD functions since
10399 // they may incur other diagnostics to be deferred. We should make all
10400 // host/device related diagnostics deferrable and remove special handling
10401 // of implicit HD functions.
10402 auto EmitThreshold =
10403 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10404 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10407 auto Cand1Emittable = P1 > EmitThreshold;
10408 auto Cand2Emittable = P2 > EmitThreshold;
10409 if (Cand1Emittable && !Cand2Emittable)
10410 return true;
10411 if (!Cand1Emittable && Cand2Emittable)
10412 return false;
10413 }
10414 }
10415
10416 // C++ [over.match.best]p1: (Changed in C++23)
10417 //
10418 // -- if F is a static member function, ICS1(F) is defined such
10419 // that ICS1(F) is neither better nor worse than ICS1(G) for
10420 // any function G, and, symmetrically, ICS1(G) is neither
10421 // better nor worse than ICS1(F).
10422 unsigned StartArg = 0;
10423 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
10424 StartArg = 1;
10425
10426 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10427 // We don't allow incompatible pointer conversions in C++.
10428 if (!S.getLangOpts().CPlusPlus)
10429 return ICS.isStandard() &&
10430 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10431
10432 // The only ill-formed conversion we allow in C++ is the string literal to
10433 // char* conversion, which is only considered ill-formed after C++11.
10434 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10436 };
10437
10438 // Define functions that don't require ill-formed conversions for a given
10439 // argument to be better candidates than functions that do.
10440 unsigned NumArgs = Cand1.Conversions.size();
10441 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10442 bool HasBetterConversion = false;
10443 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10444 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10445 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10446 if (Cand1Bad != Cand2Bad) {
10447 if (Cand1Bad)
10448 return false;
10449 HasBetterConversion = true;
10450 }
10451 }
10452
10453 if (HasBetterConversion)
10454 return true;
10455
10456 // C++ [over.match.best]p1:
10457 // A viable function F1 is defined to be a better function than another
10458 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10459 // conversion sequence than ICSi(F2), and then...
10460 bool HasWorseConversion = false;
10461 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10463 Cand1.Conversions[ArgIdx],
10464 Cand2.Conversions[ArgIdx])) {
10466 // Cand1 has a better conversion sequence.
10467 HasBetterConversion = true;
10468 break;
10469
10471 if (Cand1.Function && Cand2.Function &&
10472 Cand1.isReversed() != Cand2.isReversed() &&
10473 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
10474 // Work around large-scale breakage caused by considering reversed
10475 // forms of operator== in C++20:
10476 //
10477 // When comparing a function against a reversed function, if we have a
10478 // better conversion for one argument and a worse conversion for the
10479 // other, the implicit conversion sequences are treated as being equally
10480 // good.
10481 //
10482 // This prevents a comparison function from being considered ambiguous
10483 // with a reversed form that is written in the same way.
10484 //
10485 // We diagnose this as an extension from CreateOverloadedBinOp.
10486 HasWorseConversion = true;
10487 break;
10488 }
10489
10490 // Cand1 can't be better than Cand2.
10491 return false;
10492
10494 // Do nothing.
10495 break;
10496 }
10497 }
10498
10499 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10500 // ICSj(F2), or, if not that,
10501 if (HasBetterConversion && !HasWorseConversion)
10502 return true;
10503
10504 // -- the context is an initialization by user-defined conversion
10505 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10506 // from the return type of F1 to the destination type (i.e.,
10507 // the type of the entity being initialized) is a better
10508 // conversion sequence than the standard conversion sequence
10509 // from the return type of F2 to the destination type.
10511 Cand1.Function && Cand2.Function &&
10512 isa<CXXConversionDecl>(Cand1.Function) &&
10513 isa<CXXConversionDecl>(Cand2.Function)) {
10514 // First check whether we prefer one of the conversion functions over the
10515 // other. This only distinguishes the results in non-standard, extension
10516 // cases such as the conversion from a lambda closure type to a function
10517 // pointer or block.
10522 Cand1.FinalConversion,
10523 Cand2.FinalConversion);
10524
10527
10528 // FIXME: Compare kind of reference binding if conversion functions
10529 // convert to a reference type used in direct reference binding, per
10530 // C++14 [over.match.best]p1 section 2 bullet 3.
10531 }
10532
10533 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10534 // as combined with the resolution to CWG issue 243.
10535 //
10536 // When the context is initialization by constructor ([over.match.ctor] or
10537 // either phase of [over.match.list]), a constructor is preferred over
10538 // a conversion function.
10539 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10540 Cand1.Function && Cand2.Function &&
10541 isa<CXXConstructorDecl>(Cand1.Function) !=
10542 isa<CXXConstructorDecl>(Cand2.Function))
10543 return isa<CXXConstructorDecl>(Cand1.Function);
10544
10545 // -- F1 is a non-template function and F2 is a function template
10546 // specialization, or, if not that,
10547 bool Cand1IsSpecialization = Cand1.Function &&
10549 bool Cand2IsSpecialization = Cand2.Function &&
10551 if (Cand1IsSpecialization != Cand2IsSpecialization)
10552 return Cand2IsSpecialization;
10553
10554 // -- F1 and F2 are function template specializations, and the function
10555 // template for F1 is more specialized than the template for F2
10556 // according to the partial ordering rules described in 14.5.5.2, or,
10557 // if not that,
10558 if (Cand1IsSpecialization && Cand2IsSpecialization) {
10559 const auto *Obj1Context =
10560 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
10561 const auto *Obj2Context =
10562 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
10563 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10566 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
10567 : TPOC_Call,
10569 Obj1Context ? QualType(Obj1Context->getTypeForDecl(), 0)
10570 : QualType{},
10571 Obj2Context ? QualType(Obj2Context->getTypeForDecl(), 0)
10572 : QualType{},
10573 Cand1.isReversed() ^ Cand2.isReversed())) {
10574 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10575 }
10576 }
10577
10578 // -— F1 and F2 are non-template functions with the same
10579 // parameter-type-lists, and F1 is more constrained than F2 [...],
10580 if (!Cand1IsSpecialization && !Cand2IsSpecialization &&
10581 sameFunctionParameterTypeLists(S, Cand1, Cand2) &&
10583 Cand1.Function)
10584 return true;
10585
10586 // -- F1 is a constructor for a class D, F2 is a constructor for a base
10587 // class B of D, and for all arguments the corresponding parameters of
10588 // F1 and F2 have the same type.
10589 // FIXME: Implement the "all parameters have the same type" check.
10590 bool Cand1IsInherited =
10591 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
10592 bool Cand2IsInherited =
10593 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
10594 if (Cand1IsInherited != Cand2IsInherited)
10595 return Cand2IsInherited;
10596 else if (Cand1IsInherited) {
10597 assert(Cand2IsInherited);
10598 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
10599 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
10600 if (Cand1Class->isDerivedFrom(Cand2Class))
10601 return true;
10602 if (Cand2Class->isDerivedFrom(Cand1Class))
10603 return false;
10604 // Inherited from sibling base classes: still ambiguous.
10605 }
10606
10607 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
10608 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
10609 // with reversed order of parameters and F1 is not
10610 //
10611 // We rank reversed + different operator as worse than just reversed, but
10612 // that comparison can never happen, because we only consider reversing for
10613 // the maximally-rewritten operator (== or <=>).
10614 if (Cand1.RewriteKind != Cand2.RewriteKind)
10615 return Cand1.RewriteKind < Cand2.RewriteKind;
10616
10617 // Check C++17 tie-breakers for deduction guides.
10618 {
10619 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
10620 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
10621 if (Guide1 && Guide2) {
10622 // -- F1 is generated from a deduction-guide and F2 is not
10623 if (Guide1->isImplicit() != Guide2->isImplicit())
10624 return Guide2->isImplicit();
10625
10626 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
10627 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
10628 return true;
10629 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
10630 return false;
10631
10632 // --F1 is generated from a non-template constructor and F2 is generated
10633 // from a constructor template
10634 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
10635 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
10636 if (Constructor1 && Constructor2) {
10637 bool isC1Templated = Constructor1->getTemplatedKind() !=
10639 bool isC2Templated = Constructor2->getTemplatedKind() !=
10641 if (isC1Templated != isC2Templated)
10642 return isC2Templated;
10643 }
10644 }
10645 }
10646
10647 // Check for enable_if value-based overload resolution.
10648 if (Cand1.Function && Cand2.Function) {
10649 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
10650 if (Cmp != Comparison::Equal)
10651 return Cmp == Comparison::Better;
10652 }
10653
10654 bool HasPS1 = Cand1.Function != nullptr &&
10656 bool HasPS2 = Cand2.Function != nullptr &&
10658 if (HasPS1 != HasPS2 && HasPS1)
10659 return true;
10660
10661 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
10662 if (MV == Comparison::Better)
10663 return true;
10664 if (MV == Comparison::Worse)
10665 return false;
10666
10667 // If other rules cannot determine which is better, CUDA preference is used
10668 // to determine which is better.
10669 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
10670 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10671 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
10672 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10673 }
10674
10675 // General member function overloading is handled above, so this only handles
10676 // constructors with address spaces.
10677 // This only handles address spaces since C++ has no other
10678 // qualifier that can be used with constructors.
10679 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
10680 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
10681 if (CD1 && CD2) {
10682 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
10683 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
10684 if (AS1 != AS2) {
10686 return true;
10688 return false;
10689 }
10690 }
10691
10692 return false;
10693}
10694
10695/// Determine whether two declarations are "equivalent" for the purposes of
10696/// name lookup and overload resolution. This applies when the same internal/no
10697/// linkage entity is defined by two modules (probably by textually including
10698/// the same header). In such a case, we don't consider the declarations to
10699/// declare the same entity, but we also don't want lookups with both
10700/// declarations visible to be ambiguous in some cases (this happens when using
10701/// a modularized libstdc++).
10703 const NamedDecl *B) {
10704 auto *VA = dyn_cast_or_null<ValueDecl>(A);
10705 auto *VB = dyn_cast_or_null<ValueDecl>(B);
10706 if (!VA || !VB)
10707 return false;
10708
10709 // The declarations must be declaring the same name as an internal linkage
10710 // entity in different modules.
10711 if (!VA->getDeclContext()->getRedeclContext()->Equals(
10712 VB->getDeclContext()->getRedeclContext()) ||
10713 getOwningModule(VA) == getOwningModule(VB) ||
10714 VA->isExternallyVisible() || VB->isExternallyVisible())
10715 return false;
10716
10717 // Check that the declarations appear to be equivalent.
10718 //
10719 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
10720 // For constants and functions, we should check the initializer or body is
10721 // the same. For non-constant variables, we shouldn't allow it at all.
10722 if (Context.hasSameType(VA->getType(), VB->getType()))
10723 return true;
10724
10725 // Enum constants within unnamed enumerations will have different types, but
10726 // may still be similar enough to be interchangeable for our purposes.
10727 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
10728 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
10729 // Only handle anonymous enums. If the enumerations were named and
10730 // equivalent, they would have been merged to the same type.
10731 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
10732 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
10733 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
10734 !Context.hasSameType(EnumA->getIntegerType(),
10735 EnumB->getIntegerType()))
10736 return false;
10737 // Allow this only if the value is the same for both enumerators.
10738 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
10739 }
10740 }
10741
10742 // Nothing else is sufficiently similar.
10743 return false;
10744}
10745
10748 assert(D && "Unknown declaration");
10749 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
10750
10751 Module *M = getOwningModule(D);
10752 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
10753 << !M << (M ? M->getFullModuleName() : "");
10754
10755 for (auto *E : Equiv) {
10756 Module *M = getOwningModule(E);
10757 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
10758 << !M << (M ? M->getFullModuleName() : "");
10759 }
10760}
10761
10763 return FailureKind == ovl_fail_bad_deduction &&
10764 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
10766 static_cast<CNSInfo *>(DeductionFailure.Data)
10767 ->Satisfaction.ContainsErrors;
10768}
10769
10770/// Computes the best viable function (C++ 13.3.3)
10771/// within an overload candidate set.
10772///
10773/// \param Loc The location of the function name (or operator symbol) for
10774/// which overload resolution occurs.
10775///
10776/// \param Best If overload resolution was successful or found a deleted
10777/// function, \p Best points to the candidate function found.
10778///
10779/// \returns The result of overload resolution.
10782 iterator &Best) {
10784 std::transform(begin(), end(), std::back_inserter(Candidates),
10785 [](OverloadCandidate &Cand) { return &Cand; });
10786
10787 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10788 // are accepted by both clang and NVCC. However, during a particular
10789 // compilation mode only one call variant is viable. We need to
10790 // exclude non-viable overload candidates from consideration based
10791 // only on their host/device attributes. Specifically, if one
10792 // candidate call is WrongSide and the other is SameSide, we ignore
10793 // the WrongSide candidate.
10794 // We only need to remove wrong-sided candidates here if
10795 // -fgpu-exclude-wrong-side-overloads is off. When
10796 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10797 // uniformly in isBetterOverloadCandidate.
10798 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
10799 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10800 bool ContainsSameSideCandidate =
10801 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
10802 // Check viable function only.
10803 return Cand->Viable && Cand->Function &&
10804 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
10806 });
10807 if (ContainsSameSideCandidate) {
10808 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
10809 // Check viable function only to avoid unnecessary data copying/moving.
10810 return Cand->Viable && Cand->Function &&
10811 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
10813 };
10814 llvm::erase_if(Candidates, IsWrongSideCandidate);
10815 }
10816 }
10817
10818 // Find the best viable function.
10819 Best = end();
10820 for (auto *Cand : Candidates) {
10821 Cand->Best = false;
10822 if (Cand->Viable) {
10823 if (Best == end() ||
10824 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
10825 Best = Cand;
10826 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
10827 // This candidate has constraint that we were unable to evaluate because
10828 // it referenced an expression that contained an error. Rather than fall
10829 // back onto a potentially unintended candidate (made worse by
10830 // subsuming constraints), treat this as 'no viable candidate'.
10831 Best = end();
10832 return OR_No_Viable_Function;
10833 }
10834 }
10835
10836 // If we didn't find any viable functions, abort.
10837 if (Best == end())
10838 return OR_No_Viable_Function;
10839
10841
10843 PendingBest.push_back(&*Best);
10844 Best->Best = true;
10845
10846 // Make sure that this function is better than every other viable
10847 // function. If not, we have an ambiguity.
10848 while (!PendingBest.empty()) {
10849 auto *Curr = PendingBest.pop_back_val();
10850 for (auto *Cand : Candidates) {
10851 if (Cand->Viable && !Cand->Best &&
10852 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10853 PendingBest.push_back(Cand);
10854 Cand->Best = true;
10855
10857 Curr->Function))
10858 EquivalentCands.push_back(Cand->Function);
10859 else
10860 Best = end();
10861 }
10862 }
10863 }
10864
10865 // If we found more than one best candidate, this is ambiguous.
10866 if (Best == end())
10867 return OR_Ambiguous;
10868
10869 // Best is the best viable function.
10870 if (Best->Function && Best->Function->isDeleted())
10871 return OR_Deleted;
10872
10873 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
10874 Kind == CSK_AddressOfOverloadSet && M &&
10875 M->isImplicitObjectMemberFunction()) {
10876 return OR_No_Viable_Function;
10877 }
10878
10879 if (!EquivalentCands.empty())
10881 EquivalentCands);
10882
10883 return OR_Success;
10884}
10885
10886namespace {
10887
10888enum OverloadCandidateKind {
10889 oc_function,
10890 oc_method,
10891 oc_reversed_binary_operator,
10892 oc_constructor,
10893 oc_implicit_default_constructor,
10894 oc_implicit_copy_constructor,
10895 oc_implicit_move_constructor,
10896 oc_implicit_copy_assignment,
10897 oc_implicit_move_assignment,
10898 oc_implicit_equality_comparison,
10899 oc_inherited_constructor
10900};
10901
10902enum OverloadCandidateSelect {
10903 ocs_non_template,
10904 ocs_template,
10905 ocs_described_template,
10906};
10907
10908static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10909ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
10910 const FunctionDecl *Fn,
10912 std::string &Description) {
10913
10914 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10915 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10916 isTemplate = true;
10917 Description = S.getTemplateArgumentBindingsText(
10918 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
10919 }
10920
10921 OverloadCandidateSelect Select = [&]() {
10922 if (!Description.empty())
10923 return ocs_described_template;
10924 return isTemplate ? ocs_template : ocs_non_template;
10925 }();
10926
10927 OverloadCandidateKind Kind = [&]() {
10928 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10929 return oc_implicit_equality_comparison;
10930
10931 if (CRK & CRK_Reversed)
10932 return oc_reversed_binary_operator;
10933
10934 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10935 if (!Ctor->isImplicit()) {
10936 if (isa<ConstructorUsingShadowDecl>(Found))
10937 return oc_inherited_constructor;
10938 else
10939 return oc_constructor;
10940 }
10941
10942 if (Ctor->isDefaultConstructor())
10943 return oc_implicit_default_constructor;
10944
10945 if (Ctor->isMoveConstructor())
10946 return oc_implicit_move_constructor;
10947
10948 assert(Ctor->isCopyConstructor() &&
10949 "unexpected sort of implicit constructor");
10950 return oc_implicit_copy_constructor;
10951 }
10952
10953 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
10954 // This actually gets spelled 'candidate function' for now, but
10955 // it doesn't hurt to split it out.
10956 if (!Meth->isImplicit())
10957 return oc_method;
10958
10959 if (Meth->isMoveAssignmentOperator())
10960 return oc_implicit_move_assignment;
10961
10962 if (Meth->isCopyAssignmentOperator())
10963 return oc_implicit_copy_assignment;
10964
10965 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
10966 return oc_method;
10967 }
10968
10969 return oc_function;
10970 }();
10971
10972 return std::make_pair(Kind, Select);
10973}
10974
10975void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
10976 // FIXME: It'd be nice to only emit a note once per using-decl per overload
10977 // set.
10978 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
10979 S.Diag(FoundDecl->getLocation(),
10980 diag::note_ovl_candidate_inherited_constructor)
10981 << Shadow->getNominatedBaseClass();
10982}
10983
10984} // end anonymous namespace
10985
10987 const FunctionDecl *FD) {
10988 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
10989 bool AlwaysTrue;
10990 if (EnableIf->getCond()->isValueDependent() ||
10991 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
10992 return false;
10993 if (!AlwaysTrue)
10994 return false;
10995 }
10996 return true;
10997}
10998
10999/// Returns true if we can take the address of the function.
11000///
11001/// \param Complain - If true, we'll emit a diagnostic
11002/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11003/// we in overload resolution?
11004/// \param Loc - The location of the statement we're complaining about. Ignored
11005/// if we're not complaining, or if we're in overload resolution.
11007 bool Complain,
11008 bool InOverloadResolution,
11009 SourceLocation Loc) {
11010 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11011 if (Complain) {
11012 if (InOverloadResolution)
11013 S.Diag(FD->getBeginLoc(),
11014 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11015 else
11016 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11017 }
11018 return false;
11019 }
11020
11021 if (FD->getTrailingRequiresClause()) {
11022 ConstraintSatisfaction Satisfaction;
11023 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11024 return false;
11025 if (!Satisfaction.IsSatisfied) {
11026 if (Complain) {
11027 if (InOverloadResolution) {
11028 SmallString<128> TemplateArgString;
11029 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11030 TemplateArgString += " ";
11031 TemplateArgString += S.getTemplateArgumentBindingsText(
11032 FunTmpl->getTemplateParameters(),
11034 }
11035
11036 S.Diag(FD->getBeginLoc(),
11037 diag::note_ovl_candidate_unsatisfied_constraints)
11038 << TemplateArgString;
11039 } else
11040 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11041 << FD;
11042 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11043 }
11044 return false;
11045 }
11046 }
11047
11048 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11049 return P->hasAttr<PassObjectSizeAttr>();
11050 });
11051 if (I == FD->param_end())
11052 return true;
11053
11054 if (Complain) {
11055 // Add one to ParamNo because it's user-facing
11056 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11057 if (InOverloadResolution)
11058 S.Diag(FD->getLocation(),
11059 diag::note_ovl_candidate_has_pass_object_size_params)
11060 << ParamNo;
11061 else
11062 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11063 << FD << ParamNo;
11064 }
11065 return false;
11066}
11067
11069 const FunctionDecl *FD) {
11070 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11071 /*InOverloadResolution=*/true,
11072 /*Loc=*/SourceLocation());
11073}
11074
11076 bool Complain,
11077 SourceLocation Loc) {
11078 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11079 /*InOverloadResolution=*/false,
11080 Loc);
11081}
11082
11083// Don't print candidates other than the one that matches the calling
11084// convention of the call operator, since that is guaranteed to exist.
11086 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11087
11088 if (!ConvD)
11089 return false;
11090 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11091 if (!RD->isLambda())
11092 return false;
11093
11094 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11095 CallingConv CallOpCC =
11096 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11097 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11098 CallingConv ConvToCC =
11099 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11100
11101 return ConvToCC != CallOpCC;
11102}
11103
11104// Notes the location of an overload candidate.
11106 OverloadCandidateRewriteKind RewriteKind,
11107 QualType DestType, bool TakingAddress) {
11108 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11109 return;
11110 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11111 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11112 return;
11113 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11114 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11115 return;
11117 return;
11118
11119 std::string FnDesc;
11120 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11121 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11122 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11123 << (unsigned)KSPair.first << (unsigned)KSPair.second
11124 << Fn << FnDesc;
11125
11126 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11127 Diag(Fn->getLocation(), PD);
11128 MaybeEmitInheritedConstructorNote(*this, Found);
11129}
11130
11131static void
11133 // Perhaps the ambiguity was caused by two atomic constraints that are
11134 // 'identical' but not equivalent:
11135 //
11136 // void foo() requires (sizeof(T) > 4) { } // #1
11137 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11138 //
11139 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11140 // #2 to subsume #1, but these constraint are not considered equivalent
11141 // according to the subsumption rules because they are not the same
11142 // source-level construct. This behavior is quite confusing and we should try
11143 // to help the user figure out what happened.
11144
11145 SmallVector<const Expr *, 3> FirstAC, SecondAC;
11146 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11147 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11148 if (!I->Function)
11149 continue;
11151 if (auto *Template = I->Function->getPrimaryTemplate())
11152 Template->getAssociatedConstraints(AC);
11153 else
11154 I->Function->getAssociatedConstraints(AC);
11155 if (AC.empty())
11156 continue;
11157 if (FirstCand == nullptr) {
11158 FirstCand = I->Function;
11159 FirstAC = AC;
11160 } else if (SecondCand == nullptr) {
11161 SecondCand = I->Function;
11162 SecondAC = AC;
11163 } else {
11164 // We have more than one pair of constrained functions - this check is
11165 // expensive and we'd rather not try to diagnose it.
11166 return;
11167 }
11168 }
11169 if (!SecondCand)
11170 return;
11171 // The diagnostic can only happen if there are associated constraints on
11172 // both sides (there needs to be some identical atomic constraint).
11173 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11174 SecondCand, SecondAC))
11175 // Just show the user one diagnostic, they'll probably figure it out
11176 // from here.
11177 return;
11178}
11179
11180// Notes the location of all overload candidates designated through
11181// OverloadedExpr
11182void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11183 bool TakingAddress) {
11184 assert(OverloadedExpr->getType() == Context.OverloadTy);
11185
11186 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11187 OverloadExpr *OvlExpr = Ovl.Expression;
11188
11189 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11190 IEnd = OvlExpr->decls_end();
11191 I != IEnd; ++I) {
11192 if (FunctionTemplateDecl *FunTmpl =
11193 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11194 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11195 TakingAddress);
11196 } else if (FunctionDecl *Fun
11197 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11198 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11199 }
11200 }
11201}
11202
11203/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11204/// "lead" diagnostic; it will be given two arguments, the source and
11205/// target types of the conversion.
11207 Sema &S,
11208 SourceLocation CaretLoc,
11209 const PartialDiagnostic &PDiag) const {
11210 S.Diag(CaretLoc, PDiag)
11211 << Ambiguous.getFromType() << Ambiguous.getToType();
11212 unsigned CandsShown = 0;
11214 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11215 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11216 break;
11217 ++CandsShown;
11218 S.NoteOverloadCandidate(I->first, I->second);
11219 }
11220 S.Diags.overloadCandidatesShown(CandsShown);
11221 if (I != E)
11222 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11223}
11224
11226 unsigned I, bool TakingCandidateAddress) {
11227 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11228 assert(Conv.isBad());
11229 assert(Cand->Function && "for now, candidate must be a function");
11230 FunctionDecl *Fn = Cand->Function;
11231
11232 // There's a conversion slot for the object argument if this is a
11233 // non-constructor method. Note that 'I' corresponds the
11234 // conversion-slot index.
11235 bool isObjectArgument = false;
11236 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
11237 if (I == 0)
11238 isObjectArgument = true;
11239 else if (!Fn->hasCXXExplicitFunctionObjectParameter())
11240 I--;
11241 }
11242
11243 std::string FnDesc;
11244 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11245 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
11246 FnDesc);
11247
11248 Expr *FromExpr = Conv.Bad.FromExpr;
11249 QualType FromTy = Conv.Bad.getFromType();
11250 QualType ToTy = Conv.Bad.getToType();
11251 SourceRange ToParamRange;
11252
11253 // FIXME: In presence of parameter packs we can't determine parameter range
11254 // reliably, as we don't have access to instantiation.
11255 bool HasParamPack =
11256 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
11257 return Parm->isParameterPack();
11258 });
11259 if (!isObjectArgument && !HasParamPack)
11260 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
11261
11262 if (FromTy == S.Context.OverloadTy) {
11263 assert(FromExpr && "overload set argument came from implicit argument?");
11264 Expr *E = FromExpr->IgnoreParens();
11265 if (isa<UnaryOperator>(E))
11266 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11267 DeclarationName Name = cast<OverloadExpr>(E)->getName();
11268
11269 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
11270 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11271 << ToParamRange << ToTy << Name << I + 1;
11272 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11273 return;
11274 }
11275
11276 // Do some hand-waving analysis to see if the non-viability is due
11277 // to a qualifier mismatch.
11278 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
11279 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
11280 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11281 CToTy = RT->getPointeeType();
11282 else {
11283 // TODO: detect and diagnose the full richness of const mismatches.
11284 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11285 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11286 CFromTy = FromPT->getPointeeType();
11287 CToTy = ToPT->getPointeeType();
11288 }
11289 }
11290
11291 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11292 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
11293 Qualifiers FromQs = CFromTy.getQualifiers();
11294 Qualifiers ToQs = CToTy.getQualifiers();
11295
11296 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11297 if (isObjectArgument)
11298 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
11299 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11300 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11301 else
11302 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
11303 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11304 << FnDesc << ToParamRange << FromQs.getAddressSpace()
11305 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11306 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11307 return;
11308 }
11309
11310 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11311 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
11312 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11313 << ToParamRange << FromTy << FromQs.getObjCLifetime()
11314 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11315 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11316 return;
11317 }
11318
11319 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11320 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
11321 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11322 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11323 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11324 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11325 return;
11326 }
11327
11328 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11329 assert(CVR && "expected qualifiers mismatch");
11330
11331 if (isObjectArgument) {
11332 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
11333 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11334 << FromTy << (CVR - 1);
11335 } else {
11336 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
11337 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11338 << ToParamRange << FromTy << (CVR - 1) << I + 1;
11339 }
11340 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11341 return;
11342 }
11343
11346 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
11347 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11348 << (unsigned)isObjectArgument << I + 1
11350 << ToParamRange;
11351 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11352 return;
11353 }
11354
11355 // Special diagnostic for failure to convert an initializer list, since
11356 // telling the user that it has type void is not useful.
11357 if (FromExpr && isa<InitListExpr>(FromExpr)) {
11358 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
11359 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11360 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11363 ? 2
11364 : 0);
11365 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11366 return;
11367 }
11368
11369 // Diagnose references or pointers to incomplete types differently,
11370 // since it's far from impossible that the incompleteness triggered
11371 // the failure.
11372 QualType TempFromTy = FromTy.getNonReferenceType();
11373 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
11374 TempFromTy = PTy->getPointeeType();
11375 if (TempFromTy->isIncompleteType()) {
11376 // Emit the generic diagnostic and, optionally, add the hints to it.
11377 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
11378 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11379 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11380 << (unsigned)(Cand->Fix.Kind);
11381
11382 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11383 return;
11384 }
11385
11386 // Diagnose base -> derived pointer conversions.
11387 unsigned BaseToDerivedConversion = 0;
11388 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
11389 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
11390 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11391 FromPtrTy->getPointeeType(), S.getASTContext()) &&
11392 !FromPtrTy->getPointeeType()->isIncompleteType() &&
11393 !ToPtrTy->getPointeeType()->isIncompleteType() &&
11394 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
11395 FromPtrTy->getPointeeType()))
11396 BaseToDerivedConversion = 1;
11397 }
11398 } else if (const ObjCObjectPointerType *FromPtrTy
11399 = FromTy->getAs<ObjCObjectPointerType>()) {
11400 if (const ObjCObjectPointerType *ToPtrTy
11401 = ToTy->getAs<ObjCObjectPointerType>())
11402 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
11403 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
11404 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11405 FromPtrTy->getPointeeType(), S.getASTContext()) &&
11406 FromIface->isSuperClassOf(ToIface))
11407 BaseToDerivedConversion = 2;
11408 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
11409 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
11410 S.getASTContext()) &&
11411 !FromTy->isIncompleteType() &&
11412 !ToRefTy->getPointeeType()->isIncompleteType() &&
11413 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
11414 BaseToDerivedConversion = 3;
11415 }
11416 }
11417
11418 if (BaseToDerivedConversion) {
11419 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
11420 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11421 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
11422 << I + 1;
11423 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11424 return;
11425 }
11426
11427 if (isa<ObjCObjectPointerType>(CFromTy) &&
11428 isa<PointerType>(CToTy)) {
11429 Qualifiers FromQs = CFromTy.getQualifiers();
11430 Qualifiers ToQs = CToTy.getQualifiers();
11431 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11432 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
11433 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11434 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
11435 << I + 1;
11436 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11437 return;
11438 }
11439 }
11440
11441 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
11442 return;
11443
11444 // Emit the generic diagnostic and, optionally, add the hints to it.
11445 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
11446 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11447 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11448 << (unsigned)(Cand->Fix.Kind);
11449
11450 // Check that location of Fn is not in system header.
11451 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
11452 // If we can fix the conversion, suggest the FixIts.
11453 for (const FixItHint &HI : Cand->Fix.Hints)
11454 FDiag << HI;
11455 }
11456
11457 S.Diag(Fn->getLocation(), FDiag);
11458
11459 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11460}
11461
11462/// Additional arity mismatch diagnosis specific to a function overload
11463/// candidates. This is not covered by the more general DiagnoseArityMismatch()
11464/// over a candidate in any candidate set.
11466 unsigned NumArgs, bool IsAddressOf = false) {
11467 assert(Cand->Function && "Candidate is required to be a function.");
11468 FunctionDecl *Fn = Cand->Function;
11469 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
11470 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
11471
11472 // With invalid overloaded operators, it's possible that we think we
11473 // have an arity mismatch when in fact it looks like we have the
11474 // right number of arguments, because only overloaded operators have
11475 // the weird behavior of overloading member and non-member functions.
11476 // Just don't report anything.
11477 if (Fn->isInvalidDecl() &&
11478 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
11479 return true;
11480
11481 if (NumArgs < MinParams) {
11482 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
11484 Cand->DeductionFailure.getResult() ==
11486 } else {
11487 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
11489 Cand->DeductionFailure.getResult() ==
11491 }
11492
11493 return false;
11494}
11495
11496/// General arity mismatch diagnosis over a candidate in a candidate set.
11498 unsigned NumFormalArgs,
11499 bool IsAddressOf = false) {
11500 assert(isa<FunctionDecl>(D) &&
11501 "The templated declaration should at least be a function"
11502 " when diagnosing bad template argument deduction due to too many"
11503 " or too few arguments");
11504
11505 FunctionDecl *Fn = cast<FunctionDecl>(D);
11506
11507 // TODO: treat calls to a missing default constructor as a special case
11508 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
11509 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
11510 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
11511
11512 // at least / at most / exactly
11513 bool HasExplicitObjectParam =
11514 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
11515
11516 unsigned ParamCount =
11517 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
11518 unsigned mode, modeCount;
11519
11520 if (NumFormalArgs < MinParams) {
11521 if (MinParams != ParamCount || FnTy->isVariadic() ||
11522 FnTy->isTemplateVariadic())
11523 mode = 0; // "at least"
11524 else
11525 mode = 2; // "exactly"
11526 modeCount = MinParams;
11527 } else {
11528 if (MinParams != ParamCount)
11529 mode = 1; // "at most"
11530 else
11531 mode = 2; // "exactly"
11532 modeCount = ParamCount;
11533 }
11534
11535 std::string Description;
11536 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11537 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
11538
11539 if (modeCount == 1 && !IsAddressOf &&
11540 Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())
11541 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
11542 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11543 << Description << mode
11544 << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
11545 << HasExplicitObjectParam << Fn->getParametersSourceRange();
11546 else
11547 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
11548 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11549 << Description << mode << modeCount << NumFormalArgs
11550 << HasExplicitObjectParam << Fn->getParametersSourceRange();
11551
11552 MaybeEmitInheritedConstructorNote(S, Found);
11553}
11554
11555/// Arity mismatch diagnosis specific to a function overload candidate.
11557 unsigned NumFormalArgs) {
11558 assert(Cand->Function && "Candidate must be a function");
11559 FunctionDecl *Fn = Cand->Function;
11560 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
11561 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
11562 Cand->TookAddressOfOverload);
11563}
11564
11566 if (TemplateDecl *TD = Templated->getDescribedTemplate())
11567 return TD;
11568 llvm_unreachable("Unsupported: Getting the described template declaration"
11569 " for bad deduction diagnosis");
11570}
11571
11572/// Diagnose a failed template-argument deduction.
11573static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
11574 DeductionFailureInfo &DeductionFailure,
11575 unsigned NumArgs,
11576 bool TakingCandidateAddress) {
11577 TemplateParameter Param = DeductionFailure.getTemplateParameter();
11578 NamedDecl *ParamD;
11579 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
11580 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
11581 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
11582 switch (DeductionFailure.getResult()) {
11584 llvm_unreachable(
11585 "TemplateDeductionResult::Success while diagnosing bad deduction");
11587 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
11588 "while diagnosing bad deduction");
11591 return;
11592
11594 assert(ParamD && "no parameter found for incomplete deduction result");
11595 S.Diag(Templated->getLocation(),
11596 diag::note_ovl_candidate_incomplete_deduction)
11597 << ParamD->getDeclName();
11598 MaybeEmitInheritedConstructorNote(S, Found);
11599 return;
11600 }
11601
11603 assert(ParamD && "no parameter found for incomplete deduction result");
11604 S.Diag(Templated->getLocation(),
11605 diag::note_ovl_candidate_incomplete_deduction_pack)
11606 << ParamD->getDeclName()
11607 << (DeductionFailure.getFirstArg()->pack_size() + 1)
11608 << *DeductionFailure.getFirstArg();
11609 MaybeEmitInheritedConstructorNote(S, Found);
11610 return;
11611 }
11612
11614 assert(ParamD && "no parameter found for bad qualifiers deduction result");
11615 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
11616
11617 QualType Param = DeductionFailure.getFirstArg()->getAsType();
11618
11619 // Param will have been canonicalized, but it should just be a
11620 // qualified version of ParamD, so move the qualifiers to that.
11622 Qs.strip(Param);
11623 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
11624 assert(S.Context.hasSameType(Param, NonCanonParam));
11625
11626 // Arg has also been canonicalized, but there's nothing we can do
11627 // about that. It also doesn't matter as much, because it won't
11628 // have any template parameters in it (because deduction isn't
11629 // done on dependent types).
11630 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
11631
11632 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
11633 << ParamD->getDeclName() << Arg << NonCanonParam;
11634 MaybeEmitInheritedConstructorNote(S, Found);
11635 return;
11636 }
11637
11639 assert(ParamD && "no parameter found for inconsistent deduction result");
11640 int which = 0;
11641 if (isa<TemplateTypeParmDecl>(ParamD))
11642 which = 0;
11643 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
11644 // Deduction might have failed because we deduced arguments of two
11645 // different types for a non-type template parameter.
11646 // FIXME: Use a different TDK value for this.
11647 QualType T1 =
11648 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
11649 QualType T2 =
11650 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
11651 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
11652 S.Diag(Templated->getLocation(),
11653 diag::note_ovl_candidate_inconsistent_deduction_types)
11654 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
11655 << *DeductionFailure.getSecondArg() << T2;
11656 MaybeEmitInheritedConstructorNote(S, Found);
11657 return;
11658 }
11659
11660 which = 1;
11661 } else {
11662 which = 2;
11663 }
11664
11665 // Tweak the diagnostic if the problem is that we deduced packs of
11666 // different arities. We'll print the actual packs anyway in case that
11667 // includes additional useful information.
11668 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
11669 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
11670 DeductionFailure.getFirstArg()->pack_size() !=
11671 DeductionFailure.getSecondArg()->pack_size()) {
11672 which = 3;
11673 }
11674
11675 S.Diag(Templated->getLocation(),
11676 diag::note_ovl_candidate_inconsistent_deduction)
11677 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
11678 << *DeductionFailure.getSecondArg();
11679 MaybeEmitInheritedConstructorNote(S, Found);
11680 return;
11681 }
11682
11684 assert(ParamD && "no parameter found for invalid explicit arguments");
11685 if (ParamD->getDeclName())
11686 S.Diag(Templated->getLocation(),
11687 diag::note_ovl_candidate_explicit_arg_mismatch_named)
11688 << ParamD->getDeclName();
11689 else {
11690 int index = 0;
11691 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
11692 index = TTP->getIndex();
11693 else if (NonTypeTemplateParmDecl *NTTP
11694 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
11695 index = NTTP->getIndex();
11696 else
11697 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
11698 S.Diag(Templated->getLocation(),
11699 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
11700 << (index + 1);
11701 }
11702 MaybeEmitInheritedConstructorNote(S, Found);
11703 return;
11704
11706 // Format the template argument list into the argument string.
11707 SmallString<128> TemplateArgString;
11708 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
11709 TemplateArgString = " ";
11710 TemplateArgString += S.getTemplateArgumentBindingsText(
11711 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11712 if (TemplateArgString.size() == 1)
11713 TemplateArgString.clear();
11714 S.Diag(Templated->getLocation(),
11715 diag::note_ovl_candidate_unsatisfied_constraints)
11716 << TemplateArgString;
11717
11719 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
11720 return;
11721 }
11724 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
11725 return;
11726
11728 S.Diag(Templated->getLocation(),
11729 diag::note_ovl_candidate_instantiation_depth);
11730 MaybeEmitInheritedConstructorNote(S, Found);
11731 return;
11732
11734 // Format the template argument list into the argument string.
11735 SmallString<128> TemplateArgString;
11736 if (TemplateArgumentList *Args =
11737 DeductionFailure.getTemplateArgumentList()) {
11738 TemplateArgString = " ";
11739 TemplateArgString += S.getTemplateArgumentBindingsText(
11740 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11741 if (TemplateArgString.size() == 1)
11742 TemplateArgString.clear();
11743 }
11744
11745 // If this candidate was disabled by enable_if, say so.
11746 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
11747 if (PDiag && PDiag->second.getDiagID() ==
11748 diag::err_typename_nested_not_found_enable_if) {
11749 // FIXME: Use the source range of the condition, and the fully-qualified
11750 // name of the enable_if template. These are both present in PDiag.
11751 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
11752 << "'enable_if'" << TemplateArgString;
11753 return;
11754 }
11755
11756 // We found a specific requirement that disabled the enable_if.
11757 if (PDiag && PDiag->second.getDiagID() ==
11758 diag::err_typename_nested_not_found_requirement) {
11759 S.Diag(Templated->getLocation(),
11760 diag::note_ovl_candidate_disabled_by_requirement)
11761 << PDiag->second.getStringArg(0) << TemplateArgString;
11762 return;
11763 }
11764
11765 // Format the SFINAE diagnostic into the argument string.
11766 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
11767 // formatted message in another diagnostic.
11768 SmallString<128> SFINAEArgString;
11769 SourceRange R;
11770 if (PDiag) {
11771 SFINAEArgString = ": ";
11772 R = SourceRange(PDiag->first, PDiag->first);
11773 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
11774 }
11775
11776 S.Diag(Templated->getLocation(),
11777 diag::note_ovl_candidate_substitution_failure)
11778 << TemplateArgString << SFINAEArgString << R;
11779 MaybeEmitInheritedConstructorNote(S, Found);
11780 return;
11781 }
11782
11785 // Format the template argument list into the argument string.
11786 SmallString<128> TemplateArgString;
11787 if (TemplateArgumentList *Args =
11788 DeductionFailure.getTemplateArgumentList()) {
11789 TemplateArgString = " ";
11790 TemplateArgString += S.getTemplateArgumentBindingsText(
11791 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11792 if (TemplateArgString.size() == 1)
11793 TemplateArgString.clear();
11794 }
11795
11796 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
11797 << (*DeductionFailure.getCallArgIndex() + 1)
11798 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
11799 << TemplateArgString
11800 << (DeductionFailure.getResult() ==
11802 break;
11803 }
11804
11806 // FIXME: Provide a source location to indicate what we couldn't match.
11807 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
11808 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
11809 if (FirstTA.getKind() == TemplateArgument::Template &&
11810 SecondTA.getKind() == TemplateArgument::Template) {
11811 TemplateName FirstTN = FirstTA.getAsTemplate();
11812 TemplateName SecondTN = SecondTA.getAsTemplate();
11813 if (FirstTN.getKind() == TemplateName::Template &&
11814 SecondTN.getKind() == TemplateName::Template) {
11815 if (FirstTN.getAsTemplateDecl()->getName() ==
11816 SecondTN.getAsTemplateDecl()->getName()) {
11817 // FIXME: This fixes a bad diagnostic where both templates are named
11818 // the same. This particular case is a bit difficult since:
11819 // 1) It is passed as a string to the diagnostic printer.
11820 // 2) The diagnostic printer only attempts to find a better
11821 // name for types, not decls.
11822 // Ideally, this should folded into the diagnostic printer.
11823 S.Diag(Templated->getLocation(),
11824 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
11825 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
11826 return;
11827 }
11828 }
11829 }
11830
11831 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
11832 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
11833 return;
11834
11835 // FIXME: For generic lambda parameters, check if the function is a lambda
11836 // call operator, and if so, emit a prettier and more informative
11837 // diagnostic that mentions 'auto' and lambda in addition to
11838 // (or instead of?) the canonical template type parameters.
11839 S.Diag(Templated->getLocation(),
11840 diag::note_ovl_candidate_non_deduced_mismatch)
11841 << FirstTA << SecondTA;
11842 return;
11843 }
11844 // TODO: diagnose these individually, then kill off
11845 // note_ovl_candidate_bad_deduction, which is uselessly vague.
11847 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
11848 MaybeEmitInheritedConstructorNote(S, Found);
11849 return;
11851 S.Diag(Templated->getLocation(),
11852 diag::note_cuda_ovl_candidate_target_mismatch);
11853 return;
11854 }
11855}
11856
11857/// Diagnose a failed template-argument deduction, for function calls.
11859 unsigned NumArgs,
11860 bool TakingCandidateAddress) {
11861 assert(Cand->Function && "Candidate must be a function");
11862 FunctionDecl *Fn = Cand->Function;
11866 if (CheckArityMismatch(S, Cand, NumArgs))
11867 return;
11868 }
11869 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
11870 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11871}
11872
11873/// CUDA: diagnose an invalid call across targets.
11875 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11876 assert(Cand->Function && "Candidate must be a Function.");
11877 FunctionDecl *Callee = Cand->Function;
11878
11879 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
11880 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
11881
11882 std::string FnDesc;
11883 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11884 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
11885 Cand->getRewriteKind(), FnDesc);
11886
11887 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11888 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11889 << FnDesc /* Ignored */
11890 << llvm::to_underlying(CalleeTarget) << llvm::to_underlying(CallerTarget);
11891
11892 // This could be an implicit constructor for which we could not infer the
11893 // target due to a collsion. Diagnose that case.
11894 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
11895 if (Meth != nullptr && Meth->isImplicit()) {
11896 CXXRecordDecl *ParentClass = Meth->getParent();
11898
11899 switch (FnKindPair.first) {
11900 default:
11901 return;
11902 case oc_implicit_default_constructor:
11904 break;
11905 case oc_implicit_copy_constructor:
11907 break;
11908 case oc_implicit_move_constructor:
11910 break;
11911 case oc_implicit_copy_assignment:
11913 break;
11914 case oc_implicit_move_assignment:
11916 break;
11917 };
11918
11919 bool ConstRHS = false;
11920 if (Meth->getNumParams()) {
11921 if (const ReferenceType *RT =
11922 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11923 ConstRHS = RT->getPointeeType().isConstQualified();
11924 }
11925 }
11926
11927 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
11928 /* ConstRHS */ ConstRHS,
11929 /* Diagnose */ true);
11930 }
11931}
11932
11934 assert(Cand->Function && "Candidate must be a function");
11935 FunctionDecl *Callee = Cand->Function;
11936 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
11937
11938 S.Diag(Callee->getLocation(),
11939 diag::note_ovl_candidate_disabled_by_function_cond_attr)
11940 << Attr->getCond()->getSourceRange() << Attr->getMessage();
11941}
11942
11944 assert(Cand->Function && "Candidate must be a function");
11945 FunctionDecl *Fn = Cand->Function;
11947 assert(ES.isExplicit() && "not an explicit candidate");
11948
11949 unsigned Kind;
11950 switch (Fn->getDeclKind()) {
11951 case Decl::Kind::CXXConstructor:
11952 Kind = 0;
11953 break;
11954 case Decl::Kind::CXXConversion:
11955 Kind = 1;
11956 break;
11957 case Decl::Kind::CXXDeductionGuide:
11958 Kind = Fn->isImplicit() ? 0 : 2;
11959 break;
11960 default:
11961 llvm_unreachable("invalid Decl");
11962 }
11963
11964 // Note the location of the first (in-class) declaration; a redeclaration
11965 // (particularly an out-of-class definition) will typically lack the
11966 // 'explicit' specifier.
11967 // FIXME: This is probably a good thing to do for all 'candidate' notes.
11968 FunctionDecl *First = Fn->getFirstDecl();
11969 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
11970 First = Pattern->getFirstDecl();
11971
11972 S.Diag(First->getLocation(),
11973 diag::note_ovl_candidate_explicit)
11974 << Kind << (ES.getExpr() ? 1 : 0)
11975 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
11976}
11977
11979 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
11980 if (!DG)
11981 return;
11982 TemplateDecl *OriginTemplate =
11984 // We want to always print synthesized deduction guides for type aliases.
11985 // They would retain the explicit bit of the corresponding constructor.
11986 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
11987 return;
11988 std::string FunctionProto;
11989 llvm::raw_string_ostream OS(FunctionProto);
11990 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
11991 if (!Template) {
11992 // This also could be an instantiation. Find out the primary template.
11993 FunctionDecl *Pattern =
11994 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
11995 if (!Pattern) {
11996 // The implicit deduction guide is built on an explicit non-template
11997 // deduction guide. Currently, this might be the case only for type
11998 // aliases.
11999 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12000 // gets merged.
12001 assert(OriginTemplate->isTypeAlias() &&
12002 "Non-template implicit deduction guides are only possible for "
12003 "type aliases");
12004 DG->print(OS);
12005 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12006 << FunctionProto;
12007 return;
12008 }
12009 Template = Pattern->getDescribedFunctionTemplate();
12010 assert(Template && "Cannot find the associated function template of "
12011 "CXXDeductionGuideDecl?");
12012 }
12013 Template->print(OS);
12014 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12015 << FunctionProto;
12016}
12017
12018/// Generates a 'note' diagnostic for an overload candidate. We've
12019/// already generated a primary error at the call site.
12020///
12021/// It really does need to be a single diagnostic with its caret
12022/// pointed at the candidate declaration. Yes, this creates some
12023/// major challenges of technical writing. Yes, this makes pointing
12024/// out problems with specific arguments quite awkward. It's still
12025/// better than generating twenty screens of text for every failed
12026/// overload.
12027///
12028/// It would be great to be able to express per-candidate problems
12029/// more richly for those diagnostic clients that cared, but we'd
12030/// still have to be just as careful with the default diagnostics.
12031/// \param CtorDestAS Addr space of object being constructed (for ctor
12032/// candidates only).
12034 unsigned NumArgs,
12035 bool TakingCandidateAddress,
12036 LangAS CtorDestAS = LangAS::Default) {
12037 assert(Cand->Function && "Candidate must be a function");
12038 FunctionDecl *Fn = Cand->Function;
12040 return;
12041
12042 // There is no physical candidate declaration to point to for OpenCL builtins.
12043 // Except for failed conversions, the notes are identical for each candidate,
12044 // so do not generate such notes.
12045 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12047 return;
12048
12049 // Skip implicit member functions when trying to resolve
12050 // the address of a an overload set for a function pointer.
12051 if (Cand->TookAddressOfOverload &&
12052 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12053 return;
12054
12055 // Note deleted candidates, but only if they're viable.
12056 if (Cand->Viable) {
12057 if (Fn->isDeleted()) {
12058 std::string FnDesc;
12059 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12060 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12061 Cand->getRewriteKind(), FnDesc);
12062
12063 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12064 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12065 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12066 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12067 return;
12068 }
12069
12070 // We don't really have anything else to say about viable candidates.
12071 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12072 return;
12073 }
12074
12075 // If this is a synthesized deduction guide we're deducing against, add a note
12076 // for it. These deduction guides are not explicitly spelled in the source
12077 // code, so simply printing a deduction failure note mentioning synthesized
12078 // template parameters or pointing to the header of the surrounding RecordDecl
12079 // would be confusing.
12080 //
12081 // We prefer adding such notes at the end of the deduction failure because
12082 // duplicate code snippets appearing in the diagnostic would likely become
12083 // noisy.
12084 auto _ = llvm::make_scope_exit([&] { NoteImplicitDeductionGuide(S, Fn); });
12085
12086 switch (Cand->FailureKind) {
12089 return DiagnoseArityMismatch(S, Cand, NumArgs);
12090
12092 return DiagnoseBadDeduction(S, Cand, NumArgs,
12093 TakingCandidateAddress);
12094
12096 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12097 << (Fn->getPrimaryTemplate() ? 1 : 0);
12098 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12099 return;
12100 }
12101
12103 Qualifiers QualsForPrinting;
12104 QualsForPrinting.setAddressSpace(CtorDestAS);
12105 S.Diag(Fn->getLocation(),
12106 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12107 << QualsForPrinting;
12108 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12109 return;
12110 }
12111
12115 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12116
12118 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12119 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12120 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12121 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12122
12123 // FIXME: this currently happens when we're called from SemaInit
12124 // when user-conversion overload fails. Figure out how to handle
12125 // those conditions and diagnose them well.
12126 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12127 }
12128
12130 return DiagnoseBadTarget(S, Cand);
12131
12132 case ovl_fail_enable_if:
12133 return DiagnoseFailedEnableIfAttr(S, Cand);
12134
12135 case ovl_fail_explicit:
12136 return DiagnoseFailedExplicitSpec(S, Cand);
12137
12139 // It's generally not interesting to note copy/move constructors here.
12140 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12141 return;
12142 S.Diag(Fn->getLocation(),
12143 diag::note_ovl_candidate_inherited_constructor_slice)
12144 << (Fn->getPrimaryTemplate() ? 1 : 0)
12145 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12146 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12147 return;
12148
12150 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
12151 (void)Available;
12152 assert(!Available);
12153 break;
12154 }
12156 // Do nothing, these should simply be ignored.
12157 break;
12158
12160 std::string FnDesc;
12161 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12162 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12163 Cand->getRewriteKind(), FnDesc);
12164
12165 S.Diag(Fn->getLocation(),
12166 diag::note_ovl_candidate_constraints_not_satisfied)
12167 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12168 << FnDesc /* Ignored */;
12169 ConstraintSatisfaction Satisfaction;
12170 if (S.CheckFunctionConstraints(Fn, Satisfaction))
12171 break;
12172 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12173 }
12174 }
12175}
12176
12179 return;
12180
12181 // Desugar the type of the surrogate down to a function type,
12182 // retaining as many typedefs as possible while still showing
12183 // the function type (and, therefore, its parameter types).
12184 QualType FnType = Cand->Surrogate->getConversionType();
12185 bool isLValueReference = false;
12186 bool isRValueReference = false;
12187 bool isPointer = false;
12188 if (const LValueReferenceType *FnTypeRef =
12189 FnType->getAs<LValueReferenceType>()) {
12190 FnType = FnTypeRef->getPointeeType();
12191 isLValueReference = true;
12192 } else if (const RValueReferenceType *FnTypeRef =
12193 FnType->getAs<RValueReferenceType>()) {
12194 FnType = FnTypeRef->getPointeeType();
12195 isRValueReference = true;
12196 }
12197 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12198 FnType = FnTypePtr->getPointeeType();
12199 isPointer = true;
12200 }
12201 // Desugar down to a function type.
12202 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12203 // Reconstruct the pointer/reference as appropriate.
12204 if (isPointer) FnType = S.Context.getPointerType(FnType);
12205 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
12206 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
12207
12208 if (!Cand->Viable &&
12210 S.Diag(Cand->Surrogate->getLocation(),
12211 diag::note_ovl_surrogate_constraints_not_satisfied)
12212 << Cand->Surrogate;
12213 ConstraintSatisfaction Satisfaction;
12214 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12215 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12216 } else {
12217 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
12218 << FnType;
12219 }
12220}
12221
12222static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12223 SourceLocation OpLoc,
12224 OverloadCandidate *Cand) {
12225 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12226 std::string TypeStr("operator");
12227 TypeStr += Opc;
12228 TypeStr += "(";
12229 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12230 if (Cand->Conversions.size() == 1) {
12231 TypeStr += ")";
12232 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12233 } else {
12234 TypeStr += ", ";
12235 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12236 TypeStr += ")";
12237 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12238 }
12239}
12240
12242 OverloadCandidate *Cand) {
12243 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12244 if (ICS.isBad()) break; // all meaningless after first invalid
12245 if (!ICS.isAmbiguous()) continue;
12246
12248 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
12249 }
12250}
12251
12253 if (Cand->Function)
12254 return Cand->Function->getLocation();
12255 if (Cand->IsSurrogate)
12256 return Cand->Surrogate->getLocation();
12257 return SourceLocation();
12258}
12259
12260static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12261 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12265 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12266
12270 return 1;
12271
12274 return 2;
12275
12283 return 3;
12284
12286 return 4;
12287
12289 return 5;
12290
12293 return 6;
12294 }
12295 llvm_unreachable("Unhandled deduction result");
12296}
12297
12298namespace {
12299
12300struct CompareOverloadCandidatesForDisplay {
12301 Sema &S;
12303 size_t NumArgs;
12305
12306 CompareOverloadCandidatesForDisplay(
12307 Sema &S, SourceLocation Loc, size_t NArgs,
12309 : S(S), NumArgs(NArgs), CSK(CSK) {}
12310
12311 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12312 // If there are too many or too few arguments, that's the high-order bit we
12313 // want to sort by, even if the immediate failure kind was something else.
12314 if (C->FailureKind == ovl_fail_too_many_arguments ||
12315 C->FailureKind == ovl_fail_too_few_arguments)
12316 return static_cast<OverloadFailureKind>(C->FailureKind);
12317
12318 if (C->Function) {
12319 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12321 if (NumArgs < C->Function->getMinRequiredArguments())
12323 }
12324
12325 return static_cast<OverloadFailureKind>(C->FailureKind);
12326 }
12327
12328 bool operator()(const OverloadCandidate *L,
12329 const OverloadCandidate *R) {
12330 // Fast-path this check.
12331 if (L == R) return false;
12332
12333 // Order first by viability.
12334 if (L->Viable) {
12335 if (!R->Viable) return true;
12336
12337 if (int Ord = CompareConversions(*L, *R))
12338 return Ord < 0;
12339 // Use other tie breakers.
12340 } else if (R->Viable)
12341 return false;
12342
12343 assert(L->Viable == R->Viable);
12344
12345 // Criteria by which we can sort non-viable candidates:
12346 if (!L->Viable) {
12347 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
12348 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
12349
12350 // 1. Arity mismatches come after other candidates.
12351 if (LFailureKind == ovl_fail_too_many_arguments ||
12352 LFailureKind == ovl_fail_too_few_arguments) {
12353 if (RFailureKind == ovl_fail_too_many_arguments ||
12354 RFailureKind == ovl_fail_too_few_arguments) {
12355 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
12356 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
12357 if (LDist == RDist) {
12358 if (LFailureKind == RFailureKind)
12359 // Sort non-surrogates before surrogates.
12360 return !L->IsSurrogate && R->IsSurrogate;
12361 // Sort candidates requiring fewer parameters than there were
12362 // arguments given after candidates requiring more parameters
12363 // than there were arguments given.
12364 return LFailureKind == ovl_fail_too_many_arguments;
12365 }
12366 return LDist < RDist;
12367 }
12368 return false;
12369 }
12370 if (RFailureKind == ovl_fail_too_many_arguments ||
12371 RFailureKind == ovl_fail_too_few_arguments)
12372 return true;
12373
12374 // 2. Bad conversions come first and are ordered by the number
12375 // of bad conversions and quality of good conversions.
12376 if (LFailureKind == ovl_fail_bad_conversion) {
12377 if (RFailureKind != ovl_fail_bad_conversion)
12378 return true;
12379
12380 // The conversion that can be fixed with a smaller number of changes,
12381 // comes first.
12382 unsigned numLFixes = L->Fix.NumConversionsFixed;
12383 unsigned numRFixes = R->Fix.NumConversionsFixed;
12384 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
12385 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
12386 if (numLFixes != numRFixes) {
12387 return numLFixes < numRFixes;
12388 }
12389
12390 // If there's any ordering between the defined conversions...
12391 if (int Ord = CompareConversions(*L, *R))
12392 return Ord < 0;
12393 } else if (RFailureKind == ovl_fail_bad_conversion)
12394 return false;
12395
12396 if (LFailureKind == ovl_fail_bad_deduction) {
12397 if (RFailureKind != ovl_fail_bad_deduction)
12398 return true;
12399
12401 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
12402 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
12403 if (LRank != RRank)
12404 return LRank < RRank;
12405 }
12406 } else if (RFailureKind == ovl_fail_bad_deduction)
12407 return false;
12408
12409 // TODO: others?
12410 }
12411
12412 // Sort everything else by location.
12415
12416 // Put candidates without locations (e.g. builtins) at the end.
12417 if (LLoc.isValid() && RLoc.isValid())
12418 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12419 if (LLoc.isValid() && !RLoc.isValid())
12420 return true;
12421 if (RLoc.isValid() && !LLoc.isValid())
12422 return false;
12423 assert(!LLoc.isValid() && !RLoc.isValid());
12424 // For builtins and other functions without locations, fallback to the order
12425 // in which they were added into the candidate set.
12426 return L < R;
12427 }
12428
12429private:
12430 struct ConversionSignals {
12431 unsigned KindRank = 0;
12433
12434 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
12435 ConversionSignals Sig;
12436 Sig.KindRank = Seq.getKindRank();
12437 if (Seq.isStandard())
12438 Sig.Rank = Seq.Standard.getRank();
12439 else if (Seq.isUserDefined())
12440 Sig.Rank = Seq.UserDefined.After.getRank();
12441 // We intend StaticObjectArgumentConversion to compare the same as
12442 // StandardConversion with ICR_ExactMatch rank.
12443 return Sig;
12444 }
12445
12446 static ConversionSignals ForObjectArgument() {
12447 // We intend StaticObjectArgumentConversion to compare the same as
12448 // StandardConversion with ICR_ExactMatch rank. Default give us that.
12449 return {};
12450 }
12451 };
12452
12453 // Returns -1 if conversions in L are considered better.
12454 // 0 if they are considered indistinguishable.
12455 // 1 if conversions in R are better.
12456 int CompareConversions(const OverloadCandidate &L,
12457 const OverloadCandidate &R) {
12458 // We cannot use `isBetterOverloadCandidate` because it is defined
12459 // according to the C++ standard and provides a partial order, but we need
12460 // a total order as this function is used in sort.
12461 assert(L.Conversions.size() == R.Conversions.size());
12462 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
12463 auto LS = L.IgnoreObjectArgument && I == 0
12464 ? ConversionSignals::ForObjectArgument()
12465 : ConversionSignals::ForSequence(L.Conversions[I]);
12466 auto RS = R.IgnoreObjectArgument
12467 ? ConversionSignals::ForObjectArgument()
12468 : ConversionSignals::ForSequence(R.Conversions[I]);
12469 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
12470 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
12471 ? -1
12472 : 1;
12473 }
12474 // FIXME: find a way to compare templates for being more or less
12475 // specialized that provides a strict weak ordering.
12476 return 0;
12477 }
12478};
12479}
12480
12481/// CompleteNonViableCandidate - Normally, overload resolution only
12482/// computes up to the first bad conversion. Produces the FixIt set if
12483/// possible.
12484static void
12486 ArrayRef<Expr *> Args,
12488 assert(!Cand->Viable);
12489
12490 // Don't do anything on failures other than bad conversion.
12492 return;
12493
12494 // We only want the FixIts if all the arguments can be corrected.
12495 bool Unfixable = false;
12496 // Use a implicit copy initialization to check conversion fixes.
12498
12499 // Attempt to fix the bad conversion.
12500 unsigned ConvCount = Cand->Conversions.size();
12501 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
12502 ++ConvIdx) {
12503 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
12504 if (Cand->Conversions[ConvIdx].isInitialized() &&
12505 Cand->Conversions[ConvIdx].isBad()) {
12506 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
12507 break;
12508 }
12509 }
12510
12511 // FIXME: this should probably be preserved from the overload
12512 // operation somehow.
12513 bool SuppressUserConversions = false;
12514
12515 unsigned ConvIdx = 0;
12516 unsigned ArgIdx = 0;
12517 ArrayRef<QualType> ParamTypes;
12518 bool Reversed = Cand->isReversed();
12519
12520 if (Cand->IsSurrogate) {
12521 QualType ConvType
12523 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12524 ConvType = ConvPtrType->getPointeeType();
12525 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
12526 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12527 ConvIdx = 1;
12528 } else if (Cand->Function) {
12529 ParamTypes =
12530 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
12531 if (isa<CXXMethodDecl>(Cand->Function) &&
12532 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
12533 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12534 ConvIdx = 1;
12536 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
12538 OO_Subscript)
12539 // Argument 0 is 'this', which doesn't have a corresponding parameter.
12540 ArgIdx = 1;
12541 }
12542 } else {
12543 // Builtin operator.
12544 assert(ConvCount <= 3);
12545 ParamTypes = Cand->BuiltinParamTypes;
12546 }
12547
12548 // Fill in the rest of the conversions.
12549 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
12550 ConvIdx != ConvCount;
12551 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
12552 assert(ArgIdx < Args.size() && "no argument for this arg conversion");
12553 if (Cand->Conversions[ConvIdx].isInitialized()) {
12554 // We've already checked this conversion.
12555 } else if (ParamIdx < ParamTypes.size()) {
12556 if (ParamTypes[ParamIdx]->isDependentType())
12557 Cand->Conversions[ConvIdx].setAsIdentityConversion(
12558 Args[ArgIdx]->getType());
12559 else {
12560 Cand->Conversions[ConvIdx] =
12561 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
12562 SuppressUserConversions,
12563 /*InOverloadResolution=*/true,
12564 /*AllowObjCWritebackConversion=*/
12565 S.getLangOpts().ObjCAutoRefCount);
12566 // Store the FixIt in the candidate if it exists.
12567 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
12568 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
12569 }
12570 } else
12571 Cand->Conversions[ConvIdx].setEllipsis();
12572 }
12573}
12574
12577 SourceLocation OpLoc,
12578 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12579 // Sort the candidates by viability and position. Sorting directly would
12580 // be prohibitive, so we make a set of pointers and sort those.
12582 if (OCD == OCD_AllCandidates) Cands.reserve(size());
12583 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12584 if (!Filter(*Cand))
12585 continue;
12586 switch (OCD) {
12587 case OCD_AllCandidates:
12588 if (!Cand->Viable) {
12589 if (!Cand->Function && !Cand->IsSurrogate) {
12590 // This a non-viable builtin candidate. We do not, in general,
12591 // want to list every possible builtin candidate.
12592 continue;
12593 }
12594 CompleteNonViableCandidate(S, Cand, Args, Kind);
12595 }
12596 break;
12597
12599 if (!Cand->Viable)
12600 continue;
12601 break;
12602
12604 if (!Cand->Best)
12605 continue;
12606 break;
12607 }
12608
12609 Cands.push_back(Cand);
12610 }
12611
12612 llvm::stable_sort(
12613 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
12614
12615 return Cands;
12616}
12617
12619 SourceLocation OpLoc) {
12620 bool DeferHint = false;
12621 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
12622 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
12623 // host device candidates.
12624 auto WrongSidedCands =
12625 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
12626 return (Cand.Viable == false &&
12627 Cand.FailureKind == ovl_fail_bad_target) ||
12628 (Cand.Function &&
12629 Cand.Function->template hasAttr<CUDAHostAttr>() &&
12630 Cand.Function->template hasAttr<CUDADeviceAttr>());
12631 });
12632 DeferHint = !WrongSidedCands.empty();
12633 }
12634 return DeferHint;
12635}
12636
12637/// When overload resolution fails, prints diagnostic messages containing the
12638/// candidates in the candidate set.
12641 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
12642 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12643
12644 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
12645
12646 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
12647
12648 // In WebAssembly we don't want to emit further diagnostics if a table is
12649 // passed as an argument to a function.
12650 bool NoteCands = true;
12651 for (const Expr *Arg : Args) {
12652 if (Arg->getType()->isWebAssemblyTableType())
12653 NoteCands = false;
12654 }
12655
12656 if (NoteCands)
12657 NoteCandidates(S, Args, Cands, Opc, OpLoc);
12658
12659 if (OCD == OCD_AmbiguousCandidates)
12661}
12662
12665 StringRef Opc, SourceLocation OpLoc) {
12666 bool ReportedAmbiguousConversions = false;
12667
12668 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12669 unsigned CandsShown = 0;
12670 auto I = Cands.begin(), E = Cands.end();
12671 for (; I != E; ++I) {
12672 OverloadCandidate *Cand = *I;
12673
12674 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
12675 ShowOverloads == Ovl_Best) {
12676 break;
12677 }
12678 ++CandsShown;
12679
12680 if (Cand->Function)
12681 NoteFunctionCandidate(S, Cand, Args.size(),
12682 /*TakingCandidateAddress=*/false, DestAS);
12683 else if (Cand->IsSurrogate)
12684 NoteSurrogateCandidate(S, Cand);
12685 else {
12686 assert(Cand->Viable &&
12687 "Non-viable built-in candidates are not added to Cands.");
12688 // Generally we only see ambiguities including viable builtin
12689 // operators if overload resolution got screwed up by an
12690 // ambiguous user-defined conversion.
12691 //
12692 // FIXME: It's quite possible for different conversions to see
12693 // different ambiguities, though.
12694 if (!ReportedAmbiguousConversions) {
12695 NoteAmbiguousUserConversions(S, OpLoc, Cand);
12696 ReportedAmbiguousConversions = true;
12697 }
12698
12699 // If this is a viable builtin, print it.
12700 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
12701 }
12702 }
12703
12704 // Inform S.Diags that we've shown an overload set with N elements. This may
12705 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
12706 S.Diags.overloadCandidatesShown(CandsShown);
12707
12708 if (I != E)
12709 S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
12710 shouldDeferDiags(S, Args, OpLoc))
12711 << int(E - I);
12712}
12713
12714static SourceLocation
12716 return Cand->Specialization ? Cand->Specialization->getLocation()
12717 : SourceLocation();
12718}
12719
12720namespace {
12721struct CompareTemplateSpecCandidatesForDisplay {
12722 Sema &S;
12723 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
12724
12725 bool operator()(const TemplateSpecCandidate *L,
12726 const TemplateSpecCandidate *R) {
12727 // Fast-path this check.
12728 if (L == R)
12729 return false;
12730
12731 // Assuming that both candidates are not matches...
12732
12733 // Sort by the ranking of deduction failures.
12737
12738 // Sort everything else by location.
12741
12742 // Put candidates without locations (e.g. builtins) at the end.
12743 if (LLoc.isInvalid())
12744 return false;
12745 if (RLoc.isInvalid())
12746 return true;
12747
12748 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12749 }
12750};
12751}
12752
12753/// Diagnose a template argument deduction failure.
12754/// We are treating these failures as overload failures due to bad
12755/// deductions.
12757 bool ForTakingAddress) {
12758 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
12759 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
12760}
12761
12762void TemplateSpecCandidateSet::destroyCandidates() {
12763 for (iterator i = begin(), e = end(); i != e; ++i) {
12764 i->DeductionFailure.Destroy();
12765 }
12766}
12767
12769 destroyCandidates();
12770 Candidates.clear();
12771}
12772
12773/// NoteCandidates - When no template specialization match is found, prints
12774/// diagnostic messages containing the non-matching specializations that form
12775/// the candidate set.
12776/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
12777/// OCD == OCD_AllCandidates and Cand->Viable == false.
12779 // Sort the candidates by position (assuming no candidate is a match).
12780 // Sorting directly would be prohibitive, so we make a set of pointers
12781 // and sort those.
12783 Cands.reserve(size());
12784 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12785 if (Cand->Specialization)
12786 Cands.push_back(Cand);
12787 // Otherwise, this is a non-matching builtin candidate. We do not,
12788 // in general, want to list every possible builtin candidate.
12789 }
12790
12791 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
12792
12793 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
12794 // for generalization purposes (?).
12795 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12796
12798 unsigned CandsShown = 0;
12799 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
12800 TemplateSpecCandidate *Cand = *I;
12801
12802 // Set an arbitrary limit on the number of candidates we'll spam
12803 // the user with. FIXME: This limit should depend on details of the
12804 // candidate list.
12805 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
12806 break;
12807 ++CandsShown;
12808
12809 assert(Cand->Specialization &&
12810 "Non-matching built-in candidates are not added to Cands.");
12811 Cand->NoteDeductionFailure(S, ForTakingAddress);
12812 }
12813
12814 if (I != E)
12815 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
12816}
12817
12818// [PossiblyAFunctionType] --> [Return]
12819// NonFunctionType --> NonFunctionType
12820// R (A) --> R(A)
12821// R (*)(A) --> R (A)
12822// R (&)(A) --> R (A)
12823// R (S::*)(A) --> R (A)
12825 QualType Ret = PossiblyAFunctionType;
12826 if (const PointerType *ToTypePtr =
12827 PossiblyAFunctionType->getAs<PointerType>())
12828 Ret = ToTypePtr->getPointeeType();
12829 else if (const ReferenceType *ToTypeRef =
12830 PossiblyAFunctionType->getAs<ReferenceType>())
12831 Ret = ToTypeRef->getPointeeType();
12832 else if (const MemberPointerType *MemTypePtr =
12833 PossiblyAFunctionType->getAs<MemberPointerType>())
12834 Ret = MemTypePtr->getPointeeType();
12835 Ret =
12836 Context.getCanonicalType(Ret).getUnqualifiedType();
12837 return Ret;
12838}
12839
12841 bool Complain = true) {
12842 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
12843 S.DeduceReturnType(FD, Loc, Complain))
12844 return true;
12845
12846 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
12847 if (S.getLangOpts().CPlusPlus17 &&
12848 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
12849 !S.ResolveExceptionSpec(Loc, FPT))
12850 return true;
12851
12852 return false;
12853}
12854
12855namespace {
12856// A helper class to help with address of function resolution
12857// - allows us to avoid passing around all those ugly parameters
12858class AddressOfFunctionResolver {
12859 Sema& S;
12860 Expr* SourceExpr;
12861 const QualType& TargetType;
12862 QualType TargetFunctionType; // Extracted function type from target type
12863
12864 bool Complain;
12865 //DeclAccessPair& ResultFunctionAccessPair;
12866 ASTContext& Context;
12867
12868 bool TargetTypeIsNonStaticMemberFunction;
12869 bool FoundNonTemplateFunction;
12870 bool StaticMemberFunctionFromBoundPointer;
12871 bool HasComplained;
12872
12873 OverloadExpr::FindResult OvlExprInfo;
12874 OverloadExpr *OvlExpr;
12875 TemplateArgumentListInfo OvlExplicitTemplateArgs;
12877 TemplateSpecCandidateSet FailedCandidates;
12878
12879public:
12880 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
12881 const QualType &TargetType, bool Complain)
12882 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
12883 Complain(Complain), Context(S.getASTContext()),
12884 TargetTypeIsNonStaticMemberFunction(
12885 !!TargetType->getAs<MemberPointerType>()),
12886 FoundNonTemplateFunction(false),
12887 StaticMemberFunctionFromBoundPointer(false),
12888 HasComplained(false),
12889 OvlExprInfo(OverloadExpr::find(SourceExpr)),
12890 OvlExpr(OvlExprInfo.Expression),
12891 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
12892 ExtractUnqualifiedFunctionTypeFromTargetType();
12893
12894 if (TargetFunctionType->isFunctionType()) {
12895 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
12896 if (!UME->isImplicitAccess() &&
12898 StaticMemberFunctionFromBoundPointer = true;
12899 } else if (OvlExpr->hasExplicitTemplateArgs()) {
12900 DeclAccessPair dap;
12902 OvlExpr, false, &dap)) {
12903 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
12904 if (!Method->isStatic()) {
12905 // If the target type is a non-function type and the function found
12906 // is a non-static member function, pretend as if that was the
12907 // target, it's the only possible type to end up with.
12908 TargetTypeIsNonStaticMemberFunction = true;
12909
12910 // And skip adding the function if its not in the proper form.
12911 // We'll diagnose this due to an empty set of functions.
12912 if (!OvlExprInfo.HasFormOfMemberPointer)
12913 return;
12914 }
12915
12916 Matches.push_back(std::make_pair(dap, Fn));
12917 }
12918 return;
12919 }
12920
12921 if (OvlExpr->hasExplicitTemplateArgs())
12922 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
12923
12924 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
12925 // C++ [over.over]p4:
12926 // If more than one function is selected, [...]
12927 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12928 if (FoundNonTemplateFunction)
12929 EliminateAllTemplateMatches();
12930 else
12931 EliminateAllExceptMostSpecializedTemplate();
12932 }
12933 }
12934
12935 if (S.getLangOpts().CUDA && Matches.size() > 1)
12936 EliminateSuboptimalCudaMatches();
12937 }
12938
12939 bool hasComplained() const { return HasComplained; }
12940
12941private:
12942 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
12943 QualType Discard;
12944 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
12945 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
12946 }
12947
12948 /// \return true if A is considered a better overload candidate for the
12949 /// desired type than B.
12950 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
12951 // If A doesn't have exactly the correct type, we don't want to classify it
12952 // as "better" than anything else. This way, the user is required to
12953 // disambiguate for us if there are multiple candidates and no exact match.
12954 return candidateHasExactlyCorrectType(A) &&
12955 (!candidateHasExactlyCorrectType(B) ||
12956 compareEnableIfAttrs(S, A, B) == Comparison::Better);
12957 }
12958
12959 /// \return true if we were able to eliminate all but one overload candidate,
12960 /// false otherwise.
12961 bool eliminiateSuboptimalOverloadCandidates() {
12962 // Same algorithm as overload resolution -- one pass to pick the "best",
12963 // another pass to be sure that nothing is better than the best.
12964 auto Best = Matches.begin();
12965 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
12966 if (isBetterCandidate(I->second, Best->second))
12967 Best = I;
12968
12969 const FunctionDecl *BestFn = Best->second;
12970 auto IsBestOrInferiorToBest = [this, BestFn](
12971 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
12972 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
12973 };
12974
12975 // Note: We explicitly leave Matches unmodified if there isn't a clear best
12976 // option, so we can potentially give the user a better error
12977 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
12978 return false;
12979 Matches[0] = *Best;
12980 Matches.resize(1);
12981 return true;
12982 }
12983
12984 bool isTargetTypeAFunction() const {
12985 return TargetFunctionType->isFunctionType();
12986 }
12987
12988 // [ToType] [Return]
12989
12990 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
12991 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
12992 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
12993 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
12994 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
12995 }
12996
12997 // return true if any matching specializations were found
12998 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
12999 const DeclAccessPair& CurAccessFunPair) {
13000 if (CXXMethodDecl *Method
13001 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13002 // Skip non-static function templates when converting to pointer, and
13003 // static when converting to member pointer.
13004 bool CanConvertToFunctionPointer =
13005 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13006 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13007 return false;
13008 }
13009 else if (TargetTypeIsNonStaticMemberFunction)
13010 return false;
13011
13012 // C++ [over.over]p2:
13013 // If the name is a function template, template argument deduction is
13014 // done (14.8.2.2), and if the argument deduction succeeds, the
13015 // resulting template argument list is used to generate a single
13016 // function template specialization, which is added to the set of
13017 // overloaded functions considered.
13018 FunctionDecl *Specialization = nullptr;
13019 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13021 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13022 Specialization, Info, /*IsAddressOfFunction*/ true);
13023 Result != TemplateDeductionResult::Success) {
13024 // Make a note of the failed deduction for diagnostics.
13025 FailedCandidates.addCandidate()
13026 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13027 MakeDeductionFailureInfo(Context, Result, Info));
13028 return false;
13029 }
13030
13031 // Template argument deduction ensures that we have an exact match or
13032 // compatible pointer-to-function arguments that would be adjusted by ICS.
13033 // This function template specicalization works.
13035 Context.getCanonicalType(Specialization->getType()),
13036 Context.getCanonicalType(TargetFunctionType)));
13037
13039 return false;
13040
13041 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13042 return true;
13043 }
13044
13045 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13046 const DeclAccessPair& CurAccessFunPair) {
13047 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13048 // Skip non-static functions when converting to pointer, and static
13049 // when converting to member pointer.
13050 bool CanConvertToFunctionPointer =
13051 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13052 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13053 return false;
13054 }
13055 else if (TargetTypeIsNonStaticMemberFunction)
13056 return false;
13057
13058 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13059 if (S.getLangOpts().CUDA) {
13060 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13061 if (!(Caller && Caller->isImplicit()) &&
13062 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13063 return false;
13064 }
13065 if (FunDecl->isMultiVersion()) {
13066 const auto *TA = FunDecl->getAttr<TargetAttr>();
13067 if (TA && !TA->isDefaultVersion())
13068 return false;
13069 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13070 if (TVA && !TVA->isDefaultVersion())
13071 return false;
13072 }
13073
13074 // If any candidate has a placeholder return type, trigger its deduction
13075 // now.
13076 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13077 Complain)) {
13078 HasComplained |= Complain;
13079 return false;
13080 }
13081
13082 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13083 return false;
13084
13085 // If we're in C, we need to support types that aren't exactly identical.
13086 if (!S.getLangOpts().CPlusPlus ||
13087 candidateHasExactlyCorrectType(FunDecl)) {
13088 Matches.push_back(std::make_pair(
13089 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13090 FoundNonTemplateFunction = true;
13091 return true;
13092 }
13093 }
13094
13095 return false;
13096 }
13097
13098 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13099 bool Ret = false;
13100
13101 // If the overload expression doesn't have the form of a pointer to
13102 // member, don't try to convert it to a pointer-to-member type.
13103 if (IsInvalidFormOfPointerToMemberFunction())
13104 return false;
13105
13106 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13107 E = OvlExpr->decls_end();
13108 I != E; ++I) {
13109 // Look through any using declarations to find the underlying function.
13110 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13111
13112 // C++ [over.over]p3:
13113 // Non-member functions and static member functions match
13114 // targets of type "pointer-to-function" or "reference-to-function."
13115 // Nonstatic member functions match targets of
13116 // type "pointer-to-member-function."
13117 // Note that according to DR 247, the containing class does not matter.
13118 if (FunctionTemplateDecl *FunctionTemplate
13119 = dyn_cast<FunctionTemplateDecl>(Fn)) {
13120 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13121 Ret = true;
13122 }
13123 // If we have explicit template arguments supplied, skip non-templates.
13124 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13125 AddMatchingNonTemplateFunction(Fn, I.getPair()))
13126 Ret = true;
13127 }
13128 assert(Ret || Matches.empty());
13129 return Ret;
13130 }
13131
13132 void EliminateAllExceptMostSpecializedTemplate() {
13133 // [...] and any given function template specialization F1 is
13134 // eliminated if the set contains a second function template
13135 // specialization whose function template is more specialized
13136 // than the function template of F1 according to the partial
13137 // ordering rules of 14.5.5.2.
13138
13139 // The algorithm specified above is quadratic. We instead use a
13140 // two-pass algorithm (similar to the one used to identify the
13141 // best viable function in an overload set) that identifies the
13142 // best function template (if it exists).
13143
13144 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13145 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13146 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13147
13148 // TODO: It looks like FailedCandidates does not serve much purpose
13149 // here, since the no_viable diagnostic has index 0.
13151 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13152 SourceExpr->getBeginLoc(), S.PDiag(),
13153 S.PDiag(diag::err_addr_ovl_ambiguous)
13154 << Matches[0].second->getDeclName(),
13155 S.PDiag(diag::note_ovl_candidate)
13156 << (unsigned)oc_function << (unsigned)ocs_described_template,
13157 Complain, TargetFunctionType);
13158
13159 if (Result != MatchesCopy.end()) {
13160 // Make it the first and only element
13161 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13162 Matches[0].second = cast<FunctionDecl>(*Result);
13163 Matches.resize(1);
13164 } else
13165 HasComplained |= Complain;
13166 }
13167
13168 void EliminateAllTemplateMatches() {
13169 // [...] any function template specializations in the set are
13170 // eliminated if the set also contains a non-template function, [...]
13171 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13172 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13173 ++I;
13174 else {
13175 Matches[I] = Matches[--N];
13176 Matches.resize(N);
13177 }
13178 }
13179 }
13180
13181 void EliminateSuboptimalCudaMatches() {
13182 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
13183 Matches);
13184 }
13185
13186public:
13187 void ComplainNoMatchesFound() const {
13188 assert(Matches.empty());
13189 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
13190 << OvlExpr->getName() << TargetFunctionType
13191 << OvlExpr->getSourceRange();
13192 if (FailedCandidates.empty())
13193 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13194 /*TakingAddress=*/true);
13195 else {
13196 // We have some deduction failure messages. Use them to diagnose
13197 // the function templates, and diagnose the non-template candidates
13198 // normally.
13199 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13200 IEnd = OvlExpr->decls_end();
13201 I != IEnd; ++I)
13202 if (FunctionDecl *Fun =
13203 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
13205 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
13206 /*TakingAddress=*/true);
13207 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
13208 }
13209 }
13210
13211 bool IsInvalidFormOfPointerToMemberFunction() const {
13212 return TargetTypeIsNonStaticMemberFunction &&
13213 !OvlExprInfo.HasFormOfMemberPointer;
13214 }
13215
13216 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13217 // TODO: Should we condition this on whether any functions might
13218 // have matched, or is it more appropriate to do that in callers?
13219 // TODO: a fixit wouldn't hurt.
13220 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
13221 << TargetType << OvlExpr->getSourceRange();
13222 }
13223
13224 bool IsStaticMemberFunctionFromBoundPointer() const {
13225 return StaticMemberFunctionFromBoundPointer;
13226 }
13227
13228 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13229 S.Diag(OvlExpr->getBeginLoc(),
13230 diag::err_invalid_form_pointer_member_function)
13231 << OvlExpr->getSourceRange();
13232 }
13233
13234 void ComplainOfInvalidConversion() const {
13235 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
13236 << OvlExpr->getName() << TargetType;
13237 }
13238
13239 void ComplainMultipleMatchesFound() const {
13240 assert(Matches.size() > 1);
13241 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
13242 << OvlExpr->getName() << OvlExpr->getSourceRange();
13243 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13244 /*TakingAddress=*/true);
13245 }
13246
13247 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13248
13249 int getNumMatches() const { return Matches.size(); }
13250
13251 FunctionDecl* getMatchingFunctionDecl() const {
13252 if (Matches.size() != 1) return nullptr;
13253 return Matches[0].second;
13254 }
13255
13256 const DeclAccessPair* getMatchingFunctionAccessPair() const {
13257 if (Matches.size() != 1) return nullptr;
13258 return &Matches[0].first;
13259 }
13260};
13261}
13262
13265 QualType TargetType,
13266 bool Complain,
13267 DeclAccessPair &FoundResult,
13268 bool *pHadMultipleCandidates) {
13269 assert(AddressOfExpr->getType() == Context.OverloadTy);
13270
13271 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13272 Complain);
13273 int NumMatches = Resolver.getNumMatches();
13274 FunctionDecl *Fn = nullptr;
13275 bool ShouldComplain = Complain && !Resolver.hasComplained();
13276 if (NumMatches == 0 && ShouldComplain) {
13277 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13278 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13279 else
13280 Resolver.ComplainNoMatchesFound();
13281 }
13282 else if (NumMatches > 1 && ShouldComplain)
13283 Resolver.ComplainMultipleMatchesFound();
13284 else if (NumMatches == 1) {
13285 Fn = Resolver.getMatchingFunctionDecl();
13286 assert(Fn);
13287 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13288 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
13289 FoundResult = *Resolver.getMatchingFunctionAccessPair();
13290 if (Complain) {
13291 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13292 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13293 else
13294 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
13295 }
13296 }
13297
13298 if (pHadMultipleCandidates)
13299 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13300 return Fn;
13301}
13302
13306 OverloadExpr *Ovl = R.Expression;
13307 bool IsResultAmbiguous = false;
13308 FunctionDecl *Result = nullptr;
13309 DeclAccessPair DAP;
13310 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
13311
13312 // Return positive for better, negative for worse, 0 for equal preference.
13313 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
13314 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
13315 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
13316 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
13317 };
13318
13319 // Don't use the AddressOfResolver because we're specifically looking for
13320 // cases where we have one overload candidate that lacks
13321 // enable_if/pass_object_size/...
13322 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
13323 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
13324 if (!FD)
13325 return nullptr;
13326
13328 continue;
13329
13330 // If we found a better result, update Result.
13331 auto FoundBetter = [&]() {
13332 IsResultAmbiguous = false;
13333 DAP = I.getPair();
13334 Result = FD;
13335 };
13336
13337 // We have more than one result - see if it is more constrained than the
13338 // previous one.
13339 if (Result) {
13340 // Check CUDA preference first. If the candidates have differennt CUDA
13341 // preference, choose the one with higher CUDA preference. Otherwise,
13342 // choose the one with more constraints.
13343 if (getLangOpts().CUDA) {
13344 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
13345 // FD has different preference than Result.
13346 if (PreferenceByCUDA != 0) {
13347 // FD is more preferable than Result.
13348 if (PreferenceByCUDA > 0)
13349 FoundBetter();
13350 continue;
13351 }
13352 }
13353 // FD has the same CUDA prefernece than Result. Continue check
13354 // constraints.
13355 FunctionDecl *MoreConstrained = getMoreConstrainedFunction(FD, Result);
13356 if (MoreConstrained != FD) {
13357 if (!MoreConstrained) {
13358 IsResultAmbiguous = true;
13359 AmbiguousDecls.push_back(FD);
13360 }
13361 continue;
13362 }
13363 // FD is more constrained - replace Result with it.
13364 }
13365 FoundBetter();
13366 }
13367
13368 if (IsResultAmbiguous)
13369 return nullptr;
13370
13371 if (Result) {
13373 // We skipped over some ambiguous declarations which might be ambiguous with
13374 // the selected result.
13375 for (FunctionDecl *Skipped : AmbiguousDecls) {
13376 // If skipped candidate has different CUDA preference than the result,
13377 // there is no ambiguity. Otherwise check whether they have different
13378 // constraints.
13379 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
13380 continue;
13381 if (!getMoreConstrainedFunction(Skipped, Result))
13382 return nullptr;
13383 }
13384 Pair = DAP;
13385 }
13386 return Result;
13387}
13388
13390 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
13391 Expr *E = SrcExpr.get();
13392 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
13393
13394 DeclAccessPair DAP;
13395 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
13396 if (!Found || Found->isCPUDispatchMultiVersion() ||
13397 Found->isCPUSpecificMultiVersion())
13398 return false;
13399
13400 // Emitting multiple diagnostics for a function that is both inaccessible and
13401 // unavailable is consistent with our behavior elsewhere. So, always check
13402 // for both.
13403 DiagnoseUseOfDecl(Found, E->getExprLoc());
13404 CheckAddressOfMemberAccess(E, DAP);
13405 ExprResult Res = FixOverloadedFunctionReference(E, DAP, Found);
13406 if (Res.isInvalid())
13407 return false;
13408 Expr *Fixed = Res.get();
13409 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
13410 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
13411 else
13412 SrcExpr = Fixed;
13413 return true;
13414}
13415
13417 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
13418 TemplateSpecCandidateSet *FailedTSC) {
13419 // C++ [over.over]p1:
13420 // [...] [Note: any redundant set of parentheses surrounding the
13421 // overloaded function name is ignored (5.1). ]
13422 // C++ [over.over]p1:
13423 // [...] The overloaded function name can be preceded by the &
13424 // operator.
13425
13426 // If we didn't actually find any template-ids, we're done.
13427 if (!ovl->hasExplicitTemplateArgs())
13428 return nullptr;
13429
13430 TemplateArgumentListInfo ExplicitTemplateArgs;
13431 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
13432
13433 // Look through all of the overloaded functions, searching for one
13434 // whose type matches exactly.
13435 FunctionDecl *Matched = nullptr;
13436 for (UnresolvedSetIterator I = ovl->decls_begin(),
13437 E = ovl->decls_end(); I != E; ++I) {
13438 // C++0x [temp.arg.explicit]p3:
13439 // [...] In contexts where deduction is done and fails, or in contexts
13440 // where deduction is not done, if a template argument list is
13441 // specified and it, along with any default template arguments,
13442 // identifies a single function template specialization, then the
13443 // template-id is an lvalue for the function template specialization.
13444 FunctionTemplateDecl *FunctionTemplate
13445 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
13446
13447 // C++ [over.over]p2:
13448 // If the name is a function template, template argument deduction is
13449 // done (14.8.2.2), and if the argument deduction succeeds, the
13450 // resulting template argument list is used to generate a single
13451 // function template specialization, which is added to the set of
13452 // overloaded functions considered.
13453 FunctionDecl *Specialization = nullptr;
13454 TemplateDeductionInfo Info(ovl->getNameLoc());
13456 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
13457 /*IsAddressOfFunction*/ true);
13459 // Make a note of the failed deduction for diagnostics.
13460 if (FailedTSC)
13461 FailedTSC->addCandidate().set(
13462 I.getPair(), FunctionTemplate->getTemplatedDecl(),
13463 MakeDeductionFailureInfo(Context, Result, Info));
13464 continue;
13465 }
13466
13467 assert(Specialization && "no specialization and no error?");
13468
13469 // Multiple matches; we can't resolve to a single declaration.
13470 if (Matched) {
13471 if (Complain) {
13472 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
13473 << ovl->getName();
13474 NoteAllOverloadCandidates(ovl);
13475 }
13476 return nullptr;
13477 }
13478
13479 Matched = Specialization;
13480 if (FoundResult) *FoundResult = I.getPair();
13481 }
13482
13483 if (Matched &&
13484 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
13485 return nullptr;
13486
13487 return Matched;
13488}
13489
13491 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
13492 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
13493 unsigned DiagIDForComplaining) {
13494 assert(SrcExpr.get()->getType() == Context.OverloadTy);
13495
13497
13498 DeclAccessPair found;
13499 ExprResult SingleFunctionExpression;
13500 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
13501 ovl.Expression, /*complain*/ false, &found)) {
13502 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
13503 SrcExpr = ExprError();
13504 return true;
13505 }
13506
13507 // It is only correct to resolve to an instance method if we're
13508 // resolving a form that's permitted to be a pointer to member.
13509 // Otherwise we'll end up making a bound member expression, which
13510 // is illegal in all the contexts we resolve like this.
13511 if (!ovl.HasFormOfMemberPointer &&
13512 isa<CXXMethodDecl>(fn) &&
13513 cast<CXXMethodDecl>(fn)->isInstance()) {
13514 if (!complain) return false;
13515
13516 Diag(ovl.Expression->getExprLoc(),
13517 diag::err_bound_member_function)
13518 << 0 << ovl.Expression->getSourceRange();
13519
13520 // TODO: I believe we only end up here if there's a mix of
13521 // static and non-static candidates (otherwise the expression
13522 // would have 'bound member' type, not 'overload' type).
13523 // Ideally we would note which candidate was chosen and why
13524 // the static candidates were rejected.
13525 SrcExpr = ExprError();
13526 return true;
13527 }
13528
13529 // Fix the expression to refer to 'fn'.
13530 SingleFunctionExpression =
13531 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
13532
13533 // If desired, do function-to-pointer decay.
13534 if (doFunctionPointerConversion) {
13535 SingleFunctionExpression =
13536 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
13537 if (SingleFunctionExpression.isInvalid()) {
13538 SrcExpr = ExprError();
13539 return true;
13540 }
13541 }
13542 }
13543
13544 if (!SingleFunctionExpression.isUsable()) {
13545 if (complain) {
13546 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
13547 << ovl.Expression->getName()
13548 << DestTypeForComplaining
13549 << OpRangeForComplaining
13551 NoteAllOverloadCandidates(SrcExpr.get());
13552
13553 SrcExpr = ExprError();
13554 return true;
13555 }
13556
13557 return false;
13558 }
13559
13560 SrcExpr = SingleFunctionExpression;
13561 return true;
13562}
13563
13564/// Add a single candidate to the overload set.
13566 DeclAccessPair FoundDecl,
13567 TemplateArgumentListInfo *ExplicitTemplateArgs,
13568 ArrayRef<Expr *> Args,
13569 OverloadCandidateSet &CandidateSet,
13570 bool PartialOverloading,
13571 bool KnownValid) {
13572 NamedDecl *Callee = FoundDecl.getDecl();
13573 if (isa<UsingShadowDecl>(Callee))
13574 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
13575
13576 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
13577 if (ExplicitTemplateArgs) {
13578 assert(!KnownValid && "Explicit template arguments?");
13579 return;
13580 }
13581 // Prevent ill-formed function decls to be added as overload candidates.
13582 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
13583 return;
13584
13585 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
13586 /*SuppressUserConversions=*/false,
13587 PartialOverloading);
13588 return;
13589 }
13590
13591 if (FunctionTemplateDecl *FuncTemplate
13592 = dyn_cast<FunctionTemplateDecl>(Callee)) {
13593 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
13594 ExplicitTemplateArgs, Args, CandidateSet,
13595 /*SuppressUserConversions=*/false,
13596 PartialOverloading);
13597 return;
13598 }
13599
13600 assert(!KnownValid && "unhandled case in overloaded call candidate");
13601}
13602
13604 ArrayRef<Expr *> Args,
13605 OverloadCandidateSet &CandidateSet,
13606 bool PartialOverloading) {
13607
13608#ifndef NDEBUG
13609 // Verify that ArgumentDependentLookup is consistent with the rules
13610 // in C++0x [basic.lookup.argdep]p3:
13611 //
13612 // Let X be the lookup set produced by unqualified lookup (3.4.1)
13613 // and let Y be the lookup set produced by argument dependent
13614 // lookup (defined as follows). If X contains
13615 //
13616 // -- a declaration of a class member, or
13617 //
13618 // -- a block-scope function declaration that is not a
13619 // using-declaration, or
13620 //
13621 // -- a declaration that is neither a function or a function
13622 // template
13623 //
13624 // then Y is empty.
13625
13626 if (ULE->requiresADL()) {
13628 E = ULE->decls_end(); I != E; ++I) {
13629 assert(!(*I)->getDeclContext()->isRecord());
13630 assert(isa<UsingShadowDecl>(*I) ||
13631 !(*I)->getDeclContext()->isFunctionOrMethod());
13632 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
13633 }
13634 }
13635#endif
13636
13637 // It would be nice to avoid this copy.
13638 TemplateArgumentListInfo TABuffer;
13639 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13640 if (ULE->hasExplicitTemplateArgs()) {
13641 ULE->copyTemplateArgumentsInto(TABuffer);
13642 ExplicitTemplateArgs = &TABuffer;
13643 }
13644
13646 E = ULE->decls_end(); I != E; ++I)
13647 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13648 CandidateSet, PartialOverloading,
13649 /*KnownValid*/ true);
13650
13651 if (ULE->requiresADL())
13652 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
13653 Args, ExplicitTemplateArgs,
13654 CandidateSet, PartialOverloading);
13655}
13656
13658 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
13659 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
13660 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13661 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13662 CandidateSet, false, /*KnownValid*/ false);
13663}
13664
13665/// Determine whether a declaration with the specified name could be moved into
13666/// a different namespace.
13668 switch (Name.getCXXOverloadedOperator()) {
13669 case OO_New: case OO_Array_New:
13670 case OO_Delete: case OO_Array_Delete:
13671 return false;
13672
13673 default:
13674 return true;
13675 }
13676}
13677
13678/// Attempt to recover from an ill-formed use of a non-dependent name in a
13679/// template, where the non-dependent name was declared after the template
13680/// was defined. This is common in code written for a compilers which do not
13681/// correctly implement two-stage name lookup.
13682///
13683/// Returns true if a viable candidate was found and a diagnostic was issued.
13685 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
13687 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
13688 CXXRecordDecl **FoundInClass = nullptr) {
13689 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
13690 return false;
13691
13692 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
13693 if (DC->isTransparentContext())
13694 continue;
13695
13696 SemaRef.LookupQualifiedName(R, DC);
13697
13698 if (!R.empty()) {
13700
13701 OverloadCandidateSet Candidates(FnLoc, CSK);
13702 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
13703 Candidates);
13704
13707 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
13708
13709 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
13710 // We either found non-function declarations or a best viable function
13711 // at class scope. A class-scope lookup result disables ADL. Don't
13712 // look past this, but let the caller know that we found something that
13713 // either is, or might be, usable in this class.
13714 if (FoundInClass) {
13715 *FoundInClass = RD;
13716 if (OR == OR_Success) {
13717 R.clear();
13718 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
13719 R.resolveKind();
13720 }
13721 }
13722 return false;
13723 }
13724
13725 if (OR != OR_Success) {
13726 // There wasn't a unique best function or function template.
13727 return false;
13728 }
13729
13730 // Find the namespaces where ADL would have looked, and suggest
13731 // declaring the function there instead.
13732 Sema::AssociatedNamespaceSet AssociatedNamespaces;
13733 Sema::AssociatedClassSet AssociatedClasses;
13734 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
13735 AssociatedNamespaces,
13736 AssociatedClasses);
13737 Sema::AssociatedNamespaceSet SuggestedNamespaces;
13739 DeclContext *Std = SemaRef.getStdNamespace();
13740 for (Sema::AssociatedNamespaceSet::iterator
13741 it = AssociatedNamespaces.begin(),
13742 end = AssociatedNamespaces.end(); it != end; ++it) {
13743 // Never suggest declaring a function within namespace 'std'.
13744 if (Std && Std->Encloses(*it))
13745 continue;
13746
13747 // Never suggest declaring a function within a namespace with a
13748 // reserved name, like __gnu_cxx.
13749 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
13750 if (NS &&
13751 NS->getQualifiedNameAsString().find("__") != std::string::npos)
13752 continue;
13753
13754 SuggestedNamespaces.insert(*it);
13755 }
13756 }
13757
13758 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
13759 << R.getLookupName();
13760 if (SuggestedNamespaces.empty()) {
13761 SemaRef.Diag(Best->Function->getLocation(),
13762 diag::note_not_found_by_two_phase_lookup)
13763 << R.getLookupName() << 0;
13764 } else if (SuggestedNamespaces.size() == 1) {
13765 SemaRef.Diag(Best->Function->getLocation(),
13766 diag::note_not_found_by_two_phase_lookup)
13767 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
13768 } else {
13769 // FIXME: It would be useful to list the associated namespaces here,
13770 // but the diagnostics infrastructure doesn't provide a way to produce
13771 // a localized representation of a list of items.
13772 SemaRef.Diag(Best->Function->getLocation(),
13773 diag::note_not_found_by_two_phase_lookup)
13774 << R.getLookupName() << 2;
13775 }
13776
13777 // Try to recover by calling this function.
13778 return true;
13779 }
13780
13781 R.clear();
13782 }
13783
13784 return false;
13785}
13786
13787/// Attempt to recover from ill-formed use of a non-dependent operator in a
13788/// template, where the non-dependent operator was declared after the template
13789/// was defined.
13790///
13791/// Returns true if a viable candidate was found and a diagnostic was issued.
13792static bool
13794 SourceLocation OpLoc,
13795 ArrayRef<Expr *> Args) {
13796 DeclarationName OpName =
13798 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
13799 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
13801 /*ExplicitTemplateArgs=*/nullptr, Args);
13802}
13803
13804namespace {
13805class BuildRecoveryCallExprRAII {
13806 Sema &SemaRef;
13808
13809public:
13810 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
13811 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
13812 SemaRef.IsBuildingRecoveryCallExpr = true;
13813 }
13814
13815 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
13816};
13817}
13818
13819/// Attempts to recover from a call where no functions were found.
13820///
13821/// This function will do one of three things:
13822/// * Diagnose, recover, and return a recovery expression.
13823/// * Diagnose, fail to recover, and return ExprError().
13824/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
13825/// expected to diagnose as appropriate.
13826static ExprResult
13829 SourceLocation LParenLoc,
13831 SourceLocation RParenLoc,
13832 bool EmptyLookup, bool AllowTypoCorrection) {
13833 // Do not try to recover if it is already building a recovery call.
13834 // This stops infinite loops for template instantiations like
13835 //
13836 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
13837 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
13838 if (SemaRef.IsBuildingRecoveryCallExpr)
13839 return ExprResult();
13840 BuildRecoveryCallExprRAII RCE(SemaRef);
13841
13842 CXXScopeSpec SS;
13843 SS.Adopt(ULE->getQualifierLoc());
13844 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
13845
13846 TemplateArgumentListInfo TABuffer;
13847 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13848 if (ULE->hasExplicitTemplateArgs()) {
13849 ULE->copyTemplateArgumentsInto(TABuffer);
13850 ExplicitTemplateArgs = &TABuffer;
13851 }
13852
13853 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
13855 CXXRecordDecl *FoundInClass = nullptr;
13856 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
13858 ExplicitTemplateArgs, Args, &FoundInClass)) {
13859 // OK, diagnosed a two-phase lookup issue.
13860 } else if (EmptyLookup) {
13861 // Try to recover from an empty lookup with typo correction.
13862 R.clear();
13863 NoTypoCorrectionCCC NoTypoValidator{};
13864 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
13865 ExplicitTemplateArgs != nullptr,
13866 dyn_cast<MemberExpr>(Fn));
13867 CorrectionCandidateCallback &Validator =
13868 AllowTypoCorrection
13869 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
13870 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
13871 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
13872 Args))
13873 return ExprError();
13874 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
13875 // We found a usable declaration of the name in a dependent base of some
13876 // enclosing class.
13877 // FIXME: We should also explain why the candidates found by name lookup
13878 // were not viable.
13879 if (SemaRef.DiagnoseDependentMemberLookup(R))
13880 return ExprError();
13881 } else {
13882 // We had viable candidates and couldn't recover; let the caller diagnose
13883 // this.
13884 return ExprResult();
13885 }
13886
13887 // If we get here, we should have issued a diagnostic and formed a recovery
13888 // lookup result.
13889 assert(!R.empty() && "lookup results empty despite recovery");
13890
13891 // If recovery created an ambiguity, just bail out.
13892 if (R.isAmbiguous()) {
13894 return ExprError();
13895 }
13896
13897 // Build an implicit member call if appropriate. Just drop the
13898 // casts and such from the call, we don't really care.
13899 ExprResult NewFn = ExprError();
13900 if ((*R.begin())->isCXXClassMember())
13901 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
13902 ExplicitTemplateArgs, S);
13903 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
13904 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
13905 ExplicitTemplateArgs);
13906 else
13907 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
13908
13909 if (NewFn.isInvalid())
13910 return ExprError();
13911
13912 // This shouldn't cause an infinite loop because we're giving it
13913 // an expression with viable lookup results, which should never
13914 // end up here.
13915 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
13916 MultiExprArg(Args.data(), Args.size()),
13917 RParenLoc);
13918}
13919
13922 MultiExprArg Args,
13923 SourceLocation RParenLoc,
13924 OverloadCandidateSet *CandidateSet,
13925 ExprResult *Result) {
13926#ifndef NDEBUG
13927 if (ULE->requiresADL()) {
13928 // To do ADL, we must have found an unqualified name.
13929 assert(!ULE->getQualifier() && "qualified name with ADL");
13930
13931 // We don't perform ADL for implicit declarations of builtins.
13932 // Verify that this was correctly set up.
13933 FunctionDecl *F;
13934 if (ULE->decls_begin() != ULE->decls_end() &&
13935 ULE->decls_begin() + 1 == ULE->decls_end() &&
13936 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
13937 F->getBuiltinID() && F->isImplicit())
13938 llvm_unreachable("performing ADL for builtin");
13939
13940 // We don't perform ADL in C.
13941 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
13942 }
13943#endif
13944
13945 UnbridgedCastsSet UnbridgedCasts;
13946 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
13947 *Result = ExprError();
13948 return true;
13949 }
13950
13951 // Add the functions denoted by the callee to the set of candidate
13952 // functions, including those from argument-dependent lookup.
13953 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
13954
13955 if (getLangOpts().MSVCCompat &&
13956 CurContext->isDependentContext() && !isSFINAEContext() &&
13957 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
13958
13960 if (CandidateSet->empty() ||
13961 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
13963 // In Microsoft mode, if we are inside a template class member function
13964 // then create a type dependent CallExpr. The goal is to postpone name
13965 // lookup to instantiation time to be able to search into type dependent
13966 // base classes.
13967 CallExpr *CE =
13968 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
13969 RParenLoc, CurFPFeatureOverrides());
13971 *Result = CE;
13972 return true;
13973 }
13974 }
13975
13976 if (CandidateSet->empty())
13977 return false;
13978
13979 UnbridgedCasts.restore();
13980 return false;
13981}
13982
13983// Guess at what the return type for an unresolvable overload should be.
13986 std::optional<QualType> Result;
13987 // Adjust Type after seeing a candidate.
13988 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
13989 if (!Candidate.Function)
13990 return;
13991 if (Candidate.Function->isInvalidDecl())
13992 return;
13993 QualType T = Candidate.Function->getReturnType();
13994 if (T.isNull())
13995 return;
13996 if (!Result)
13997 Result = T;
13998 else if (Result != T)
13999 Result = QualType();
14000 };
14001
14002 // Look for an unambiguous type from a progressively larger subset.
14003 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14004 //
14005 // First, consider only the best candidate.
14006 if (Best && *Best != CS.end())
14007 ConsiderCandidate(**Best);
14008 // Next, consider only viable candidates.
14009 if (!Result)
14010 for (const auto &C : CS)
14011 if (C.Viable)
14012 ConsiderCandidate(C);
14013 // Finally, consider all candidates.
14014 if (!Result)
14015 for (const auto &C : CS)
14016 ConsiderCandidate(C);
14017
14018 if (!Result)
14019 return QualType();
14020 auto Value = *Result;
14021 if (Value.isNull() || Value->isUndeducedType())
14022 return QualType();
14023 return Value;
14024}
14025
14026/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14027/// the completed call expression. If overload resolution fails, emits
14028/// diagnostics and returns ExprError()
14031 SourceLocation LParenLoc,
14032 MultiExprArg Args,
14033 SourceLocation RParenLoc,
14034 Expr *ExecConfig,
14035 OverloadCandidateSet *CandidateSet,
14037 OverloadingResult OverloadResult,
14038 bool AllowTypoCorrection) {
14039 switch (OverloadResult) {
14040 case OR_Success: {
14041 FunctionDecl *FDecl = (*Best)->Function;
14042 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14043 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14044 return ExprError();
14045 ExprResult Res =
14046 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14047 if (Res.isInvalid())
14048 return ExprError();
14049 return SemaRef.BuildResolvedCallExpr(
14050 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14051 /*IsExecConfig=*/false, (*Best)->IsADLCandidate);
14052 }
14053
14054 case OR_No_Viable_Function: {
14055 if (*Best != CandidateSet->end() &&
14056 CandidateSet->getKind() ==
14058 if (CXXMethodDecl *M =
14059 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
14061 CandidateSet->NoteCandidates(
14063 Fn->getBeginLoc(),
14064 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
14065 SemaRef, OCD_AmbiguousCandidates, Args);
14066 return ExprError();
14067 }
14068 }
14069
14070 // Try to recover by looking for viable functions which the user might
14071 // have meant to call.
14072 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14073 Args, RParenLoc,
14074 CandidateSet->empty(),
14075 AllowTypoCorrection);
14076 if (Recovery.isInvalid() || Recovery.isUsable())
14077 return Recovery;
14078
14079 // If the user passes in a function that we can't take the address of, we
14080 // generally end up emitting really bad error messages. Here, we attempt to
14081 // emit better ones.
14082 for (const Expr *Arg : Args) {
14083 if (!Arg->getType()->isFunctionType())
14084 continue;
14085 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14086 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14087 if (FD &&
14088 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14089 Arg->getExprLoc()))
14090 return ExprError();
14091 }
14092 }
14093
14094 CandidateSet->NoteCandidates(
14096 Fn->getBeginLoc(),
14097 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14098 << ULE->getName() << Fn->getSourceRange()),
14099 SemaRef, OCD_AllCandidates, Args);
14100 break;
14101 }
14102
14103 case OR_Ambiguous:
14104 CandidateSet->NoteCandidates(
14105 PartialDiagnosticAt(Fn->getBeginLoc(),
14106 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14107 << ULE->getName() << Fn->getSourceRange()),
14108 SemaRef, OCD_AmbiguousCandidates, Args);
14109 break;
14110
14111 case OR_Deleted: {
14112 FunctionDecl *FDecl = (*Best)->Function;
14113 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
14114 Fn->getSourceRange(), ULE->getName(),
14115 *CandidateSet, FDecl, Args);
14116
14117 // We emitted an error for the unavailable/deleted function call but keep
14118 // the call in the AST.
14119 ExprResult Res =
14120 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14121 if (Res.isInvalid())
14122 return ExprError();
14123 return SemaRef.BuildResolvedCallExpr(
14124 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14125 /*IsExecConfig=*/false, (*Best)->IsADLCandidate);
14126 }
14127 }
14128
14129 // Overload resolution failed, try to recover.
14130 SmallVector<Expr *, 8> SubExprs = {Fn};
14131 SubExprs.append(Args.begin(), Args.end());
14132 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
14133 chooseRecoveryType(*CandidateSet, Best));
14134}
14135
14138 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14139 if (I->Viable &&
14140 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
14141 I->Viable = false;
14142 I->FailureKind = ovl_fail_addr_not_available;
14143 }
14144 }
14145}
14146
14149 SourceLocation LParenLoc,
14150 MultiExprArg Args,
14151 SourceLocation RParenLoc,
14152 Expr *ExecConfig,
14153 bool AllowTypoCorrection,
14154 bool CalleesAddressIsTaken) {
14155 OverloadCandidateSet CandidateSet(
14156 Fn->getExprLoc(), CalleesAddressIsTaken
14159 ExprResult result;
14160
14161 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
14162 &result))
14163 return result;
14164
14165 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14166 // functions that aren't addressible are considered unviable.
14167 if (CalleesAddressIsTaken)
14168 markUnaddressableCandidatesUnviable(*this, CandidateSet);
14169
14171 OverloadingResult OverloadResult =
14172 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
14173
14174 // Model the case with a call to a templated function whose definition
14175 // encloses the call and whose return type contains a placeholder type as if
14176 // the UnresolvedLookupExpr was type-dependent.
14177 if (OverloadResult == OR_Success) {
14178 const FunctionDecl *FDecl = Best->Function;
14179 if (FDecl && FDecl->isTemplateInstantiation() &&
14180 FDecl->getReturnType()->isUndeducedType()) {
14181 if (const auto *TP =
14182 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14183 TP && TP->willHaveBody()) {
14184 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
14185 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
14186 }
14187 }
14188 }
14189
14190 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14191 ExecConfig, &CandidateSet, &Best,
14192 OverloadResult, AllowTypoCorrection);
14193}
14194
14198 const UnresolvedSetImpl &Fns,
14199 bool PerformADL) {
14201 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
14202 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
14203}
14204
14206 CXXConversionDecl *Method,
14207 bool HadMultipleCandidates) {
14208 // Convert the expression to match the conversion function's implicit object
14209 // parameter.
14210 ExprResult Exp;
14211 if (Method->isExplicitObjectMemberFunction())
14212 Exp = InitializeExplicitObjectArgument(*this, E, Method);
14213 else
14214 Exp = PerformImplicitObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
14215 FoundDecl, Method);
14216 if (Exp.isInvalid())
14217 return true;
14218
14219 if (Method->getParent()->isLambda() &&
14221 // This is a lambda conversion to block pointer; check if the argument
14222 // was a LambdaExpr.
14223 Expr *SubE = E;
14224 auto *CE = dyn_cast<CastExpr>(SubE);
14225 if (CE && CE->getCastKind() == CK_NoOp)
14226 SubE = CE->getSubExpr();
14227 SubE = SubE->IgnoreParens();
14228 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
14229 SubE = BE->getSubExpr();
14230 if (isa<LambdaExpr>(SubE)) {
14231 // For the conversion to block pointer on a lambda expression, we
14232 // construct a special BlockLiteral instead; this doesn't really make
14233 // a difference in ARC, but outside of ARC the resulting block literal
14234 // follows the normal lifetime rules for block literals instead of being
14235 // autoreleased.
14236 PushExpressionEvaluationContext(
14237 ExpressionEvaluationContext::PotentiallyEvaluated);
14238 ExprResult BlockExp = BuildBlockForLambdaConversion(
14239 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
14240 PopExpressionEvaluationContext();
14241
14242 // FIXME: This note should be produced by a CodeSynthesisContext.
14243 if (BlockExp.isInvalid())
14244 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
14245 return BlockExp;
14246 }
14247 }
14248 CallExpr *CE;
14249 QualType ResultType = Method->getReturnType();
14251 ResultType = ResultType.getNonLValueExprType(Context);
14252 if (Method->isExplicitObjectMemberFunction()) {
14253 ExprResult FnExpr =
14254 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
14255 HadMultipleCandidates, E->getBeginLoc());
14256 if (FnExpr.isInvalid())
14257 return ExprError();
14258 Expr *ObjectParam = Exp.get();
14259 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
14260 ResultType, VK, Exp.get()->getEndLoc(),
14261 CurFPFeatureOverrides());
14262 } else {
14263 MemberExpr *ME =
14264 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
14266 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
14267 HadMultipleCandidates, DeclarationNameInfo(),
14269
14270 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
14271 Exp.get()->getEndLoc(),
14272 CurFPFeatureOverrides());
14273 }
14274
14275 if (CheckFunctionCall(Method, CE,
14276 Method->getType()->castAs<FunctionProtoType>()))
14277 return ExprError();
14278
14279 return CheckForImmediateInvocation(CE, CE->getDirectCallee());
14280}
14281
14284 const UnresolvedSetImpl &Fns,
14285 Expr *Input, bool PerformADL) {
14287 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
14289 // TODO: provide better source location info.
14290 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14291
14292 if (checkPlaceholderForOverload(*this, Input))
14293 return ExprError();
14294
14295 Expr *Args[2] = { Input, nullptr };
14296 unsigned NumArgs = 1;
14297
14298 // For post-increment and post-decrement, add the implicit '0' as
14299 // the second argument, so that we know this is a post-increment or
14300 // post-decrement.
14301 if (Opc == UO_PostInc || Opc == UO_PostDec) {
14302 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14303 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
14304 SourceLocation());
14305 NumArgs = 2;
14306 }
14307
14308 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
14309
14310 if (Input->isTypeDependent()) {
14312 // [C++26][expr.unary.op][expr.pre.incr]
14313 // The * operator yields an lvalue of type
14314 // The pre/post increment operators yied an lvalue.
14315 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
14316 VK = VK_LValue;
14317
14318 if (Fns.empty())
14319 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
14320 OK_Ordinary, OpLoc, false,
14321 CurFPFeatureOverrides());
14322
14323 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14324 ExprResult Fn = CreateUnresolvedLookupExpr(
14325 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
14326 if (Fn.isInvalid())
14327 return ExprError();
14328 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
14329 Context.DependentTy, VK_PRValue, OpLoc,
14330 CurFPFeatureOverrides());
14331 }
14332
14333 // Build an empty overload set.
14335
14336 // Add the candidates from the given function set.
14337 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
14338
14339 // Add operator candidates that are member functions.
14340 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14341
14342 // Add candidates from ADL.
14343 if (PerformADL) {
14344 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
14345 /*ExplicitTemplateArgs*/nullptr,
14346 CandidateSet);
14347 }
14348
14349 // Add builtin operator candidates.
14350 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14351
14352 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14353
14354 // Perform overload resolution.
14356 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14357 case OR_Success: {
14358 // We found a built-in operator or an overloaded operator.
14359 FunctionDecl *FnDecl = Best->Function;
14360
14361 if (FnDecl) {
14362 Expr *Base = nullptr;
14363 // We matched an overloaded operator. Build a call to that
14364 // operator.
14365
14366 // Convert the arguments.
14367 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14368 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
14369
14370 ExprResult InputInit;
14371 if (Method->isExplicitObjectMemberFunction())
14372 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
14373 else
14374 InputInit = PerformImplicitObjectArgumentInitialization(
14375 Input, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14376 if (InputInit.isInvalid())
14377 return ExprError();
14378 Base = Input = InputInit.get();
14379 } else {
14380 // Convert the arguments.
14381 ExprResult InputInit
14382 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14383 Context,
14384 FnDecl->getParamDecl(0)),
14386 Input);
14387 if (InputInit.isInvalid())
14388 return ExprError();
14389 Input = InputInit.get();
14390 }
14391
14392 // Build the actual expression node.
14393 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
14394 Base, HadMultipleCandidates,
14395 OpLoc);
14396 if (FnExpr.isInvalid())
14397 return ExprError();
14398
14399 // Determine the result type.
14400 QualType ResultTy = FnDecl->getReturnType();
14402 ResultTy = ResultTy.getNonLValueExprType(Context);
14403
14404 Args[0] = Input;
14406 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
14407 CurFPFeatureOverrides(), Best->IsADLCandidate);
14408
14409 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
14410 return ExprError();
14411
14412 if (CheckFunctionCall(FnDecl, TheCall,
14413 FnDecl->getType()->castAs<FunctionProtoType>()))
14414 return ExprError();
14415 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
14416 } else {
14417 // We matched a built-in operator. Convert the arguments, then
14418 // break out so that we will build the appropriate built-in
14419 // operator node.
14420 ExprResult InputRes = PerformImplicitConversion(
14421 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
14424 if (InputRes.isInvalid())
14425 return ExprError();
14426 Input = InputRes.get();
14427 break;
14428 }
14429 }
14430
14432 // This is an erroneous use of an operator which can be overloaded by
14433 // a non-member function. Check for non-member operators which were
14434 // defined too late to be candidates.
14435 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
14436 // FIXME: Recover by calling the found function.
14437 return ExprError();
14438
14439 // No viable function; fall through to handling this as a
14440 // built-in operator, which will produce an error message for us.
14441 break;
14442
14443 case OR_Ambiguous:
14444 CandidateSet.NoteCandidates(
14445 PartialDiagnosticAt(OpLoc,
14446 PDiag(diag::err_ovl_ambiguous_oper_unary)
14448 << Input->getType() << Input->getSourceRange()),
14449 *this, OCD_AmbiguousCandidates, ArgsArray,
14450 UnaryOperator::getOpcodeStr(Opc), OpLoc);
14451 return ExprError();
14452
14453 case OR_Deleted: {
14454 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
14455 // object whose method was called. Later in NoteCandidates size of ArgsArray
14456 // is passed further and it eventually ends up compared to number of
14457 // function candidate parameters which never includes the object parameter,
14458 // so slice ArgsArray to make sure apples are compared to apples.
14459 StringLiteral *Msg = Best->Function->getDeletedMessage();
14460 CandidateSet.NoteCandidates(
14461 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14463 << (Msg != nullptr)
14464 << (Msg ? Msg->getString() : StringRef())
14465 << Input->getSourceRange()),
14466 *this, OCD_AllCandidates, ArgsArray.drop_front(),
14467 UnaryOperator::getOpcodeStr(Opc), OpLoc);
14468 return ExprError();
14469 }
14470 }
14471
14472 // Either we found no viable overloaded operator or we matched a
14473 // built-in operator. In either case, fall through to trying to
14474 // build a built-in operation.
14475 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14476}
14477
14480 const UnresolvedSetImpl &Fns,
14481 ArrayRef<Expr *> Args, bool PerformADL) {
14482 SourceLocation OpLoc = CandidateSet.getLocation();
14483
14484 OverloadedOperatorKind ExtraOp =
14487 : OO_None;
14488
14489 // Add the candidates from the given function set. This also adds the
14490 // rewritten candidates using these functions if necessary.
14491 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
14492
14493 // Add operator candidates that are member functions.
14494 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14495 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
14496 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
14498
14499 // In C++20, also add any rewritten member candidates.
14500 if (ExtraOp) {
14501 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
14502 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
14503 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
14504 CandidateSet,
14506 }
14507
14508 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
14509 // performed for an assignment operator (nor for operator[] nor operator->,
14510 // which don't get here).
14511 if (Op != OO_Equal && PerformADL) {
14513 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
14514 /*ExplicitTemplateArgs*/ nullptr,
14515 CandidateSet);
14516 if (ExtraOp) {
14517 DeclarationName ExtraOpName =
14518 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
14519 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
14520 /*ExplicitTemplateArgs*/ nullptr,
14521 CandidateSet);
14522 }
14523 }
14524
14525 // Add builtin operator candidates.
14526 //
14527 // FIXME: We don't add any rewritten candidates here. This is strictly
14528 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
14529 // resulting in our selecting a rewritten builtin candidate. For example:
14530 //
14531 // enum class E { e };
14532 // bool operator!=(E, E) requires false;
14533 // bool k = E::e != E::e;
14534 //
14535 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
14536 // it seems unreasonable to consider rewritten builtin candidates. A core
14537 // issue has been filed proposing to removed this requirement.
14538 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14539}
14540
14543 const UnresolvedSetImpl &Fns, Expr *LHS,
14544 Expr *RHS, bool PerformADL,
14545 bool AllowRewrittenCandidates,
14546 FunctionDecl *DefaultedFn) {
14547 Expr *Args[2] = { LHS, RHS };
14548 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
14549
14550 if (!getLangOpts().CPlusPlus20)
14551 AllowRewrittenCandidates = false;
14552
14554
14555 // If either side is type-dependent, create an appropriate dependent
14556 // expression.
14557 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
14558 if (Fns.empty()) {
14559 // If there are no functions to store, just build a dependent
14560 // BinaryOperator or CompoundAssignment.
14563 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
14564 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
14565 Context.DependentTy);
14567 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
14568 OK_Ordinary, OpLoc, CurFPFeatureOverrides());
14569 }
14570
14571 // FIXME: save results of ADL from here?
14572 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14573 // TODO: provide better source location info in DNLoc component.
14575 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14576 ExprResult Fn = CreateUnresolvedLookupExpr(
14577 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
14578 if (Fn.isInvalid())
14579 return ExprError();
14580 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
14581 Context.DependentTy, VK_PRValue, OpLoc,
14582 CurFPFeatureOverrides());
14583 }
14584
14585 // If this is the .* operator, which is not overloadable, just
14586 // create a built-in binary operator.
14587 if (Opc == BO_PtrMemD) {
14588 auto CheckPlaceholder = [&](Expr *&Arg) {
14589 ExprResult Res = CheckPlaceholderExpr(Arg);
14590 if (Res.isUsable())
14591 Arg = Res.get();
14592 return !Res.isUsable();
14593 };
14594
14595 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
14596 // expression that contains placeholders (in either the LHS or RHS).
14597 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
14598 return ExprError();
14599 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14600 }
14601
14602 // Always do placeholder-like conversions on the RHS.
14603 if (checkPlaceholderForOverload(*this, Args[1]))
14604 return ExprError();
14605
14606 // Do placeholder-like conversion on the LHS; note that we should
14607 // not get here with a PseudoObject LHS.
14608 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
14609 if (checkPlaceholderForOverload(*this, Args[0]))
14610 return ExprError();
14611
14612 // If this is the assignment operator, we only perform overload resolution
14613 // if the left-hand side is a class or enumeration type. This is actually
14614 // a hack. The standard requires that we do overload resolution between the
14615 // various built-in candidates, but as DR507 points out, this can lead to
14616 // problems. So we do it this way, which pretty much follows what GCC does.
14617 // Note that we go the traditional code path for compound assignment forms.
14618 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
14619 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14620
14621 // Build the overload set.
14624 Op, OpLoc, AllowRewrittenCandidates));
14625 if (DefaultedFn)
14626 CandidateSet.exclude(DefaultedFn);
14627 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
14628
14629 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14630
14631 // Perform overload resolution.
14633 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14634 case OR_Success: {
14635 // We found a built-in operator or an overloaded operator.
14636 FunctionDecl *FnDecl = Best->Function;
14637
14638 bool IsReversed = Best->isReversed();
14639 if (IsReversed)
14640 std::swap(Args[0], Args[1]);
14641
14642 if (FnDecl) {
14643
14644 if (FnDecl->isInvalidDecl())
14645 return ExprError();
14646
14647 Expr *Base = nullptr;
14648 // We matched an overloaded operator. Build a call to that
14649 // operator.
14650
14651 OverloadedOperatorKind ChosenOp =
14653
14654 // C++2a [over.match.oper]p9:
14655 // If a rewritten operator== candidate is selected by overload
14656 // resolution for an operator@, its return type shall be cv bool
14657 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
14658 !FnDecl->getReturnType()->isBooleanType()) {
14659 bool IsExtension =
14661 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
14662 : diag::err_ovl_rewrite_equalequal_not_bool)
14663 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
14664 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14665 Diag(FnDecl->getLocation(), diag::note_declared_at);
14666 if (!IsExtension)
14667 return ExprError();
14668 }
14669
14670 if (AllowRewrittenCandidates && !IsReversed &&
14671 CandidateSet.getRewriteInfo().isReversible()) {
14672 // We could have reversed this operator, but didn't. Check if some
14673 // reversed form was a viable candidate, and if so, if it had a
14674 // better conversion for either parameter. If so, this call is
14675 // formally ambiguous, and allowing it is an extension.
14677 for (OverloadCandidate &Cand : CandidateSet) {
14678 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
14679 allowAmbiguity(Context, Cand.Function, FnDecl)) {
14680 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
14682 *this, OpLoc, Cand.Conversions[ArgIdx],
14683 Best->Conversions[ArgIdx]) ==
14685 AmbiguousWith.push_back(Cand.Function);
14686 break;
14687 }
14688 }
14689 }
14690 }
14691
14692 if (!AmbiguousWith.empty()) {
14693 bool AmbiguousWithSelf =
14694 AmbiguousWith.size() == 1 &&
14695 declaresSameEntity(AmbiguousWith.front(), FnDecl);
14696 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
14698 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
14699 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14700 if (AmbiguousWithSelf) {
14701 Diag(FnDecl->getLocation(),
14702 diag::note_ovl_ambiguous_oper_binary_reversed_self);
14703 // Mark member== const or provide matching != to disallow reversed
14704 // args. Eg.
14705 // struct S { bool operator==(const S&); };
14706 // S()==S();
14707 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
14708 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
14709 !MD->isConst() &&
14710 !MD->hasCXXExplicitFunctionObjectParameter() &&
14711 Context.hasSameUnqualifiedType(
14712 MD->getFunctionObjectParameterType(),
14713 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
14714 Context.hasSameUnqualifiedType(
14715 MD->getFunctionObjectParameterType(),
14716 Args[0]->getType()) &&
14717 Context.hasSameUnqualifiedType(
14718 MD->getFunctionObjectParameterType(),
14719 Args[1]->getType()))
14720 Diag(FnDecl->getLocation(),
14721 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
14722 } else {
14723 Diag(FnDecl->getLocation(),
14724 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
14725 for (auto *F : AmbiguousWith)
14726 Diag(F->getLocation(),
14727 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
14728 }
14729 }
14730 }
14731
14732 // Check for nonnull = nullable.
14733 // This won't be caught in the arg's initialization: the parameter to
14734 // the assignment operator is not marked nonnull.
14735 if (Op == OO_Equal)
14736 diagnoseNullableToNonnullConversion(Args[0]->getType(),
14737 Args[1]->getType(), OpLoc);
14738
14739 // Convert the arguments.
14740 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14741 // Best->Access is only meaningful for class members.
14742 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
14743
14744 ExprResult Arg0, Arg1;
14745 unsigned ParamIdx = 0;
14746 if (Method->isExplicitObjectMemberFunction()) {
14747 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
14748 ParamIdx = 1;
14749 } else {
14750 Arg0 = PerformImplicitObjectArgumentInitialization(
14751 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14752 }
14753 Arg1 = PerformCopyInitialization(
14755 Context, FnDecl->getParamDecl(ParamIdx)),
14756 SourceLocation(), Args[1]);
14757 if (Arg0.isInvalid() || Arg1.isInvalid())
14758 return ExprError();
14759
14760 Base = Args[0] = Arg0.getAs<Expr>();
14761 Args[1] = RHS = Arg1.getAs<Expr>();
14762 } else {
14763 // Convert the arguments.
14764 ExprResult Arg0 = PerformCopyInitialization(
14766 FnDecl->getParamDecl(0)),
14767 SourceLocation(), Args[0]);
14768 if (Arg0.isInvalid())
14769 return ExprError();
14770
14771 ExprResult Arg1 =
14772 PerformCopyInitialization(
14774 FnDecl->getParamDecl(1)),
14775 SourceLocation(), Args[1]);
14776 if (Arg1.isInvalid())
14777 return ExprError();
14778 Args[0] = LHS = Arg0.getAs<Expr>();
14779 Args[1] = RHS = Arg1.getAs<Expr>();
14780 }
14781
14782 // Build the actual expression node.
14783 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
14784 Best->FoundDecl, Base,
14785 HadMultipleCandidates, OpLoc);
14786 if (FnExpr.isInvalid())
14787 return ExprError();
14788
14789 // Determine the result type.
14790 QualType ResultTy = FnDecl->getReturnType();
14792 ResultTy = ResultTy.getNonLValueExprType(Context);
14793
14794 CallExpr *TheCall;
14795 ArrayRef<const Expr *> ArgsArray(Args, 2);
14796 const Expr *ImplicitThis = nullptr;
14797
14798 // We always create a CXXOperatorCallExpr, even for explicit object
14799 // members; CodeGen should take care not to emit the this pointer.
14801 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
14802 CurFPFeatureOverrides(), Best->IsADLCandidate);
14803
14804 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
14805 Method && Method->isImplicitObjectMemberFunction()) {
14806 // Cut off the implicit 'this'.
14807 ImplicitThis = ArgsArray[0];
14808 ArgsArray = ArgsArray.slice(1);
14809 }
14810
14811 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
14812 FnDecl))
14813 return ExprError();
14814
14815 if (Op == OO_Equal) {
14816 // Check for a self move.
14817 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
14818 // lifetime check.
14820 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
14821 Args[1]);
14822 }
14823 if (ImplicitThis) {
14824 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
14825 QualType ThisTypeFromDecl = Context.getPointerType(
14826 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
14827
14828 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
14829 ThisTypeFromDecl);
14830 }
14831
14832 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
14833 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
14834 VariadicDoesNotApply);
14835
14836 ExprResult R = MaybeBindToTemporary(TheCall);
14837 if (R.isInvalid())
14838 return ExprError();
14839
14840 R = CheckForImmediateInvocation(R, FnDecl);
14841 if (R.isInvalid())
14842 return ExprError();
14843
14844 // For a rewritten candidate, we've already reversed the arguments
14845 // if needed. Perform the rest of the rewrite now.
14846 if ((Best->RewriteKind & CRK_DifferentOperator) ||
14847 (Op == OO_Spaceship && IsReversed)) {
14848 if (Op == OO_ExclaimEqual) {
14849 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
14850 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
14851 } else {
14852 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
14853 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14854 Expr *ZeroLiteral =
14855 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
14856
14859 Ctx.Entity = FnDecl;
14860 pushCodeSynthesisContext(Ctx);
14861
14862 R = CreateOverloadedBinOp(
14863 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
14864 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
14865 /*AllowRewrittenCandidates=*/false);
14866
14867 popCodeSynthesisContext();
14868 }
14869 if (R.isInvalid())
14870 return ExprError();
14871 } else {
14872 assert(ChosenOp == Op && "unexpected operator name");
14873 }
14874
14875 // Make a note in the AST if we did any rewriting.
14876 if (Best->RewriteKind != CRK_None)
14877 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
14878
14879 return R;
14880 } else {
14881 // We matched a built-in operator. Convert the arguments, then
14882 // break out so that we will build the appropriate built-in
14883 // operator node.
14884 ExprResult ArgsRes0 = PerformImplicitConversion(
14885 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14888 if (ArgsRes0.isInvalid())
14889 return ExprError();
14890 Args[0] = ArgsRes0.get();
14891
14892 ExprResult ArgsRes1 = PerformImplicitConversion(
14893 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14896 if (ArgsRes1.isInvalid())
14897 return ExprError();
14898 Args[1] = ArgsRes1.get();
14899 break;
14900 }
14901 }
14902
14903 case OR_No_Viable_Function: {
14904 // C++ [over.match.oper]p9:
14905 // If the operator is the operator , [...] and there are no
14906 // viable functions, then the operator is assumed to be the
14907 // built-in operator and interpreted according to clause 5.
14908 if (Opc == BO_Comma)
14909 break;
14910
14911 // When defaulting an 'operator<=>', we can try to synthesize a three-way
14912 // compare result using '==' and '<'.
14913 if (DefaultedFn && Opc == BO_Cmp) {
14914 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
14915 Args[1], DefaultedFn);
14916 if (E.isInvalid() || E.isUsable())
14917 return E;
14918 }
14919
14920 // For class as left operand for assignment or compound assignment
14921 // operator do not fall through to handling in built-in, but report that
14922 // no overloaded assignment operator found
14924 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
14925 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
14926 Args, OpLoc);
14927 DeferDiagsRAII DDR(*this,
14928 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
14929 if (Args[0]->getType()->isRecordType() &&
14930 Opc >= BO_Assign && Opc <= BO_OrAssign) {
14931 Diag(OpLoc, diag::err_ovl_no_viable_oper)
14933 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14934 if (Args[0]->getType()->isIncompleteType()) {
14935 Diag(OpLoc, diag::note_assign_lhs_incomplete)
14936 << Args[0]->getType()
14937 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14938 }
14939 } else {
14940 // This is an erroneous use of an operator which can be overloaded by
14941 // a non-member function. Check for non-member operators which were
14942 // defined too late to be candidates.
14943 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
14944 // FIXME: Recover by calling the found function.
14945 return ExprError();
14946
14947 // No viable function; try to create a built-in operation, which will
14948 // produce an error. Then, show the non-viable candidates.
14949 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14950 }
14951 assert(Result.isInvalid() &&
14952 "C++ binary operator overloading is missing candidates!");
14953 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
14954 return Result;
14955 }
14956
14957 case OR_Ambiguous:
14958 CandidateSet.NoteCandidates(
14959 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14961 << Args[0]->getType()
14962 << Args[1]->getType()
14963 << Args[0]->getSourceRange()
14964 << Args[1]->getSourceRange()),
14966 OpLoc);
14967 return ExprError();
14968
14969 case OR_Deleted: {
14970 if (isImplicitlyDeleted(Best->Function)) {
14971 FunctionDecl *DeletedFD = Best->Function;
14972 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
14973 if (DFK.isSpecialMember()) {
14974 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
14975 << Args[0]->getType()
14976 << llvm::to_underlying(DFK.asSpecialMember());
14977 } else {
14978 assert(DFK.isComparison());
14979 Diag(OpLoc, diag::err_ovl_deleted_comparison)
14980 << Args[0]->getType() << DeletedFD;
14981 }
14982
14983 // The user probably meant to call this special member. Just
14984 // explain why it's deleted.
14985 NoteDeletedFunction(DeletedFD);
14986 return ExprError();
14987 }
14988
14989 StringLiteral *Msg = Best->Function->getDeletedMessage();
14990 CandidateSet.NoteCandidates(
14992 OpLoc,
14993 PDiag(diag::err_ovl_deleted_oper)
14994 << getOperatorSpelling(Best->Function->getDeclName()
14995 .getCXXOverloadedOperator())
14996 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
14997 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
14999 OpLoc);
15000 return ExprError();
15001 }
15002 }
15003
15004 // We matched a built-in operator; build it.
15005 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15006}
15007
15009 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15010 FunctionDecl *DefaultedFn) {
15011 const ComparisonCategoryInfo *Info =
15012 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
15013 // If we're not producing a known comparison category type, we can't
15014 // synthesize a three-way comparison. Let the caller diagnose this.
15015 if (!Info)
15016 return ExprResult((Expr*)nullptr);
15017
15018 // If we ever want to perform this synthesis more generally, we will need to
15019 // apply the temporary materialization conversion to the operands.
15020 assert(LHS->isGLValue() && RHS->isGLValue() &&
15021 "cannot use prvalue expressions more than once");
15022 Expr *OrigLHS = LHS;
15023 Expr *OrigRHS = RHS;
15024
15025 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15026 // each of them multiple times below.
15027 LHS = new (Context)
15028 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15029 LHS->getObjectKind(), LHS);
15030 RHS = new (Context)
15031 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15032 RHS->getObjectKind(), RHS);
15033
15034 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
15035 DefaultedFn);
15036 if (Eq.isInvalid())
15037 return ExprError();
15038
15039 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
15040 true, DefaultedFn);
15041 if (Less.isInvalid())
15042 return ExprError();
15043
15045 if (Info->isPartial()) {
15046 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
15047 DefaultedFn);
15048 if (Greater.isInvalid())
15049 return ExprError();
15050 }
15051
15052 // Form the list of comparisons we're going to perform.
15053 struct Comparison {
15054 ExprResult Cmp;
15056 } Comparisons[4] =
15062 };
15063
15064 int I = Info->isPartial() ? 3 : 2;
15065
15066 // Combine the comparisons with suitable conditional expressions.
15068 for (; I >= 0; --I) {
15069 // Build a reference to the comparison category constant.
15070 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
15071 // FIXME: Missing a constant for a comparison category. Diagnose this?
15072 if (!VI)
15073 return ExprResult((Expr*)nullptr);
15074 ExprResult ThisResult =
15075 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
15076 if (ThisResult.isInvalid())
15077 return ExprError();
15078
15079 // Build a conditional unless this is the final case.
15080 if (Result.get()) {
15081 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
15082 ThisResult.get(), Result.get());
15083 if (Result.isInvalid())
15084 return ExprError();
15085 } else {
15086 Result = ThisResult;
15087 }
15088 }
15089
15090 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15091 // bind the OpaqueValueExprs before they're (repeatedly) used.
15092 Expr *SyntacticForm = BinaryOperator::Create(
15093 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
15094 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
15095 CurFPFeatureOverrides());
15096 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15097 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
15098}
15099
15101 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15102 MultiExprArg Args, SourceLocation LParenLoc) {
15103
15104 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15105 unsigned NumParams = Proto->getNumParams();
15106 unsigned NumArgsSlots =
15107 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
15108 // Build the full argument list for the method call (the implicit object
15109 // parameter is placed at the beginning of the list).
15110 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
15111 bool IsError = false;
15112 // Initialize the implicit object parameter.
15113 // Check the argument types.
15114 for (unsigned i = 0; i != NumParams; i++) {
15115 Expr *Arg;
15116 if (i < Args.size()) {
15117 Arg = Args[i];
15118 ExprResult InputInit =
15120 S.Context, Method->getParamDecl(i)),
15121 SourceLocation(), Arg);
15122 IsError |= InputInit.isInvalid();
15123 Arg = InputInit.getAs<Expr>();
15124 } else {
15125 ExprResult DefArg =
15126 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
15127 if (DefArg.isInvalid()) {
15128 IsError = true;
15129 break;
15130 }
15131 Arg = DefArg.getAs<Expr>();
15132 }
15133
15134 MethodArgs.push_back(Arg);
15135 }
15136 return IsError;
15137}
15138
15140 SourceLocation RLoc,
15141 Expr *Base,
15142 MultiExprArg ArgExpr) {
15144 Args.push_back(Base);
15145 for (auto *e : ArgExpr) {
15146 Args.push_back(e);
15147 }
15148 DeclarationName OpName =
15149 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
15150
15151 SourceRange Range = ArgExpr.empty()
15152 ? SourceRange{}
15153 : SourceRange(ArgExpr.front()->getBeginLoc(),
15154 ArgExpr.back()->getEndLoc());
15155
15156 // If either side is type-dependent, create an appropriate dependent
15157 // expression.
15159
15160 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15161 // CHECKME: no 'operator' keyword?
15162 DeclarationNameInfo OpNameInfo(OpName, LLoc);
15163 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15164 ExprResult Fn = CreateUnresolvedLookupExpr(
15165 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
15166 if (Fn.isInvalid())
15167 return ExprError();
15168 // Can't add any actual overloads yet
15169
15170 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
15171 Context.DependentTy, VK_PRValue, RLoc,
15172 CurFPFeatureOverrides());
15173 }
15174
15175 // Handle placeholders
15176 UnbridgedCastsSet UnbridgedCasts;
15177 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
15178 return ExprError();
15179 }
15180 // Build an empty overload set.
15182
15183 // Subscript can only be overloaded as a member function.
15184
15185 // Add operator candidates that are member functions.
15186 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15187
15188 // Add builtin operator candidates.
15189 if (Args.size() == 2)
15190 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15191
15192 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15193
15194 // Perform overload resolution.
15196 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
15197 case OR_Success: {
15198 // We found a built-in operator or an overloaded operator.
15199 FunctionDecl *FnDecl = Best->Function;
15200
15201 if (FnDecl) {
15202 // We matched an overloaded operator. Build a call to that
15203 // operator.
15204
15205 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
15206
15207 // Convert the arguments.
15208 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
15209 SmallVector<Expr *, 2> MethodArgs;
15210
15211 // Initialize the object parameter.
15212 if (Method->isExplicitObjectMemberFunction()) {
15213 ExprResult Res =
15214 InitializeExplicitObjectArgument(*this, Args[0], Method);
15215 if (Res.isInvalid())
15216 return ExprError();
15217 Args[0] = Res.get();
15218 ArgExpr = Args;
15219 } else {
15220 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
15221 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15222 if (Arg0.isInvalid())
15223 return ExprError();
15224
15225 MethodArgs.push_back(Arg0.get());
15226 }
15227
15229 *this, MethodArgs, Method, ArgExpr, LLoc);
15230 if (IsError)
15231 return ExprError();
15232
15233 // Build the actual expression node.
15234 DeclarationNameInfo OpLocInfo(OpName, LLoc);
15235 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15237 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
15238 OpLocInfo.getLoc(), OpLocInfo.getInfo());
15239 if (FnExpr.isInvalid())
15240 return ExprError();
15241
15242 // Determine the result type
15243 QualType ResultTy = FnDecl->getReturnType();
15245 ResultTy = ResultTy.getNonLValueExprType(Context);
15246
15248 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
15249 CurFPFeatureOverrides());
15250
15251 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
15252 return ExprError();
15253
15254 if (CheckFunctionCall(Method, TheCall,
15255 Method->getType()->castAs<FunctionProtoType>()))
15256 return ExprError();
15257
15258 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
15259 FnDecl);
15260 } else {
15261 // We matched a built-in operator. Convert the arguments, then
15262 // break out so that we will build the appropriate built-in
15263 // operator node.
15264 ExprResult ArgsRes0 = PerformImplicitConversion(
15265 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15268 if (ArgsRes0.isInvalid())
15269 return ExprError();
15270 Args[0] = ArgsRes0.get();
15271
15272 ExprResult ArgsRes1 = PerformImplicitConversion(
15273 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15276 if (ArgsRes1.isInvalid())
15277 return ExprError();
15278 Args[1] = ArgsRes1.get();
15279
15280 break;
15281 }
15282 }
15283
15284 case OR_No_Viable_Function: {
15286 CandidateSet.empty()
15287 ? (PDiag(diag::err_ovl_no_oper)
15288 << Args[0]->getType() << /*subscript*/ 0
15289 << Args[0]->getSourceRange() << Range)
15290 : (PDiag(diag::err_ovl_no_viable_subscript)
15291 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
15292 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
15293 OCD_AllCandidates, ArgExpr, "[]", LLoc);
15294 return ExprError();
15295 }
15296
15297 case OR_Ambiguous:
15298 if (Args.size() == 2) {
15299 CandidateSet.NoteCandidates(
15301 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15302 << "[]" << Args[0]->getType() << Args[1]->getType()
15303 << Args[0]->getSourceRange() << Range),
15304 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15305 } else {
15306 CandidateSet.NoteCandidates(
15308 PDiag(diag::err_ovl_ambiguous_subscript_call)
15309 << Args[0]->getType()
15310 << Args[0]->getSourceRange() << Range),
15311 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15312 }
15313 return ExprError();
15314
15315 case OR_Deleted: {
15316 StringLiteral *Msg = Best->Function->getDeletedMessage();
15317 CandidateSet.NoteCandidates(
15319 PDiag(diag::err_ovl_deleted_oper)
15320 << "[]" << (Msg != nullptr)
15321 << (Msg ? Msg->getString() : StringRef())
15322 << Args[0]->getSourceRange() << Range),
15323 *this, OCD_AllCandidates, Args, "[]", LLoc);
15324 return ExprError();
15325 }
15326 }
15327
15328 // We matched a built-in operator; build it.
15329 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
15330}
15331
15333 SourceLocation LParenLoc,
15334 MultiExprArg Args,
15335 SourceLocation RParenLoc,
15336 Expr *ExecConfig, bool IsExecConfig,
15337 bool AllowRecovery) {
15338 assert(MemExprE->getType() == Context.BoundMemberTy ||
15339 MemExprE->getType() == Context.OverloadTy);
15340
15341 // Dig out the member expression. This holds both the object
15342 // argument and the member function we're referring to.
15343 Expr *NakedMemExpr = MemExprE->IgnoreParens();
15344
15345 // Determine whether this is a call to a pointer-to-member function.
15346 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
15347 assert(op->getType() == Context.BoundMemberTy);
15348 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
15349
15350 QualType fnType =
15351 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
15352
15353 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
15354 QualType resultType = proto->getCallResultType(Context);
15356
15357 // Check that the object type isn't more qualified than the
15358 // member function we're calling.
15359 Qualifiers funcQuals = proto->getMethodQuals();
15360
15361 QualType objectType = op->getLHS()->getType();
15362 if (op->getOpcode() == BO_PtrMemI)
15363 objectType = objectType->castAs<PointerType>()->getPointeeType();
15364 Qualifiers objectQuals = objectType.getQualifiers();
15365
15366 Qualifiers difference = objectQuals - funcQuals;
15367 difference.removeObjCGCAttr();
15368 difference.removeAddressSpace();
15369 if (difference) {
15370 std::string qualsString = difference.getAsString();
15371 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
15372 << fnType.getUnqualifiedType()
15373 << qualsString
15374 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
15375 }
15376
15378 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
15379 CurFPFeatureOverrides(), proto->getNumParams());
15380
15381 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
15382 call, nullptr))
15383 return ExprError();
15384
15385 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
15386 return ExprError();
15387
15388 if (CheckOtherCall(call, proto))
15389 return ExprError();
15390
15391 return MaybeBindToTemporary(call);
15392 }
15393
15394 // We only try to build a recovery expr at this level if we can preserve
15395 // the return type, otherwise we return ExprError() and let the caller
15396 // recover.
15397 auto BuildRecoveryExpr = [&](QualType Type) {
15398 if (!AllowRecovery)
15399 return ExprError();
15400 std::vector<Expr *> SubExprs = {MemExprE};
15401 llvm::append_range(SubExprs, Args);
15402 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
15403 Type);
15404 };
15405 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
15406 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
15407 RParenLoc, CurFPFeatureOverrides());
15408
15409 UnbridgedCastsSet UnbridgedCasts;
15410 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
15411 return ExprError();
15412
15413 MemberExpr *MemExpr;
15414 CXXMethodDecl *Method = nullptr;
15415 bool HadMultipleCandidates = false;
15416 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
15417 NestedNameSpecifier *Qualifier = nullptr;
15418 if (isa<MemberExpr>(NakedMemExpr)) {
15419 MemExpr = cast<MemberExpr>(NakedMemExpr);
15420 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
15421 FoundDecl = MemExpr->getFoundDecl();
15422 Qualifier = MemExpr->getQualifier();
15423 UnbridgedCasts.restore();
15424 } else {
15425 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
15426 Qualifier = UnresExpr->getQualifier();
15427
15428 QualType ObjectType = UnresExpr->getBaseType();
15429 Expr::Classification ObjectClassification
15431 : UnresExpr->getBase()->Classify(Context);
15432
15433 // Add overload candidates
15434 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
15436
15437 // FIXME: avoid copy.
15438 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15439 if (UnresExpr->hasExplicitTemplateArgs()) {
15440 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15441 TemplateArgs = &TemplateArgsBuffer;
15442 }
15443
15445 E = UnresExpr->decls_end(); I != E; ++I) {
15446
15447 QualType ExplicitObjectType = ObjectType;
15448
15449 NamedDecl *Func = *I;
15450 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
15451 if (isa<UsingShadowDecl>(Func))
15452 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
15453
15454 bool HasExplicitParameter = false;
15455 if (const auto *M = dyn_cast<FunctionDecl>(Func);
15456 M && M->hasCXXExplicitFunctionObjectParameter())
15457 HasExplicitParameter = true;
15458 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
15459 M &&
15460 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
15461 HasExplicitParameter = true;
15462
15463 if (HasExplicitParameter)
15464 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
15465
15466 // Microsoft supports direct constructor calls.
15467 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
15468 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
15469 CandidateSet,
15470 /*SuppressUserConversions*/ false);
15471 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
15472 // If explicit template arguments were provided, we can't call a
15473 // non-template member function.
15474 if (TemplateArgs)
15475 continue;
15476
15477 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
15478 ObjectClassification, Args, CandidateSet,
15479 /*SuppressUserConversions=*/false);
15480 } else {
15481 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
15482 I.getPair(), ActingDC, TemplateArgs,
15483 ExplicitObjectType, ObjectClassification,
15484 Args, CandidateSet,
15485 /*SuppressUserConversions=*/false);
15486 }
15487 }
15488
15489 HadMultipleCandidates = (CandidateSet.size() > 1);
15490
15491 DeclarationName DeclName = UnresExpr->getMemberName();
15492
15493 UnbridgedCasts.restore();
15494
15496 bool Succeeded = false;
15497 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
15498 Best)) {
15499 case OR_Success:
15500 Method = cast<CXXMethodDecl>(Best->Function);
15501 FoundDecl = Best->FoundDecl;
15502 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
15503 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
15504 break;
15505 // If FoundDecl is different from Method (such as if one is a template
15506 // and the other a specialization), make sure DiagnoseUseOfDecl is
15507 // called on both.
15508 // FIXME: This would be more comprehensively addressed by modifying
15509 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
15510 // being used.
15511 if (Method != FoundDecl.getDecl() &&
15512 DiagnoseUseOfOverloadedDecl(Method, UnresExpr->getNameLoc()))
15513 break;
15514 Succeeded = true;
15515 break;
15516
15518 CandidateSet.NoteCandidates(
15520 UnresExpr->getMemberLoc(),
15521 PDiag(diag::err_ovl_no_viable_member_function_in_call)
15522 << DeclName << MemExprE->getSourceRange()),
15523 *this, OCD_AllCandidates, Args);
15524 break;
15525 case OR_Ambiguous:
15526 CandidateSet.NoteCandidates(
15527 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
15528 PDiag(diag::err_ovl_ambiguous_member_call)
15529 << DeclName << MemExprE->getSourceRange()),
15530 *this, OCD_AmbiguousCandidates, Args);
15531 break;
15532 case OR_Deleted:
15533 DiagnoseUseOfDeletedFunction(
15534 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
15535 CandidateSet, Best->Function, Args, /*IsMember=*/true);
15536 break;
15537 }
15538 // Overload resolution fails, try to recover.
15539 if (!Succeeded)
15540 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
15541
15542 ExprResult Res =
15543 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
15544 if (Res.isInvalid())
15545 return ExprError();
15546 MemExprE = Res.get();
15547
15548 // If overload resolution picked a static member
15549 // build a non-member call based on that function.
15550 if (Method->isStatic()) {
15551 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
15552 ExecConfig, IsExecConfig);
15553 }
15554
15555 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
15556 }
15557
15558 QualType ResultType = Method->getReturnType();
15560 ResultType = ResultType.getNonLValueExprType(Context);
15561
15562 assert(Method && "Member call to something that isn't a method?");
15563 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15564
15565 CallExpr *TheCall = nullptr;
15567 if (Method->isExplicitObjectMemberFunction()) {
15568 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
15569 NewArgs))
15570 return ExprError();
15571
15572 // Build the actual expression node.
15573 ExprResult FnExpr =
15574 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
15575 HadMultipleCandidates, MemExpr->getExprLoc());
15576 if (FnExpr.isInvalid())
15577 return ExprError();
15578
15579 TheCall =
15580 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
15581 CurFPFeatureOverrides(), Proto->getNumParams());
15582 } else {
15583 // Convert the object argument (for a non-static member function call).
15584 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
15585 MemExpr->getBase(), Qualifier, FoundDecl, Method);
15586 if (ObjectArg.isInvalid())
15587 return ExprError();
15588 MemExpr->setBase(ObjectArg.get());
15589 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
15590 RParenLoc, CurFPFeatureOverrides(),
15591 Proto->getNumParams());
15592 }
15593
15594 // Check for a valid return type.
15595 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
15596 TheCall, Method))
15597 return BuildRecoveryExpr(ResultType);
15598
15599 // Convert the rest of the arguments
15600 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
15601 RParenLoc))
15602 return BuildRecoveryExpr(ResultType);
15603
15604 DiagnoseSentinelCalls(Method, LParenLoc, Args);
15605
15606 if (CheckFunctionCall(Method, TheCall, Proto))
15607 return ExprError();
15608
15609 // In the case the method to call was not selected by the overloading
15610 // resolution process, we still need to handle the enable_if attribute. Do
15611 // that here, so it will not hide previous -- and more relevant -- errors.
15612 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
15613 if (const EnableIfAttr *Attr =
15614 CheckEnableIf(Method, LParenLoc, Args, true)) {
15615 Diag(MemE->getMemberLoc(),
15616 diag::err_ovl_no_viable_member_function_in_call)
15617 << Method << Method->getSourceRange();
15618 Diag(Method->getLocation(),
15619 diag::note_ovl_candidate_disabled_by_function_cond_attr)
15620 << Attr->getCond()->getSourceRange() << Attr->getMessage();
15621 return ExprError();
15622 }
15623 }
15624
15625 if (isa<CXXConstructorDecl, CXXDestructorDecl>(CurContext) &&
15626 TheCall->getDirectCallee()->isPureVirtual()) {
15627 const FunctionDecl *MD = TheCall->getDirectCallee();
15628
15629 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
15630 MemExpr->performsVirtualDispatch(getLangOpts())) {
15631 Diag(MemExpr->getBeginLoc(),
15632 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
15633 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
15634 << MD->getParent();
15635
15636 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
15637 if (getLangOpts().AppleKext)
15638 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
15639 << MD->getParent() << MD->getDeclName();
15640 }
15641 }
15642
15643 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
15644 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
15645 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
15646 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
15647 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
15648 MemExpr->getMemberLoc());
15649 }
15650
15651 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
15652 TheCall->getDirectCallee());
15653}
15654
15657 SourceLocation LParenLoc,
15658 MultiExprArg Args,
15659 SourceLocation RParenLoc) {
15660 if (checkPlaceholderForOverload(*this, Obj))
15661 return ExprError();
15662 ExprResult Object = Obj;
15663
15664 UnbridgedCastsSet UnbridgedCasts;
15665 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
15666 return ExprError();
15667
15668 assert(Object.get()->getType()->isRecordType() &&
15669 "Requires object type argument");
15670
15671 // C++ [over.call.object]p1:
15672 // If the primary-expression E in the function call syntax
15673 // evaluates to a class object of type "cv T", then the set of
15674 // candidate functions includes at least the function call
15675 // operators of T. The function call operators of T are obtained by
15676 // ordinary lookup of the name operator() in the context of
15677 // (E).operator().
15678 OverloadCandidateSet CandidateSet(LParenLoc,
15680 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
15681
15682 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
15683 diag::err_incomplete_object_call, Object.get()))
15684 return true;
15685
15686 const auto *Record = Object.get()->getType()->castAs<RecordType>();
15687 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
15688 LookupQualifiedName(R, Record->getDecl());
15689 R.suppressAccessDiagnostics();
15690
15691 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15692 Oper != OperEnd; ++Oper) {
15693 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
15694 Object.get()->Classify(Context), Args, CandidateSet,
15695 /*SuppressUserConversion=*/false);
15696 }
15697
15698 // When calling a lambda, both the call operator, and
15699 // the conversion operator to function pointer
15700 // are considered. But when constraint checking
15701 // on the call operator fails, it will also fail on the
15702 // conversion operator as the constraints are always the same.
15703 // As the user probably does not intend to perform a surrogate call,
15704 // we filter them out to produce better error diagnostics, ie to avoid
15705 // showing 2 failed overloads instead of one.
15706 bool IgnoreSurrogateFunctions = false;
15707 if (CandidateSet.size() == 1 && Record->getAsCXXRecordDecl()->isLambda()) {
15708 const OverloadCandidate &Candidate = *CandidateSet.begin();
15709 if (!Candidate.Viable &&
15711 IgnoreSurrogateFunctions = true;
15712 }
15713
15714 // C++ [over.call.object]p2:
15715 // In addition, for each (non-explicit in C++0x) conversion function
15716 // declared in T of the form
15717 //
15718 // operator conversion-type-id () cv-qualifier;
15719 //
15720 // where cv-qualifier is the same cv-qualification as, or a
15721 // greater cv-qualification than, cv, and where conversion-type-id
15722 // denotes the type "pointer to function of (P1,...,Pn) returning
15723 // R", or the type "reference to pointer to function of
15724 // (P1,...,Pn) returning R", or the type "reference to function
15725 // of (P1,...,Pn) returning R", a surrogate call function [...]
15726 // is also considered as a candidate function. Similarly,
15727 // surrogate call functions are added to the set of candidate
15728 // functions for each conversion function declared in an
15729 // accessible base class provided the function is not hidden
15730 // within T by another intervening declaration.
15731 const auto &Conversions =
15732 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
15733 for (auto I = Conversions.begin(), E = Conversions.end();
15734 !IgnoreSurrogateFunctions && I != E; ++I) {
15735 NamedDecl *D = *I;
15736 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
15737 if (isa<UsingShadowDecl>(D))
15738 D = cast<UsingShadowDecl>(D)->getTargetDecl();
15739
15740 // Skip over templated conversion functions; they aren't
15741 // surrogates.
15742 if (isa<FunctionTemplateDecl>(D))
15743 continue;
15744
15745 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
15746 if (!Conv->isExplicit()) {
15747 // Strip the reference type (if any) and then the pointer type (if
15748 // any) to get down to what might be a function type.
15749 QualType ConvType = Conv->getConversionType().getNonReferenceType();
15750 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
15751 ConvType = ConvPtrType->getPointeeType();
15752
15753 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
15754 {
15755 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
15756 Object.get(), Args, CandidateSet);
15757 }
15758 }
15759 }
15760
15761 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15762
15763 // Perform overload resolution.
15765 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
15766 Best)) {
15767 case OR_Success:
15768 // Overload resolution succeeded; we'll build the appropriate call
15769 // below.
15770 break;
15771
15772 case OR_No_Viable_Function: {
15774 CandidateSet.empty()
15775 ? (PDiag(diag::err_ovl_no_oper)
15776 << Object.get()->getType() << /*call*/ 1
15777 << Object.get()->getSourceRange())
15778 : (PDiag(diag::err_ovl_no_viable_object_call)
15779 << Object.get()->getType() << Object.get()->getSourceRange());
15780 CandidateSet.NoteCandidates(
15781 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
15782 OCD_AllCandidates, Args);
15783 break;
15784 }
15785 case OR_Ambiguous:
15786 if (!R.isAmbiguous())
15787 CandidateSet.NoteCandidates(
15788 PartialDiagnosticAt(Object.get()->getBeginLoc(),
15789 PDiag(diag::err_ovl_ambiguous_object_call)
15790 << Object.get()->getType()
15791 << Object.get()->getSourceRange()),
15792 *this, OCD_AmbiguousCandidates, Args);
15793 break;
15794
15795 case OR_Deleted: {
15796 // FIXME: Is this diagnostic here really necessary? It seems that
15797 // 1. we don't have any tests for this diagnostic, and
15798 // 2. we already issue err_deleted_function_use for this later on anyway.
15799 StringLiteral *Msg = Best->Function->getDeletedMessage();
15800 CandidateSet.NoteCandidates(
15801 PartialDiagnosticAt(Object.get()->getBeginLoc(),
15802 PDiag(diag::err_ovl_deleted_object_call)
15803 << Object.get()->getType() << (Msg != nullptr)
15804 << (Msg ? Msg->getString() : StringRef())
15805 << Object.get()->getSourceRange()),
15806 *this, OCD_AllCandidates, Args);
15807 break;
15808 }
15809 }
15810
15811 if (Best == CandidateSet.end())
15812 return true;
15813
15814 UnbridgedCasts.restore();
15815
15816 if (Best->Function == nullptr) {
15817 // Since there is no function declaration, this is one of the
15818 // surrogate candidates. Dig out the conversion function.
15819 CXXConversionDecl *Conv
15820 = cast<CXXConversionDecl>(
15821 Best->Conversions[0].UserDefined.ConversionFunction);
15822
15823 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
15824 Best->FoundDecl);
15825 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
15826 return ExprError();
15827 assert(Conv == Best->FoundDecl.getDecl() &&
15828 "Found Decl & conversion-to-functionptr should be same, right?!");
15829 // We selected one of the surrogate functions that converts the
15830 // object parameter to a function pointer. Perform the conversion
15831 // on the object argument, then let BuildCallExpr finish the job.
15832
15833 // Create an implicit member expr to refer to the conversion operator.
15834 // and then call it.
15835 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
15836 Conv, HadMultipleCandidates);
15837 if (Call.isInvalid())
15838 return ExprError();
15839 // Record usage of conversion in an implicit cast.
15841 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
15842 nullptr, VK_PRValue, CurFPFeatureOverrides());
15843
15844 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
15845 }
15846
15847 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
15848
15849 // We found an overloaded operator(). Build a CXXOperatorCallExpr
15850 // that calls this method, using Object for the implicit object
15851 // parameter and passing along the remaining arguments.
15852 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
15853
15854 // An error diagnostic has already been printed when parsing the declaration.
15855 if (Method->isInvalidDecl())
15856 return ExprError();
15857
15858 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15859 unsigned NumParams = Proto->getNumParams();
15860
15861 DeclarationNameInfo OpLocInfo(
15862 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
15863 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
15864 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15865 Obj, HadMultipleCandidates,
15866 OpLocInfo.getLoc(),
15867 OpLocInfo.getInfo());
15868 if (NewFn.isInvalid())
15869 return true;
15870
15871 SmallVector<Expr *, 8> MethodArgs;
15872 MethodArgs.reserve(NumParams + 1);
15873
15874 bool IsError = false;
15875
15876 // Initialize the object parameter.
15878 if (Method->isExplicitObjectMemberFunction()) {
15879 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
15880 } else {
15881 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
15882 Object.get(), /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15883 if (ObjRes.isInvalid())
15884 IsError = true;
15885 else
15886 Object = ObjRes;
15887 MethodArgs.push_back(Object.get());
15888 }
15889
15891 *this, MethodArgs, Method, Args, LParenLoc);
15892
15893 // If this is a variadic call, handle args passed through "...".
15894 if (Proto->isVariadic()) {
15895 // Promote the arguments (C99 6.5.2.2p7).
15896 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
15897 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
15898 nullptr);
15899 IsError |= Arg.isInvalid();
15900 MethodArgs.push_back(Arg.get());
15901 }
15902 }
15903
15904 if (IsError)
15905 return true;
15906
15907 DiagnoseSentinelCalls(Method, LParenLoc, Args);
15908
15909 // Once we've built TheCall, all of the expressions are properly owned.
15910 QualType ResultTy = Method->getReturnType();
15912 ResultTy = ResultTy.getNonLValueExprType(Context);
15913
15915 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
15916 CurFPFeatureOverrides());
15917
15918 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
15919 return true;
15920
15921 if (CheckFunctionCall(Method, TheCall, Proto))
15922 return true;
15923
15924 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
15925}
15926
15929 bool *NoArrowOperatorFound) {
15930 assert(Base->getType()->isRecordType() &&
15931 "left-hand side must have class type");
15932
15934 return ExprError();
15935
15936 SourceLocation Loc = Base->getExprLoc();
15937
15938 // C++ [over.ref]p1:
15939 //
15940 // [...] An expression x->m is interpreted as (x.operator->())->m
15941 // for a class object x of type T if T::operator->() exists and if
15942 // the operator is selected as the best match function by the
15943 // overload resolution mechanism (13.3).
15944 DeclarationName OpName =
15945 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
15947
15948 if (RequireCompleteType(Loc, Base->getType(),
15949 diag::err_typecheck_incomplete_tag, Base))
15950 return ExprError();
15951
15952 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
15953 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
15955
15956 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15957 Oper != OperEnd; ++Oper) {
15958 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
15959 {}, CandidateSet,
15960 /*SuppressUserConversion=*/false);
15961 }
15962
15963 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15964
15965 // Perform overload resolution.
15967 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15968 case OR_Success:
15969 // Overload resolution succeeded; we'll build the call below.
15970 break;
15971
15972 case OR_No_Viable_Function: {
15973 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
15974 if (CandidateSet.empty()) {
15975 QualType BaseType = Base->getType();
15976 if (NoArrowOperatorFound) {
15977 // Report this specific error to the caller instead of emitting a
15978 // diagnostic, as requested.
15979 *NoArrowOperatorFound = true;
15980 return ExprError();
15981 }
15982 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
15983 << BaseType << Base->getSourceRange();
15984 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
15985 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
15986 << FixItHint::CreateReplacement(OpLoc, ".");
15987 }
15988 } else
15989 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15990 << "operator->" << Base->getSourceRange();
15991 CandidateSet.NoteCandidates(*this, Base, Cands);
15992 return ExprError();
15993 }
15994 case OR_Ambiguous:
15995 if (!R.isAmbiguous())
15996 CandidateSet.NoteCandidates(
15997 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
15998 << "->" << Base->getType()
15999 << Base->getSourceRange()),
16001 return ExprError();
16002
16003 case OR_Deleted: {
16004 StringLiteral *Msg = Best->Function->getDeletedMessage();
16005 CandidateSet.NoteCandidates(
16006 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16007 << "->" << (Msg != nullptr)
16008 << (Msg ? Msg->getString() : StringRef())
16009 << Base->getSourceRange()),
16010 *this, OCD_AllCandidates, Base);
16011 return ExprError();
16012 }
16013 }
16014
16015 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
16016
16017 // Convert the object parameter.
16018 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16019
16020 if (Method->isExplicitObjectMemberFunction()) {
16021 ExprResult R = InitializeExplicitObjectArgument(*this, Base, Method);
16022 if (R.isInvalid())
16023 return ExprError();
16024 Base = R.get();
16025 } else {
16026 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
16027 Base, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
16028 if (BaseResult.isInvalid())
16029 return ExprError();
16030 Base = BaseResult.get();
16031 }
16032
16033 // Build the operator call.
16034 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16035 Base, HadMultipleCandidates, OpLoc);
16036 if (FnExpr.isInvalid())
16037 return ExprError();
16038
16039 QualType ResultTy = Method->getReturnType();
16041 ResultTy = ResultTy.getNonLValueExprType(Context);
16042
16043 CallExpr *TheCall =
16044 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
16045 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
16046
16047 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
16048 return ExprError();
16049
16050 if (CheckFunctionCall(Method, TheCall,
16051 Method->getType()->castAs<FunctionProtoType>()))
16052 return ExprError();
16053
16054 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
16055}
16056
16058 DeclarationNameInfo &SuffixInfo,
16059 ArrayRef<Expr*> Args,
16060 SourceLocation LitEndLoc,
16061 TemplateArgumentListInfo *TemplateArgs) {
16062 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16063
16064 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16066 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
16067 TemplateArgs);
16068
16069 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16070
16071 // Perform overload resolution. This will usually be trivial, but might need
16072 // to perform substitutions for a literal operator template.
16074 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
16075 case OR_Success:
16076 case OR_Deleted:
16077 break;
16078
16080 CandidateSet.NoteCandidates(
16081 PartialDiagnosticAt(UDSuffixLoc,
16082 PDiag(diag::err_ovl_no_viable_function_in_call)
16083 << R.getLookupName()),
16084 *this, OCD_AllCandidates, Args);
16085 return ExprError();
16086
16087 case OR_Ambiguous:
16088 CandidateSet.NoteCandidates(
16089 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
16090 << R.getLookupName()),
16091 *this, OCD_AmbiguousCandidates, Args);
16092 return ExprError();
16093 }
16094
16095 FunctionDecl *FD = Best->Function;
16096 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
16097 nullptr, HadMultipleCandidates,
16098 SuffixInfo.getLoc(),
16099 SuffixInfo.getInfo());
16100 if (Fn.isInvalid())
16101 return true;
16102
16103 // Check the argument types. This should almost always be a no-op, except
16104 // that array-to-pointer decay is applied to string literals.
16105 Expr *ConvArgs[2];
16106 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16107 ExprResult InputInit = PerformCopyInitialization(
16109 SourceLocation(), Args[ArgIdx]);
16110 if (InputInit.isInvalid())
16111 return true;
16112 ConvArgs[ArgIdx] = InputInit.get();
16113 }
16114
16115 QualType ResultTy = FD->getReturnType();
16117 ResultTy = ResultTy.getNonLValueExprType(Context);
16118
16120 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
16121 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
16122
16123 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
16124 return ExprError();
16125
16126 if (CheckFunctionCall(FD, UDL, nullptr))
16127 return ExprError();
16128
16129 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
16130}
16131
16134 SourceLocation RangeLoc,
16135 const DeclarationNameInfo &NameInfo,
16136 LookupResult &MemberLookup,
16137 OverloadCandidateSet *CandidateSet,
16139 Scope *S = nullptr;
16140
16142 if (!MemberLookup.empty()) {
16143 ExprResult MemberRef =
16144 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
16145 /*IsPtr=*/false, CXXScopeSpec(),
16146 /*TemplateKWLoc=*/SourceLocation(),
16147 /*FirstQualifierInScope=*/nullptr,
16148 MemberLookup,
16149 /*TemplateArgs=*/nullptr, S);
16150 if (MemberRef.isInvalid()) {
16151 *CallExpr = ExprError();
16152 return FRS_DiagnosticIssued;
16153 }
16154 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
16155 if (CallExpr->isInvalid()) {
16156 *CallExpr = ExprError();
16157 return FRS_DiagnosticIssued;
16158 }
16159 } else {
16160 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16162 NameInfo, UnresolvedSet<0>());
16163 if (FnR.isInvalid())
16164 return FRS_DiagnosticIssued;
16165 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
16166
16167 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
16168 CandidateSet, CallExpr);
16169 if (CandidateSet->empty() || CandidateSetError) {
16170 *CallExpr = ExprError();
16171 return FRS_NoViableFunction;
16172 }
16174 OverloadingResult OverloadResult =
16175 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
16176
16177 if (OverloadResult == OR_No_Viable_Function) {
16178 *CallExpr = ExprError();
16179 return FRS_NoViableFunction;
16180 }
16181 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
16182 Loc, nullptr, CandidateSet, &Best,
16183 OverloadResult,
16184 /*AllowTypoCorrection=*/false);
16185 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16186 *CallExpr = ExprError();
16187 return FRS_DiagnosticIssued;
16188 }
16189 }
16190 return FRS_Success;
16191}
16192
16194 FunctionDecl *Fn) {
16195 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
16196 ExprResult SubExpr =
16197 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
16198 if (SubExpr.isInvalid())
16199 return ExprError();
16200 if (SubExpr.get() == PE->getSubExpr())
16201 return PE;
16202
16203 return new (Context)
16204 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16205 }
16206
16207 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
16208 ExprResult SubExpr =
16209 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
16210 if (SubExpr.isInvalid())
16211 return ExprError();
16212 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16213 SubExpr.get()->getType()) &&
16214 "Implicit cast type cannot be determined from overload");
16215 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16216 if (SubExpr.get() == ICE->getSubExpr())
16217 return ICE;
16218
16219 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
16220 SubExpr.get(), nullptr, ICE->getValueKind(),
16221 CurFPFeatureOverrides());
16222 }
16223
16224 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
16225 if (!GSE->isResultDependent()) {
16226 ExprResult SubExpr =
16227 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
16228 if (SubExpr.isInvalid())
16229 return ExprError();
16230 if (SubExpr.get() == GSE->getResultExpr())
16231 return GSE;
16232
16233 // Replace the resulting type information before rebuilding the generic
16234 // selection expression.
16235 ArrayRef<Expr *> A = GSE->getAssocExprs();
16236 SmallVector<Expr *, 4> AssocExprs(A);
16237 unsigned ResultIdx = GSE->getResultIndex();
16238 AssocExprs[ResultIdx] = SubExpr.get();
16239
16240 if (GSE->isExprPredicate())
16242 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
16243 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16244 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16245 ResultIdx);
16247 Context, GSE->getGenericLoc(), GSE->getControllingType(),
16248 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16249 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16250 ResultIdx);
16251 }
16252 // Rather than fall through to the unreachable, return the original generic
16253 // selection expression.
16254 return GSE;
16255 }
16256
16257 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
16258 assert(UnOp->getOpcode() == UO_AddrOf &&
16259 "Can only take the address of an overloaded function");
16260 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
16261 if (!Method->isImplicitObjectMemberFunction()) {
16262 // Do nothing: the address of static and
16263 // explicit object member functions is a (non-member) function pointer.
16264 } else {
16265 // Fix the subexpression, which really has to be an
16266 // UnresolvedLookupExpr holding an overloaded member function
16267 // or template.
16268 ExprResult SubExpr =
16269 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16270 if (SubExpr.isInvalid())
16271 return ExprError();
16272 if (SubExpr.get() == UnOp->getSubExpr())
16273 return UnOp;
16274
16275 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
16276 SubExpr.get(), Method))
16277 return ExprError();
16278
16279 assert(isa<DeclRefExpr>(SubExpr.get()) &&
16280 "fixed to something other than a decl ref");
16281 assert(cast<DeclRefExpr>(SubExpr.get())->getQualifier() &&
16282 "fixed to a member ref with no nested name qualifier");
16283
16284 // We have taken the address of a pointer to member
16285 // function. Perform the computation here so that we get the
16286 // appropriate pointer to member type.
16287 QualType ClassType
16288 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
16289 QualType MemPtrType
16290 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
16291 // Under the MS ABI, lock down the inheritance model now.
16292 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
16293 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
16294
16295 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
16296 MemPtrType, VK_PRValue, OK_Ordinary,
16297 UnOp->getOperatorLoc(), false,
16298 CurFPFeatureOverrides());
16299 }
16300 }
16301 ExprResult SubExpr =
16302 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16303 if (SubExpr.isInvalid())
16304 return ExprError();
16305 if (SubExpr.get() == UnOp->getSubExpr())
16306 return UnOp;
16307
16308 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
16309 SubExpr.get());
16310 }
16311
16312 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16313 // FIXME: avoid copy.
16314 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16315 if (ULE->hasExplicitTemplateArgs()) {
16316 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
16317 TemplateArgs = &TemplateArgsBuffer;
16318 }
16319
16320 QualType Type = Fn->getType();
16321 ExprValueKind ValueKind =
16322 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
16323 ? VK_LValue
16324 : VK_PRValue;
16325
16326 // FIXME: Duplicated from BuildDeclarationNameExpr.
16327 if (unsigned BID = Fn->getBuiltinID()) {
16328 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
16329 Type = Context.BuiltinFnTy;
16330 ValueKind = VK_PRValue;
16331 }
16332 }
16333
16334 DeclRefExpr *DRE = BuildDeclRefExpr(
16335 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
16336 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
16337 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
16338 return DRE;
16339 }
16340
16341 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
16342 // FIXME: avoid copy.
16343 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16344 if (MemExpr->hasExplicitTemplateArgs()) {
16345 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16346 TemplateArgs = &TemplateArgsBuffer;
16347 }
16348
16349 Expr *Base;
16350
16351 // If we're filling in a static method where we used to have an
16352 // implicit member access, rewrite to a simple decl ref.
16353 if (MemExpr->isImplicitAccess()) {
16354 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
16355 DeclRefExpr *DRE = BuildDeclRefExpr(
16356 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
16357 MemExpr->getQualifierLoc(), Found.getDecl(),
16358 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
16359 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
16360 return DRE;
16361 } else {
16362 SourceLocation Loc = MemExpr->getMemberLoc();
16363 if (MemExpr->getQualifier())
16364 Loc = MemExpr->getQualifierLoc().getBeginLoc();
16365 Base =
16366 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
16367 }
16368 } else
16369 Base = MemExpr->getBase();
16370
16371 ExprValueKind valueKind;
16372 QualType type;
16373 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
16374 valueKind = VK_LValue;
16375 type = Fn->getType();
16376 } else {
16377 valueKind = VK_PRValue;
16378 type = Context.BoundMemberTy;
16379 }
16380
16381 return BuildMemberExpr(
16382 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
16383 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
16384 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
16385 type, valueKind, OK_Ordinary, TemplateArgs);
16386 }
16387
16388 llvm_unreachable("Invalid reference to overloaded function");
16389}
16390
16393 FunctionDecl *Fn) {
16394 return FixOverloadedFunctionReference(E.get(), Found, Fn);
16395}
16396
16397bool clang::shouldEnforceArgLimit(bool PartialOverloading,
16399 if (!PartialOverloading || !Function)
16400 return true;
16401 if (Function->isVariadic())
16402 return false;
16403 if (const auto *Proto =
16404 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
16405 if (Proto->isTemplateVariadic())
16406 return false;
16407 if (auto *Pattern = Function->getTemplateInstantiationPattern())
16408 if (const auto *Proto =
16409 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
16410 if (Proto->isTemplateVariadic())
16411 return false;
16412 return true;
16413}
16414
16416 DeclarationName Name,
16417 OverloadCandidateSet &CandidateSet,
16418 FunctionDecl *Fn, MultiExprArg Args,
16419 bool IsMember) {
16420 StringLiteral *Msg = Fn->getDeletedMessage();
16421 CandidateSet.NoteCandidates(
16422 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
16423 << IsMember << Name << (Msg != nullptr)
16424 << (Msg ? Msg->getString() : StringRef())
16425 << Range),
16426 *this, OCD_AllCandidates, Args);
16427}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3443
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:144
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.
static std::string getName(const CallEvent &Call)
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:5934
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
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 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 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 ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, Sema::CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
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 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 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 ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From, QualType T, Sema::CCEKind CCE, NamedDecl *Dest, APValue &PreNarrowingValue)
BuildConvertedConstantExpression - Check that the expression From is a converted constant expression ...
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 bool IsVectorElementConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, Expr *From)
@ ft_different_class
@ ft_parameter_mismatch
@ ft_noexcept
@ ft_return_type
@ ft_parameter_arity
@ ft_default
@ ft_qualifer_mismatch
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 ImplicitConversionSequence TryContextuallyConvertToBool(Sema &S, Expr *From)
TryContextuallyConvertToBool - Attempt to contextually convert the expression From to bool (C++0x [co...
static ImplicitConversionSequence TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, Expr::Classification FromClassification, CXXMethodDecl *Method, const CXXRecordDecl *ActingContext, bool InOverloadResolution=false, QualType ExplicitParameterType=QualType(), bool SuppressUserConversion=false)
TryObjectArgumentInitialization - Try to initialize the object parameter of the given member function...
static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, DeclAccessPair &Found)
static ImplicitConversionSequence::CompareKind CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, const ImplicitConversionSequence &ICS1, const ImplicitConversionSequence &ICS2)
CompareImplicitConversionSequences - Compare two implicit conversion sequences to determine whether o...
static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, unsigned NumArgs, bool TakingCandidateAddress, LangAS CtorDestAS=LangAS::Default)
Generates a 'note' diagnostic for an overload candidate.
static ImplicitConversionSequence TryCopyInitialization(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion, bool AllowExplicit=false)
TryCopyInitialization - Try to copy-initialize a value of type ToType from the expression From.
static ExprResult diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter, QualType T, UnresolvedSetImpl &ViableConversions)
static void markUnaddressableCandidatesUnviable(Sema &S, OverloadCandidateSet &CS)
static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE)
static bool sameFunctionParameterTypeLists(Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2)
We're allowed to use constraints partial ordering only if the candidates have the same parameter type...
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 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 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 class for storing results from argument-dependent lookup.
Definition: Lookup.h:869
iterator end()
Definition: Lookup.h:893
void erase(NamedDecl *D)
Removes any data associated with a given decl.
Definition: Lookup.h:885
iterator begin()
Definition: Lookup.h:892
llvm::mapped_iterator< decltype(Decls)::iterator, select_second > iterator
Definition: Lookup.h:890
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
bool isAbsent() const
Definition: APValue.h:439
bool isFloat() const
Definition: APValue.h:444
bool isInt() const
Definition: APValue.h:443
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:946
APFloat & getFloat()
Definition: APValue.h:479
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:2915
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
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:1169
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:1169
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.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:684
QualType getRecordType(const RecordDecl *Decl) const
CanQualType FloatTy
Definition: ASTContext.h:1172
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:2716
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:2732
CanQualType DoubleTy
Definition: ASTContext.h:1172
CanQualType LongDoubleTy
Definition: ASTContext.h:1172
CanQualType Char16Ty
Definition: ASTContext.h:1167
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
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:1188
CanQualType NullPtrTy
Definition: ASTContext.h:1187
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1703
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:682
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:834
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...
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:1172
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:2413
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:1161
const TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:800
CanQualType Float128Ty
Definition: ASTContext.h:1172
CanQualType UnsignedLongTy
Definition: ASTContext.h:1170
bool hasAnyFunctionEffects() const
Definition: ASTContext.h:3014
QualType getRestrictType(QualType T) const
Return the uniqued reference to the type for a restrict qualified type.
Definition: ASTContext.h:1372
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType BoundMemberTy
Definition: ASTContext.h:1188
CanQualType CharTy
Definition: ASTContext.h:1162
CanQualType IntTy
Definition: ASTContext.h:1169
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2289
CanQualType SignedCharTy
Definition: ASTContext.h:1169
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
Definition: ASTContext.h:1188
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2196
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2763
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:2482
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:1171
CanQualType BuiltinFnTy
Definition: ASTContext.h:1190
CanQualType VoidTy
Definition: ASTContext.h:1160
CanQualType UnsignedCharTy
Definition: ASTContext.h:1170
CanQualType UnsignedIntTy
Definition: ASTContext.h:1170
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
Definition: ASTContext.h:1381
CanQualType UnknownAnyTy
Definition: ASTContext.h:1189
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1171
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
CanQualType UnsignedShortTy
Definition: ASTContext.h:1170
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:1681
CanQualType ShortTy
Definition: ASTContext.h:1169
bool hasSimilarType(QualType T1, QualType T2) const
Determine if two types are similar, according to the C++ rules.
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...
CanQualType Char32Ty
Definition: ASTContext.h:1168
QualType getCVRQualifiedType(QualType T, unsigned CVR) const
Return a type with additional const, volatile, or restrict qualifiers.
Definition: ASTContext.h:2284
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:799
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:1169
CanQualType WCharTy
Definition: ASTContext.h:1163
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
CanQualType Char8Ty
Definition: ASTContext.h:1166
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:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition: Type.h:3747
QualType getConstantArrayType(const ASTContext &Ctx) const
Definition: Type.cpp:270
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3577
QualType getElementType() const
Definition: Type.h:3589
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:7761
Attr - This represents one attribute.
Definition: Attr.h:43
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3909
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition: Expr.cpp:2189
StringRef getOpcodeStr() const
Definition: Expr.h:3975
bool isCompoundAssignmentOp() const
Definition: Expr.h:4053
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:4895
Pointer to a block type.
Definition: Type.h:3408
This class is used for builtin types like 'int'.
Definition: Type.h:3034
Kind getKind() const
Definition: Type.h:3082
bool isDirectlyAddressable(unsigned ID) const
Determines whether this builtin can have its address taken with no special action required.
Definition: Builtins.h:186
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:2553
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2880
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition: DeclCXX.h:2916
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2920
Represents a call to a member function that may be written either with member call syntax (e....
Definition: ExprCXX.h:176
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:675
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
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:2549
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:2556
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition: DeclCXX.cpp:2668
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2254
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2204
QualType getThisType() const
Return the type of the this pointer.
Definition: DeclCXX.cpp:2657
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2582
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2239
QualType getFunctionObjectParameterType() const
Definition: DeclCXX.h:2228
bool isStatic() const
Definition: DeclCXX.cpp:2280
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:611
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:1030
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition: DeclCXX.cpp:1927
bool hasDefinition() const
Definition: DeclCXX.h:572
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1688
A rewritten comparison expression that was originally written using operator syntax.
Definition: ExprCXX.h:283
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:208
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:129
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2874
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:1492
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3047
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition: Expr.h:3206
static CallExpr * CreateTemporary(void *Mem, Expr *Fn, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, ADLCallKind UsesADL=NotADL)
Create a temporary call expression with no arguments in the memory pointed to by Mem.
Definition: Expr.cpp:1506
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 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: Type.h:3145
QualType getElementType() const
Definition: Type.h:3155
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:4917
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3615
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:350
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
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:1435
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2089
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2218
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1854
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:2008
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
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:1452
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:258
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1215
T * getAttr() const
Definition: DeclBase.h:576
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:520
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:596
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:151
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
Definition: DeclBase.cpp:1179
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:293
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:246
bool isInvalidDecl() const
Definition: DeclBase.h:591
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:562
SourceLocation getLocation() const
Definition: DeclBase.h:442
DeclContext * getDeclContext()
Definition: DeclBase.h:451
AccessSpecifier getAccess() const
Definition: DeclBase.h:510
specific_attr_iterator< T > specific_attr_end() const
Definition: DeclBase.h:572
specific_attr_iterator< T > specific_attr_begin() const
Definition: DeclBase.h:567
void print(raw_ostream &Out, unsigned Indentation=0, bool PrintInstantiation=false) const
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:907
bool hasAttr() const
Definition: DeclBase.h:580
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...
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition: Decl.h:792
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:786
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:810
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition: Diagnostic.h:769
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition: Diagnostic.h:754
OverloadsShown getShowOverloads() const
Definition: Diagnostic.h:745
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3847
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4052
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6098
EnumDecl * getDecl() const
Definition: Type.h:6105
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1912
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition: DeclCXX.h:1936
const Expr * getExpr() const
Definition: DeclCXX.h:1921
static ExplicitSpecifier getFromDecl(FunctionDecl *Function)
Definition: DeclCXX.cpp:2237
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition: ExprCXX.cpp:1446
The return type of classify().
Definition: Expr.h:330
bool isLValue() const
Definition: Expr.h:380
bool isPRValue() const
Definition: Expr.h:383
bool isXValue() const
Definition: Expr.h:381
static Classification makeSimpleLValue()
Create a simple, modifiable lvalue.
Definition: Expr.h:388
bool isRValue() const
Definition: Expr.h:384
This represents one expression.
Definition: Expr.h:110
bool isGLValue() const
Definition: Expr.h:280
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3095
void setType(QualType t)
Definition: Expr.h:143
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
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:3086
bool isPRValue() const
Definition: Expr.h:278
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition: Expr.cpp:3310
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:4124
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:826
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:830
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:444
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
bool isIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition: Expr.h:806
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:3963
ConstantExprKind
Definition: Expr.h:748
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition: Expr.h:469
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition: Expr.h:405
QualType getType() const
Definition: Expr.h:142
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:516
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:427
ExtVectorType - Extended vector type.
Definition: Type.h:4126
Represents difference between two FPOptions values.
Definition: LangOptions.h:978
Represents a member of a struct/union/class.
Definition: Decl.h:3033
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:75
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:138
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:101
Represents a function declaration or definition.
Definition: Decl.h:1935
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2565
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2672
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3723
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4052
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3638
param_iterator param_end()
Definition: Decl.h:2662
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition: Decl.cpp:3542
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3741
QualType getReturnType() const
Definition: Decl.h:2720
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2649
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:4123
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4172
param_iterator param_begin()
Definition: Decl.h:2661
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3096
DependentFunctionTemplateSpecializationInfo * getDependentSpecializationInfo() const
Definition: Decl.cpp:4247
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2468
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4188
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition: Decl.cpp:3320
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4116
unsigned getNumNonObjectParams() const
Definition: Decl.cpp:3745
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2398
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3313
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2313
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4405
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3989
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4276
bool isConsteval() const
Definition: Decl.h:2410
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition: Decl.cpp:3586
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:2737
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:3591
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3702
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2561
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5102
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5568
unsigned getNumParams() const
Definition: Type.h:5355
Qualifiers getMethodQuals() const
Definition: Type.h:5497
QualType getParamType(unsigned i) const
Definition: Type.h:5357
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5479
ArrayRef< QualType > param_types() const
Definition: Type.h:5511
Declaration of a template function.
Definition: DeclTemplate.h:959
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4432
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4506
bool getNoReturn() const
Definition: Type.h:4480
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition: Type.h:4360
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4321
ExtInfo getExtInfo() const
Definition: Type.h:4655
CallingConv getCallConv() const
Definition: Type.h:4654
QualType getReturnType() const
Definition: Type.h:4643
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition: Type.h:4667
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:4515
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:3724
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2082
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:567
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:618
void setBad(BadConversionSequence::FailureKind Failure, Expr *FromExpr, QualType ToType)
Sets this sequence as a bad conversion for an explicit argument.
Definition: Overload.h:715
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition: Overload.h:622
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:766
AmbiguousConversionSequence Ambiguous
When ConversionKind == AmbiguousConversion, provides the details of the ambiguous conversion.
Definition: Overload.h:626
bool hasInitializerListContainerType() const
Definition: Overload.h:748
unsigned getKindRank() const
Return a ranking of the implicit conversion sequence kind, where smaller ranks represent better conve...
Definition: Overload.h:679
bool isInitializerListOfIncompleteArray() const
Definition: Overload.h:755
BadConversionSequence Bad
When ConversionKind == BadConversion, provides the details of the bad conversion.
Definition: Overload.h:630
QualType getInitializerListContainerType() const
Definition: Overload.h:758
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition: Expr.h:5088
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition: Expr.h:5195
unsigned getNumInits() const
Definition: Expr.h:5118
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:2494
const Expr * getInit(unsigned Init) const
Definition: Expr.h:5134
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:2512
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, NonTypeTemplateParmDecl *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:973
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3483
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:672
Represents the results of name lookup.
Definition: Lookup.h:46
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:605
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:484
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:664
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:641
const UnresolvedSetImpl & asUnresolvedSet() const
Definition: Lookup.h:354
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
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:3236
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition: Expr.h:3425
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3319
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition: Expr.h:3333
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition: Expr.h:3454
Expr * getBase() const
Definition: Expr.h:3313
void setBase(Expr *E)
Definition: Expr.h:3312
NestedNameSpecifier * getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition: Expr.h:3347
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1806
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:3431
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition: Expr.h:3323
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3519
QualType getPointeeType() const
Definition: Type.h:3535
const Type * getClass() const
Definition: Type.h:3549
Describes a module or submodule.
Definition: Module.h:115
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition: Module.cpp:240
This represents a decl that may have a name.
Definition: Decl.h:253
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:280
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
std::string getQualifiedNameAsString() const
Definition: Decl.cpp:1668
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
Represent a C++ namespace.
Definition: Decl.h:551
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:1153
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:7524
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
ArrayRef< ParmVarDecl * > parameters() const
Definition: DeclObjC.h:373
unsigned param_size() const
Definition: DeclObjC.h:347
bool isVariadic() const
Definition: DeclObjC.h:431
Represents a pointer to an Objective C object.
Definition: Type.h:7580
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition: Type.h:7669
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition: Type.h:7638
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7592
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition: Type.h:7632
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1833
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition: Type.h:7644
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:1008
void clear(CandidateSetKind CSK)
Clear out all of the candidates.
bool isNewCandidate(Decl *F, OverloadCandidateParamOrder PO=OverloadCandidateParamOrder::Normal)
Determine when this overload candidate will be new to the overload set.
Definition: Overload.h:1169
ConversionSequenceList allocateConversionSequences(unsigned NumConversions)
Allocate storage for conversion sequences for NumConversions conversions.
Definition: Overload.h:1196
OperatorRewriteInfo getRewriteInfo() const
Definition: Overload.h:1162
@ CSK_AddressOfOverloadSet
C++ [over.match.call.general] Resolve a call through the address of an overload set.
Definition: Overload.h:1033
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition: Overload.h:1029
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition: Overload.h:1024
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1012
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition: Overload.h:1019
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1185
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:1177
SourceLocation getLocation() const
Definition: Overload.h:1160
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions={})
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition: Overload.h:1209
CandidateSetKind getKind() const
Definition: Overload.h:1161
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:2983
NestedNameSpecifier * getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition: ExprCXX.h:3099
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition: ExprCXX.h:3135
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3044
SourceLocation getNameLoc() const
Gets the location of the name.
Definition: ExprCXX.h:3096
decls_iterator decls_begin() const
Definition: ExprCXX.h:3076
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition: ExprCXX.h:3087
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition: ExprCXX.h:3109
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition: ExprCXX.h:3105
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition: ExprCXX.h:3155
decls_iterator decls_end() const
Definition: ExprCXX.h:3079
DeclarationName getName() const
Gets the name looked up.
Definition: ExprCXX.h:3093
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:255
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2170
Represents a parameter to a function.
Definition: Decl.h:1725
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3198
QualType getPointeeType() const
Definition: Type.h:3208
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition: Expr.cpp:4989
A (possibly-)qualified type.
Definition: Type.h:929
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:8015
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:8009
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:8020
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3521
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:1220
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1151
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7931
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:8057
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7971
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: Type.h:8134
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8025
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition: Type.h:1081
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: Type.h:8103
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:8004
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:8052
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7977
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
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: Type.h:8114
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:7963
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7871
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7878
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:4420
bool hasAtomic() const
Definition: Type.h:833
bool hasRestrict() const
Definition: Type.h:832
QualifiersAndAtomic withVolatile()
Definition: Type.h:845
QualifiersAndAtomic withAtomic()
Definition: Type.h:852
bool hasVolatile() const
Definition: Type.h:830
The collection of all-type qualifiers we support.
Definition: Type.h:324
unsigned getCVRQualifiers() const
Definition: Type.h:481
GC getObjCGCAttr() const
Definition: Type.h:512
bool hasOnlyConst() const
Definition: Type.h:451
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:347
void removeObjCLifetime()
Definition: Type.h:544
bool hasConst() const
Definition: Type.h:450
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:720
void addRestrict()
Definition: Type.h:473
bool hasRestrict() const
Definition: Type.h:470
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: Type.h:701
void removeObjCGCAttr()
Definition: Type.h:516
void removeUnaligned()
Definition: Type.h:508
void removeAddressSpace()
Definition: Type.h:589
void addConst()
Definition: Type.h:453
void setAddressSpace(LangAS space)
Definition: Type.h:584
bool hasVolatile() const
Definition: Type.h:460
bool hasObjCGCAttr() const
Definition: Type.h:511
ObjCLifetime getObjCLifetime() const
Definition: Type.h:538
void removeVolatile()
Definition: Type.h:462
std::string getAsString() const
LangAS getAddressSpace() const
Definition: Type.h:564
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition: Type.h:743
void addVolatile()
Definition: Type.h:463
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3501
Represents a struct/union/class.
Definition: Decl.h:4148
field_range fields() const
Definition: Decl.h:4354
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6072
RecordDecl * getDecl() const
Definition: Type.h:6082
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3439
QualType getPointeeType() const
Definition: Type.h:3457
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
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:60
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:32
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:370
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:1318
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:10024
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:5884
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:5913
RAII class to control scope of DeferDiags.
Definition: Sema.h:9751
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:12079
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12109
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:463
ExprResult PerformImplicitObjectArgumentInitialization(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method)
PerformObjectArgumentInitialization - Perform initialization of the implicit object parameter for the...
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:9767
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:8983
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition: Sema.h:8995
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:8991
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args={}, DeclContext *LookupCtx=nullptr, TypoExpr **Out=nullptr)
Diagnose an empty lookup.
Definition: SemaExpr.cpp:2452
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:165
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:1070
void AddConversionCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true)
AddConversionCandidate - Add a C++ conversion function as a candidate in the candidate set (C++ [over...
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:10107
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition: Sema.h:10110
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition: Sema.h:10116
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition: Sema.h:10114
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:1658
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.
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:1568
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:908
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:528
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 isObjCPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType, bool &IncompatibleObjC)
isObjCPointerConversion - Determines whether this is an Objective-C pointer conversion.
SemaObjC & ObjC()
Definition: Sema.h:1110
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...
ASTContext & getASTContext() const
Definition: Sema.h:531
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:690
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:10472
AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, const SourceRange &, DeclAccessPair FoundDecl)
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...
FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain=false, DeclAccessPair *Found=nullptr, TemplateSpecCandidateSet *FailedTSC=nullptr)
Given an expression that refers to an overloaded function, try to resolve that overloaded function ex...
AllowedExplicit
Definition: Sema.h:9827
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:816
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:11782
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...
bool CheckMemberPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess)
CheckMemberPointerConversion - Check the member pointer conversion from the expression From to the ty...
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:81
const LangOptions & getLangOpts() const
Definition: Sema.h:524
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,...
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:6475
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 (...
const LangOptions & LangOpts
Definition: Sema.h:906
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:6732
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
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)
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.
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
FunctionTemplateDecl * getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, QualType RawObj1Ty={}, QualType RawObj2Ty={}, bool Reversed=false)
Returns the more specialized function template according to the rules of function template partial or...
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:9628
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...
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1, ArrayRef< const Expr * > AC1, NamedDecl *D2, ArrayRef< const Expr * > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:640
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3189
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:14983
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:1043
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.
ObjCMethodDecl * SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, SmallVectorImpl< ObjCMethodDecl * > &Methods)
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:7573
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition: Sema.h:7612
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition: Sema.h:7591
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:7575
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition: Sema.h:7608
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:20008
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20964
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:13483
void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversion=false, OverloadCandidateParamOrder PO={})
AddMethodCandidate - Adds a named decl (which is some kind of method) as a method candidate to the gi...
void diagnoseEquivalentInternalLinkageDeclarations(SourceLocation Loc, const NamedDecl *D, ArrayRef< const NamedDecl * > Equiv)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
ExprResult 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:5487
bool anyAltivecTypes(QualType srcType, QualType destType)
Definition: SemaExpr.cpp:7563
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:7600
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:216
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:14938
bool CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity &Entity, InitListExpr *From)
Determine whether we can perform aggregate initialization for the purposes of overload resolution.
Definition: SemaInit.cpp:3459
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,...
CCEKind
Contexts in which a converted constant expression is required.
Definition: Sema.h:9991
@ CCEK_ExplicitBool
Condition in an explicit(bool) specifier.
Definition: Sema.h:9996
@ CCEK_Noexcept
Condition in a noexcept(bool) specifier.
Definition: Sema.h:9997
@ CCEK_ArrayBound
Array bound in array declarator or new-expression.
Definition: Sema.h:9995
@ CCEK_TemplateArg
Value of a non-type template parameter.
Definition: Sema.h:9994
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.
OverloadKind
Definition: Sema.h:9769
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.
SourceManager & SourceMgr
Definition: Sema.h:911
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
Definition: SemaExpr.cpp:2393
DiagnosticsEngine & Diags
Definition: Sema.h:910
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9718
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:21161
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
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:9703
bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method, SourceLocation CallLoc)
Returns true if the explicit object parameter was invalid.
Definition: SemaLambda.cpp:393
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType)
Helper function to determine whether this is the (deprecated) C++ conversion from a string literal to...
bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate, ArrayRef< QualType > ParamTypes, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, bool SuppressUserConversions, 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...
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.
bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
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:8261
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)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
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:381
DeclAccessPair FoundCopyConstructor
Definition: Overload.h:379
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:394
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:378
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:383
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:371
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:388
QualType getToType(unsigned Idx) const
Definition: Overload.h:398
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:357
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:333
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:345
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
StringRef getString() const
Definition: Expr.h:1855
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:1262
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition: TargetInfo.h:665
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition: TargetInfo.h:718
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition: TargetInfo.h:703
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1333
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
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:319
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:343
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:438
@ 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:295
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:399
bool isTypeAlias() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:418
Represents a C++ template name within the type system.
Definition: TemplateName.h:220
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:237
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: Type.h:6661
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Declaration of a template type parameter.
const Type * getTypeForDecl() const
Definition: Decl.h:3395
The base class of the type hierarchy.
Definition: Type.h:1828
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition: Type.h:2441
bool isBlockPointerType() const
Definition: Type.h:8200
bool isVoidType() const
Definition: Type.h:8510
bool isBooleanType() const
Definition: Type.h:8638
bool isObjCBuiltinType() const
Definition: Type.h:8379
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2201
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:1933
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:773
bool isIncompleteArrayType() const
Definition: Type.h:8266
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2180
bool isFloat16Type() const
Definition: Type.h:8519
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:710
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2105
bool isRValueReferenceType() const
Definition: Type.h:8212
bool isConstantArrayType() const
Definition: Type.h:8262
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8668
bool isArrayType() const
Definition: Type.h:8258
bool isCharType() const
Definition: Type.cpp:2123
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition: Type.h:8575
bool isArithmeticType() const
Definition: Type.cpp:2315
bool isPointerType() const
Definition: Type.h:8186
bool isArrayParameterType() const
Definition: Type.h:8274
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8550
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2517
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8800
bool isReferenceType() const
Definition: Type.h:8204
bool isEnumeralType() const
Definition: Type.h:8290
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2092
bool isObjCQualifiedIdType() const
Definition: Type.h:8349
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8625
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2159
bool isObjCObjectOrInterfaceType() const
Definition: Type.h:8336
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2714
bool isLValueReferenceType() const
Definition: Type.h:8208
bool isBitIntType() const
Definition: Type.h:8424
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2706
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2372
bool isAnyComplexType() const
Definition: Type.h:8294
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8563
bool isHalfType() const
Definition: Type.h:8514
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:8492
bool isQueueT() const
Definition: Type.h:8405
bool isMemberPointerType() const
Definition: Type.h:8240
bool isObjCIdType() const
Definition: Type.h:8361
bool isMatrixType() const
Definition: Type.h:8316
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8644
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2446
bool isEventT() const
Definition: Type.h:8397
bool isBFloat16Type() const
Definition: Type.h:8531
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2396
bool isFunctionType() const
Definition: Type.h:8182
bool isObjCObjectPointerType() const
Definition: Type.h:8328
bool isVectorType() const
Definition: Type.h:8298
bool isObjCClassType() const
Definition: Type.h:8367
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2300
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2541
bool isHLSLAttributedResourceType() const
Definition: Type.h:8471
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:2230
bool isAnyPointerType() const
Definition: Type.h:8194
TypeClass getTypeClass() const
Definition: Type.h:2341
bool isSamplerT() const
Definition: Type.h:8393
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8731
bool isNullPtrType() const
Definition: Type.h:8543
bool isRecordType() const
Definition: Type.h:8286
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2232
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition: Expr.cpp:1425
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:4952
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition: Expr.cpp:1401
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3203
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition: ExprCXX.h:3272
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:419
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition: ExprCXX.h:3943
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition: ExprCXX.h:4051
QualType getBaseType() const
Definition: ExprCXX.h:4025
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition: ExprCXX.h:4035
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition: ExprCXX.h:4016
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprCXX.h:4061
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition: ExprCXX.h:4055
A set of unresolved declarations.
Definition: UnresolvedSet.h:62
unsigned size() const
ArrayRef< DeclAccessPair > pairs() const
Definition: UnresolvedSet.h:90
void addDecl(NamedDecl *D)
Definition: UnresolvedSet.h:92
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:637
static UserDefinedLiteral * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation LitEndLoc, SourceLocation SuffixLoc, FPOptionsOverride FPFeatures)
Definition: ExprCXX.cpp:949
QualType getType() const
Definition: Decl.h:682
unsigned getNumElements() const
Definition: Type.h:4049
QualType getElementType() const
Definition: Type.h:4048
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:35
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition: limits.h:64
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
bool Ret(InterpState &S, CodePtr &PC)
Definition: Interp.h:318
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
@ 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:145
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
OverloadFailureKind
Definition: Overload.h:798
@ ovl_fail_final_conversion_not_exact
This conversion function template specialization candidate is not viable because the final conversion...
Definition: Overload.h:826
@ ovl_fail_enable_if
This candidate function was not viable because an enable_if attribute disabled it.
Definition: Overload.h:835
@ ovl_fail_illegal_constructor
This conversion candidate was not considered because it is an illegal instantiation of a constructor ...
Definition: Overload.h:818
@ ovl_fail_bad_final_conversion
This conversion candidate is not viable because its result type is not implicitly convertible to the ...
Definition: Overload.h:822
@ 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:863
@ ovl_fail_too_few_arguments
Definition: Overload.h:800
@ ovl_fail_addr_not_available
This candidate was not viable because its address could not be taken.
Definition: Overload.h:842
@ ovl_fail_too_many_arguments
Definition: Overload.h:799
@ ovl_non_default_multiversion_function
This candidate was not viable because it is a non-default multiversioned function.
Definition: Overload.h:850
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition: Overload.h:859
@ ovl_fail_bad_conversion
Definition: Overload.h:801
@ ovl_fail_bad_target
(CUDA) This candidate was not viable because the callee was not accessible from the caller's target (...
Definition: Overload.h:831
@ ovl_fail_bad_deduction
Definition: Overload.h:802
@ ovl_fail_inhctor_slice
This inherited constructor is not viable because it would slice the argument.
Definition: Overload.h:846
@ ovl_fail_object_addrspace_mismatch
This constructor/conversion candidate fail due to an address space mismatch between the object being ...
Definition: Overload.h:855
@ ovl_fail_explicit
This candidate constructor or conversion function is explicit but the context doesn't permit explicit...
Definition: Overload.h:839
@ ovl_fail_trivial_conversion
This conversion candidate was not considered because it duplicates the work of a trivial or derived-t...
Definition: Overload.h:807
@ RQ_None
No ref-qualifier was provided.
Definition: Type.h:1768
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1771
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1774
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.
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
UnaryOperatorKind
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
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:264
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
Definition: DeclTemplate.h:65
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:210
CXXSpecialMemberKind
Kinds of C++ special members.
Definition: Sema.h:422
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
bool isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind)
isBetterOverloadCandidate - Determines whether the first overload candidate is a better candidate tha...
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:1274
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:364
@ 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
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:1272
@ None
The alignment was not explicit in code.
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.
@ AS_public
Definition: Specifiers.h:124
@ AS_none
Definition: Specifiers.h:127
__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:467
ConversionSet::const_iterator const_iterator
Definition: Overload.h:503
ConversionSet & conversions()
Definition: Overload.h:486
void addConversion(NamedDecl *Found, FunctionDecl *D)
Definition: Overload.h:494
SmallVector< std::pair< NamedDecl *, FunctionDecl * >, 4 > ConversionSet
Definition: Overload.h:469
void copyFrom(const AmbiguousConversionSequence &)
QualType getToType() const
Definition: Overload.h:552
QualType getFromType() const
Definition: Overload.h:551
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.
std::optional< unsigned > getCallArgIndex()
Return the index of the call argument that this deduction failure refers to, 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.
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.
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:644
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:630
Extra information about a function prototype.
Definition: Type.h:5187
FunctionEffectsRef FunctionEffects
Definition: Type.h:5197
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:5195
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition: Overload.h:1038
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:1051
bool isReversible()
Determines whether this operator could be implemented by a function with reversed parameter order.
Definition: Overload.h:1087
bool isAcceptableCandidate(const FunctionDecl *FD)
Definition: Overload.h:1060
OverloadCandidateRewriteKind getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO)
Determine the kind of rewrite that should be performed for this candidate.
Definition: Overload.h:1077
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition: Overload.h:872
CallExpr::ADLCallKind IsADLCandidate
True if the candidate was found using ADL.
Definition: Overload.h:929
bool TryToFixBadConversion(unsigned Idx, Sema &S)
Definition: Overload.h:971
bool NotValidBecauseConstraintExprHasError() const
bool isReversed() const
Definition: Overload.h:959
bool IsSurrogate
IsSurrogate - True to indicate that this candidate is a surrogate for a conversion to a function poin...
Definition: Overload.h:915
QualType BuiltinParamTypes[3]
BuiltinParamTypes - Provides the parameter types of a built-in overload candidate.
Definition: Overload.h:886
bool IgnoreObjectArgument
IgnoreObjectArgument - True to indicate that the first argument's conversion, which for this function...
Definition: Overload.h:924
DeclAccessPair FoundDecl
FoundDecl - The original declaration that was looked up / invented / otherwise found,...
Definition: Overload.h:882
FunctionDecl * Function
Function - The actual function that this candidate represents.
Definition: Overload.h:877
bool Viable
Viable - True to indicate that this overload candidate is viable.
Definition: Overload.h:901
unsigned RewriteKind
Whether this is a rewritten candidate, and if so, of what kind?
Definition: Overload.h:933
ConversionFixItGenerator Fix
The FixIt hints which can be used to fix the Bad candidate.
Definition: Overload.h:898
StandardConversionSequence FinalConversion
FinalConversion - For a conversion function (where Function is a CXXConversionDecl),...
Definition: Overload.h:950
unsigned getNumParams() const
Definition: Overload.h:984
unsigned ExplicitCallArguments
The number of call arguments that were explicitly provided, to be used while performing partial order...
Definition: Overload.h:941
unsigned char FailureKind
FailureKind - The reason why this candidate is not viable.
Definition: Overload.h:937
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition: Overload.h:895
DeductionFailureInfo DeductionFailure
Definition: Overload.h:944
bool Best
Whether this candidate is the best viable function, or tied for being the best viable function.
Definition: Overload.h:910
CXXConversionDecl * Surrogate
Surrogate - The conversion function for which this candidate is a surrogate, but only if IsSurrogate ...
Definition: Overload.h:890
OverloadCandidateRewriteKind getRewriteKind() const
Get RewriteKind value in OverloadCandidateRewriteKind type (This function is to workaround the spurio...
Definition: Overload.h:955
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:12653
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition: Sema.h:12741
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:12773
ReferenceConversions
The conversions that would be performed on an lvalue of type T2 when binding a reference of type T1 t...
Definition: Sema.h:10124
Abstract class used to diagnose incomplete types.
Definition: Sema.h:7851
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition: Type.h:862
const Type * Ty
The locally-unqualified type.
Definition: Type.h:864
Qualifiers Quals
The local qualifiers.
Definition: Type.h:867
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:422
StandardConversionSequence Before
Represents the standard conversion that occurs before the actual user-defined conversion.
Definition: Overload.h:434
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition: Overload.h:456
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition: Overload.h:447
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition: Overload.h:451
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition: Overload.h:442
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition: Overload.h:461
void dump() const
dump - Print this user-defined conversion sequence to standard error.
Describes an entity that is being assigned.