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();
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
1312template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1313 assert(D && "function decl should not be null");
1314 if (auto *A = D->getAttr<AttrT>())
1315 return !A->isImplicit();
1316 return false;
1317}
1318
1319static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1320 FunctionDecl *Old,
1321 bool UseMemberUsingDeclRules,
1322 bool ConsiderCudaAttrs,
1323 bool UseOverrideRules = false) {
1324 // C++ [basic.start.main]p2: This function shall not be overloaded.
1325 if (New->isMain())
1326 return false;
1327
1328 // MSVCRT user defined entry points cannot be overloaded.
1329 if (New->isMSVCRTEntryPoint())
1330 return false;
1331
1332 NamedDecl *OldDecl = Old;
1333 NamedDecl *NewDecl = New;
1336
1337 // C++ [temp.fct]p2:
1338 // A function template can be overloaded with other function templates
1339 // and with normal (non-template) functions.
1340 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1341 return true;
1342
1343 // Is the function New an overload of the function Old?
1344 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1345 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1346
1347 // Compare the signatures (C++ 1.3.10) of the two functions to
1348 // determine whether they are overloads. If we find any mismatch
1349 // in the signature, they are overloads.
1350
1351 // If either of these functions is a K&R-style function (no
1352 // prototype), then we consider them to have matching signatures.
1353 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1354 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1355 return false;
1356
1357 const auto *OldType = cast<FunctionProtoType>(OldQType);
1358 const auto *NewType = cast<FunctionProtoType>(NewQType);
1359
1360 // The signature of a function includes the types of its
1361 // parameters (C++ 1.3.10), which includes the presence or absence
1362 // of the ellipsis; see C++ DR 357).
1363 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1364 return true;
1365
1366 // For member-like friends, the enclosing class is part of the signature.
1367 if ((New->isMemberLikeConstrainedFriend() ||
1370 return true;
1371
1372 // Compare the parameter lists.
1373 // This can only be done once we have establish that friend functions
1374 // inhabit the same context, otherwise we might tried to instantiate
1375 // references to non-instantiated entities during constraint substitution.
1376 // GH78101.
1377 if (NewTemplate) {
1378 OldDecl = OldTemplate;
1379 NewDecl = NewTemplate;
1380 // C++ [temp.over.link]p4:
1381 // The signature of a function template consists of its function
1382 // signature, its return type and its template parameter list. The names
1383 // of the template parameters are significant only for establishing the
1384 // relationship between the template parameters and the rest of the
1385 // signature.
1386 //
1387 // We check the return type and template parameter lists for function
1388 // templates first; the remaining checks follow.
1389 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1390 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1391 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1392 bool SameReturnType = SemaRef.Context.hasSameType(
1394 // FIXME(GH58571): Match template parameter list even for non-constrained
1395 // template heads. This currently ensures that the code prior to C++20 is
1396 // not newly broken.
1397 bool ConstraintsInTemplateHead =
1400 // C++ [namespace.udecl]p11:
1401 // The set of declarations named by a using-declarator that inhabits a
1402 // class C does not include member functions and member function
1403 // templates of a base class that "correspond" to (and thus would
1404 // conflict with) a declaration of a function or function template in
1405 // C.
1406 // Comparing return types is not required for the "correspond" check to
1407 // decide whether a member introduced by a shadow declaration is hidden.
1408 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1409 !SameTemplateParameterList)
1410 return true;
1411 if (!UseMemberUsingDeclRules &&
1412 (!SameTemplateParameterList || !SameReturnType))
1413 return true;
1414 }
1415
1416 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1417 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1418
1419 int OldParamsOffset = 0;
1420 int NewParamsOffset = 0;
1421
1422 // When determining if a method is an overload from a base class, act as if
1423 // the implicit object parameter are of the same type.
1424
1425 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1427 auto ThisType = M->getFunctionObjectParameterReferenceType();
1428 if (ThisType.isConstQualified())
1429 Q.removeConst();
1430 return Q;
1431 }
1432
1433 // We do not allow overloading based off of '__restrict'.
1434 Q.removeRestrict();
1435
1436 // We may not have applied the implicit const for a constexpr member
1437 // function yet (because we haven't yet resolved whether this is a static
1438 // or non-static member function). Add it now, on the assumption that this
1439 // is a redeclaration of OldMethod.
1440 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1441 (M->isConstexpr() || M->isConsteval()) &&
1442 !isa<CXXConstructorDecl>(NewMethod))
1443 Q.addConst();
1444 return Q;
1445 };
1446
1447 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1448 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1449 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1450
1451 if (OldMethod->isExplicitObjectMemberFunction()) {
1452 BS.Quals.removeVolatile();
1453 DS.Quals.removeVolatile();
1454 }
1455
1456 return BS.Quals == DS.Quals;
1457 };
1458
1459 auto CompareType = [&](QualType Base, QualType D) {
1460 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1461 auto DS = D.getNonReferenceType().getCanonicalType().split();
1462
1463 if (!AreQualifiersEqual(BS, DS))
1464 return false;
1465
1466 if (OldMethod->isImplicitObjectMemberFunction() &&
1467 OldMethod->getParent() != NewMethod->getParent()) {
1468 QualType ParentType =
1469 SemaRef.Context.getTypeDeclType(OldMethod->getParent())
1470 .getCanonicalType();
1471 if (ParentType.getTypePtr() != BS.Ty)
1472 return false;
1473 BS.Ty = DS.Ty;
1474 }
1475
1476 // FIXME: should we ignore some type attributes here?
1477 if (BS.Ty != DS.Ty)
1478 return false;
1479
1480 if (Base->isLValueReferenceType())
1481 return D->isLValueReferenceType();
1482 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1483 };
1484
1485 // If the function is a class member, its signature includes the
1486 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1487 auto DiagnoseInconsistentRefQualifiers = [&]() {
1488 if (SemaRef.LangOpts.CPlusPlus23)
1489 return false;
1490 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1491 return false;
1492 if (OldMethod->isExplicitObjectMemberFunction() ||
1493 NewMethod->isExplicitObjectMemberFunction())
1494 return false;
1495 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1496 NewMethod->getRefQualifier() == RQ_None)) {
1497 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1498 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1499 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1500 return true;
1501 }
1502 return false;
1503 };
1504
1505 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1506 OldParamsOffset++;
1507 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1508 NewParamsOffset++;
1509
1510 if (OldType->getNumParams() - OldParamsOffset !=
1511 NewType->getNumParams() - NewParamsOffset ||
1513 {OldType->param_type_begin() + OldParamsOffset,
1514 OldType->param_type_end()},
1515 {NewType->param_type_begin() + NewParamsOffset,
1516 NewType->param_type_end()},
1517 nullptr)) {
1518 return true;
1519 }
1520
1521 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1522 !NewMethod->isStatic()) {
1523 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1524 const CXXMethodDecl *New) {
1525 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1526 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1527
1528 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1529 return F->getRefQualifier() == RQ_None &&
1530 !F->isExplicitObjectMemberFunction();
1531 };
1532
1533 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1534 CompareType(OldObjectType.getNonReferenceType(),
1535 NewObjectType.getNonReferenceType()))
1536 return true;
1537 return CompareType(OldObjectType, NewObjectType);
1538 }(OldMethod, NewMethod);
1539
1540 if (!HaveCorrespondingObjectParameters) {
1541 if (DiagnoseInconsistentRefQualifiers())
1542 return true;
1543 // CWG2554
1544 // and, if at least one is an explicit object member function, ignoring
1545 // object parameters
1546 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1547 !OldMethod->isExplicitObjectMemberFunction()))
1548 return true;
1549 }
1550 }
1551
1552 if (!UseOverrideRules &&
1554 Expr *NewRC = New->getTrailingRequiresClause(),
1555 *OldRC = Old->getTrailingRequiresClause();
1556 if ((NewRC != nullptr) != (OldRC != nullptr))
1557 return true;
1558 if (NewRC &&
1559 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC, NewDecl, NewRC))
1560 return true;
1561 }
1562
1563 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1564 NewMethod->isImplicitObjectMemberFunction()) {
1565 if (DiagnoseInconsistentRefQualifiers())
1566 return true;
1567 }
1568
1569 // Though pass_object_size is placed on parameters and takes an argument, we
1570 // consider it to be a function-level modifier for the sake of function
1571 // identity. Either the function has one or more parameters with
1572 // pass_object_size or it doesn't.
1575 return true;
1576
1577 // enable_if attributes are an order-sensitive part of the signature.
1579 NewI = New->specific_attr_begin<EnableIfAttr>(),
1580 NewE = New->specific_attr_end<EnableIfAttr>(),
1581 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1582 OldE = Old->specific_attr_end<EnableIfAttr>();
1583 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1584 if (NewI == NewE || OldI == OldE)
1585 return true;
1586 llvm::FoldingSetNodeID NewID, OldID;
1587 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1588 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1589 if (NewID != OldID)
1590 return true;
1591 }
1592
1593 // At this point, it is known that the two functions have the same signature.
1594 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1595 // Don't allow overloading of destructors. (In theory we could, but it
1596 // would be a giant change to clang.)
1597 if (!isa<CXXDestructorDecl>(New)) {
1598 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1599 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1600 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1601 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1602 "Unexpected invalid target.");
1603
1604 // Allow overloading of functions with same signature and different CUDA
1605 // target attributes.
1606 if (NewTarget != OldTarget) {
1607 // Special case: non-constexpr function is allowed to override
1608 // constexpr virtual function
1609 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1610 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1611 !hasExplicitAttr<CUDAHostAttr>(Old) &&
1612 !hasExplicitAttr<CUDADeviceAttr>(Old) &&
1613 !hasExplicitAttr<CUDAHostAttr>(New) &&
1614 !hasExplicitAttr<CUDADeviceAttr>(New)) {
1615 return false;
1616 }
1617 return true;
1618 }
1619 }
1620 }
1621 }
1622
1623 // The signatures match; this is not an overload.
1624 return false;
1625}
1626
1628 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1629 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1630 ConsiderCudaAttrs);
1631}
1632
1634 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1635 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1636 /*UseMemberUsingDeclRules=*/false,
1637 /*ConsiderCudaAttrs=*/true,
1638 /*UseOverrideRules=*/true);
1639}
1640
1641/// Tries a user-defined conversion from From to ToType.
1642///
1643/// Produces an implicit conversion sequence for when a standard conversion
1644/// is not an option. See TryImplicitConversion for more information.
1647 bool SuppressUserConversions,
1648 AllowedExplicit AllowExplicit,
1649 bool InOverloadResolution,
1650 bool CStyle,
1651 bool AllowObjCWritebackConversion,
1652 bool AllowObjCConversionOnExplicit) {
1654
1655 if (SuppressUserConversions) {
1656 // We're not in the case above, so there is no conversion that
1657 // we can perform.
1659 return ICS;
1660 }
1661
1662 // Attempt user-defined conversion.
1663 OverloadCandidateSet Conversions(From->getExprLoc(),
1665 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1666 Conversions, AllowExplicit,
1667 AllowObjCConversionOnExplicit)) {
1668 case OR_Success:
1669 case OR_Deleted:
1670 ICS.setUserDefined();
1671 // C++ [over.ics.user]p4:
1672 // A conversion of an expression of class type to the same class
1673 // type is given Exact Match rank, and a conversion of an
1674 // expression of class type to a base class of that type is
1675 // given Conversion rank, in spite of the fact that a copy
1676 // constructor (i.e., a user-defined conversion function) is
1677 // called for those cases.
1678 if (CXXConstructorDecl *Constructor
1679 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1680 QualType FromType;
1681 SourceLocation FromLoc;
1682 // C++11 [over.ics.list]p6, per DR2137:
1683 // C++17 [over.ics.list]p6:
1684 // If C is not an initializer-list constructor and the initializer list
1685 // has a single element of type cv U, where U is X or a class derived
1686 // from X, the implicit conversion sequence has Exact Match rank if U is
1687 // X, or Conversion rank if U is derived from X.
1688 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1689 InitList && InitList->getNumInits() == 1 &&
1690 !S.isInitListConstructor(Constructor)) {
1691 const Expr *SingleInit = InitList->getInit(0);
1692 FromType = SingleInit->getType();
1693 FromLoc = SingleInit->getBeginLoc();
1694 } else {
1695 FromType = From->getType();
1696 FromLoc = From->getBeginLoc();
1697 }
1698 QualType FromCanon =
1700 QualType ToCanon
1702 if ((FromCanon == ToCanon ||
1703 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1704 // Turn this into a "standard" conversion sequence, so that it
1705 // gets ranked with standard conversion sequences.
1707 ICS.setStandard();
1709 ICS.Standard.setFromType(FromType);
1710 ICS.Standard.setAllToTypes(ToType);
1711 ICS.Standard.CopyConstructor = Constructor;
1713 if (ToCanon != FromCanon)
1715 }
1716 }
1717 break;
1718
1719 case OR_Ambiguous:
1720 ICS.setAmbiguous();
1721 ICS.Ambiguous.setFromType(From->getType());
1722 ICS.Ambiguous.setToType(ToType);
1723 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1724 Cand != Conversions.end(); ++Cand)
1725 if (Cand->Best)
1726 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1727 break;
1728
1729 // Fall through.
1732 break;
1733 }
1734
1735 return ICS;
1736}
1737
1738/// TryImplicitConversion - Attempt to perform an implicit conversion
1739/// from the given expression (Expr) to the given type (ToType). This
1740/// function returns an implicit conversion sequence that can be used
1741/// to perform the initialization. Given
1742///
1743/// void f(float f);
1744/// void g(int i) { f(i); }
1745///
1746/// this routine would produce an implicit conversion sequence to
1747/// describe the initialization of f from i, which will be a standard
1748/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1749/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1750//
1751/// Note that this routine only determines how the conversion can be
1752/// performed; it does not actually perform the conversion. As such,
1753/// it will not produce any diagnostics if no conversion is available,
1754/// but will instead return an implicit conversion sequence of kind
1755/// "BadConversion".
1756///
1757/// If @p SuppressUserConversions, then user-defined conversions are
1758/// not permitted.
1759/// If @p AllowExplicit, then explicit user-defined conversions are
1760/// permitted.
1761///
1762/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1763/// writeback conversion, which allows __autoreleasing id* parameters to
1764/// be initialized with __strong id* or __weak id* arguments.
1767 bool SuppressUserConversions,
1768 AllowedExplicit AllowExplicit,
1769 bool InOverloadResolution,
1770 bool CStyle,
1771 bool AllowObjCWritebackConversion,
1772 bool AllowObjCConversionOnExplicit) {
1774 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1775 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1776 ICS.setStandard();
1777 return ICS;
1778 }
1779
1780 if (!S.getLangOpts().CPlusPlus) {
1782 return ICS;
1783 }
1784
1785 // C++ [over.ics.user]p4:
1786 // A conversion of an expression of class type to the same class
1787 // type is given Exact Match rank, and a conversion of an
1788 // expression of class type to a base class of that type is
1789 // given Conversion rank, in spite of the fact that a copy/move
1790 // constructor (i.e., a user-defined conversion function) is
1791 // called for those cases.
1792 QualType FromType = From->getType();
1793 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1794 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1795 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1796 ICS.setStandard();
1798 ICS.Standard.setFromType(FromType);
1799 ICS.Standard.setAllToTypes(ToType);
1800
1801 // We don't actually check at this point whether there is a valid
1802 // copy/move constructor, since overloading just assumes that it
1803 // exists. When we actually perform initialization, we'll find the
1804 // appropriate constructor to copy the returned object, if needed.
1805 ICS.Standard.CopyConstructor = nullptr;
1806
1807 // Determine whether this is considered a derived-to-base conversion.
1808 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1810
1811 return ICS;
1812 }
1813
1814 if (S.getLangOpts().HLSL && ToType->isHLSLAttributedResourceType() &&
1815 FromType->isHLSLAttributedResourceType()) {
1816 auto *ToResType = cast<HLSLAttributedResourceType>(ToType);
1817 auto *FromResType = cast<HLSLAttributedResourceType>(FromType);
1818 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1819 FromResType->getWrappedType()) &&
1820 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1821 FromResType->getContainedType()) &&
1822 ToResType->getAttrs() == FromResType->getAttrs()) {
1823 ICS.setStandard();
1825 ICS.Standard.setFromType(FromType);
1826 ICS.Standard.setAllToTypes(ToType);
1827 return ICS;
1828 }
1829 }
1830
1831 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1832 AllowExplicit, InOverloadResolution, CStyle,
1833 AllowObjCWritebackConversion,
1834 AllowObjCConversionOnExplicit);
1835}
1836
1839 bool SuppressUserConversions,
1840 AllowedExplicit AllowExplicit,
1841 bool InOverloadResolution,
1842 bool CStyle,
1843 bool AllowObjCWritebackConversion) {
1844 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1845 AllowExplicit, InOverloadResolution, CStyle,
1846 AllowObjCWritebackConversion,
1847 /*AllowObjCConversionOnExplicit=*/false);
1848}
1849
1851 AssignmentAction Action,
1852 bool AllowExplicit) {
1853 if (checkPlaceholderForOverload(*this, From))
1854 return ExprError();
1855
1856 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1857 bool AllowObjCWritebackConversion =
1858 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1859 Action == AssignmentAction::Sending);
1860 if (getLangOpts().ObjC)
1861 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1862 From->getType(), From);
1864 *this, From, ToType,
1865 /*SuppressUserConversions=*/false,
1866 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1867 /*InOverloadResolution=*/false,
1868 /*CStyle=*/false, AllowObjCWritebackConversion,
1869 /*AllowObjCConversionOnExplicit=*/false);
1870 return PerformImplicitConversion(From, ToType, ICS, Action);
1871}
1872
1874 QualType &ResultTy) {
1875 if (Context.hasSameUnqualifiedType(FromType, ToType))
1876 return false;
1877
1878 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1879 // or F(t noexcept) -> F(t)
1880 // where F adds one of the following at most once:
1881 // - a pointer
1882 // - a member pointer
1883 // - a block pointer
1884 // Changes here need matching changes in FindCompositePointerType.
1885 CanQualType CanTo = Context.getCanonicalType(ToType);
1886 CanQualType CanFrom = Context.getCanonicalType(FromType);
1887 Type::TypeClass TyClass = CanTo->getTypeClass();
1888 if (TyClass != CanFrom->getTypeClass()) return false;
1889 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1890 if (TyClass == Type::Pointer) {
1891 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1892 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1893 } else if (TyClass == Type::BlockPointer) {
1894 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1895 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1896 } else if (TyClass == Type::MemberPointer) {
1897 auto ToMPT = CanTo.castAs<MemberPointerType>();
1898 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1899 // A function pointer conversion cannot change the class of the function.
1900 if (ToMPT->getClass() != FromMPT->getClass())
1901 return false;
1902 CanTo = ToMPT->getPointeeType();
1903 CanFrom = FromMPT->getPointeeType();
1904 } else {
1905 return false;
1906 }
1907
1908 TyClass = CanTo->getTypeClass();
1909 if (TyClass != CanFrom->getTypeClass()) return false;
1910 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1911 return false;
1912 }
1913
1914 const auto *FromFn = cast<FunctionType>(CanFrom);
1915 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1916
1917 const auto *ToFn = cast<FunctionType>(CanTo);
1918 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1919
1920 bool Changed = false;
1921
1922 // Drop 'noreturn' if not present in target type.
1923 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1924 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1925 Changed = true;
1926 }
1927
1928 // Drop 'noexcept' if not present in target type.
1929 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1930 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1931 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1932 FromFn = cast<FunctionType>(
1933 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1934 EST_None)
1935 .getTypePtr());
1936 Changed = true;
1937 }
1938
1939 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1940 // only if the ExtParameterInfo lists of the two function prototypes can be
1941 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1943 bool CanUseToFPT, CanUseFromFPT;
1944 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1945 CanUseFromFPT, NewParamInfos) &&
1946 CanUseToFPT && !CanUseFromFPT) {
1947 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1948 ExtInfo.ExtParameterInfos =
1949 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1950 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1951 FromFPT->getParamTypes(), ExtInfo);
1952 FromFn = QT->getAs<FunctionType>();
1953 Changed = true;
1954 }
1955
1956 // For C, when called from checkPointerTypesForAssignment,
1957 // we need to not alter FromFn, or else even an innocuous cast
1958 // like dropping effects will fail. In C++ however we do want to
1959 // alter FromFn (because of the way PerformImplicitConversion works).
1960 if (Context.hasAnyFunctionEffects() && getLangOpts().CPlusPlus) {
1961 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
1962
1963 // Transparently add/drop effects; here we are concerned with
1964 // language rules/canonicalization. Adding/dropping effects is a warning.
1965 const auto FromFX = FromFPT->getFunctionEffects();
1966 const auto ToFX = ToFPT->getFunctionEffects();
1967 if (FromFX != ToFX) {
1968 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1969 ExtInfo.FunctionEffects = ToFX;
1970 QualType QT = Context.getFunctionType(
1971 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
1972 FromFn = QT->getAs<FunctionType>();
1973 Changed = true;
1974 }
1975 }
1976 }
1977
1978 if (!Changed)
1979 return false;
1980
1981 assert(QualType(FromFn, 0).isCanonical());
1982 if (QualType(FromFn, 0) != CanTo) return false;
1983
1984 ResultTy = ToType;
1985 return true;
1986}
1987
1988/// Determine whether the conversion from FromType to ToType is a valid
1989/// floating point conversion.
1990///
1991static bool IsFloatingPointConversion(Sema &S, QualType FromType,
1992 QualType ToType) {
1993 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
1994 return false;
1995 // FIXME: disable conversions between long double, __ibm128 and __float128
1996 // if their representation is different until there is back end support
1997 // We of course allow this conversion if long double is really double.
1998
1999 // Conversions between bfloat16 and float16 are currently not supported.
2000 if ((FromType->isBFloat16Type() &&
2001 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2002 (ToType->isBFloat16Type() &&
2003 (FromType->isFloat16Type() || FromType->isHalfType())))
2004 return false;
2005
2006 // Conversions between IEEE-quad and IBM-extended semantics are not
2007 // permitted.
2008 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
2009 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2010 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2011 &ToSem == &llvm::APFloat::IEEEquad()) ||
2012 (&FromSem == &llvm::APFloat::IEEEquad() &&
2013 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2014 return false;
2015 return true;
2016}
2017
2018static bool IsVectorElementConversion(Sema &S, QualType FromType,
2019 QualType ToType,
2020 ImplicitConversionKind &ICK, Expr *From) {
2021 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2022 return true;
2023
2024 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2026 return true;
2027 }
2028
2029 if (IsFloatingPointConversion(S, FromType, ToType)) {
2031 return true;
2032 }
2033
2034 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2036 return true;
2037 }
2038
2039 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2041 ToType->isRealFloatingType())) {
2043 return true;
2044 }
2045
2046 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2048 return true;
2049 }
2050
2051 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2052 ToType->isIntegralType(S.Context)) {
2054 return true;
2055 }
2056
2057 return false;
2058}
2059
2060/// Determine whether the conversion from FromType to ToType is a valid
2061/// vector conversion.
2062///
2063/// \param ICK Will be set to the vector conversion kind, if this is a vector
2064/// conversion.
2065static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2067 ImplicitConversionKind &ElConv, Expr *From,
2068 bool InOverloadResolution, bool CStyle) {
2069 // We need at least one of these types to be a vector type to have a vector
2070 // conversion.
2071 if (!ToType->isVectorType() && !FromType->isVectorType())
2072 return false;
2073
2074 // Identical types require no conversions.
2075 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2076 return false;
2077
2078 // HLSL allows implicit truncation of vector types.
2079 if (S.getLangOpts().HLSL) {
2080 auto *ToExtType = ToType->getAs<ExtVectorType>();
2081 auto *FromExtType = FromType->getAs<ExtVectorType>();
2082
2083 // If both arguments are vectors, handle possible vector truncation and
2084 // element conversion.
2085 if (ToExtType && FromExtType) {
2086 unsigned FromElts = FromExtType->getNumElements();
2087 unsigned ToElts = ToExtType->getNumElements();
2088 if (FromElts < ToElts)
2089 return false;
2090 if (FromElts == ToElts)
2091 ElConv = ICK_Identity;
2092 else
2094
2095 QualType FromElTy = FromExtType->getElementType();
2096 QualType ToElTy = ToExtType->getElementType();
2097 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2098 return true;
2099 return IsVectorElementConversion(S, FromElTy, ToElTy, ICK, From);
2100 }
2101 if (FromExtType && !ToExtType) {
2103 QualType FromElTy = FromExtType->getElementType();
2104 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2105 return true;
2106 return IsVectorElementConversion(S, FromElTy, ToType, ICK, From);
2107 }
2108 // Fallthrough for the case where ToType is a vector and FromType is not.
2109 }
2110
2111 // There are no conversions between extended vector types, only identity.
2112 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2113 if (FromType->getAs<ExtVectorType>()) {
2114 // There are no conversions between extended vector types other than the
2115 // identity conversion.
2116 return false;
2117 }
2118
2119 // Vector splat from any arithmetic type to a vector.
2120 if (FromType->isArithmeticType()) {
2121 if (S.getLangOpts().HLSL) {
2122 ElConv = ICK_HLSL_Vector_Splat;
2123 QualType ToElTy = ToExtType->getElementType();
2124 return IsVectorElementConversion(S, FromType, ToElTy, ICK, From);
2125 }
2126 ICK = ICK_Vector_Splat;
2127 return true;
2128 }
2129 }
2130
2131 if (ToType->isSVESizelessBuiltinType() ||
2132 FromType->isSVESizelessBuiltinType())
2133 if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
2134 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
2136 return true;
2137 }
2138
2139 if (ToType->isRVVSizelessBuiltinType() ||
2140 FromType->isRVVSizelessBuiltinType())
2141 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2142 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2144 return true;
2145 }
2146
2147 // We can perform the conversion between vector types in the following cases:
2148 // 1)vector types are equivalent AltiVec and GCC vector types
2149 // 2)lax vector conversions are permitted and the vector types are of the
2150 // same size
2151 // 3)the destination type does not have the ARM MVE strict-polymorphism
2152 // attribute, which inhibits lax vector conversion for overload resolution
2153 // only
2154 if (ToType->isVectorType() && FromType->isVectorType()) {
2155 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2156 (S.isLaxVectorConversion(FromType, ToType) &&
2157 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2158 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2159 S.isLaxVectorConversion(FromType, ToType) &&
2160 S.anyAltivecTypes(FromType, ToType) &&
2161 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2162 !InOverloadResolution && !CStyle) {
2163 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2164 << FromType << ToType;
2165 }
2167 return true;
2168 }
2169 }
2170
2171 return false;
2172}
2173
2174static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2175 bool InOverloadResolution,
2177 bool CStyle);
2178
2179/// IsStandardConversion - Determines whether there is a standard
2180/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2181/// expression From to the type ToType. Standard conversion sequences
2182/// only consider non-class types; for conversions that involve class
2183/// types, use TryImplicitConversion. If a conversion exists, SCS will
2184/// contain the standard conversion sequence required to perform this
2185/// conversion and this routine will return true. Otherwise, this
2186/// routine will return false and the value of SCS is unspecified.
2187static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2188 bool InOverloadResolution,
2190 bool CStyle,
2191 bool AllowObjCWritebackConversion) {
2192 QualType FromType = From->getType();
2193
2194 // Standard conversions (C++ [conv])
2196 SCS.IncompatibleObjC = false;
2197 SCS.setFromType(FromType);
2198 SCS.CopyConstructor = nullptr;
2199
2200 // There are no standard conversions for class types in C++, so
2201 // abort early. When overloading in C, however, we do permit them.
2202 if (S.getLangOpts().CPlusPlus &&
2203 (FromType->isRecordType() || ToType->isRecordType()))
2204 return false;
2205
2206 // The first conversion can be an lvalue-to-rvalue conversion,
2207 // array-to-pointer conversion, or function-to-pointer conversion
2208 // (C++ 4p1).
2209
2210 if (FromType == S.Context.OverloadTy) {
2211 DeclAccessPair AccessPair;
2212 if (FunctionDecl *Fn
2213 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2214 AccessPair)) {
2215 // We were able to resolve the address of the overloaded function,
2216 // so we can convert to the type of that function.
2217 FromType = Fn->getType();
2218 SCS.setFromType(FromType);
2219
2220 // we can sometimes resolve &foo<int> regardless of ToType, so check
2221 // if the type matches (identity) or we are converting to bool
2223 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2224 QualType resultTy;
2225 // if the function type matches except for [[noreturn]], it's ok
2226 if (!S.IsFunctionConversion(FromType,
2227 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
2228 // otherwise, only a boolean conversion is standard
2229 if (!ToType->isBooleanType())
2230 return false;
2231 }
2232
2233 // Check if the "from" expression is taking the address of an overloaded
2234 // function and recompute the FromType accordingly. Take advantage of the
2235 // fact that non-static member functions *must* have such an address-of
2236 // expression.
2237 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2238 if (Method && !Method->isStatic() &&
2239 !Method->isExplicitObjectMemberFunction()) {
2240 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2241 "Non-unary operator on non-static member address");
2242 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2243 == UO_AddrOf &&
2244 "Non-address-of operator on non-static member address");
2245 const Type *ClassType
2247 FromType = S.Context.getMemberPointerType(FromType, ClassType);
2248 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2249 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2250 UO_AddrOf &&
2251 "Non-address-of operator for overloaded function expression");
2252 FromType = S.Context.getPointerType(FromType);
2253 }
2254 } else {
2255 return false;
2256 }
2257 }
2258
2259 bool argIsLValue = From->isGLValue();
2260 // To handle conversion from ArrayParameterType to ConstantArrayType
2261 // this block must be above the one below because Array parameters
2262 // do not decay and when handling HLSLOutArgExprs and
2263 // the From expression is an LValue.
2264 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2265 ToType->isConstantArrayType()) {
2266 // HLSL constant array parameters do not decay, so if the argument is a
2267 // constant array and the parameter is an ArrayParameterType we have special
2268 // handling here.
2269 if (ToType->isArrayParameterType()) {
2270 FromType = S.Context.getArrayParameterType(FromType);
2272 } else if (FromType->isArrayParameterType()) {
2273 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2274 FromType = APT->getConstantArrayType(S.Context);
2276 } else {
2277 SCS.First = ICK_Identity;
2278 }
2279
2280 if (S.Context.getCanonicalType(FromType) !=
2281 S.Context.getCanonicalType(ToType))
2282 return false;
2283
2284 SCS.setAllToTypes(ToType);
2285 return true;
2286 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2287 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2288 // Lvalue-to-rvalue conversion (C++11 4.1):
2289 // A glvalue (3.10) of a non-function, non-array type T can
2290 // be converted to a prvalue.
2291
2293
2294 // C11 6.3.2.1p2:
2295 // ... if the lvalue has atomic type, the value has the non-atomic version
2296 // of the type of the lvalue ...
2297 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2298 FromType = Atomic->getValueType();
2299
2300 // If T is a non-class type, the type of the rvalue is the
2301 // cv-unqualified version of T. Otherwise, the type of the rvalue
2302 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2303 // just strip the qualifiers because they don't matter.
2304 FromType = FromType.getUnqualifiedType();
2305 } else if (FromType->isArrayType()) {
2306 // Array-to-pointer conversion (C++ 4.2)
2308
2309 // An lvalue or rvalue of type "array of N T" or "array of unknown
2310 // bound of T" can be converted to an rvalue of type "pointer to
2311 // T" (C++ 4.2p1).
2312 FromType = S.Context.getArrayDecayedType(FromType);
2313
2314 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2315 // This conversion is deprecated in C++03 (D.4)
2317
2318 // For the purpose of ranking in overload resolution
2319 // (13.3.3.1.1), this conversion is considered an
2320 // array-to-pointer conversion followed by a qualification
2321 // conversion (4.4). (C++ 4.2p2)
2322 SCS.Second = ICK_Identity;
2325 SCS.setAllToTypes(FromType);
2326 return true;
2327 }
2328 } else if (FromType->isFunctionType() && argIsLValue) {
2329 // Function-to-pointer conversion (C++ 4.3).
2331
2332 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2333 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2335 return false;
2336
2337 // An lvalue of function type T can be converted to an rvalue of
2338 // type "pointer to T." The result is a pointer to the
2339 // function. (C++ 4.3p1).
2340 FromType = S.Context.getPointerType(FromType);
2341 } else {
2342 // We don't require any conversions for the first step.
2343 SCS.First = ICK_Identity;
2344 }
2345 SCS.setToType(0, FromType);
2346
2347 // The second conversion can be an integral promotion, floating
2348 // point promotion, integral conversion, floating point conversion,
2349 // floating-integral conversion, pointer conversion,
2350 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2351 // For overloading in C, this can also be a "compatible-type"
2352 // conversion.
2353 bool IncompatibleObjC = false;
2355 ImplicitConversionKind DimensionICK = ICK_Identity;
2356 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2357 // The unqualified versions of the types are the same: there's no
2358 // conversion to do.
2359 SCS.Second = ICK_Identity;
2360 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2361 // Integral promotion (C++ 4.5).
2363 FromType = ToType.getUnqualifiedType();
2364 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2365 // Floating point promotion (C++ 4.6).
2367 FromType = ToType.getUnqualifiedType();
2368 } else if (S.IsComplexPromotion(FromType, ToType)) {
2369 // Complex promotion (Clang extension)
2371 FromType = ToType.getUnqualifiedType();
2372 } else if (ToType->isBooleanType() &&
2373 (FromType->isArithmeticType() ||
2374 FromType->isAnyPointerType() ||
2375 FromType->isBlockPointerType() ||
2376 FromType->isMemberPointerType())) {
2377 // Boolean conversions (C++ 4.12).
2379 FromType = S.Context.BoolTy;
2380 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2381 ToType->isIntegralType(S.Context)) {
2382 // Integral conversions (C++ 4.7).
2384 FromType = ToType.getUnqualifiedType();
2385 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2386 // Complex conversions (C99 6.3.1.6)
2388 FromType = ToType.getUnqualifiedType();
2389 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2390 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2391 // Complex-real conversions (C99 6.3.1.7)
2393 FromType = ToType.getUnqualifiedType();
2394 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2395 // Floating point conversions (C++ 4.8).
2397 FromType = ToType.getUnqualifiedType();
2398 } else if ((FromType->isRealFloatingType() &&
2399 ToType->isIntegralType(S.Context)) ||
2401 ToType->isRealFloatingType())) {
2402
2403 // Floating-integral conversions (C++ 4.9).
2405 FromType = ToType.getUnqualifiedType();
2406 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2408 } else if (AllowObjCWritebackConversion &&
2409 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2411 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2412 FromType, IncompatibleObjC)) {
2413 // Pointer conversions (C++ 4.10).
2415 SCS.IncompatibleObjC = IncompatibleObjC;
2416 FromType = FromType.getUnqualifiedType();
2417 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2418 InOverloadResolution, FromType)) {
2419 // Pointer to member conversions (4.11).
2421 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2422 From, InOverloadResolution, CStyle)) {
2423 SCS.Second = SecondICK;
2424 SCS.Dimension = DimensionICK;
2425 FromType = ToType.getUnqualifiedType();
2426 } else if (!S.getLangOpts().CPlusPlus &&
2427 S.Context.typesAreCompatible(ToType, FromType)) {
2428 // Compatible conversions (Clang extension for C function overloading)
2430 FromType = ToType.getUnqualifiedType();
2432 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2434 FromType = ToType;
2435 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2436 CStyle)) {
2437 // tryAtomicConversion has updated the standard conversion sequence
2438 // appropriately.
2439 return true;
2440 } else if (ToType->isEventT() &&
2442 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2444 FromType = ToType;
2445 } else if (ToType->isQueueT() &&
2447 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2449 FromType = ToType;
2450 } else if (ToType->isSamplerT() &&
2453 FromType = ToType;
2454 } else if ((ToType->isFixedPointType() &&
2455 FromType->isConvertibleToFixedPointType()) ||
2456 (FromType->isFixedPointType() &&
2457 ToType->isConvertibleToFixedPointType())) {
2459 FromType = ToType;
2460 } else {
2461 // No second conversion required.
2462 SCS.Second = ICK_Identity;
2463 }
2464 SCS.setToType(1, FromType);
2465
2466 // The third conversion can be a function pointer conversion or a
2467 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2468 bool ObjCLifetimeConversion;
2469 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
2470 // Function pointer conversions (removing 'noexcept') including removal of
2471 // 'noreturn' (Clang extension).
2473 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2474 ObjCLifetimeConversion)) {
2476 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2477 FromType = ToType;
2478 } else {
2479 // No conversion required
2480 SCS.Third = ICK_Identity;
2481 }
2482
2483 // C++ [over.best.ics]p6:
2484 // [...] Any difference in top-level cv-qualification is
2485 // subsumed by the initialization itself and does not constitute
2486 // a conversion. [...]
2487 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2488 QualType CanonTo = S.Context.getCanonicalType(ToType);
2489 if (CanonFrom.getLocalUnqualifiedType()
2490 == CanonTo.getLocalUnqualifiedType() &&
2491 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2492 FromType = ToType;
2493 CanonFrom = CanonTo;
2494 }
2495
2496 SCS.setToType(2, FromType);
2497
2498 if (CanonFrom == CanonTo)
2499 return true;
2500
2501 // If we have not converted the argument type to the parameter type,
2502 // this is a bad conversion sequence, unless we're resolving an overload in C.
2503 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2504 return false;
2505
2506 ExprResult ER = ExprResult{From};
2509 /*Diagnose=*/false,
2510 /*DiagnoseCFAudited=*/false,
2511 /*ConvertRHS=*/false);
2512 ImplicitConversionKind SecondConv;
2513 switch (Conv) {
2514 case Sema::Compatible:
2515 SecondConv = ICK_C_Only_Conversion;
2516 break;
2517 // For our purposes, discarding qualifiers is just as bad as using an
2518 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2519 // qualifiers, as well.
2524 break;
2525 default:
2526 return false;
2527 }
2528
2529 // First can only be an lvalue conversion, so we pretend that this was the
2530 // second conversion. First should already be valid from earlier in the
2531 // function.
2532 SCS.Second = SecondConv;
2533 SCS.setToType(1, ToType);
2534
2535 // Third is Identity, because Second should rank us worse than any other
2536 // conversion. This could also be ICK_Qualification, but it's simpler to just
2537 // lump everything in with the second conversion, and we don't gain anything
2538 // from making this ICK_Qualification.
2539 SCS.Third = ICK_Identity;
2540 SCS.setToType(2, ToType);
2541 return true;
2542}
2543
2544static bool
2546 QualType &ToType,
2547 bool InOverloadResolution,
2549 bool CStyle) {
2550
2551 const RecordType *UT = ToType->getAsUnionType();
2552 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2553 return false;
2554 // The field to initialize within the transparent union.
2555 RecordDecl *UD = UT->getDecl();
2556 // It's compatible if the expression matches any of the fields.
2557 for (const auto *it : UD->fields()) {
2558 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2559 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2560 ToType = it->getType();
2561 return true;
2562 }
2563 }
2564 return false;
2565}
2566
2567bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2568 const BuiltinType *To = ToType->getAs<BuiltinType>();
2569 // All integers are built-in.
2570 if (!To) {
2571 return false;
2572 }
2573
2574 // An rvalue of type char, signed char, unsigned char, short int, or
2575 // unsigned short int can be converted to an rvalue of type int if
2576 // int can represent all the values of the source type; otherwise,
2577 // the source rvalue can be converted to an rvalue of type unsigned
2578 // int (C++ 4.5p1).
2579 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2580 !FromType->isEnumeralType()) {
2581 if ( // We can promote any signed, promotable integer type to an int
2582 (FromType->isSignedIntegerType() ||
2583 // We can promote any unsigned integer type whose size is
2584 // less than int to an int.
2585 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2586 return To->getKind() == BuiltinType::Int;
2587 }
2588
2589 return To->getKind() == BuiltinType::UInt;
2590 }
2591
2592 // C++11 [conv.prom]p3:
2593 // A prvalue of an unscoped enumeration type whose underlying type is not
2594 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2595 // following types that can represent all the values of the enumeration
2596 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2597 // unsigned int, long int, unsigned long int, long long int, or unsigned
2598 // long long int. If none of the types in that list can represent all the
2599 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2600 // type can be converted to an rvalue a prvalue of the extended integer type
2601 // with lowest integer conversion rank (4.13) greater than the rank of long
2602 // long in which all the values of the enumeration can be represented. If
2603 // there are two such extended types, the signed one is chosen.
2604 // C++11 [conv.prom]p4:
2605 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2606 // can be converted to a prvalue of its underlying type. Moreover, if
2607 // integral promotion can be applied to its underlying type, a prvalue of an
2608 // unscoped enumeration type whose underlying type is fixed can also be
2609 // converted to a prvalue of the promoted underlying type.
2610 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2611 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2612 // provided for a scoped enumeration.
2613 if (FromEnumType->getDecl()->isScoped())
2614 return false;
2615
2616 // We can perform an integral promotion to the underlying type of the enum,
2617 // even if that's not the promoted type. Note that the check for promoting
2618 // the underlying type is based on the type alone, and does not consider
2619 // the bitfield-ness of the actual source expression.
2620 if (FromEnumType->getDecl()->isFixed()) {
2621 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2622 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2623 IsIntegralPromotion(nullptr, Underlying, ToType);
2624 }
2625
2626 // We have already pre-calculated the promotion type, so this is trivial.
2627 if (ToType->isIntegerType() &&
2628 isCompleteType(From->getBeginLoc(), FromType))
2629 return Context.hasSameUnqualifiedType(
2630 ToType, FromEnumType->getDecl()->getPromotionType());
2631
2632 // C++ [conv.prom]p5:
2633 // If the bit-field has an enumerated type, it is treated as any other
2634 // value of that type for promotion purposes.
2635 //
2636 // ... so do not fall through into the bit-field checks below in C++.
2637 if (getLangOpts().CPlusPlus)
2638 return false;
2639 }
2640
2641 // C++0x [conv.prom]p2:
2642 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2643 // to an rvalue a prvalue of the first of the following types that can
2644 // represent all the values of its underlying type: int, unsigned int,
2645 // long int, unsigned long int, long long int, or unsigned long long int.
2646 // If none of the types in that list can represent all the values of its
2647 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2648 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2649 // type.
2650 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2651 ToType->isIntegerType()) {
2652 // Determine whether the type we're converting from is signed or
2653 // unsigned.
2654 bool FromIsSigned = FromType->isSignedIntegerType();
2655 uint64_t FromSize = Context.getTypeSize(FromType);
2656
2657 // The types we'll try to promote to, in the appropriate
2658 // order. Try each of these types.
2659 QualType PromoteTypes[6] = {
2660 Context.IntTy, Context.UnsignedIntTy,
2661 Context.LongTy, Context.UnsignedLongTy ,
2662 Context.LongLongTy, Context.UnsignedLongLongTy
2663 };
2664 for (int Idx = 0; Idx < 6; ++Idx) {
2665 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2666 if (FromSize < ToSize ||
2667 (FromSize == ToSize &&
2668 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2669 // We found the type that we can promote to. If this is the
2670 // type we wanted, we have a promotion. Otherwise, no
2671 // promotion.
2672 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2673 }
2674 }
2675 }
2676
2677 // An rvalue for an integral bit-field (9.6) can be converted to an
2678 // rvalue of type int if int can represent all the values of the
2679 // bit-field; otherwise, it can be converted to unsigned int if
2680 // unsigned int can represent all the values of the bit-field. If
2681 // the bit-field is larger yet, no integral promotion applies to
2682 // it. If the bit-field has an enumerated type, it is treated as any
2683 // other value of that type for promotion purposes (C++ 4.5p3).
2684 // FIXME: We should delay checking of bit-fields until we actually perform the
2685 // conversion.
2686 //
2687 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2688 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2689 // bit-fields and those whose underlying type is larger than int) for GCC
2690 // compatibility.
2691 if (From) {
2692 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2693 std::optional<llvm::APSInt> BitWidth;
2694 if (FromType->isIntegralType(Context) &&
2695 (BitWidth =
2696 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2697 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2698 ToSize = Context.getTypeSize(ToType);
2699
2700 // Are we promoting to an int from a bitfield that fits in an int?
2701 if (*BitWidth < ToSize ||
2702 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2703 return To->getKind() == BuiltinType::Int;
2704 }
2705
2706 // Are we promoting to an unsigned int from an unsigned bitfield
2707 // that fits into an unsigned int?
2708 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2709 return To->getKind() == BuiltinType::UInt;
2710 }
2711
2712 return false;
2713 }
2714 }
2715 }
2716
2717 // An rvalue of type bool can be converted to an rvalue of type int,
2718 // with false becoming zero and true becoming one (C++ 4.5p4).
2719 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2720 return true;
2721 }
2722
2723 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2724 // integral type.
2725 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2726 ToType->isIntegerType())
2727 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2728
2729 return false;
2730}
2731
2733 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2734 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2735 /// An rvalue of type float can be converted to an rvalue of type
2736 /// double. (C++ 4.6p1).
2737 if (FromBuiltin->getKind() == BuiltinType::Float &&
2738 ToBuiltin->getKind() == BuiltinType::Double)
2739 return true;
2740
2741 // C99 6.3.1.5p1:
2742 // When a float is promoted to double or long double, or a
2743 // double is promoted to long double [...].
2744 if (!getLangOpts().CPlusPlus &&
2745 (FromBuiltin->getKind() == BuiltinType::Float ||
2746 FromBuiltin->getKind() == BuiltinType::Double) &&
2747 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2748 ToBuiltin->getKind() == BuiltinType::Float128 ||
2749 ToBuiltin->getKind() == BuiltinType::Ibm128))
2750 return true;
2751
2752 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2753 // or not native half types are enabled.
2754 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2755 (ToBuiltin->getKind() == BuiltinType::Float ||
2756 ToBuiltin->getKind() == BuiltinType::Double))
2757 return true;
2758
2759 // Half can be promoted to float.
2760 if (!getLangOpts().NativeHalfType &&
2761 FromBuiltin->getKind() == BuiltinType::Half &&
2762 ToBuiltin->getKind() == BuiltinType::Float)
2763 return true;
2764 }
2765
2766 return false;
2767}
2768
2770 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2771 if (!FromComplex)
2772 return false;
2773
2774 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2775 if (!ToComplex)
2776 return false;
2777
2778 return IsFloatingPointPromotion(FromComplex->getElementType(),
2779 ToComplex->getElementType()) ||
2780 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2781 ToComplex->getElementType());
2782}
2783
2784/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2785/// the pointer type FromPtr to a pointer to type ToPointee, with the
2786/// same type qualifiers as FromPtr has on its pointee type. ToType,
2787/// if non-empty, will be a pointer to ToType that may or may not have
2788/// the right set of qualifiers on its pointee.
2789///
2790static QualType
2792 QualType ToPointee, QualType ToType,
2793 ASTContext &Context,
2794 bool StripObjCLifetime = false) {
2795 assert((FromPtr->getTypeClass() == Type::Pointer ||
2796 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2797 "Invalid similarly-qualified pointer type");
2798
2799 /// Conversions to 'id' subsume cv-qualifier conversions.
2800 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2801 return ToType.getUnqualifiedType();
2802
2803 QualType CanonFromPointee
2804 = Context.getCanonicalType(FromPtr->getPointeeType());
2805 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2806 Qualifiers Quals = CanonFromPointee.getQualifiers();
2807
2808 if (StripObjCLifetime)
2809 Quals.removeObjCLifetime();
2810
2811 // Exact qualifier match -> return the pointer type we're converting to.
2812 if (CanonToPointee.getLocalQualifiers() == Quals) {
2813 // ToType is exactly what we need. Return it.
2814 if (!ToType.isNull())
2815 return ToType.getUnqualifiedType();
2816
2817 // Build a pointer to ToPointee. It has the right qualifiers
2818 // already.
2819 if (isa<ObjCObjectPointerType>(ToType))
2820 return Context.getObjCObjectPointerType(ToPointee);
2821 return Context.getPointerType(ToPointee);
2822 }
2823
2824 // Just build a canonical type that has the right qualifiers.
2825 QualType QualifiedCanonToPointee
2826 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2827
2828 if (isa<ObjCObjectPointerType>(ToType))
2829 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2830 return Context.getPointerType(QualifiedCanonToPointee);
2831}
2832
2834 bool InOverloadResolution,
2835 ASTContext &Context) {
2836 // Handle value-dependent integral null pointer constants correctly.
2837 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2838 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2840 return !InOverloadResolution;
2841
2842 return Expr->isNullPointerConstant(Context,
2843 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2845}
2846
2848 bool InOverloadResolution,
2849 QualType& ConvertedType,
2850 bool &IncompatibleObjC) {
2851 IncompatibleObjC = false;
2852 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2853 IncompatibleObjC))
2854 return true;
2855
2856 // Conversion from a null pointer constant to any Objective-C pointer type.
2857 if (ToType->isObjCObjectPointerType() &&
2858 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2859 ConvertedType = ToType;
2860 return true;
2861 }
2862
2863 // Blocks: Block pointers can be converted to void*.
2864 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2865 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2866 ConvertedType = ToType;
2867 return true;
2868 }
2869 // Blocks: A null pointer constant can be converted to a block
2870 // pointer type.
2871 if (ToType->isBlockPointerType() &&
2872 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2873 ConvertedType = ToType;
2874 return true;
2875 }
2876
2877 // If the left-hand-side is nullptr_t, the right side can be a null
2878 // pointer constant.
2879 if (ToType->isNullPtrType() &&
2880 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2881 ConvertedType = ToType;
2882 return true;
2883 }
2884
2885 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2886 if (!ToTypePtr)
2887 return false;
2888
2889 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2890 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2891 ConvertedType = ToType;
2892 return true;
2893 }
2894
2895 // Beyond this point, both types need to be pointers
2896 // , including objective-c pointers.
2897 QualType ToPointeeType = ToTypePtr->getPointeeType();
2898 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2899 !getLangOpts().ObjCAutoRefCount) {
2900 ConvertedType = BuildSimilarlyQualifiedPointerType(
2901 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2902 Context);
2903 return true;
2904 }
2905 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2906 if (!FromTypePtr)
2907 return false;
2908
2909 QualType FromPointeeType = FromTypePtr->getPointeeType();
2910
2911 // If the unqualified pointee types are the same, this can't be a
2912 // pointer conversion, so don't do all of the work below.
2913 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2914 return false;
2915
2916 // An rvalue of type "pointer to cv T," where T is an object type,
2917 // can be converted to an rvalue of type "pointer to cv void" (C++
2918 // 4.10p2).
2919 if (FromPointeeType->isIncompleteOrObjectType() &&
2920 ToPointeeType->isVoidType()) {
2921 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2922 ToPointeeType,
2923 ToType, Context,
2924 /*StripObjCLifetime=*/true);
2925 return true;
2926 }
2927
2928 // MSVC allows implicit function to void* type conversion.
2929 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2930 ToPointeeType->isVoidType()) {
2931 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2932 ToPointeeType,
2933 ToType, Context);
2934 return true;
2935 }
2936
2937 // When we're overloading in C, we allow a special kind of pointer
2938 // conversion for compatible-but-not-identical pointee types.
2939 if (!getLangOpts().CPlusPlus &&
2940 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2941 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2942 ToPointeeType,
2943 ToType, Context);
2944 return true;
2945 }
2946
2947 // C++ [conv.ptr]p3:
2948 //
2949 // An rvalue of type "pointer to cv D," where D is a class type,
2950 // can be converted to an rvalue of type "pointer to cv B," where
2951 // B is a base class (clause 10) of D. If B is an inaccessible
2952 // (clause 11) or ambiguous (10.2) base class of D, a program that
2953 // necessitates this conversion is ill-formed. The result of the
2954 // conversion is a pointer to the base class sub-object of the
2955 // derived class object. The null pointer value is converted to
2956 // the null pointer value of the destination type.
2957 //
2958 // Note that we do not check for ambiguity or inaccessibility
2959 // here. That is handled by CheckPointerConversion.
2960 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2961 ToPointeeType->isRecordType() &&
2962 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2963 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2964 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2965 ToPointeeType,
2966 ToType, Context);
2967 return true;
2968 }
2969
2970 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2971 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2972 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2973 ToPointeeType,
2974 ToType, Context);
2975 return true;
2976 }
2977
2978 return false;
2979}
2980
2981/// Adopt the given qualifiers for the given type.
2983 Qualifiers TQs = T.getQualifiers();
2984
2985 // Check whether qualifiers already match.
2986 if (TQs == Qs)
2987 return T;
2988
2989 if (Qs.compatiblyIncludes(TQs, Context))
2990 return Context.getQualifiedType(T, Qs);
2991
2992 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2993}
2994
2996 QualType& ConvertedType,
2997 bool &IncompatibleObjC) {
2998 if (!getLangOpts().ObjC)
2999 return false;
3000
3001 // The set of qualifiers on the type we're converting from.
3002 Qualifiers FromQualifiers = FromType.getQualifiers();
3003
3004 // First, we handle all conversions on ObjC object pointer types.
3005 const ObjCObjectPointerType* ToObjCPtr =
3006 ToType->getAs<ObjCObjectPointerType>();
3007 const ObjCObjectPointerType *FromObjCPtr =
3008 FromType->getAs<ObjCObjectPointerType>();
3009
3010 if (ToObjCPtr && FromObjCPtr) {
3011 // If the pointee types are the same (ignoring qualifications),
3012 // then this is not a pointer conversion.
3013 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
3014 FromObjCPtr->getPointeeType()))
3015 return false;
3016
3017 // Conversion between Objective-C pointers.
3018 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3019 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3020 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3021 if (getLangOpts().CPlusPlus && LHS && RHS &&
3023 FromObjCPtr->getPointeeType(), getASTContext()))
3024 return false;
3025 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3026 ToObjCPtr->getPointeeType(),
3027 ToType, Context);
3028 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3029 return true;
3030 }
3031
3032 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3033 // Okay: this is some kind of implicit downcast of Objective-C
3034 // interfaces, which is permitted. However, we're going to
3035 // complain about it.
3036 IncompatibleObjC = true;
3037 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3038 ToObjCPtr->getPointeeType(),
3039 ToType, Context);
3040 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3041 return true;
3042 }
3043 }
3044 // Beyond this point, both types need to be C pointers or block pointers.
3045 QualType ToPointeeType;
3046 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3047 ToPointeeType = ToCPtr->getPointeeType();
3048 else if (const BlockPointerType *ToBlockPtr =
3049 ToType->getAs<BlockPointerType>()) {
3050 // Objective C++: We're able to convert from a pointer to any object
3051 // to a block pointer type.
3052 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3053 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3054 return true;
3055 }
3056 ToPointeeType = ToBlockPtr->getPointeeType();
3057 }
3058 else if (FromType->getAs<BlockPointerType>() &&
3059 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3060 // Objective C++: We're able to convert from a block pointer type to a
3061 // pointer to any object.
3062 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3063 return true;
3064 }
3065 else
3066 return false;
3067
3068 QualType FromPointeeType;
3069 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3070 FromPointeeType = FromCPtr->getPointeeType();
3071 else if (const BlockPointerType *FromBlockPtr =
3072 FromType->getAs<BlockPointerType>())
3073 FromPointeeType = FromBlockPtr->getPointeeType();
3074 else
3075 return false;
3076
3077 // If we have pointers to pointers, recursively check whether this
3078 // is an Objective-C conversion.
3079 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3080 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3081 IncompatibleObjC)) {
3082 // We always complain about this conversion.
3083 IncompatibleObjC = true;
3084 ConvertedType = Context.getPointerType(ConvertedType);
3085 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3086 return true;
3087 }
3088 // Allow conversion of pointee being objective-c pointer to another one;
3089 // as in I* to id.
3090 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3091 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3092 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3093 IncompatibleObjC)) {
3094
3095 ConvertedType = Context.getPointerType(ConvertedType);
3096 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3097 return true;
3098 }
3099
3100 // If we have pointers to functions or blocks, check whether the only
3101 // differences in the argument and result types are in Objective-C
3102 // pointer conversions. If so, we permit the conversion (but
3103 // complain about it).
3104 const FunctionProtoType *FromFunctionType
3105 = FromPointeeType->getAs<FunctionProtoType>();
3106 const FunctionProtoType *ToFunctionType
3107 = ToPointeeType->getAs<FunctionProtoType>();
3108 if (FromFunctionType && ToFunctionType) {
3109 // If the function types are exactly the same, this isn't an
3110 // Objective-C pointer conversion.
3111 if (Context.getCanonicalType(FromPointeeType)
3112 == Context.getCanonicalType(ToPointeeType))
3113 return false;
3114
3115 // Perform the quick checks that will tell us whether these
3116 // function types are obviously different.
3117 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3118 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3119 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3120 return false;
3121
3122 bool HasObjCConversion = false;
3123 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3124 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3125 // Okay, the types match exactly. Nothing to do.
3126 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3127 ToFunctionType->getReturnType(),
3128 ConvertedType, IncompatibleObjC)) {
3129 // Okay, we have an Objective-C pointer conversion.
3130 HasObjCConversion = true;
3131 } else {
3132 // Function types are too different. Abort.
3133 return false;
3134 }
3135
3136 // Check argument types.
3137 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3138 ArgIdx != NumArgs; ++ArgIdx) {
3139 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3140 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3141 if (Context.getCanonicalType(FromArgType)
3142 == Context.getCanonicalType(ToArgType)) {
3143 // Okay, the types match exactly. Nothing to do.
3144 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3145 ConvertedType, IncompatibleObjC)) {
3146 // Okay, we have an Objective-C pointer conversion.
3147 HasObjCConversion = true;
3148 } else {
3149 // Argument types are too different. Abort.
3150 return false;
3151 }
3152 }
3153
3154 if (HasObjCConversion) {
3155 // We had an Objective-C conversion. Allow this pointer
3156 // conversion, but complain about it.
3157 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3158 IncompatibleObjC = true;
3159 return true;
3160 }
3161 }
3162
3163 return false;
3164}
3165
3167 QualType& ConvertedType) {
3168 QualType ToPointeeType;
3169 if (const BlockPointerType *ToBlockPtr =
3170 ToType->getAs<BlockPointerType>())
3171 ToPointeeType = ToBlockPtr->getPointeeType();
3172 else
3173 return false;
3174
3175 QualType FromPointeeType;
3176 if (const BlockPointerType *FromBlockPtr =
3177 FromType->getAs<BlockPointerType>())
3178 FromPointeeType = FromBlockPtr->getPointeeType();
3179 else
3180 return false;
3181 // We have pointer to blocks, check whether the only
3182 // differences in the argument and result types are in Objective-C
3183 // pointer conversions. If so, we permit the conversion.
3184
3185 const FunctionProtoType *FromFunctionType
3186 = FromPointeeType->getAs<FunctionProtoType>();
3187 const FunctionProtoType *ToFunctionType
3188 = ToPointeeType->getAs<FunctionProtoType>();
3189
3190 if (!FromFunctionType || !ToFunctionType)
3191 return false;
3192
3193 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3194 return true;
3195
3196 // Perform the quick checks that will tell us whether these
3197 // function types are obviously different.
3198 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3199 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3200 return false;
3201
3202 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3203 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3204 if (FromEInfo != ToEInfo)
3205 return false;
3206
3207 bool IncompatibleObjC = false;
3208 if (Context.hasSameType(FromFunctionType->getReturnType(),
3209 ToFunctionType->getReturnType())) {
3210 // Okay, the types match exactly. Nothing to do.
3211 } else {
3212 QualType RHS = FromFunctionType->getReturnType();
3213 QualType LHS = ToFunctionType->getReturnType();
3214 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3215 !RHS.hasQualifiers() && LHS.hasQualifiers())
3216 LHS = LHS.getUnqualifiedType();
3217
3218 if (Context.hasSameType(RHS,LHS)) {
3219 // OK exact match.
3220 } else if (isObjCPointerConversion(RHS, LHS,
3221 ConvertedType, IncompatibleObjC)) {
3222 if (IncompatibleObjC)
3223 return false;
3224 // Okay, we have an Objective-C pointer conversion.
3225 }
3226 else
3227 return false;
3228 }
3229
3230 // Check argument types.
3231 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3232 ArgIdx != NumArgs; ++ArgIdx) {
3233 IncompatibleObjC = false;
3234 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3235 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3236 if (Context.hasSameType(FromArgType, ToArgType)) {
3237 // Okay, the types match exactly. Nothing to do.
3238 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3239 ConvertedType, IncompatibleObjC)) {
3240 if (IncompatibleObjC)
3241 return false;
3242 // Okay, we have an Objective-C pointer conversion.
3243 } else
3244 // Argument types are too different. Abort.
3245 return false;
3246 }
3247
3249 bool CanUseToFPT, CanUseFromFPT;
3250 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3251 CanUseToFPT, CanUseFromFPT,
3252 NewParamInfos))
3253 return false;
3254
3255 ConvertedType = ToType;
3256 return true;
3257}
3258
3259enum {
3268
3269/// Attempts to get the FunctionProtoType from a Type. Handles
3270/// MemberFunctionPointers properly.
3272 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3273 return FPT;
3274
3275 if (auto *MPT = FromType->getAs<MemberPointerType>())
3276 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3277
3278 return nullptr;
3279}
3280
3282 QualType FromType, QualType ToType) {
3283 // If either type is not valid, include no extra info.
3284 if (FromType.isNull() || ToType.isNull()) {
3285 PDiag << ft_default;
3286 return;
3287 }
3288
3289 // Get the function type from the pointers.
3290 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3291 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3292 *ToMember = ToType->castAs<MemberPointerType>();
3293 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
3294 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
3295 << QualType(FromMember->getClass(), 0);
3296 return;
3297 }
3298 FromType = FromMember->getPointeeType();
3299 ToType = ToMember->getPointeeType();
3300 }
3301
3302 if (FromType->isPointerType())
3303 FromType = FromType->getPointeeType();
3304 if (ToType->isPointerType())
3305 ToType = ToType->getPointeeType();
3306
3307 // Remove references.
3308 FromType = FromType.getNonReferenceType();
3309 ToType = ToType.getNonReferenceType();
3310
3311 // Don't print extra info for non-specialized template functions.
3312 if (FromType->isInstantiationDependentType() &&
3313 !FromType->getAs<TemplateSpecializationType>()) {
3314 PDiag << ft_default;
3315 return;
3316 }
3317
3318 // No extra info for same types.
3319 if (Context.hasSameType(FromType, ToType)) {
3320 PDiag << ft_default;
3321 return;
3322 }
3323
3324 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3325 *ToFunction = tryGetFunctionProtoType(ToType);
3326
3327 // Both types need to be function types.
3328 if (!FromFunction || !ToFunction) {
3329 PDiag << ft_default;
3330 return;
3331 }
3332
3333 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3334 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3335 << FromFunction->getNumParams();
3336 return;
3337 }
3338
3339 // Handle different parameter types.
3340 unsigned ArgPos;
3341 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3342 PDiag << ft_parameter_mismatch << ArgPos + 1
3343 << ToFunction->getParamType(ArgPos)
3344 << FromFunction->getParamType(ArgPos);
3345 return;
3346 }
3347
3348 // Handle different return type.
3349 if (!Context.hasSameType(FromFunction->getReturnType(),
3350 ToFunction->getReturnType())) {
3351 PDiag << ft_return_type << ToFunction->getReturnType()
3352 << FromFunction->getReturnType();
3353 return;
3354 }
3355
3356 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3357 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3358 << FromFunction->getMethodQuals();
3359 return;
3360 }
3361
3362 // Handle exception specification differences on canonical type (in C++17
3363 // onwards).
3364 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
3365 ->isNothrow() !=
3366 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3367 ->isNothrow()) {
3368 PDiag << ft_noexcept;
3369 return;
3370 }
3371
3372 // Unable to find a difference, so add no extra info.
3373 PDiag << ft_default;
3374}
3375
3377 ArrayRef<QualType> New, unsigned *ArgPos,
3378 bool Reversed) {
3379 assert(llvm::size(Old) == llvm::size(New) &&
3380 "Can't compare parameters of functions with different number of "
3381 "parameters!");
3382
3383 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3384 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3385 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3386
3387 // Ignore address spaces in pointee type. This is to disallow overloading
3388 // on __ptr32/__ptr64 address spaces.
3389 QualType OldType =
3390 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3391 QualType NewType =
3392 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3393
3394 if (!Context.hasSameType(OldType, NewType)) {
3395 if (ArgPos)
3396 *ArgPos = Idx;
3397 return false;
3398 }
3399 }
3400 return true;
3401}
3402
3404 const FunctionProtoType *NewType,
3405 unsigned *ArgPos, bool Reversed) {
3406 return FunctionParamTypesAreEqual(OldType->param_types(),
3407 NewType->param_types(), ArgPos, Reversed);
3408}
3409
3411 const FunctionDecl *NewFunction,
3412 unsigned *ArgPos,
3413 bool Reversed) {
3414
3415 if (OldFunction->getNumNonObjectParams() !=
3416 NewFunction->getNumNonObjectParams())
3417 return false;
3418
3419 unsigned OldIgnore =
3421 unsigned NewIgnore =
3423
3424 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3425 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3426
3427 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3428 NewPT->param_types().slice(NewIgnore),
3429 ArgPos, Reversed);
3430}
3431
3433 CastKind &Kind,
3434 CXXCastPath& BasePath,
3435 bool IgnoreBaseAccess,
3436 bool Diagnose) {
3437 QualType FromType = From->getType();
3438 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3439
3440 Kind = CK_BitCast;
3441
3442 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3445 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3446 DiagRuntimeBehavior(From->getExprLoc(), From,
3447 PDiag(diag::warn_impcast_bool_to_null_pointer)
3448 << ToType << From->getSourceRange());
3449 else if (!isUnevaluatedContext())
3450 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3451 << ToType << From->getSourceRange();
3452 }
3453 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3454 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3455 QualType FromPointeeType = FromPtrType->getPointeeType(),
3456 ToPointeeType = ToPtrType->getPointeeType();
3457
3458 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3459 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3460 // We must have a derived-to-base conversion. Check an
3461 // ambiguous or inaccessible conversion.
3462 unsigned InaccessibleID = 0;
3463 unsigned AmbiguousID = 0;
3464 if (Diagnose) {
3465 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3466 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3467 }
3468 if (CheckDerivedToBaseConversion(
3469 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3470 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3471 &BasePath, IgnoreBaseAccess))
3472 return true;
3473
3474 // The conversion was successful.
3475 Kind = CK_DerivedToBase;
3476 }
3477
3478 if (Diagnose && !IsCStyleOrFunctionalCast &&
3479 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3480 assert(getLangOpts().MSVCCompat &&
3481 "this should only be possible with MSVCCompat!");
3482 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3483 << From->getSourceRange();
3484 }
3485 }
3486 } else if (const ObjCObjectPointerType *ToPtrType =
3487 ToType->getAs<ObjCObjectPointerType>()) {
3488 if (const ObjCObjectPointerType *FromPtrType =
3489 FromType->getAs<ObjCObjectPointerType>()) {
3490 // Objective-C++ conversions are always okay.
3491 // FIXME: We should have a different class of conversions for the
3492 // Objective-C++ implicit conversions.
3493 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3494 return false;
3495 } else if (FromType->isBlockPointerType()) {
3496 Kind = CK_BlockPointerToObjCPointerCast;
3497 } else {
3498 Kind = CK_CPointerToObjCPointerCast;
3499 }
3500 } else if (ToType->isBlockPointerType()) {
3501 if (!FromType->isBlockPointerType())
3502 Kind = CK_AnyPointerToBlockPointerCast;
3503 }
3504
3505 // We shouldn't fall into this case unless it's valid for other
3506 // reasons.
3508 Kind = CK_NullToPointer;
3509
3510 return false;
3511}
3512
3514 QualType ToType,
3515 bool InOverloadResolution,
3516 QualType &ConvertedType) {
3517 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3518 if (!ToTypePtr)
3519 return false;
3520
3521 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3522 if (From->isNullPointerConstant(Context,
3523 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3525 ConvertedType = ToType;
3526 return true;
3527 }
3528
3529 // Otherwise, both types have to be member pointers.
3530 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3531 if (!FromTypePtr)
3532 return false;
3533
3534 // A pointer to member of B can be converted to a pointer to member of D,
3535 // where D is derived from B (C++ 4.11p2).
3536 QualType FromClass(FromTypePtr->getClass(), 0);
3537 QualType ToClass(ToTypePtr->getClass(), 0);
3538
3539 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3540 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3541 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3542 ToClass.getTypePtr());
3543 return true;
3544 }
3545
3546 return false;
3547}
3548
3550 CastKind &Kind,
3551 CXXCastPath &BasePath,
3552 bool IgnoreBaseAccess) {
3553 QualType FromType = From->getType();
3554 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3555 if (!FromPtrType) {
3556 // This must be a null pointer to member pointer conversion
3557 assert(From->isNullPointerConstant(Context,
3559 "Expr must be null pointer constant!");
3560 Kind = CK_NullToMemberPointer;
3561 return false;
3562 }
3563
3564 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3565 assert(ToPtrType && "No member pointer cast has a target type "
3566 "that is not a member pointer.");
3567
3568 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3569 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3570
3571 // FIXME: What about dependent types?
3572 assert(FromClass->isRecordType() && "Pointer into non-class.");
3573 assert(ToClass->isRecordType() && "Pointer into non-class.");
3574
3575 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3576 /*DetectVirtual=*/true);
3577 bool DerivationOkay =
3578 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3579 assert(DerivationOkay &&
3580 "Should not have been called if derivation isn't OK.");
3581 (void)DerivationOkay;
3582
3583 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3584 getUnqualifiedType())) {
3585 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3586 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3587 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3588 return true;
3589 }
3590
3591 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3592 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3593 << FromClass << ToClass << QualType(VBase, 0)
3594 << From->getSourceRange();
3595 return true;
3596 }
3597
3598 if (!IgnoreBaseAccess)
3599 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3600 Paths.front(),
3601 diag::err_downcast_from_inaccessible_base);
3602
3603 // Must be a base to derived member conversion.
3604 BuildBasePathArray(Paths, BasePath);
3605 Kind = CK_BaseToDerivedMemberPointer;
3606 return false;
3607}
3608
3609/// Determine whether the lifetime conversion between the two given
3610/// qualifiers sets is nontrivial.
3612 Qualifiers ToQuals) {
3613 // Converting anything to const __unsafe_unretained is trivial.
3614 if (ToQuals.hasConst() &&
3616 return false;
3617
3618 return true;
3619}
3620
3621/// Perform a single iteration of the loop for checking if a qualification
3622/// conversion is valid.
3623///
3624/// Specifically, check whether any change between the qualifiers of \p
3625/// FromType and \p ToType is permissible, given knowledge about whether every
3626/// outer layer is const-qualified.
3628 bool CStyle, bool IsTopLevel,
3629 bool &PreviousToQualsIncludeConst,
3630 bool &ObjCLifetimeConversion,
3631 const ASTContext &Ctx) {
3632 Qualifiers FromQuals = FromType.getQualifiers();
3633 Qualifiers ToQuals = ToType.getQualifiers();
3634
3635 // Ignore __unaligned qualifier.
3636 FromQuals.removeUnaligned();
3637
3638 // Objective-C ARC:
3639 // Check Objective-C lifetime conversions.
3640 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3641 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3642 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3643 ObjCLifetimeConversion = true;
3644 FromQuals.removeObjCLifetime();
3645 ToQuals.removeObjCLifetime();
3646 } else {
3647 // Qualification conversions cannot cast between different
3648 // Objective-C lifetime qualifiers.
3649 return false;
3650 }
3651 }
3652
3653 // Allow addition/removal of GC attributes but not changing GC attributes.
3654 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3655 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3656 FromQuals.removeObjCGCAttr();
3657 ToQuals.removeObjCGCAttr();
3658 }
3659
3660 // -- for every j > 0, if const is in cv 1,j then const is in cv
3661 // 2,j, and similarly for volatile.
3662 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3663 return false;
3664
3665 // If address spaces mismatch:
3666 // - in top level it is only valid to convert to addr space that is a
3667 // superset in all cases apart from C-style casts where we allow
3668 // conversions between overlapping address spaces.
3669 // - in non-top levels it is not a valid conversion.
3670 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3671 (!IsTopLevel ||
3672 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
3673 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
3674 return false;
3675
3676 // -- if the cv 1,j and cv 2,j are different, then const is in
3677 // every cv for 0 < k < j.
3678 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3679 !PreviousToQualsIncludeConst)
3680 return false;
3681
3682 // The following wording is from C++20, where the result of the conversion
3683 // is T3, not T2.
3684 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3685 // "array of unknown bound of"
3686 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3687 return false;
3688
3689 // -- if the resulting P3,i is different from P1,i [...], then const is
3690 // added to every cv 3_k for 0 < k < i.
3691 if (!CStyle && FromType->isConstantArrayType() &&
3692 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3693 return false;
3694
3695 // Keep track of whether all prior cv-qualifiers in the "to" type
3696 // include const.
3697 PreviousToQualsIncludeConst =
3698 PreviousToQualsIncludeConst && ToQuals.hasConst();
3699 return true;
3700}
3701
3702bool
3704 bool CStyle, bool &ObjCLifetimeConversion) {
3705 FromType = Context.getCanonicalType(FromType);
3706 ToType = Context.getCanonicalType(ToType);
3707 ObjCLifetimeConversion = false;
3708
3709 // If FromType and ToType are the same type, this is not a
3710 // qualification conversion.
3711 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3712 return false;
3713
3714 // (C++ 4.4p4):
3715 // A conversion can add cv-qualifiers at levels other than the first
3716 // in multi-level pointers, subject to the following rules: [...]
3717 bool PreviousToQualsIncludeConst = true;
3718 bool UnwrappedAnyPointer = false;
3719 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3720 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3721 !UnwrappedAnyPointer,
3722 PreviousToQualsIncludeConst,
3723 ObjCLifetimeConversion, getASTContext()))
3724 return false;
3725 UnwrappedAnyPointer = true;
3726 }
3727
3728 // We are left with FromType and ToType being the pointee types
3729 // after unwrapping the original FromType and ToType the same number
3730 // of times. If we unwrapped any pointers, and if FromType and
3731 // ToType have the same unqualified type (since we checked
3732 // qualifiers above), then this is a qualification conversion.
3733 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3734}
3735
3736/// - Determine whether this is a conversion from a scalar type to an
3737/// atomic type.
3738///
3739/// If successful, updates \c SCS's second and third steps in the conversion
3740/// sequence to finish the conversion.
3741static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3742 bool InOverloadResolution,
3744 bool CStyle) {
3745 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3746 if (!ToAtomic)
3747 return false;
3748
3750 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3751 InOverloadResolution, InnerSCS,
3752 CStyle, /*AllowObjCWritebackConversion=*/false))
3753 return false;
3754
3755 SCS.Second = InnerSCS.Second;
3756 SCS.setToType(1, InnerSCS.getToType(1));
3757 SCS.Third = InnerSCS.Third;
3760 SCS.setToType(2, InnerSCS.getToType(2));
3761 return true;
3762}
3763
3765 CXXConstructorDecl *Constructor,
3766 QualType Type) {
3767 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3768 if (CtorType->getNumParams() > 0) {
3769 QualType FirstArg = CtorType->getParamType(0);
3770 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3771 return true;
3772 }
3773 return false;
3774}
3775
3776static OverloadingResult
3778 CXXRecordDecl *To,
3780 OverloadCandidateSet &CandidateSet,
3781 bool AllowExplicit) {
3783 for (auto *D : S.LookupConstructors(To)) {
3784 auto Info = getConstructorInfo(D);
3785 if (!Info)
3786 continue;
3787
3788 bool Usable = !Info.Constructor->isInvalidDecl() &&
3789 S.isInitListConstructor(Info.Constructor);
3790 if (Usable) {
3791 bool SuppressUserConversions = false;
3792 if (Info.ConstructorTmpl)
3793 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3794 /*ExplicitArgs*/ nullptr, From,
3795 CandidateSet, SuppressUserConversions,
3796 /*PartialOverloading*/ false,
3797 AllowExplicit);
3798 else
3799 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3800 CandidateSet, SuppressUserConversions,
3801 /*PartialOverloading*/ false, AllowExplicit);
3802 }
3803 }
3804
3805 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3806
3808 switch (auto Result =
3809 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3810 case OR_Deleted:
3811 case OR_Success: {
3812 // Record the standard conversion we used and the conversion function.
3813 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3814 QualType ThisType = Constructor->getFunctionObjectParameterType();
3815 // Initializer lists don't have conversions as such.
3817 User.HadMultipleCandidates = HadMultipleCandidates;
3818 User.ConversionFunction = Constructor;
3819 User.FoundConversionFunction = Best->FoundDecl;
3821 User.After.setFromType(ThisType);
3822 User.After.setAllToTypes(ToType);
3823 return Result;
3824 }
3825
3827 return OR_No_Viable_Function;
3828 case OR_Ambiguous:
3829 return OR_Ambiguous;
3830 }
3831
3832 llvm_unreachable("Invalid OverloadResult!");
3833}
3834
3835/// Determines whether there is a user-defined conversion sequence
3836/// (C++ [over.ics.user]) that converts expression From to the type
3837/// ToType. If such a conversion exists, User will contain the
3838/// user-defined conversion sequence that performs such a conversion
3839/// and this routine will return true. Otherwise, this routine returns
3840/// false and User is unspecified.
3841///
3842/// \param AllowExplicit true if the conversion should consider C++0x
3843/// "explicit" conversion functions as well as non-explicit conversion
3844/// functions (C++0x [class.conv.fct]p2).
3845///
3846/// \param AllowObjCConversionOnExplicit true if the conversion should
3847/// allow an extra Objective-C pointer conversion on uses of explicit
3848/// constructors. Requires \c AllowExplicit to also be set.
3849static OverloadingResult
3852 OverloadCandidateSet &CandidateSet,
3853 AllowedExplicit AllowExplicit,
3854 bool AllowObjCConversionOnExplicit) {
3855 assert(AllowExplicit != AllowedExplicit::None ||
3856 !AllowObjCConversionOnExplicit);
3858
3859 // Whether we will only visit constructors.
3860 bool ConstructorsOnly = false;
3861
3862 // If the type we are conversion to is a class type, enumerate its
3863 // constructors.
3864 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3865 // C++ [over.match.ctor]p1:
3866 // When objects of class type are direct-initialized (8.5), or
3867 // copy-initialized from an expression of the same or a
3868 // derived class type (8.5), overload resolution selects the
3869 // constructor. [...] For copy-initialization, the candidate
3870 // functions are all the converting constructors (12.3.1) of
3871 // that class. The argument list is the expression-list within
3872 // the parentheses of the initializer.
3873 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3874 (From->getType()->getAs<RecordType>() &&
3875 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3876 ConstructorsOnly = true;
3877
3878 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3879 // We're not going to find any constructors.
3880 } else if (CXXRecordDecl *ToRecordDecl
3881 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3882
3883 Expr **Args = &From;
3884 unsigned NumArgs = 1;
3885 bool ListInitializing = false;
3886 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3887 // But first, see if there is an init-list-constructor that will work.
3889 S, From, ToType, ToRecordDecl, User, CandidateSet,
3890 AllowExplicit == AllowedExplicit::All);
3892 return Result;
3893 // Never mind.
3894 CandidateSet.clear(
3896
3897 // If we're list-initializing, we pass the individual elements as
3898 // arguments, not the entire list.
3899 Args = InitList->getInits();
3900 NumArgs = InitList->getNumInits();
3901 ListInitializing = true;
3902 }
3903
3904 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3905 auto Info = getConstructorInfo(D);
3906 if (!Info)
3907 continue;
3908
3909 bool Usable = !Info.Constructor->isInvalidDecl();
3910 if (!ListInitializing)
3911 Usable = Usable && Info.Constructor->isConvertingConstructor(
3912 /*AllowExplicit*/ true);
3913 if (Usable) {
3914 bool SuppressUserConversions = !ConstructorsOnly;
3915 // C++20 [over.best.ics.general]/4.5:
3916 // if the target is the first parameter of a constructor [of class
3917 // X] and the constructor [...] is a candidate by [...] the second
3918 // phase of [over.match.list] when the initializer list has exactly
3919 // one element that is itself an initializer list, [...] and the
3920 // conversion is to X or reference to cv X, user-defined conversion
3921 // sequences are not cnosidered.
3922 if (SuppressUserConversions && ListInitializing) {
3923 SuppressUserConversions =
3924 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3925 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3926 ToType);
3927 }
3928 if (Info.ConstructorTmpl)
3930 Info.ConstructorTmpl, Info.FoundDecl,
3931 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
3932 CandidateSet, SuppressUserConversions,
3933 /*PartialOverloading*/ false,
3934 AllowExplicit == AllowedExplicit::All);
3935 else
3936 // Allow one user-defined conversion when user specifies a
3937 // From->ToType conversion via an static cast (c-style, etc).
3938 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3939 llvm::ArrayRef(Args, NumArgs), CandidateSet,
3940 SuppressUserConversions,
3941 /*PartialOverloading*/ false,
3942 AllowExplicit == AllowedExplicit::All);
3943 }
3944 }
3945 }
3946 }
3947
3948 // Enumerate conversion functions, if we're allowed to.
3949 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3950 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3951 // No conversion functions from incomplete types.
3952 } else if (const RecordType *FromRecordType =
3953 From->getType()->getAs<RecordType>()) {
3954 if (CXXRecordDecl *FromRecordDecl
3955 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3956 // Add all of the conversion functions as candidates.
3957 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3958 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3959 DeclAccessPair FoundDecl = I.getPair();
3960 NamedDecl *D = FoundDecl.getDecl();
3961 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3962 if (isa<UsingShadowDecl>(D))
3963 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3964
3965 CXXConversionDecl *Conv;
3966 FunctionTemplateDecl *ConvTemplate;
3967 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3968 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3969 else
3970 Conv = cast<CXXConversionDecl>(D);
3971
3972 if (ConvTemplate)
3974 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3975 CandidateSet, AllowObjCConversionOnExplicit,
3976 AllowExplicit != AllowedExplicit::None);
3977 else
3978 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3979 CandidateSet, AllowObjCConversionOnExplicit,
3980 AllowExplicit != AllowedExplicit::None);
3981 }
3982 }
3983 }
3984
3985 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3986
3988 switch (auto Result =
3989 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3990 case OR_Success:
3991 case OR_Deleted:
3992 // Record the standard conversion we used and the conversion function.
3993 if (CXXConstructorDecl *Constructor
3994 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3995 // C++ [over.ics.user]p1:
3996 // If the user-defined conversion is specified by a
3997 // constructor (12.3.1), the initial standard conversion
3998 // sequence converts the source type to the type required by
3999 // the argument of the constructor.
4000 //
4001 if (isa<InitListExpr>(From)) {
4002 // Initializer lists don't have conversions as such.
4004 } else {
4005 if (Best->Conversions[0].isEllipsis())
4006 User.EllipsisConversion = true;
4007 else {
4008 User.Before = Best->Conversions[0].Standard;
4009 User.EllipsisConversion = false;
4010 }
4011 }
4012 User.HadMultipleCandidates = HadMultipleCandidates;
4013 User.ConversionFunction = Constructor;
4014 User.FoundConversionFunction = Best->FoundDecl;
4016 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4017 User.After.setAllToTypes(ToType);
4018 return Result;
4019 }
4020 if (CXXConversionDecl *Conversion
4021 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4022 // C++ [over.ics.user]p1:
4023 //
4024 // [...] If the user-defined conversion is specified by a
4025 // conversion function (12.3.2), the initial standard
4026 // conversion sequence converts the source type to the
4027 // implicit object parameter of the conversion function.
4028 User.Before = Best->Conversions[0].Standard;
4029 User.HadMultipleCandidates = HadMultipleCandidates;
4030 User.ConversionFunction = Conversion;
4031 User.FoundConversionFunction = Best->FoundDecl;
4032 User.EllipsisConversion = false;
4033
4034 // C++ [over.ics.user]p2:
4035 // The second standard conversion sequence converts the
4036 // result of the user-defined conversion to the target type
4037 // for the sequence. Since an implicit conversion sequence
4038 // is an initialization, the special rules for
4039 // initialization by user-defined conversion apply when
4040 // selecting the best user-defined conversion for a
4041 // user-defined conversion sequence (see 13.3.3 and
4042 // 13.3.3.1).
4043 User.After = Best->FinalConversion;
4044 return Result;
4045 }
4046 llvm_unreachable("Not a constructor or conversion function?");
4047
4049 return OR_No_Viable_Function;
4050
4051 case OR_Ambiguous:
4052 return OR_Ambiguous;
4053 }
4054
4055 llvm_unreachable("Invalid OverloadResult!");
4056}
4057
4058bool
4061 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4063 OverloadingResult OvResult =
4064 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4065 CandidateSet, AllowedExplicit::None, false);
4066
4067 if (!(OvResult == OR_Ambiguous ||
4068 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4069 return false;
4070
4071 auto Cands = CandidateSet.CompleteCandidates(
4072 *this,
4074 From);
4075 if (OvResult == OR_Ambiguous)
4076 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4077 << From->getType() << ToType << From->getSourceRange();
4078 else { // OR_No_Viable_Function && !CandidateSet.empty()
4079 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4080 diag::err_typecheck_nonviable_condition_incomplete,
4081 From->getType(), From->getSourceRange()))
4082 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4083 << false << From->getType() << From->getSourceRange() << ToType;
4084 }
4085
4086 CandidateSet.NoteCandidates(
4087 *this, From, Cands);
4088 return true;
4089}
4090
4091// Helper for compareConversionFunctions that gets the FunctionType that the
4092// conversion-operator return value 'points' to, or nullptr.
4093static const FunctionType *
4095 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4096 const PointerType *RetPtrTy =
4097 ConvFuncTy->getReturnType()->getAs<PointerType>();
4098
4099 if (!RetPtrTy)
4100 return nullptr;
4101
4102 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4103}
4104
4105/// Compare the user-defined conversion functions or constructors
4106/// of two user-defined conversion sequences to determine whether any ordering
4107/// is possible.
4110 FunctionDecl *Function2) {
4111 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4112 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4113 if (!Conv1 || !Conv2)
4115
4116 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4118
4119 // Objective-C++:
4120 // If both conversion functions are implicitly-declared conversions from
4121 // a lambda closure type to a function pointer and a block pointer,
4122 // respectively, always prefer the conversion to a function pointer,
4123 // because the function pointer is more lightweight and is more likely
4124 // to keep code working.
4125 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4126 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4127 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4128 if (Block1 != Block2)
4129 return Block1 ? ImplicitConversionSequence::Worse
4131 }
4132
4133 // In order to support multiple calling conventions for the lambda conversion
4134 // operator (such as when the free and member function calling convention is
4135 // different), prefer the 'free' mechanism, followed by the calling-convention
4136 // of operator(). The latter is in place to support the MSVC-like solution of
4137 // defining ALL of the possible conversions in regards to calling-convention.
4138 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4139 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4140
4141 if (Conv1FuncRet && Conv2FuncRet &&
4142 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4143 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4144 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4145
4146 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4147 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4148
4149 CallingConv CallOpCC =
4150 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4152 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4154 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4155
4156 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4157 for (CallingConv CC : PrefOrder) {
4158 if (Conv1CC == CC)
4160 if (Conv2CC == CC)
4162 }
4163 }
4164
4166}
4167
4169 const ImplicitConversionSequence &ICS) {
4171 (ICS.isUserDefined() &&
4173}
4174
4175/// CompareImplicitConversionSequences - Compare two implicit
4176/// conversion sequences to determine whether one is better than the
4177/// other or if they are indistinguishable (C++ 13.3.3.2).
4180 const ImplicitConversionSequence& ICS1,
4181 const ImplicitConversionSequence& ICS2)
4182{
4183 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4184 // conversion sequences (as defined in 13.3.3.1)
4185 // -- a standard conversion sequence (13.3.3.1.1) is a better
4186 // conversion sequence than a user-defined conversion sequence or
4187 // an ellipsis conversion sequence, and
4188 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4189 // conversion sequence than an ellipsis conversion sequence
4190 // (13.3.3.1.3).
4191 //
4192 // C++0x [over.best.ics]p10:
4193 // For the purpose of ranking implicit conversion sequences as
4194 // described in 13.3.3.2, the ambiguous conversion sequence is
4195 // treated as a user-defined sequence that is indistinguishable
4196 // from any other user-defined conversion sequence.
4197
4198 // String literal to 'char *' conversion has been deprecated in C++03. It has
4199 // been removed from C++11. We still accept this conversion, if it happens at
4200 // the best viable function. Otherwise, this conversion is considered worse
4201 // than ellipsis conversion. Consider this as an extension; this is not in the
4202 // standard. For example:
4203 //
4204 // int &f(...); // #1
4205 // void f(char*); // #2
4206 // void g() { int &r = f("foo"); }
4207 //
4208 // In C++03, we pick #2 as the best viable function.
4209 // In C++11, we pick #1 as the best viable function, because ellipsis
4210 // conversion is better than string-literal to char* conversion (since there
4211 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4212 // convert arguments, #2 would be the best viable function in C++11.
4213 // If the best viable function has this conversion, a warning will be issued
4214 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4215
4216 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4219 // Ill-formedness must not differ
4220 ICS1.isBad() == ICS2.isBad())
4224
4225 if (ICS1.getKindRank() < ICS2.getKindRank())
4227 if (ICS2.getKindRank() < ICS1.getKindRank())
4229
4230 // The following checks require both conversion sequences to be of
4231 // the same kind.
4232 if (ICS1.getKind() != ICS2.getKind())
4234
4237
4238 // Two implicit conversion sequences of the same form are
4239 // indistinguishable conversion sequences unless one of the
4240 // following rules apply: (C++ 13.3.3.2p3):
4241
4242 // List-initialization sequence L1 is a better conversion sequence than
4243 // list-initialization sequence L2 if:
4244 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4245 // if not that,
4246 // — L1 and L2 convert to arrays of the same element type, and either the
4247 // number of elements n_1 initialized by L1 is less than the number of
4248 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4249 // an array of unknown bound and L1 does not,
4250 // even if one of the other rules in this paragraph would otherwise apply.
4251 if (!ICS1.isBad()) {
4252 bool StdInit1 = false, StdInit2 = false;
4255 nullptr);
4258 nullptr);
4259 if (StdInit1 != StdInit2)
4260 return StdInit1 ? ImplicitConversionSequence::Better
4262
4265 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4267 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4269 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4270 CAT2->getElementType())) {
4271 // Both to arrays of the same element type
4272 if (CAT1->getSize() != CAT2->getSize())
4273 // Different sized, the smaller wins
4274 return CAT1->getSize().ult(CAT2->getSize())
4279 // One is incomplete, it loses
4283 }
4284 }
4285 }
4286
4287 if (ICS1.isStandard())
4288 // Standard conversion sequence S1 is a better conversion sequence than
4289 // standard conversion sequence S2 if [...]
4291 ICS1.Standard, ICS2.Standard);
4292 else if (ICS1.isUserDefined()) {
4293 // User-defined conversion sequence U1 is a better conversion
4294 // sequence than another user-defined conversion sequence U2 if
4295 // they contain the same user-defined conversion function or
4296 // constructor and if the second standard conversion sequence of
4297 // U1 is better than the second standard conversion sequence of
4298 // U2 (C++ 13.3.3.2p3).
4302 ICS1.UserDefined.After,
4303 ICS2.UserDefined.After);
4304 else
4308 }
4309
4310 return Result;
4311}
4312
4313// Per 13.3.3.2p3, compare the given standard conversion sequences to
4314// determine if one is a proper subset of the other.
4317 const StandardConversionSequence& SCS1,
4318 const StandardConversionSequence& SCS2) {
4321
4322 // the identity conversion sequence is considered to be a subsequence of
4323 // any non-identity conversion sequence
4324 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4326 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4328
4329 if (SCS1.Second != SCS2.Second) {
4330 if (SCS1.Second == ICK_Identity)
4332 else if (SCS2.Second == ICK_Identity)
4334 else
4336 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4338
4339 if (SCS1.Third == SCS2.Third) {
4340 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4342 }
4343
4344 if (SCS1.Third == ICK_Identity)
4348
4349 if (SCS2.Third == ICK_Identity)
4353
4355}
4356
4357/// Determine whether one of the given reference bindings is better
4358/// than the other based on what kind of bindings they are.
4359static bool
4361 const StandardConversionSequence &SCS2) {
4362 // C++0x [over.ics.rank]p3b4:
4363 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4364 // implicit object parameter of a non-static member function declared
4365 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4366 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4367 // lvalue reference to a function lvalue and S2 binds an rvalue
4368 // reference*.
4369 //
4370 // FIXME: Rvalue references. We're going rogue with the above edits,
4371 // because the semantics in the current C++0x working paper (N3225 at the
4372 // time of this writing) break the standard definition of std::forward
4373 // and std::reference_wrapper when dealing with references to functions.
4374 // Proposed wording changes submitted to CWG for consideration.
4377 return false;
4378
4379 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4380 SCS2.IsLvalueReference) ||
4383}
4384
4386 None,
4389};
4390
4391/// Returns kind of fixed enum promotion the \a SCS uses.
4392static FixedEnumPromotion
4394
4395 if (SCS.Second != ICK_Integral_Promotion)
4396 return FixedEnumPromotion::None;
4397
4398 QualType FromType = SCS.getFromType();
4399 if (!FromType->isEnumeralType())
4400 return FixedEnumPromotion::None;
4401
4402 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
4403 if (!Enum->isFixed())
4404 return FixedEnumPromotion::None;
4405
4406 QualType UnderlyingType = Enum->getIntegerType();
4407 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4408 return FixedEnumPromotion::ToUnderlyingType;
4409
4410 return FixedEnumPromotion::ToPromotedUnderlyingType;
4411}
4412
4413/// CompareStandardConversionSequences - Compare two standard
4414/// conversion sequences to determine whether one is better than the
4415/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4418 const StandardConversionSequence& SCS1,
4419 const StandardConversionSequence& SCS2)
4420{
4421 // Standard conversion sequence S1 is a better conversion sequence
4422 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4423
4424 // -- S1 is a proper subsequence of S2 (comparing the conversion
4425 // sequences in the canonical form defined by 13.3.3.1.1,
4426 // excluding any Lvalue Transformation; the identity conversion
4427 // sequence is considered to be a subsequence of any
4428 // non-identity conversion sequence) or, if not that,
4431 return CK;
4432
4433 // -- the rank of S1 is better than the rank of S2 (by the rules
4434 // defined below), or, if not that,
4435 ImplicitConversionRank Rank1 = SCS1.getRank();
4436 ImplicitConversionRank Rank2 = SCS2.getRank();
4437 if (Rank1 < Rank2)
4439 else if (Rank2 < Rank1)
4441
4442 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4443 // are indistinguishable unless one of the following rules
4444 // applies:
4445
4446 // A conversion that is not a conversion of a pointer, or
4447 // pointer to member, to bool is better than another conversion
4448 // that is such a conversion.
4450 return SCS2.isPointerConversionToBool()
4453
4454 // C++14 [over.ics.rank]p4b2:
4455 // This is retroactively applied to C++11 by CWG 1601.
4456 //
4457 // A conversion that promotes an enumeration whose underlying type is fixed
4458 // to its underlying type is better than one that promotes to the promoted
4459 // underlying type, if the two are different.
4462 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4463 FEP1 != FEP2)
4464 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4467
4468 // C++ [over.ics.rank]p4b2:
4469 //
4470 // If class B is derived directly or indirectly from class A,
4471 // conversion of B* to A* is better than conversion of B* to
4472 // void*, and conversion of A* to void* is better than conversion
4473 // of B* to void*.
4474 bool SCS1ConvertsToVoid
4476 bool SCS2ConvertsToVoid
4478 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4479 // Exactly one of the conversion sequences is a conversion to
4480 // a void pointer; it's the worse conversion.
4481 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4483 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4484 // Neither conversion sequence converts to a void pointer; compare
4485 // their derived-to-base conversions.
4487 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4488 return DerivedCK;
4489 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4490 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4491 // Both conversion sequences are conversions to void
4492 // pointers. Compare the source types to determine if there's an
4493 // inheritance relationship in their sources.
4494 QualType FromType1 = SCS1.getFromType();
4495 QualType FromType2 = SCS2.getFromType();
4496
4497 // Adjust the types we're converting from via the array-to-pointer
4498 // conversion, if we need to.
4499 if (SCS1.First == ICK_Array_To_Pointer)
4500 FromType1 = S.Context.getArrayDecayedType(FromType1);
4501 if (SCS2.First == ICK_Array_To_Pointer)
4502 FromType2 = S.Context.getArrayDecayedType(FromType2);
4503
4504 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4505 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4506
4507 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4509 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4511
4512 // Objective-C++: If one interface is more specific than the
4513 // other, it is the better one.
4514 const ObjCObjectPointerType* FromObjCPtr1
4515 = FromType1->getAs<ObjCObjectPointerType>();
4516 const ObjCObjectPointerType* FromObjCPtr2
4517 = FromType2->getAs<ObjCObjectPointerType>();
4518 if (FromObjCPtr1 && FromObjCPtr2) {
4519 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4520 FromObjCPtr2);
4521 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4522 FromObjCPtr1);
4523 if (AssignLeft != AssignRight) {
4524 return AssignLeft? ImplicitConversionSequence::Better
4526 }
4527 }
4528 }
4529
4530 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4531 // Check for a better reference binding based on the kind of bindings.
4532 if (isBetterReferenceBindingKind(SCS1, SCS2))
4534 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4536 }
4537
4538 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4539 // bullet 3).
4541 = CompareQualificationConversions(S, SCS1, SCS2))
4542 return QualCK;
4543
4544 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4545 // C++ [over.ics.rank]p3b4:
4546 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4547 // which the references refer are the same type except for
4548 // top-level cv-qualifiers, and the type to which the reference
4549 // initialized by S2 refers is more cv-qualified than the type
4550 // to which the reference initialized by S1 refers.
4551 QualType T1 = SCS1.getToType(2);
4552 QualType T2 = SCS2.getToType(2);
4553 T1 = S.Context.getCanonicalType(T1);
4554 T2 = S.Context.getCanonicalType(T2);
4555 Qualifiers T1Quals, T2Quals;
4556 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4557 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4558 if (UnqualT1 == UnqualT2) {
4559 // Objective-C++ ARC: If the references refer to objects with different
4560 // lifetimes, prefer bindings that don't change lifetime.
4566 }
4567
4568 // If the type is an array type, promote the element qualifiers to the
4569 // type for comparison.
4570 if (isa<ArrayType>(T1) && T1Quals)
4571 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4572 if (isa<ArrayType>(T2) && T2Quals)
4573 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4574 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4576 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4578 }
4579 }
4580
4581 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4582 // floating-to-integral conversion if the integral conversion
4583 // is between types of the same size.
4584 // For example:
4585 // void f(float);
4586 // void f(int);
4587 // int main {
4588 // long a;
4589 // f(a);
4590 // }
4591 // Here, MSVC will call f(int) instead of generating a compile error
4592 // as clang will do in standard mode.
4593 if (S.getLangOpts().MSVCCompat &&
4596 SCS2.Second == ICK_Floating_Integral &&
4597 S.Context.getTypeSize(SCS1.getFromType()) ==
4598 S.Context.getTypeSize(SCS1.getToType(2)))
4600
4601 // Prefer a compatible vector conversion over a lax vector conversion
4602 // For example:
4603 //
4604 // typedef float __v4sf __attribute__((__vector_size__(16)));
4605 // void f(vector float);
4606 // void f(vector signed int);
4607 // int main() {
4608 // __v4sf a;
4609 // f(a);
4610 // }
4611 // Here, we'd like to choose f(vector float) and not
4612 // report an ambiguous call error
4613 if (SCS1.Second == ICK_Vector_Conversion &&
4614 SCS2.Second == ICK_Vector_Conversion) {
4615 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4616 SCS1.getFromType(), SCS1.getToType(2));
4617 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4618 SCS2.getFromType(), SCS2.getToType(2));
4619
4620 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4621 return SCS1IsCompatibleVectorConversion
4624 }
4625
4626 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4628 bool SCS1IsCompatibleSVEVectorConversion =
4630 bool SCS2IsCompatibleSVEVectorConversion =
4632
4633 if (SCS1IsCompatibleSVEVectorConversion !=
4634 SCS2IsCompatibleSVEVectorConversion)
4635 return SCS1IsCompatibleSVEVectorConversion
4638 }
4639
4640 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4642 bool SCS1IsCompatibleRVVVectorConversion =
4644 bool SCS2IsCompatibleRVVVectorConversion =
4646
4647 if (SCS1IsCompatibleRVVVectorConversion !=
4648 SCS2IsCompatibleRVVVectorConversion)
4649 return SCS1IsCompatibleRVVVectorConversion
4652 }
4654}
4655
4656/// CompareQualificationConversions - Compares two standard conversion
4657/// sequences to determine whether they can be ranked based on their
4658/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4661 const StandardConversionSequence& SCS1,
4662 const StandardConversionSequence& SCS2) {
4663 // C++ [over.ics.rank]p3:
4664 // -- S1 and S2 differ only in their qualification conversion and
4665 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4666 // [C++98]
4667 // [...] and the cv-qualification signature of type T1 is a proper subset
4668 // of the cv-qualification signature of type T2, and S1 is not the
4669 // deprecated string literal array-to-pointer conversion (4.2).
4670 // [C++2a]
4671 // [...] where T1 can be converted to T2 by a qualification conversion.
4672 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4673 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4675
4676 // FIXME: the example in the standard doesn't use a qualification
4677 // conversion (!)
4678 QualType T1 = SCS1.getToType(2);
4679 QualType T2 = SCS2.getToType(2);
4680 T1 = S.Context.getCanonicalType(T1);
4681 T2 = S.Context.getCanonicalType(T2);
4682 assert(!T1->isReferenceType() && !T2->isReferenceType());
4683 Qualifiers T1Quals, T2Quals;
4684 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4685 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4686
4687 // If the types are the same, we won't learn anything by unwrapping
4688 // them.
4689 if (UnqualT1 == UnqualT2)
4691
4692 // Don't ever prefer a standard conversion sequence that uses the deprecated
4693 // string literal array to pointer conversion.
4694 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4695 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4696
4697 // Objective-C++ ARC:
4698 // Prefer qualification conversions not involving a change in lifetime
4699 // to qualification conversions that do change lifetime.
4702 CanPick1 = false;
4705 CanPick2 = false;
4706
4707 bool ObjCLifetimeConversion;
4708 if (CanPick1 &&
4709 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4710 CanPick1 = false;
4711 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4712 // directions, so we can't short-cut this second check in general.
4713 if (CanPick2 &&
4714 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4715 CanPick2 = false;
4716
4717 if (CanPick1 != CanPick2)
4718 return CanPick1 ? ImplicitConversionSequence::Better
4721}
4722
4723/// CompareDerivedToBaseConversions - Compares two standard conversion
4724/// sequences to determine whether they can be ranked based on their
4725/// various kinds of derived-to-base conversions (C++
4726/// [over.ics.rank]p4b3). As part of these checks, we also look at
4727/// conversions between Objective-C interface types.
4730 const StandardConversionSequence& SCS1,
4731 const StandardConversionSequence& SCS2) {
4732 QualType FromType1 = SCS1.getFromType();
4733 QualType ToType1 = SCS1.getToType(1);
4734 QualType FromType2 = SCS2.getFromType();
4735 QualType ToType2 = SCS2.getToType(1);
4736
4737 // Adjust the types we're converting from via the array-to-pointer
4738 // conversion, if we need to.
4739 if (SCS1.First == ICK_Array_To_Pointer)
4740 FromType1 = S.Context.getArrayDecayedType(FromType1);
4741 if (SCS2.First == ICK_Array_To_Pointer)
4742 FromType2 = S.Context.getArrayDecayedType(FromType2);
4743
4744 // Canonicalize all of the types.
4745 FromType1 = S.Context.getCanonicalType(FromType1);
4746 ToType1 = S.Context.getCanonicalType(ToType1);
4747 FromType2 = S.Context.getCanonicalType(FromType2);
4748 ToType2 = S.Context.getCanonicalType(ToType2);
4749
4750 // C++ [over.ics.rank]p4b3:
4751 //
4752 // If class B is derived directly or indirectly from class A and
4753 // class C is derived directly or indirectly from B,
4754 //
4755 // Compare based on pointer conversions.
4756 if (SCS1.Second == ICK_Pointer_Conversion &&
4758 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4759 FromType1->isPointerType() && FromType2->isPointerType() &&
4760 ToType1->isPointerType() && ToType2->isPointerType()) {
4761 QualType FromPointee1 =
4763 QualType ToPointee1 =
4765 QualType FromPointee2 =
4767 QualType ToPointee2 =
4769
4770 // -- conversion of C* to B* is better than conversion of C* to A*,
4771 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4772 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4774 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4776 }
4777
4778 // -- conversion of B* to A* is better than conversion of C* to A*,
4779 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4780 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4782 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4784 }
4785 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4787 const ObjCObjectPointerType *FromPtr1
4788 = FromType1->getAs<ObjCObjectPointerType>();
4789 const ObjCObjectPointerType *FromPtr2
4790 = FromType2->getAs<ObjCObjectPointerType>();
4791 const ObjCObjectPointerType *ToPtr1
4792 = ToType1->getAs<ObjCObjectPointerType>();
4793 const ObjCObjectPointerType *ToPtr2
4794 = ToType2->getAs<ObjCObjectPointerType>();
4795
4796 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4797 // Apply the same conversion ranking rules for Objective-C pointer types
4798 // that we do for C++ pointers to class types. However, we employ the
4799 // Objective-C pseudo-subtyping relationship used for assignment of
4800 // Objective-C pointer types.
4801 bool FromAssignLeft
4802 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4803 bool FromAssignRight
4804 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4805 bool ToAssignLeft
4806 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4807 bool ToAssignRight
4808 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4809
4810 // A conversion to an a non-id object pointer type or qualified 'id'
4811 // type is better than a conversion to 'id'.
4812 if (ToPtr1->isObjCIdType() &&
4813 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4815 if (ToPtr2->isObjCIdType() &&
4816 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4818
4819 // A conversion to a non-id object pointer type is better than a
4820 // conversion to a qualified 'id' type
4821 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4823 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4825
4826 // A conversion to an a non-Class object pointer type or qualified 'Class'
4827 // type is better than a conversion to 'Class'.
4828 if (ToPtr1->isObjCClassType() &&
4829 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4831 if (ToPtr2->isObjCClassType() &&
4832 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4834
4835 // A conversion to a non-Class object pointer type is better than a
4836 // conversion to a qualified 'Class' type.
4837 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4839 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4841
4842 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4843 if (S.Context.hasSameType(FromType1, FromType2) &&
4844 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4845 (ToAssignLeft != ToAssignRight)) {
4846 if (FromPtr1->isSpecialized()) {
4847 // "conversion of B<A> * to B * is better than conversion of B * to
4848 // C *.
4849 bool IsFirstSame =
4850 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4851 bool IsSecondSame =
4852 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4853 if (IsFirstSame) {
4854 if (!IsSecondSame)
4856 } else if (IsSecondSame)
4858 }
4859 return ToAssignLeft? ImplicitConversionSequence::Worse
4861 }
4862
4863 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4864 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4865 (FromAssignLeft != FromAssignRight))
4866 return FromAssignLeft? ImplicitConversionSequence::Better
4868 }
4869 }
4870
4871 // Ranking of member-pointer types.
4872 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4873 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4874 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4875 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4876 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4877 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4878 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4879 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4880 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4881 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4882 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4883 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4884 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4885 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4886 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4887 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4888 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4889 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4891 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4893 }
4894 // conversion of B::* to C::* is better than conversion of A::* to C::*
4895 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4896 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4898 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4900 }
4901 }
4902
4903 if (SCS1.Second == ICK_Derived_To_Base) {
4904 // -- conversion of C to B is better than conversion of C to A,
4905 // -- binding of an expression of type C to a reference of type
4906 // B& is better than binding an expression of type C to a
4907 // reference of type A&,
4908 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4909 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4910 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4912 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4914 }
4915
4916 // -- conversion of B to A is better than conversion of C to A.
4917 // -- binding of an expression of type B to a reference of type
4918 // A& is better than binding an expression of type C to a
4919 // reference of type A&,
4920 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4921 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4922 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4924 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4926 }
4927 }
4928
4930}
4931
4933 if (!T.getQualifiers().hasUnaligned())
4934 return T;
4935
4936 Qualifiers Q;
4937 T = Ctx.getUnqualifiedArrayType(T, Q);
4938 Q.removeUnaligned();
4939 return Ctx.getQualifiedType(T, Q);
4940}
4941
4944 QualType OrigT1, QualType OrigT2,
4945 ReferenceConversions *ConvOut) {
4946 assert(!OrigT1->isReferenceType() &&
4947 "T1 must be the pointee type of the reference type");
4948 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4949
4950 QualType T1 = Context.getCanonicalType(OrigT1);
4951 QualType T2 = Context.getCanonicalType(OrigT2);
4952 Qualifiers T1Quals, T2Quals;
4953 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4954 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4955
4956 ReferenceConversions ConvTmp;
4957 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4958 Conv = ReferenceConversions();
4959
4960 // C++2a [dcl.init.ref]p4:
4961 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4962 // reference-related to "cv2 T2" if T1 is similar to T2, or
4963 // T1 is a base class of T2.
4964 // "cv1 T1" is reference-compatible with "cv2 T2" if
4965 // a prvalue of type "pointer to cv2 T2" can be converted to the type
4966 // "pointer to cv1 T1" via a standard conversion sequence.
4967
4968 // Check for standard conversions we can apply to pointers: derived-to-base
4969 // conversions, ObjC pointer conversions, and function pointer conversions.
4970 // (Qualification conversions are checked last.)
4971 QualType ConvertedT2;
4972 if (UnqualT1 == UnqualT2) {
4973 // Nothing to do.
4974 } else if (isCompleteType(Loc, OrigT2) &&
4975 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4976 Conv |= ReferenceConversions::DerivedToBase;
4977 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4978 UnqualT2->isObjCObjectOrInterfaceType() &&
4979 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4980 Conv |= ReferenceConversions::ObjC;
4981 else if (UnqualT2->isFunctionType() &&
4982 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4983 Conv |= ReferenceConversions::Function;
4984 // No need to check qualifiers; function types don't have them.
4985 return Ref_Compatible;
4986 }
4987 bool ConvertedReferent = Conv != 0;
4988
4989 // We can have a qualification conversion. Compute whether the types are
4990 // similar at the same time.
4991 bool PreviousToQualsIncludeConst = true;
4992 bool TopLevel = true;
4993 do {
4994 if (T1 == T2)
4995 break;
4996
4997 // We will need a qualification conversion.
4998 Conv |= ReferenceConversions::Qualification;
4999
5000 // Track whether we performed a qualification conversion anywhere other
5001 // than the top level. This matters for ranking reference bindings in
5002 // overload resolution.
5003 if (!TopLevel)
5004 Conv |= ReferenceConversions::NestedQualification;
5005
5006 // MS compiler ignores __unaligned qualifier for references; do the same.
5007 T1 = withoutUnaligned(Context, T1);
5008 T2 = withoutUnaligned(Context, T2);
5009
5010 // If we find a qualifier mismatch, the types are not reference-compatible,
5011 // but are still be reference-related if they're similar.
5012 bool ObjCLifetimeConversion = false;
5013 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5014 PreviousToQualsIncludeConst,
5015 ObjCLifetimeConversion, getASTContext()))
5016 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5017 ? Ref_Related
5018 : Ref_Incompatible;
5019
5020 // FIXME: Should we track this for any level other than the first?
5021 if (ObjCLifetimeConversion)
5022 Conv |= ReferenceConversions::ObjCLifetime;
5023
5024 TopLevel = false;
5025 } while (Context.UnwrapSimilarTypes(T1, T2));
5026
5027 // At this point, if the types are reference-related, we must either have the
5028 // same inner type (ignoring qualifiers), or must have already worked out how
5029 // to convert the referent.
5030 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5031 ? Ref_Compatible
5032 : Ref_Incompatible;
5033}
5034
5035/// Look for a user-defined conversion to a value reference-compatible
5036/// with DeclType. Return true if something definite is found.
5037static bool
5039 QualType DeclType, SourceLocation DeclLoc,
5040 Expr *Init, QualType T2, bool AllowRvalues,
5041 bool AllowExplicit) {
5042 assert(T2->isRecordType() && "Can only find conversions of record types.");
5043 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
5044
5045 OverloadCandidateSet CandidateSet(
5047 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5048 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5049 NamedDecl *D = *I;
5050 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5051 if (isa<UsingShadowDecl>(D))
5052 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5053
5054 FunctionTemplateDecl *ConvTemplate
5055 = dyn_cast<FunctionTemplateDecl>(D);
5056 CXXConversionDecl *Conv;
5057 if (ConvTemplate)
5058 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5059 else
5060 Conv = cast<CXXConversionDecl>(D);
5061
5062 if (AllowRvalues) {
5063 // If we are initializing an rvalue reference, don't permit conversion
5064 // functions that return lvalues.
5065 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5066 const ReferenceType *RefType
5068 if (RefType && !RefType->getPointeeType()->isFunctionType())
5069 continue;
5070 }
5071
5072 if (!ConvTemplate &&
5074 DeclLoc,
5075 Conv->getConversionType()
5080 continue;
5081 } else {
5082 // If the conversion function doesn't return a reference type,
5083 // it can't be considered for this conversion. An rvalue reference
5084 // is only acceptable if its referencee is a function type.
5085
5086 const ReferenceType *RefType =
5088 if (!RefType ||
5089 (!RefType->isLValueReferenceType() &&
5090 !RefType->getPointeeType()->isFunctionType()))
5091 continue;
5092 }
5093
5094 if (ConvTemplate)
5096 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5097 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5098 else
5100 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5101 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5102 }
5103
5104 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5105
5107 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5108 case OR_Success:
5109 // C++ [over.ics.ref]p1:
5110 //
5111 // [...] If the parameter binds directly to the result of
5112 // applying a conversion function to the argument
5113 // expression, the implicit conversion sequence is a
5114 // user-defined conversion sequence (13.3.3.1.2), with the
5115 // second standard conversion sequence either an identity
5116 // conversion or, if the conversion function returns an
5117 // entity of a type that is a derived class of the parameter
5118 // type, a derived-to-base Conversion.
5119 if (!Best->FinalConversion.DirectBinding)
5120 return false;
5121
5122 ICS.setUserDefined();
5123 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5124 ICS.UserDefined.After = Best->FinalConversion;
5125 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5126 ICS.UserDefined.ConversionFunction = Best->Function;
5127 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5128 ICS.UserDefined.EllipsisConversion = false;
5129 assert(ICS.UserDefined.After.ReferenceBinding &&
5131 "Expected a direct reference binding!");
5132 return true;
5133
5134 case OR_Ambiguous:
5135 ICS.setAmbiguous();
5136 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5137 Cand != CandidateSet.end(); ++Cand)
5138 if (Cand->Best)
5139 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5140 return true;
5141
5143 case OR_Deleted:
5144 // There was no suitable conversion, or we found a deleted
5145 // conversion; continue with other checks.
5146 return false;
5147 }
5148
5149 llvm_unreachable("Invalid OverloadResult!");
5150}
5151
5152/// Compute an implicit conversion sequence for reference
5153/// initialization.
5156 SourceLocation DeclLoc,
5157 bool SuppressUserConversions,
5158 bool AllowExplicit) {
5159 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5160
5161 // Most paths end in a failed conversion.
5164
5165 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5166 QualType T2 = Init->getType();
5167
5168 // If the initializer is the address of an overloaded function, try
5169 // to resolve the overloaded function. If all goes well, T2 is the
5170 // type of the resulting function.
5171 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5174 false, Found))
5175 T2 = Fn->getType();
5176 }
5177
5178 // Compute some basic properties of the types and the initializer.
5179 bool isRValRef = DeclType->isRValueReferenceType();
5180 Expr::Classification InitCategory = Init->Classify(S.Context);
5181
5183 Sema::ReferenceCompareResult RefRelationship =
5184 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5185
5186 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5187 ICS.setStandard();
5189 // FIXME: A reference binding can be a function conversion too. We should
5190 // consider that when ordering reference-to-function bindings.
5191 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5193 : (RefConv & Sema::ReferenceConversions::ObjC)
5195 : ICK_Identity;
5197 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5198 // a reference binding that performs a non-top-level qualification
5199 // conversion as a qualification conversion, not as an identity conversion.
5200 ICS.Standard.Third = (RefConv &
5201 Sema::ReferenceConversions::NestedQualification)
5203 : ICK_Identity;
5204 ICS.Standard.setFromType(T2);
5205 ICS.Standard.setToType(0, T2);
5206 ICS.Standard.setToType(1, T1);
5207 ICS.Standard.setToType(2, T1);
5208 ICS.Standard.ReferenceBinding = true;
5209 ICS.Standard.DirectBinding = BindsDirectly;
5210 ICS.Standard.IsLvalueReference = !isRValRef;
5212 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5215 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5216 ICS.Standard.CopyConstructor = nullptr;
5218 };
5219
5220 // C++0x [dcl.init.ref]p5:
5221 // A reference to type "cv1 T1" is initialized by an expression
5222 // of type "cv2 T2" as follows:
5223
5224 // -- If reference is an lvalue reference and the initializer expression
5225 if (!isRValRef) {
5226 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5227 // reference-compatible with "cv2 T2," or
5228 //
5229 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5230 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5231 // C++ [over.ics.ref]p1:
5232 // When a parameter of reference type binds directly (8.5.3)
5233 // to an argument expression, the implicit conversion sequence
5234 // is the identity conversion, unless the argument expression
5235 // has a type that is a derived class of the parameter type,
5236 // in which case the implicit conversion sequence is a
5237 // derived-to-base Conversion (13.3.3.1).
5238 SetAsReferenceBinding(/*BindsDirectly=*/true);
5239
5240 // Nothing more to do: the inaccessibility/ambiguity check for
5241 // derived-to-base conversions is suppressed when we're
5242 // computing the implicit conversion sequence (C++
5243 // [over.best.ics]p2).
5244 return ICS;
5245 }
5246
5247 // -- has a class type (i.e., T2 is a class type), where T1 is
5248 // not reference-related to T2, and can be implicitly
5249 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5250 // is reference-compatible with "cv3 T3" 92) (this
5251 // conversion is selected by enumerating the applicable
5252 // conversion functions (13.3.1.6) and choosing the best
5253 // one through overload resolution (13.3)),
5254 if (!SuppressUserConversions && T2->isRecordType() &&
5255 S.isCompleteType(DeclLoc, T2) &&
5256 RefRelationship == Sema::Ref_Incompatible) {
5257 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5258 Init, T2, /*AllowRvalues=*/false,
5259 AllowExplicit))
5260 return ICS;
5261 }
5262 }
5263
5264 // -- Otherwise, the reference shall be an lvalue reference to a
5265 // non-volatile const type (i.e., cv1 shall be const), or the reference
5266 // shall be an rvalue reference.
5267 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5268 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5270 return ICS;
5271 }
5272
5273 // -- If the initializer expression
5274 //
5275 // -- is an xvalue, class prvalue, array prvalue or function
5276 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5277 if (RefRelationship == Sema::Ref_Compatible &&
5278 (InitCategory.isXValue() ||
5279 (InitCategory.isPRValue() &&
5280 (T2->isRecordType() || T2->isArrayType())) ||
5281 (InitCategory.isLValue() && T2->isFunctionType()))) {
5282 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5283 // binding unless we're binding to a class prvalue.
5284 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5285 // allow the use of rvalue references in C++98/03 for the benefit of
5286 // standard library implementors; therefore, we need the xvalue check here.
5287 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5288 !(InitCategory.isPRValue() || T2->isRecordType()));
5289 return ICS;
5290 }
5291
5292 // -- has a class type (i.e., T2 is a class type), where T1 is not
5293 // reference-related to T2, and can be implicitly converted to
5294 // an xvalue, class prvalue, or function lvalue of type
5295 // "cv3 T3", where "cv1 T1" is reference-compatible with
5296 // "cv3 T3",
5297 //
5298 // then the reference is bound to the value of the initializer
5299 // expression in the first case and to the result of the conversion
5300 // in the second case (or, in either case, to an appropriate base
5301 // class subobject).
5302 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5303 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5304 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5305 Init, T2, /*AllowRvalues=*/true,
5306 AllowExplicit)) {
5307 // In the second case, if the reference is an rvalue reference
5308 // and the second standard conversion sequence of the
5309 // user-defined conversion sequence includes an lvalue-to-rvalue
5310 // conversion, the program is ill-formed.
5311 if (ICS.isUserDefined() && isRValRef &&
5314
5315 return ICS;
5316 }
5317
5318 // A temporary of function type cannot be created; don't even try.
5319 if (T1->isFunctionType())
5320 return ICS;
5321
5322 // -- Otherwise, a temporary of type "cv1 T1" is created and
5323 // initialized from the initializer expression using the
5324 // rules for a non-reference copy initialization (8.5). The
5325 // reference is then bound to the temporary. If T1 is
5326 // reference-related to T2, cv1 must be the same
5327 // cv-qualification as, or greater cv-qualification than,
5328 // cv2; otherwise, the program is ill-formed.
5329 if (RefRelationship == Sema::Ref_Related) {
5330 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5331 // we would be reference-compatible or reference-compatible with
5332 // added qualification. But that wasn't the case, so the reference
5333 // initialization fails.
5334 //
5335 // Note that we only want to check address spaces and cvr-qualifiers here.
5336 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5337 Qualifiers T1Quals = T1.getQualifiers();
5338 Qualifiers T2Quals = T2.getQualifiers();
5339 T1Quals.removeObjCGCAttr();
5340 T1Quals.removeObjCLifetime();
5341 T2Quals.removeObjCGCAttr();
5342 T2Quals.removeObjCLifetime();
5343 // MS compiler ignores __unaligned qualifier for references; do the same.
5344 T1Quals.removeUnaligned();
5345 T2Quals.removeUnaligned();
5346 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5347 return ICS;
5348 }
5349
5350 // If at least one of the types is a class type, the types are not
5351 // related, and we aren't allowed any user conversions, the
5352 // reference binding fails. This case is important for breaking
5353 // recursion, since TryImplicitConversion below will attempt to
5354 // create a temporary through the use of a copy constructor.
5355 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5356 (T1->isRecordType() || T2->isRecordType()))
5357 return ICS;
5358
5359 // If T1 is reference-related to T2 and the reference is an rvalue
5360 // reference, the initializer expression shall not be an lvalue.
5361 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5362 Init->Classify(S.Context).isLValue()) {
5364 return ICS;
5365 }
5366
5367 // C++ [over.ics.ref]p2:
5368 // When a parameter of reference type is not bound directly to
5369 // an argument expression, the conversion sequence is the one
5370 // required to convert the argument expression to the
5371 // underlying type of the reference according to
5372 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5373 // to copy-initializing a temporary of the underlying type with
5374 // the argument expression. Any difference in top-level
5375 // cv-qualification is subsumed by the initialization itself
5376 // and does not constitute a conversion.
5377 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5378 AllowedExplicit::None,
5379 /*InOverloadResolution=*/false,
5380 /*CStyle=*/false,
5381 /*AllowObjCWritebackConversion=*/false,
5382 /*AllowObjCConversionOnExplicit=*/false);
5383
5384 // Of course, that's still a reference binding.
5385 if (ICS.isStandard()) {
5386 ICS.Standard.ReferenceBinding = true;
5387 ICS.Standard.IsLvalueReference = !isRValRef;
5388 ICS.Standard.BindsToFunctionLvalue = false;
5389 ICS.Standard.BindsToRvalue = true;
5392 } else if (ICS.isUserDefined()) {
5393 const ReferenceType *LValRefType =
5396
5397 // C++ [over.ics.ref]p3:
5398 // Except for an implicit object parameter, for which see 13.3.1, a
5399 // standard conversion sequence cannot be formed if it requires [...]
5400 // binding an rvalue reference to an lvalue other than a function
5401 // lvalue.
5402 // Note that the function case is not possible here.
5403 if (isRValRef && LValRefType) {
5405 return ICS;
5406 }
5407
5409 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5411 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5414 }
5415
5416 return ICS;
5417}
5418
5420TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5421 bool SuppressUserConversions,
5422 bool InOverloadResolution,
5423 bool AllowObjCWritebackConversion,
5424 bool AllowExplicit = false);
5425
5426/// TryListConversion - Try to copy-initialize a value of type ToType from the
5427/// initializer list From.
5430 bool SuppressUserConversions,
5431 bool InOverloadResolution,
5432 bool AllowObjCWritebackConversion) {
5433 // C++11 [over.ics.list]p1:
5434 // When an argument is an initializer list, it is not an expression and
5435 // special rules apply for converting it to a parameter type.
5436
5438 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5439
5440 // We need a complete type for what follows. With one C++20 exception,
5441 // incomplete types can never be initialized from init lists.
5442 QualType InitTy = ToType;
5443 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5444 if (AT && S.getLangOpts().CPlusPlus20)
5445 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5446 // C++20 allows list initialization of an incomplete array type.
5447 InitTy = IAT->getElementType();
5448 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5449 return Result;
5450
5451 // C++20 [over.ics.list]/2:
5452 // If the initializer list is a designated-initializer-list, a conversion
5453 // is only possible if the parameter has an aggregate type
5454 //
5455 // FIXME: The exception for reference initialization here is not part of the
5456 // language rules, but follow other compilers in adding it as a tentative DR
5457 // resolution.
5458 bool IsDesignatedInit = From->hasDesignatedInit();
5459 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5460 IsDesignatedInit)
5461 return Result;
5462
5463 // Per DR1467 and DR2137:
5464 // If the parameter type is an aggregate class X and the initializer list
5465 // has a single element of type cv U, where U is X or a class derived from
5466 // X, the implicit conversion sequence is the one required to convert the
5467 // element to the parameter type.
5468 //
5469 // Otherwise, if the parameter type is a character array [... ]
5470 // and the initializer list has a single element that is an
5471 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5472 // implicit conversion sequence is the identity conversion.
5473 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5474 if (ToType->isRecordType() && ToType->isAggregateType()) {
5475 QualType InitType = From->getInit(0)->getType();
5476 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5477 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5478 return TryCopyInitialization(S, From->getInit(0), ToType,
5479 SuppressUserConversions,
5480 InOverloadResolution,
5481 AllowObjCWritebackConversion);
5482 }
5483
5484 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5485 InitializedEntity Entity =
5487 /*Consumed=*/false);
5488 if (S.CanPerformCopyInitialization(Entity, From)) {
5489 Result.setStandard();
5490 Result.Standard.setAsIdentityConversion();
5491 Result.Standard.setFromType(ToType);
5492 Result.Standard.setAllToTypes(ToType);
5493 return Result;
5494 }
5495 }
5496 }
5497
5498 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5499 // C++11 [over.ics.list]p2:
5500 // If the parameter type is std::initializer_list<X> or "array of X" and
5501 // all the elements can be implicitly converted to X, the implicit
5502 // conversion sequence is the worst conversion necessary to convert an
5503 // element of the list to X.
5504 //
5505 // C++14 [over.ics.list]p3:
5506 // Otherwise, if the parameter type is "array of N X", if the initializer
5507 // list has exactly N elements or if it has fewer than N elements and X is
5508 // default-constructible, and if all the elements of the initializer list
5509 // can be implicitly converted to X, the implicit conversion sequence is
5510 // the worst conversion necessary to convert an element of the list to X.
5511 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5512 unsigned e = From->getNumInits();
5515 QualType());
5516 QualType ContTy = ToType;
5517 bool IsUnbounded = false;
5518 if (AT) {
5519 InitTy = AT->getElementType();
5520 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5521 if (CT->getSize().ult(e)) {
5522 // Too many inits, fatally bad
5524 ToType);
5525 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5526 return Result;
5527 }
5528 if (CT->getSize().ugt(e)) {
5529 // Need an init from empty {}, is there one?
5530 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5531 From->getEndLoc());
5532 EmptyList.setType(S.Context.VoidTy);
5533 DfltElt = TryListConversion(
5534 S, &EmptyList, InitTy, SuppressUserConversions,
5535 InOverloadResolution, AllowObjCWritebackConversion);
5536 if (DfltElt.isBad()) {
5537 // No {} init, fatally bad
5539 ToType);
5540 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5541 return Result;
5542 }
5543 }
5544 } else {
5545 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5546 IsUnbounded = true;
5547 if (!e) {
5548 // Cannot convert to zero-sized.
5550 ToType);
5551 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5552 return Result;
5553 }
5554 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5555 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5557 }
5558 }
5559
5560 Result.setStandard();
5561 Result.Standard.setAsIdentityConversion();
5562 Result.Standard.setFromType(InitTy);
5563 Result.Standard.setAllToTypes(InitTy);
5564 for (unsigned i = 0; i < e; ++i) {
5565 Expr *Init = From->getInit(i);
5567 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5568 AllowObjCWritebackConversion);
5569
5570 // Keep the worse conversion seen so far.
5571 // FIXME: Sequences are not totally ordered, so 'worse' can be
5572 // ambiguous. CWG has been informed.
5574 Result) ==
5576 Result = ICS;
5577 // Bail as soon as we find something unconvertible.
5578 if (Result.isBad()) {
5579 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5580 return Result;
5581 }
5582 }
5583 }
5584
5585 // If we needed any implicit {} initialization, compare that now.
5586 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5587 // has been informed that this might not be the best thing.
5588 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5589 S, From->getEndLoc(), DfltElt, Result) ==
5591 Result = DfltElt;
5592 // Record the type being initialized so that we may compare sequences
5593 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5594 return Result;
5595 }
5596
5597 // C++14 [over.ics.list]p4:
5598 // C++11 [over.ics.list]p3:
5599 // Otherwise, if the parameter is a non-aggregate class X and overload
5600 // resolution chooses a single best constructor [...] the implicit
5601 // conversion sequence is a user-defined conversion sequence. If multiple
5602 // constructors are viable but none is better than the others, the
5603 // implicit conversion sequence is a user-defined conversion sequence.
5604 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5605 // This function can deal with initializer lists.
5606 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5607 AllowedExplicit::None,
5608 InOverloadResolution, /*CStyle=*/false,
5609 AllowObjCWritebackConversion,
5610 /*AllowObjCConversionOnExplicit=*/false);
5611 }
5612
5613 // C++14 [over.ics.list]p5:
5614 // C++11 [over.ics.list]p4:
5615 // Otherwise, if the parameter has an aggregate type which can be
5616 // initialized from the initializer list [...] the implicit conversion
5617 // sequence is a user-defined conversion sequence.
5618 if (ToType->isAggregateType()) {
5619 // Type is an aggregate, argument is an init list. At this point it comes
5620 // down to checking whether the initialization works.
5621 // FIXME: Find out whether this parameter is consumed or not.
5622 InitializedEntity Entity =
5624 /*Consumed=*/false);
5626 From)) {
5627 Result.setUserDefined();
5628 Result.UserDefined.Before.setAsIdentityConversion();
5629 // Initializer lists don't have a type.
5630 Result.UserDefined.Before.setFromType(QualType());
5631 Result.UserDefined.Before.setAllToTypes(QualType());
5632
5633 Result.UserDefined.After.setAsIdentityConversion();
5634 Result.UserDefined.After.setFromType(ToType);
5635 Result.UserDefined.After.setAllToTypes(ToType);
5636 Result.UserDefined.ConversionFunction = nullptr;
5637 }
5638 return Result;
5639 }
5640
5641 // C++14 [over.ics.list]p6:
5642 // C++11 [over.ics.list]p5:
5643 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5644 if (ToType->isReferenceType()) {
5645 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5646 // mention initializer lists in any way. So we go by what list-
5647 // initialization would do and try to extrapolate from that.
5648
5649 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5650
5651 // If the initializer list has a single element that is reference-related
5652 // to the parameter type, we initialize the reference from that.
5653 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5654 Expr *Init = From->getInit(0);
5655
5656 QualType T2 = Init->getType();
5657
5658 // If the initializer is the address of an overloaded function, try
5659 // to resolve the overloaded function. If all goes well, T2 is the
5660 // type of the resulting function.
5661 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5664 Init, ToType, false, Found))
5665 T2 = Fn->getType();
5666 }
5667
5668 // Compute some basic properties of the types and the initializer.
5669 Sema::ReferenceCompareResult RefRelationship =
5670 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5671
5672 if (RefRelationship >= Sema::Ref_Related) {
5673 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5674 SuppressUserConversions,
5675 /*AllowExplicit=*/false);
5676 }
5677 }
5678
5679 // Otherwise, we bind the reference to a temporary created from the
5680 // initializer list.
5681 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5682 InOverloadResolution,
5683 AllowObjCWritebackConversion);
5684 if (Result.isFailure())
5685 return Result;
5686 assert(!Result.isEllipsis() &&
5687 "Sub-initialization cannot result in ellipsis conversion.");
5688
5689 // Can we even bind to a temporary?
5690 if (ToType->isRValueReferenceType() ||
5691 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5692 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5693 Result.UserDefined.After;
5694 SCS.ReferenceBinding = true;
5696 SCS.BindsToRvalue = true;
5697 SCS.BindsToFunctionLvalue = false;
5700 } else
5702 From, ToType);
5703 return Result;
5704 }
5705
5706 // C++14 [over.ics.list]p7:
5707 // C++11 [over.ics.list]p6:
5708 // Otherwise, if the parameter type is not a class:
5709 if (!ToType->isRecordType()) {
5710 // - if the initializer list has one element that is not itself an
5711 // initializer list, the implicit conversion sequence is the one
5712 // required to convert the element to the parameter type.
5713 unsigned NumInits = From->getNumInits();
5714 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5715 Result = TryCopyInitialization(S, From->getInit(0), ToType,
5716 SuppressUserConversions,
5717 InOverloadResolution,
5718 AllowObjCWritebackConversion);
5719 // - if the initializer list has no elements, the implicit conversion
5720 // sequence is the identity conversion.
5721 else if (NumInits == 0) {
5722 Result.setStandard();
5723 Result.Standard.setAsIdentityConversion();
5724 Result.Standard.setFromType(ToType);
5725 Result.Standard.setAllToTypes(ToType);
5726 }
5727 return Result;
5728 }
5729
5730 // C++14 [over.ics.list]p8:
5731 // C++11 [over.ics.list]p7:
5732 // In all cases other than those enumerated above, no conversion is possible
5733 return Result;
5734}
5735
5736/// TryCopyInitialization - Try to copy-initialize a value of type
5737/// ToType from the expression From. Return the implicit conversion
5738/// sequence required to pass this argument, which may be a bad
5739/// conversion sequence (meaning that the argument cannot be passed to
5740/// a parameter of this type). If @p SuppressUserConversions, then we
5741/// do not permit any user-defined conversion sequences.
5744 bool SuppressUserConversions,
5745 bool InOverloadResolution,
5746 bool AllowObjCWritebackConversion,
5747 bool AllowExplicit) {
5748 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5749 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5750 InOverloadResolution,AllowObjCWritebackConversion);
5751
5752 if (ToType->isReferenceType())
5753 return TryReferenceInit(S, From, ToType,
5754 /*FIXME:*/ From->getBeginLoc(),
5755 SuppressUserConversions, AllowExplicit);
5756
5757 return TryImplicitConversion(S, From, ToType,
5758 SuppressUserConversions,
5759 AllowedExplicit::None,
5760 InOverloadResolution,
5761 /*CStyle=*/false,
5762 AllowObjCWritebackConversion,
5763 /*AllowObjCConversionOnExplicit=*/false);
5764}
5765
5766static bool TryCopyInitialization(const CanQualType FromQTy,
5767 const CanQualType ToQTy,
5768 Sema &S,
5769 SourceLocation Loc,
5770 ExprValueKind FromVK) {
5771 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5773 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5774
5775 return !ICS.isBad();
5776}
5777
5778/// TryObjectArgumentInitialization - Try to initialize the object
5779/// parameter of the given member function (@c Method) from the
5780/// expression @p From.
5782 Sema &S, SourceLocation Loc, QualType FromType,
5783 Expr::Classification FromClassification, CXXMethodDecl *Method,
5784 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5785 QualType ExplicitParameterType = QualType(),
5786 bool SuppressUserConversion = false) {
5787
5788 // We need to have an object of class type.
5789 if (const auto *PT = FromType->getAs<PointerType>()) {
5790 FromType = PT->getPointeeType();
5791
5792 // When we had a pointer, it's implicitly dereferenced, so we
5793 // better have an lvalue.
5794 assert(FromClassification.isLValue());
5795 }
5796
5797 auto ValueKindFromClassification = [](Expr::Classification C) {
5798 if (C.isPRValue())
5799 return clang::VK_PRValue;
5800 if (C.isXValue())
5801 return VK_XValue;
5802 return clang::VK_LValue;
5803 };
5804
5805 if (Method->isExplicitObjectMemberFunction()) {
5806 if (ExplicitParameterType.isNull())
5807 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
5808 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
5809 ValueKindFromClassification(FromClassification));
5811 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
5812 /*InOverloadResolution=*/true, false);
5813 if (ICS.isBad())
5814 ICS.Bad.FromExpr = nullptr;
5815 return ICS;
5816 }
5817
5818 assert(FromType->isRecordType());
5819
5820 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5821 // C++98 [class.dtor]p2:
5822 // A destructor can be invoked for a const, volatile or const volatile
5823 // object.
5824 // C++98 [over.match.funcs]p4:
5825 // For static member functions, the implicit object parameter is considered
5826 // to match any object (since if the function is selected, the object is
5827 // discarded).
5828 Qualifiers Quals = Method->getMethodQualifiers();
5829 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
5830 Quals.addConst();
5831 Quals.addVolatile();
5832 }
5833
5834 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5835
5836 // Set up the conversion sequence as a "bad" conversion, to allow us
5837 // to exit early.
5839
5840 // C++0x [over.match.funcs]p4:
5841 // For non-static member functions, the type of the implicit object
5842 // parameter is
5843 //
5844 // - "lvalue reference to cv X" for functions declared without a
5845 // ref-qualifier or with the & ref-qualifier
5846 // - "rvalue reference to cv X" for functions declared with the &&
5847 // ref-qualifier
5848 //
5849 // where X is the class of which the function is a member and cv is the
5850 // cv-qualification on the member function declaration.
5851 //
5852 // However, when finding an implicit conversion sequence for the argument, we
5853 // are not allowed to perform user-defined conversions
5854 // (C++ [over.match.funcs]p5). We perform a simplified version of
5855 // reference binding here, that allows class rvalues to bind to
5856 // non-constant references.
5857
5858 // First check the qualifiers.
5859 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5860 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
5861 if (ImplicitParamType.getCVRQualifiers() !=
5862 FromTypeCanon.getLocalCVRQualifiers() &&
5863 !ImplicitParamType.isAtLeastAsQualifiedAs(
5864 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
5866 FromType, ImplicitParamType);
5867 return ICS;
5868 }
5869
5870 if (FromTypeCanon.hasAddressSpace()) {
5871 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5872 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5873 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
5874 S.getASTContext())) {
5876 FromType, ImplicitParamType);
5877 return ICS;
5878 }
5879 }
5880
5881 // Check that we have either the same type or a derived type. It
5882 // affects the conversion rank.
5883 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5884 ImplicitConversionKind SecondKind;
5885 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5886 SecondKind = ICK_Identity;
5887 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
5888 SecondKind = ICK_Derived_To_Base;
5889 } else if (!Method->isExplicitObjectMemberFunction()) {
5891 FromType, ImplicitParamType);
5892 return ICS;
5893 }
5894
5895 // Check the ref-qualifier.
5896 switch (Method->getRefQualifier()) {
5897 case RQ_None:
5898 // Do nothing; we don't care about lvalueness or rvalueness.
5899 break;
5900
5901 case RQ_LValue:
5902 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5903 // non-const lvalue reference cannot bind to an rvalue
5905 ImplicitParamType);
5906 return ICS;
5907 }
5908 break;
5909
5910 case RQ_RValue:
5911 if (!FromClassification.isRValue()) {
5912 // rvalue reference cannot bind to an lvalue
5914 ImplicitParamType);
5915 return ICS;
5916 }
5917 break;
5918 }
5919
5920 // Success. Mark this as a reference binding.
5921 ICS.setStandard();
5923 ICS.Standard.Second = SecondKind;
5924 ICS.Standard.setFromType(FromType);
5925 ICS.Standard.setAllToTypes(ImplicitParamType);
5926 ICS.Standard.ReferenceBinding = true;
5927 ICS.Standard.DirectBinding = true;
5929 ICS.Standard.BindsToFunctionLvalue = false;
5930 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5932 = (Method->getRefQualifier() == RQ_None);
5933 return ICS;
5934}
5935
5936/// PerformObjectArgumentInitialization - Perform initialization of
5937/// the implicit object parameter for the given Method with the given
5938/// expression.
5940 Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl,
5941 CXXMethodDecl *Method) {
5942 QualType FromRecordType, DestType;
5943 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
5944
5945 Expr::Classification FromClassification;
5946 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5947 FromRecordType = PT->getPointeeType();
5948 DestType = Method->getThisType();
5949 FromClassification = Expr::Classification::makeSimpleLValue();
5950 } else {
5951 FromRecordType = From->getType();
5952 DestType = ImplicitParamRecordType;
5953 FromClassification = From->Classify(Context);
5954
5955 // CWG2813 [expr.call]p6:
5956 // If the function is an implicit object member function, the object
5957 // expression of the class member access shall be a glvalue [...]
5958 if (From->isPRValue()) {
5959 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5960 Method->getRefQualifier() !=
5962 }
5963 }
5964
5965 // Note that we always use the true parent context when performing
5966 // the actual argument initialization.
5968 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5969 Method->getParent());
5970 if (ICS.isBad()) {
5971 switch (ICS.Bad.Kind) {
5973 Qualifiers FromQs = FromRecordType.getQualifiers();
5974 Qualifiers ToQs = DestType.getQualifiers();
5975 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5976 if (CVR) {
5977 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5978 << Method->getDeclName() << FromRecordType << (CVR - 1)
5979 << From->getSourceRange();
5980 Diag(Method->getLocation(), diag::note_previous_decl)
5981 << Method->getDeclName();
5982 return ExprError();
5983 }
5984 break;
5985 }
5986
5989 bool IsRValueQualified =
5991 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5992 << Method->getDeclName() << FromClassification.isRValue()
5993 << IsRValueQualified;
5994 Diag(Method->getLocation(), diag::note_previous_decl)
5995 << Method->getDeclName();
5996 return ExprError();
5997 }
5998
6001 break;
6002
6005 llvm_unreachable("Lists are not objects");
6006 }
6007
6008 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
6009 << ImplicitParamRecordType << FromRecordType
6010 << From->getSourceRange();
6011 }
6012
6013 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6014 ExprResult FromRes =
6015 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6016 if (FromRes.isInvalid())
6017 return ExprError();
6018 From = FromRes.get();
6019 }
6020
6021 if (!Context.hasSameType(From->getType(), DestType)) {
6022 CastKind CK;
6023 QualType PteeTy = DestType->getPointeeType();
6024 LangAS DestAS =
6025 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6026 if (FromRecordType.getAddressSpace() != DestAS)
6027 CK = CK_AddressSpaceConversion;
6028 else
6029 CK = CK_NoOp;
6030 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6031 }
6032 return From;
6033}
6034
6035/// TryContextuallyConvertToBool - Attempt to contextually convert the
6036/// expression From to bool (C++0x [conv]p3).
6039 // C++ [dcl.init]/17.8:
6040 // - Otherwise, if the initialization is direct-initialization, the source
6041 // type is std::nullptr_t, and the destination type is bool, the initial
6042 // value of the object being initialized is false.
6043 if (From->getType()->isNullPtrType())
6045 S.Context.BoolTy,
6046 From->isGLValue());
6047
6048 // All other direct-initialization of bool is equivalent to an implicit
6049 // conversion to bool in which explicit conversions are permitted.
6050 return TryImplicitConversion(S, From, S.Context.BoolTy,
6051 /*SuppressUserConversions=*/false,
6052 AllowedExplicit::Conversions,
6053 /*InOverloadResolution=*/false,
6054 /*CStyle=*/false,
6055 /*AllowObjCWritebackConversion=*/false,
6056 /*AllowObjCConversionOnExplicit=*/false);
6057}
6058
6060 if (checkPlaceholderForOverload(*this, From))
6061 return ExprError();
6062
6064 if (!ICS.isBad())
6065 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6067
6068 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
6069 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6070 << From->getType() << From->getSourceRange();
6071 return ExprError();
6072}
6073
6074/// Check that the specified conversion is permitted in a converted constant
6075/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6076/// is acceptable.
6079 // Since we know that the target type is an integral or unscoped enumeration
6080 // type, most conversion kinds are impossible. All possible First and Third
6081 // conversions are fine.
6082 switch (SCS.Second) {
6083 case ICK_Identity:
6085 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6087 return true;
6088
6090 // Conversion from an integral or unscoped enumeration type to bool is
6091 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6092 // conversion, so we allow it in a converted constant expression.
6093 //
6094 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6095 // a lot of popular code. We should at least add a warning for this
6096 // (non-conforming) extension.
6098 SCS.getToType(2)->isBooleanType();
6099
6101 case ICK_Pointer_Member:
6102 // C++1z: null pointer conversions and null member pointer conversions are
6103 // only permitted if the source type is std::nullptr_t.
6104 return SCS.getFromType()->isNullPtrType();
6105
6117 case ICK_Vector_Splat:
6118 case ICK_Complex_Real:
6127 return false;
6128
6133 llvm_unreachable("found a first conversion kind in Second");
6134
6136 case ICK_Qualification:
6137 llvm_unreachable("found a third conversion kind in Second");
6138
6140 break;
6141 }
6142
6143 llvm_unreachable("unknown conversion kind");
6144}
6145
6146/// BuildConvertedConstantExpression - Check that the expression From is a
6147/// converted constant expression of type T, perform the conversion but
6148/// does not evaluate the expression
6150 QualType T,
6151 Sema::CCEKind CCE,
6152 NamedDecl *Dest,
6153 APValue &PreNarrowingValue) {
6154 assert(S.getLangOpts().CPlusPlus11 &&
6155 "converted constant expression outside C++11");
6156
6157 if (checkPlaceholderForOverload(S, From))
6158 return ExprError();
6159
6160 // C++1z [expr.const]p3:
6161 // A converted constant expression of type T is an expression,
6162 // implicitly converted to type T, where the converted
6163 // expression is a constant expression and the implicit conversion
6164 // sequence contains only [... list of conversions ...].
6168 : TryCopyInitialization(S, From, T,
6169 /*SuppressUserConversions=*/false,
6170 /*InOverloadResolution=*/false,
6171 /*AllowObjCWritebackConversion=*/false,
6172 /*AllowExplicit=*/false);
6173 StandardConversionSequence *SCS = nullptr;
6174 switch (ICS.getKind()) {
6176 SCS = &ICS.Standard;
6177 break;
6179 if (T->isRecordType())
6180 SCS = &ICS.UserDefined.Before;
6181 else
6182 SCS = &ICS.UserDefined.After;
6183 break;
6187 return S.Diag(From->getBeginLoc(),
6188 diag::err_typecheck_converted_constant_expression)
6189 << From->getType() << From->getSourceRange() << T;
6190 return ExprError();
6191
6194 llvm_unreachable("bad conversion in converted constant expression");
6195 }
6196
6197 // Check that we would only use permitted conversions.
6198 if (!CheckConvertedConstantConversions(S, *SCS)) {
6199 return S.Diag(From->getBeginLoc(),
6200 diag::err_typecheck_converted_constant_expression_disallowed)
6201 << From->getType() << From->getSourceRange() << T;
6202 }
6203 // [...] and where the reference binding (if any) binds directly.
6204 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6205 return S.Diag(From->getBeginLoc(),
6206 diag::err_typecheck_converted_constant_expression_indirect)
6207 << From->getType() << From->getSourceRange() << T;
6208 }
6209 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6210 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6211 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6212 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6213 // case explicitly.
6214 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6215 return S.Diag(From->getBeginLoc(),
6216 diag::err_reference_bind_to_bitfield_in_cce)
6217 << From->getSourceRange();
6218 }
6219
6220 // Usually we can simply apply the ImplicitConversionSequence we formed
6221 // earlier, but that's not guaranteed to work when initializing an object of
6222 // class type.
6224 if (T->isRecordType()) {
6225 assert(CCE == Sema::CCEK_TemplateArg &&
6226 "unexpected class type converted constant expr");
6229 T, cast<NonTypeTemplateParmDecl>(Dest)),
6230 SourceLocation(), From);
6231 } else {
6232 Result =
6234 }
6235 if (Result.isInvalid())
6236 return Result;
6237
6238 // C++2a [intro.execution]p5:
6239 // A full-expression is [...] a constant-expression [...]
6240 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6241 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6243 if (Result.isInvalid())
6244 return Result;
6245
6246 // Check for a narrowing implicit conversion.
6247 bool ReturnPreNarrowingValue = false;
6248 QualType PreNarrowingType;
6249 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6250 PreNarrowingType)) {
6252 // Implicit conversion to a narrower type, but the expression is
6253 // value-dependent so we can't tell whether it's actually narrowing.
6255 // Implicit conversion to a narrower type, and the value is not a constant
6256 // expression. We'll diagnose this in a moment.
6257 case NK_Not_Narrowing:
6258 break;
6259
6261 if (CCE == Sema::CCEK_ArrayBound &&
6262 PreNarrowingType->isIntegralOrEnumerationType() &&
6263 PreNarrowingValue.isInt()) {
6264 // Don't diagnose array bound narrowing here; we produce more precise
6265 // errors by allowing the un-narrowed value through.
6266 ReturnPreNarrowingValue = true;
6267 break;
6268 }
6269 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6270 << CCE << /*Constant*/ 1
6271 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6272 break;
6273
6274 case NK_Type_Narrowing:
6275 // FIXME: It would be better to diagnose that the expression is not a
6276 // constant expression.
6277 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6278 << CCE << /*Constant*/ 0 << From->getType() << T;
6279 break;
6280 }
6281 if (!ReturnPreNarrowingValue)
6282 PreNarrowingValue = {};
6283
6284 return Result;
6285}
6286
6287/// CheckConvertedConstantExpression - Check that the expression From is a
6288/// converted constant expression of type T, perform the conversion and produce
6289/// the converted expression, per C++11 [expr.const]p3.
6292 Sema::CCEKind CCE,
6293 bool RequireInt,
6294 NamedDecl *Dest) {
6295
6296 APValue PreNarrowingValue;
6298 PreNarrowingValue);
6299 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6300 Value = APValue();
6301 return Result;
6302 }
6303 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6304 RequireInt, PreNarrowingValue);
6305}
6306
6308 CCEKind CCE,
6309 NamedDecl *Dest) {
6310 APValue PreNarrowingValue;
6311 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6312 PreNarrowingValue);
6313}
6314
6316 APValue &Value, CCEKind CCE,
6317 NamedDecl *Dest) {
6318 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6319 Dest);
6320}
6321
6323 llvm::APSInt &Value,
6324 CCEKind CCE) {
6325 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6326
6327 APValue V;
6328 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6329 /*Dest=*/nullptr);
6330 if (!R.isInvalid() && !R.get()->isValueDependent())
6331 Value = V.getInt();
6332 return R;
6333}
6334
6337 Sema::CCEKind CCE, bool RequireInt,
6338 const APValue &PreNarrowingValue) {
6339
6341 // Check the expression is a constant expression.
6343 Expr::EvalResult Eval;
6344 Eval.Diag = &Notes;
6345
6346 ConstantExprKind Kind;
6347 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
6348 Kind = ConstantExprKind::ClassTemplateArgument;
6349 else if (CCE == Sema::CCEK_TemplateArg)
6350 Kind = ConstantExprKind::NonClassTemplateArgument;
6351 else
6352 Kind = ConstantExprKind::Normal;
6353
6354 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6355 (RequireInt && !Eval.Val.isInt())) {
6356 // The expression can't be folded, so we can't keep it at this position in
6357 // the AST.
6358 Result = ExprError();
6359 } else {
6360 Value = Eval.Val;
6361
6362 if (Notes.empty()) {
6363 // It's a constant expression.
6364 Expr *E = Result.get();
6365 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6366 // We expect a ConstantExpr to have a value associated with it
6367 // by this point.
6368 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6369 "ConstantExpr has no value associated with it");
6370 (void)CE;
6371 } else {
6372 E = ConstantExpr::Create(Context, Result.get(), Value);
6373 }
6374 if (!PreNarrowingValue.isAbsent())
6375 Value = std::move(PreNarrowingValue);
6376 return E;
6377 }
6378 }
6379
6380 // It's not a constant expression. Produce an appropriate diagnostic.
6381 if (Notes.size() == 1 &&
6382 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6383 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6384 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6385 diag::note_constexpr_invalid_template_arg) {
6386 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6387 for (unsigned I = 0; I < Notes.size(); ++I)
6388 Diag(Notes[I].first, Notes[I].second);
6389 } else {
6390 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6391 << CCE << E->getSourceRange();
6392 for (unsigned I = 0; I < Notes.size(); ++I)
6393 Diag(Notes[I].first, Notes[I].second);
6394 }
6395 return ExprError();
6396}
6397
6398/// dropPointerConversions - If the given standard conversion sequence
6399/// involves any pointer conversions, remove them. This may change
6400/// the result type of the conversion sequence.
6402 if (SCS.Second == ICK_Pointer_Conversion) {
6403 SCS.Second = ICK_Identity;
6404 SCS.Dimension = ICK_Identity;
6405 SCS.Third = ICK_Identity;
6406 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6407 }
6408}
6409
6410/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6411/// convert the expression From to an Objective-C pointer type.
6414 // Do an implicit conversion to 'id'.
6417 = TryImplicitConversion(S, From, Ty,
6418 // FIXME: Are these flags correct?
6419 /*SuppressUserConversions=*/false,
6420 AllowedExplicit::Conversions,
6421 /*InOverloadResolution=*/false,
6422 /*CStyle=*/false,
6423 /*AllowObjCWritebackConversion=*/false,
6424 /*AllowObjCConversionOnExplicit=*/true);
6425
6426 // Strip off any final conversions to 'id'.
6427 switch (ICS.getKind()) {
6432 break;
6433
6436 break;
6437
6440 break;
6441 }
6442
6443 return ICS;
6444}
6445
6447 if (checkPlaceholderForOverload(*this, From))
6448 return ExprError();
6449
6450 QualType Ty = Context.getObjCIdType();
6453 if (!ICS.isBad())
6454 return PerformImplicitConversion(From, Ty, ICS,
6456 return ExprResult();
6457}
6458
6459static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6460 const Expr *Base = nullptr;
6461 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6462 "expected a member expression");
6463
6464 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6465 M && !M->isImplicitAccess())
6466 Base = M->getBase();
6467 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6468 M && !M->isImplicitAccess())
6469 Base = M->getBase();
6470
6471 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6472
6473 if (T->isPointerType())
6474 T = T->getPointeeType();
6475
6476 return T;
6477}
6478
6480 const FunctionDecl *Fun) {
6481 QualType ObjType = Obj->getType();
6482 if (ObjType->isPointerType()) {
6483 ObjType = ObjType->getPointeeType();
6484 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6486 /*CanOverflow=*/false, FPOptionsOverride());
6487 }
6488 return Obj;
6489}
6490
6492 FunctionDecl *Fun) {
6493 Obj = GetExplicitObjectExpr(S, Obj, Fun);
6496 Obj->getExprLoc(), Obj);
6497}
6498
6500 Expr *Object, MultiExprArg &Args,
6501 SmallVectorImpl<Expr *> &NewArgs) {
6502 assert(Method->isExplicitObjectMemberFunction() &&
6503 "Method is not an explicit member function");
6504 assert(NewArgs.empty() && "NewArgs should be empty");
6505
6506 NewArgs.reserve(Args.size() + 1);
6507 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6508 NewArgs.push_back(This);
6509 NewArgs.append(Args.begin(), Args.end());
6510 Args = NewArgs;
6512 Method, Object->getBeginLoc());
6513}
6514
6515/// Determine whether the provided type is an integral type, or an enumeration
6516/// type of a permitted flavor.
6518 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6520}
6521
6522static ExprResult
6525 QualType T, UnresolvedSetImpl &ViableConversions) {
6526
6527 if (Converter.Suppress)
6528 return ExprError();
6529
6530 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6531 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6532 CXXConversionDecl *Conv =
6533 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6535 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6536 }
6537 return From;
6538}
6539
6540static bool
6543 QualType T, bool HadMultipleCandidates,
6544 UnresolvedSetImpl &ExplicitConversions) {
6545 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6546 DeclAccessPair Found = ExplicitConversions[0];
6547 CXXConversionDecl *Conversion =
6548 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6549
6550 // The user probably meant to invoke the given explicit
6551 // conversion; use it.
6552 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6553 std::string TypeStr;
6554 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6555
6556 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6558 "static_cast<" + TypeStr + ">(")
6560 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6561 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6562
6563 // If we aren't in a SFINAE context, build a call to the
6564 // explicit conversion function.
6565 if (SemaRef.isSFINAEContext())
6566 return true;
6567
6568 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6569 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6570 HadMultipleCandidates);
6571 if (Result.isInvalid())
6572 return true;
6573
6574 // Replace the conversion with a RecoveryExpr, so we don't try to
6575 // instantiate it later, but can further diagnose here.
6576 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6577 From, Result.get()->getType());
6578 if (Result.isInvalid())
6579 return true;
6580 From = Result.get();
6581 }
6582 return false;
6583}
6584
6585static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6587 QualType T, bool HadMultipleCandidates,
6589 CXXConversionDecl *Conversion =
6590 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6591 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6592
6593 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6594 if (!Converter.SuppressConversion) {
6595 if (SemaRef.isSFINAEContext())
6596 return true;
6597
6598 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6599 << From->getSourceRange();
6600 }
6601
6602 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6603 HadMultipleCandidates);
6604 if (Result.isInvalid())
6605 return true;
6606 // Record usage of conversion in an implicit cast.
6607 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6608 CK_UserDefinedConversion, Result.get(),
6609 nullptr, Result.get()->getValueKind(),
6610 SemaRef.CurFPFeatureOverrides());
6611 return false;
6612}
6613
6615 Sema &SemaRef, SourceLocation Loc, Expr *From,
6617 if (!Converter.match(From->getType()) && !Converter.Suppress)
6618 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6619 << From->getSourceRange();
6620
6621 return SemaRef.DefaultLvalueConversion(From);
6622}
6623
6624static void
6626 UnresolvedSetImpl &ViableConversions,
6627 OverloadCandidateSet &CandidateSet) {
6628 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6629 NamedDecl *D = FoundDecl.getDecl();
6630 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6631 if (isa<UsingShadowDecl>(D))
6632 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6633
6634 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
6636 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6637 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6638 continue;
6639 }
6640 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6641 SemaRef.AddConversionCandidate(
6642 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
6643 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6644 }
6645}
6646
6647/// Attempt to convert the given expression to a type which is accepted
6648/// by the given converter.
6649///
6650/// This routine will attempt to convert an expression of class type to a
6651/// type accepted by the specified converter. In C++11 and before, the class
6652/// must have a single non-explicit conversion function converting to a matching
6653/// type. In C++1y, there can be multiple such conversion functions, but only
6654/// one target type.
6655///
6656/// \param Loc The source location of the construct that requires the
6657/// conversion.
6658///
6659/// \param From The expression we're converting from.
6660///
6661/// \param Converter Used to control and diagnose the conversion process.
6662///
6663/// \returns The expression, converted to an integral or enumeration type if
6664/// successful.
6666 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6667 // We can't perform any more checking for type-dependent expressions.
6668 if (From->isTypeDependent())
6669 return From;
6670
6671 // Process placeholders immediately.
6672 if (From->hasPlaceholderType()) {
6673 ExprResult result = CheckPlaceholderExpr(From);
6674 if (result.isInvalid())
6675 return result;
6676 From = result.get();
6677 }
6678
6679 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6680 ExprResult Converted = DefaultLvalueConversion(From);
6681 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6682 // If the expression already has a matching type, we're golden.
6683 if (Converter.match(T))
6684 return Converted;
6685
6686 // FIXME: Check for missing '()' if T is a function type?
6687
6688 // We can only perform contextual implicit conversions on objects of class
6689 // type.
6690 const RecordType *RecordTy = T->getAs<RecordType>();
6691 if (!RecordTy || !getLangOpts().CPlusPlus) {
6692 if (!Converter.Suppress)
6693 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6694 return From;
6695 }
6696
6697 // We must have a complete class type.
6698 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6699 ContextualImplicitConverter &Converter;
6700 Expr *From;
6701
6702 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6703 : Converter(Converter), From(From) {}
6704
6705 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6706 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6707 }
6708 } IncompleteDiagnoser(Converter, From);
6709
6710 if (Converter.Suppress ? !isCompleteType(Loc, T)
6711 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6712 return From;
6713
6714 // Look for a conversion to an integral or enumeration type.
6716 ViableConversions; // These are *potentially* viable in C++1y.
6717 UnresolvedSet<4> ExplicitConversions;
6718 const auto &Conversions =
6719 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6720
6721 bool HadMultipleCandidates =
6722 (std::distance(Conversions.begin(), Conversions.end()) > 1);
6723
6724 // To check that there is only one target type, in C++1y:
6725 QualType ToType;
6726 bool HasUniqueTargetType = true;
6727
6728 // Collect explicit or viable (potentially in C++1y) conversions.
6729 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6730 NamedDecl *D = (*I)->getUnderlyingDecl();
6731 CXXConversionDecl *Conversion;
6732 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6733 if (ConvTemplate) {
6734 if (getLangOpts().CPlusPlus14)
6735 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6736 else
6737 continue; // C++11 does not consider conversion operator templates(?).
6738 } else
6739 Conversion = cast<CXXConversionDecl>(D);
6740
6741 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6742 "Conversion operator templates are considered potentially "
6743 "viable in C++1y");
6744
6745 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6746 if (Converter.match(CurToType) || ConvTemplate) {
6747
6748 if (Conversion->isExplicit()) {
6749 // FIXME: For C++1y, do we need this restriction?
6750 // cf. diagnoseNoViableConversion()
6751 if (!ConvTemplate)
6752 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6753 } else {
6754 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6755 if (ToType.isNull())
6756 ToType = CurToType.getUnqualifiedType();
6757 else if (HasUniqueTargetType &&
6758 (CurToType.getUnqualifiedType() != ToType))
6759 HasUniqueTargetType = false;
6760 }
6761 ViableConversions.addDecl(I.getDecl(), I.getAccess());
6762 }
6763 }
6764 }
6765
6766 if (getLangOpts().CPlusPlus14) {
6767 // C++1y [conv]p6:
6768 // ... An expression e of class type E appearing in such a context
6769 // is said to be contextually implicitly converted to a specified
6770 // type T and is well-formed if and only if e can be implicitly
6771 // converted to a type T that is determined as follows: E is searched
6772 // for conversion functions whose return type is cv T or reference to
6773 // cv T such that T is allowed by the context. There shall be
6774 // exactly one such T.
6775
6776 // If no unique T is found:
6777 if (ToType.isNull()) {
6778 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6779 HadMultipleCandidates,
6780 ExplicitConversions))
6781 return ExprError();
6782 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6783 }
6784
6785 // If more than one unique Ts are found:
6786 if (!HasUniqueTargetType)
6787 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6788 ViableConversions);
6789
6790 // If one unique T is found:
6791 // First, build a candidate set from the previously recorded
6792 // potentially viable conversions.
6794 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6795 CandidateSet);
6796
6797 // Then, perform overload resolution over the candidate set.
6799 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6800 case OR_Success: {
6801 // Apply this conversion.
6803 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6804 if (recordConversion(*this, Loc, From, Converter, T,
6805 HadMultipleCandidates, Found))
6806 return ExprError();
6807 break;
6808 }
6809 case OR_Ambiguous:
6810 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6811 ViableConversions);
6813 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6814 HadMultipleCandidates,
6815 ExplicitConversions))
6816 return ExprError();
6817 [[fallthrough]];
6818 case OR_Deleted:
6819 // We'll complain below about a non-integral condition type.
6820 break;
6821 }
6822 } else {
6823 switch (ViableConversions.size()) {
6824 case 0: {
6825 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6826 HadMultipleCandidates,
6827 ExplicitConversions))
6828 return ExprError();
6829
6830 // We'll complain below about a non-integral condition type.
6831 break;
6832 }
6833 case 1: {
6834 // Apply this conversion.
6835 DeclAccessPair Found = ViableConversions[0];
6836 if (recordConversion(*this, Loc, From, Converter, T,
6837 HadMultipleCandidates, Found))
6838 return ExprError();
6839 break;
6840 }
6841 default:
6842 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6843 ViableConversions);
6844 }
6845 }
6846
6847 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6848}
6849
6850/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6851/// an acceptable non-member overloaded operator for a call whose
6852/// arguments have types T1 (and, if non-empty, T2). This routine
6853/// implements the check in C++ [over.match.oper]p3b2 concerning
6854/// enumeration types.
6856 FunctionDecl *Fn,
6857 ArrayRef<Expr *> Args) {
6858 QualType T1 = Args[0]->getType();
6859 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6860
6861 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6862 return true;
6863
6864 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6865 return true;
6866
6867 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6868 if (Proto->getNumParams() < 1)
6869 return false;
6870
6871 if (T1->isEnumeralType()) {
6872 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6873 if (Context.hasSameUnqualifiedType(T1, ArgType))
6874 return true;
6875 }
6876
6877 if (Proto->getNumParams() < 2)
6878 return false;
6879
6880 if (!T2.isNull() && T2->isEnumeralType()) {
6881 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6882 if (Context.hasSameUnqualifiedType(T2, ArgType))
6883 return true;
6884 }
6885
6886 return false;
6887}
6888
6891 return false;
6892
6893 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
6894 return FD->isTargetMultiVersion();
6895
6896 if (!FD->isMultiVersion())
6897 return false;
6898
6899 // Among multiple target versions consider either the default,
6900 // or the first non-default in the absence of default version.
6901 unsigned SeenAt = 0;
6902 unsigned I = 0;
6903 bool HasDefault = false;
6905 FD, [&](const FunctionDecl *CurFD) {
6906 if (FD == CurFD)
6907 SeenAt = I;
6908 else if (CurFD->isTargetMultiVersionDefault())
6909 HasDefault = true;
6910 ++I;
6911 });
6912 return HasDefault || SeenAt != 0;
6913}
6914
6917 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6918 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6919 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6920 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
6921 const FunctionProtoType *Proto
6922 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6923 assert(Proto && "Functions without a prototype cannot be overloaded");
6924 assert(!Function->getDescribedFunctionTemplate() &&
6925 "Use AddTemplateOverloadCandidate for function templates");
6926
6927 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6928 if (!isa<CXXConstructorDecl>(Method)) {
6929 // If we get here, it's because we're calling a member function
6930 // that is named without a member access expression (e.g.,
6931 // "this->f") that was either written explicitly or created
6932 // implicitly. This can happen with a qualified call to a member
6933 // function, e.g., X::f(). We use an empty type for the implied
6934 // object argument (C++ [over.call.func]p3), and the acting context
6935 // is irrelevant.
6936 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6938 CandidateSet, SuppressUserConversions,
6939 PartialOverloading, EarlyConversions, PO);
6940 return;
6941 }
6942 // We treat a constructor like a non-member function, since its object
6943 // argument doesn't participate in overload resolution.
6944 }
6945
6946 if (!CandidateSet.isNewCandidate(Function, PO))
6947 return;
6948
6949 // C++11 [class.copy]p11: [DR1402]
6950 // A defaulted move constructor that is defined as deleted is ignored by
6951 // overload resolution.
6952 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6953 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6954 Constructor->isMoveConstructor())
6955 return;
6956
6957 // Overload resolution is always an unevaluated context.
6960
6961 // C++ [over.match.oper]p3:
6962 // if no operand has a class type, only those non-member functions in the
6963 // lookup set that have a first parameter of type T1 or "reference to
6964 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6965 // is a right operand) a second parameter of type T2 or "reference to
6966 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
6967 // candidate functions.
6968 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6970 return;
6971
6972 // Add this candidate
6973 OverloadCandidate &Candidate =
6974 CandidateSet.addCandidate(Args.size(), EarlyConversions);
6975 Candidate.FoundDecl = FoundDecl;
6976 Candidate.Function = Function;
6977 Candidate.Viable = true;
6978 Candidate.RewriteKind =
6979 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6980 Candidate.IsADLCandidate = IsADLCandidate;
6981 Candidate.ExplicitCallArguments = Args.size();
6982
6983 // Explicit functions are not actually candidates at all if we're not
6984 // allowing them in this context, but keep them around so we can point
6985 // to them in diagnostics.
6986 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6987 Candidate.Viable = false;
6988 Candidate.FailureKind = ovl_fail_explicit;
6989 return;
6990 }
6991
6992 // Functions with internal linkage are only viable in the same module unit.
6993 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
6994 /// FIXME: Currently, the semantics of linkage in clang is slightly
6995 /// different from the semantics in C++ spec. In C++ spec, only names
6996 /// have linkage. So that all entities of the same should share one
6997 /// linkage. But in clang, different entities of the same could have
6998 /// different linkage.
6999 const NamedDecl *ND = Function;
7000 bool IsImplicitlyInstantiated = false;
7001 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7002 ND = SpecInfo->getTemplate();
7003 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7005 }
7006
7007 /// Don't remove inline functions with internal linkage from the overload
7008 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7009 /// However:
7010 /// - Inline functions with internal linkage are a common pattern in
7011 /// headers to avoid ODR issues.
7012 /// - The global module is meant to be a transition mechanism for C and C++
7013 /// headers, and the current rules as written work against that goal.
7014 const bool IsInlineFunctionInGMF =
7015 Function->isFromGlobalModule() &&
7016 (IsImplicitlyInstantiated || Function->isInlined());
7017
7018 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7019 Candidate.Viable = false;
7021 return;
7022 }
7023 }
7024
7026 Candidate.Viable = false;
7028 return;
7029 }
7030
7031 if (Constructor) {
7032 // C++ [class.copy]p3:
7033 // A member function template is never instantiated to perform the copy
7034 // of a class object to an object of its class type.
7035 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
7036 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7037 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7038 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7039 ClassType))) {
7040 Candidate.Viable = false;
7042 return;
7043 }
7044
7045 // C++ [over.match.funcs]p8: (proposed DR resolution)
7046 // A constructor inherited from class type C that has a first parameter
7047 // of type "reference to P" (including such a constructor instantiated
7048 // from a template) is excluded from the set of candidate functions when
7049 // constructing an object of type cv D if the argument list has exactly
7050 // one argument and D is reference-related to P and P is reference-related
7051 // to C.
7052 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7053 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7054 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7055 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7056 QualType C = Context.getRecordType(Constructor->getParent());
7057 QualType D = Context.getRecordType(Shadow->getParent());
7058 SourceLocation Loc = Args.front()->getExprLoc();
7059 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7060 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7061 Candidate.Viable = false;
7063 return;
7064 }
7065 }
7066
7067 // Check that the constructor is capable of constructing an object in the
7068 // destination address space.
7070 Constructor->getMethodQualifiers().getAddressSpace(),
7071 CandidateSet.getDestAS(), getASTContext())) {
7072 Candidate.Viable = false;
7074 }
7075 }
7076
7077 unsigned NumParams = Proto->getNumParams();
7078
7079 // (C++ 13.3.2p2): A candidate function having fewer than m
7080 // parameters is viable only if it has an ellipsis in its parameter
7081 // list (8.3.5).
7082 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7083 !Proto->isVariadic() &&
7084 shouldEnforceArgLimit(PartialOverloading, Function)) {
7085 Candidate.Viable = false;
7087 return;
7088 }
7089
7090 // (C++ 13.3.2p2): A candidate function having more than m parameters
7091 // is viable only if the (m+1)st parameter has a default argument
7092 // (8.3.6). For the purposes of overload resolution, the
7093 // parameter list is truncated on the right, so that there are
7094 // exactly m parameters.
7095 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7096 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7097 !PartialOverloading) {
7098 // Not enough arguments.
7099 Candidate.Viable = false;
7101 return;
7102 }
7103
7104 // (CUDA B.1): Check for invalid calls between targets.
7105 if (getLangOpts().CUDA) {
7106 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7107 // Skip the check for callers that are implicit members, because in this
7108 // case we may not yet know what the member's target is; the target is
7109 // inferred for the member automatically, based on the bases and fields of
7110 // the class.
7111 if (!(Caller && Caller->isImplicit()) &&
7112 !CUDA().IsAllowedCall(Caller, Function)) {
7113 Candidate.Viable = false;
7114 Candidate.FailureKind = ovl_fail_bad_target;
7115 return;
7116 }
7117 }
7118
7119 if (Function->getTrailingRequiresClause()) {
7120 ConstraintSatisfaction Satisfaction;
7121 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7122 /*ForOverloadResolution*/ true) ||
7123 !Satisfaction.IsSatisfied) {
7124 Candidate.Viable = false;
7126 return;
7127 }
7128 }
7129
7130 // Determine the implicit conversion sequences for each of the
7131 // arguments.
7132 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7133 unsigned ConvIdx =
7134 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7135 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7136 // We already formed a conversion sequence for this parameter during
7137 // template argument deduction.
7138 } else if (ArgIdx < NumParams) {
7139 // (C++ 13.3.2p3): for F to be a viable function, there shall
7140 // exist for each argument an implicit conversion sequence
7141 // (13.3.3.1) that converts that argument to the corresponding
7142 // parameter of F.
7143 QualType ParamType = Proto->getParamType(ArgIdx);
7144 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7145 if (ParamABI == ParameterABI::HLSLOut ||
7146 ParamABI == ParameterABI::HLSLInOut)
7147 ParamType = ParamType.getNonReferenceType();
7148 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7149 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7150 /*InOverloadResolution=*/true,
7151 /*AllowObjCWritebackConversion=*/
7152 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7153 if (Candidate.Conversions[ConvIdx].isBad()) {
7154 Candidate.Viable = false;
7156 return;
7157 }
7158 } else {
7159 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7160 // argument for which there is no corresponding parameter is
7161 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7162 Candidate.Conversions[ConvIdx].setEllipsis();
7163 }
7164 }
7165
7166 if (EnableIfAttr *FailedAttr =
7167 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7168 Candidate.Viable = false;
7169 Candidate.FailureKind = ovl_fail_enable_if;
7170 Candidate.DeductionFailure.Data = FailedAttr;
7171 return;
7172 }
7173}
7174
7178 if (Methods.size() <= 1)
7179 return nullptr;
7180
7181 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7182 bool Match = true;
7183 ObjCMethodDecl *Method = Methods[b];
7184 unsigned NumNamedArgs = Sel.getNumArgs();
7185 // Method might have more arguments than selector indicates. This is due
7186 // to addition of c-style arguments in method.
7187 if (Method->param_size() > NumNamedArgs)
7188 NumNamedArgs = Method->param_size();
7189 if (Args.size() < NumNamedArgs)
7190 continue;
7191
7192 for (unsigned i = 0; i < NumNamedArgs; i++) {
7193 // We can't do any type-checking on a type-dependent argument.
7194 if (Args[i]->isTypeDependent()) {
7195 Match = false;
7196 break;
7197 }
7198
7199 ParmVarDecl *param = Method->parameters()[i];
7200 Expr *argExpr = Args[i];
7201 assert(argExpr && "SelectBestMethod(): missing expression");
7202
7203 // Strip the unbridged-cast placeholder expression off unless it's
7204 // a consumed argument.
7205 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7206 !param->hasAttr<CFConsumedAttr>())
7207 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7208
7209 // If the parameter is __unknown_anytype, move on to the next method.
7210 if (param->getType() == Context.UnknownAnyTy) {
7211 Match = false;
7212 break;
7213 }
7214
7215 ImplicitConversionSequence ConversionState
7216 = TryCopyInitialization(*this, argExpr, param->getType(),
7217 /*SuppressUserConversions*/false,
7218 /*InOverloadResolution=*/true,
7219 /*AllowObjCWritebackConversion=*/
7220 getLangOpts().ObjCAutoRefCount,
7221 /*AllowExplicit*/false);
7222 // This function looks for a reasonably-exact match, so we consider
7223 // incompatible pointer conversions to be a failure here.
7224 if (ConversionState.isBad() ||
7225 (ConversionState.isStandard() &&
7226 ConversionState.Standard.Second ==
7228 Match = false;
7229 break;
7230 }
7231 }
7232 // Promote additional arguments to variadic methods.
7233 if (Match && Method->isVariadic()) {
7234 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7235 if (Args[i]->isTypeDependent()) {
7236 Match = false;
7237 break;
7238 }
7239 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
7240 nullptr);
7241 if (Arg.isInvalid()) {
7242 Match = false;
7243 break;
7244 }
7245 }
7246 } else {
7247 // Check for extra arguments to non-variadic methods.
7248 if (Args.size() != NumNamedArgs)
7249 Match = false;
7250 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7251 // Special case when selectors have no argument. In this case, select
7252 // one with the most general result type of 'id'.
7253 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7254 QualType ReturnT = Methods[b]->getReturnType();
7255 if (ReturnT->isObjCIdType())
7256 return Methods[b];
7257 }
7258 }
7259 }
7260
7261 if (Match)
7262 return Method;
7263 }
7264 return nullptr;
7265}
7266
7268 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7269 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7270 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7271 if (ThisArg) {
7272 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7273 assert(!isa<CXXConstructorDecl>(Method) &&
7274 "Shouldn't have `this` for ctors!");
7275 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7277 ThisArg, /*Qualifier=*/nullptr, Method, Method);
7278 if (R.isInvalid())
7279 return false;
7280 ConvertedThis = R.get();
7281 } else {
7282 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7283 (void)MD;
7284 assert((MissingImplicitThis || MD->isStatic() ||
7285 isa<CXXConstructorDecl>(MD)) &&
7286 "Expected `this` for non-ctor instance methods");
7287 }
7288 ConvertedThis = nullptr;
7289 }
7290
7291 // Ignore any variadic arguments. Converting them is pointless, since the
7292 // user can't refer to them in the function condition.
7293 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7294
7295 // Convert the arguments.
7296 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7297 ExprResult R;
7299 S.Context, Function->getParamDecl(I)),
7300 SourceLocation(), Args[I]);
7301
7302 if (R.isInvalid())
7303 return false;
7304
7305 ConvertedArgs.push_back(R.get());
7306 }
7307
7308 if (Trap.hasErrorOccurred())
7309 return false;
7310
7311 // Push default arguments if needed.
7312 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7313 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7314 ParmVarDecl *P = Function->getParamDecl(i);
7315 if (!P->hasDefaultArg())
7316 return false;
7318 if (R.isInvalid())
7319 return false;
7320 ConvertedArgs.push_back(R.get());
7321 }
7322
7323 if (Trap.hasErrorOccurred())
7324 return false;
7325 }
7326 return true;
7327}
7328
7330 SourceLocation CallLoc,
7331 ArrayRef<Expr *> Args,
7332 bool MissingImplicitThis) {
7333 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7334 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7335 return nullptr;
7336
7337 SFINAETrap Trap(*this);
7338 SmallVector<Expr *, 16> ConvertedArgs;
7339 // FIXME: We should look into making enable_if late-parsed.
7340 Expr *DiscardedThis;
7342 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7343 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7344 return *EnableIfAttrs.begin();
7345
7346 for (auto *EIA : EnableIfAttrs) {
7348 // FIXME: This doesn't consider value-dependent cases, because doing so is
7349 // very difficult. Ideally, we should handle them more gracefully.
7350 if (EIA->getCond()->isValueDependent() ||
7351 !EIA->getCond()->EvaluateWithSubstitution(
7352 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7353 return EIA;
7354
7355 if (!Result.isInt() || !Result.getInt().getBoolValue())
7356 return EIA;
7357 }
7358 return nullptr;
7359}
7360
7361template <typename CheckFn>
7363 bool ArgDependent, SourceLocation Loc,
7364 CheckFn &&IsSuccessful) {
7366 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7367 if (ArgDependent == DIA->getArgDependent())
7368 Attrs.push_back(DIA);
7369 }
7370
7371 // Common case: No diagnose_if attributes, so we can quit early.
7372 if (Attrs.empty())
7373 return false;
7374
7375 auto WarningBegin = std::stable_partition(
7376 Attrs.begin(), Attrs.end(),
7377 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
7378
7379 // Note that diagnose_if attributes are late-parsed, so they appear in the
7380 // correct order (unlike enable_if attributes).
7381 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7382 IsSuccessful);
7383 if (ErrAttr != WarningBegin) {
7384 const DiagnoseIfAttr *DIA = *ErrAttr;
7385 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7386 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7387 << DIA->getParent() << DIA->getCond()->getSourceRange();
7388 return true;
7389 }
7390
7391 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7392 if (IsSuccessful(DIA)) {
7393 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7394 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7395 << DIA->getParent() << DIA->getCond()->getSourceRange();
7396 }
7397
7398 return false;
7399}
7400
7402 const Expr *ThisArg,
7404 SourceLocation Loc) {
7406 *this, Function, /*ArgDependent=*/true, Loc,
7407 [&](const DiagnoseIfAttr *DIA) {
7409 // It's sane to use the same Args for any redecl of this function, since
7410 // EvaluateWithSubstitution only cares about the position of each
7411 // argument in the arg list, not the ParmVarDecl* it maps to.
7412 if (!DIA->getCond()->EvaluateWithSubstitution(
7413 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7414 return false;
7415 return Result.isInt() && Result.getInt().getBoolValue();
7416 });
7417}
7418
7420 SourceLocation Loc) {
7422 *this, ND, /*ArgDependent=*/false, Loc,
7423 [&](const DiagnoseIfAttr *DIA) {
7424 bool Result;
7425 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7426 Result;
7427 });
7428}
7429
7431 ArrayRef<Expr *> Args,
7432 OverloadCandidateSet &CandidateSet,
7433 TemplateArgumentListInfo *ExplicitTemplateArgs,
7434 bool SuppressUserConversions,
7435 bool PartialOverloading,
7436 bool FirstArgumentIsBase) {
7437 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7438 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7439 ArrayRef<Expr *> FunctionArgs = Args;
7440
7441 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7442 FunctionDecl *FD =
7443 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7444
7445 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7446 QualType ObjectType;
7447 Expr::Classification ObjectClassification;
7448 if (Args.size() > 0) {
7449 if (Expr *E = Args[0]) {
7450 // Use the explicit base to restrict the lookup:
7451 ObjectType = E->getType();
7452 // Pointers in the object arguments are implicitly dereferenced, so we
7453 // always classify them as l-values.
7454 if (!ObjectType.isNull() && ObjectType->isPointerType())
7455 ObjectClassification = Expr::Classification::makeSimpleLValue();
7456 else
7457 ObjectClassification = E->Classify(Context);
7458 } // .. else there is an implicit base.
7459 FunctionArgs = Args.slice(1);
7460 }
7461 if (FunTmpl) {
7462 AddMethodTemplateCandidate(
7463 FunTmpl, F.getPair(),
7464 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
7465 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7466 FunctionArgs, CandidateSet, SuppressUserConversions,
7467 PartialOverloading);
7468 } else {
7469 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7470 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7471 ObjectClassification, FunctionArgs, CandidateSet,
7472 SuppressUserConversions, PartialOverloading);
7473 }
7474 } else {
7475 // This branch handles both standalone functions and static methods.
7476
7477 // Slice the first argument (which is the base) when we access
7478 // static method as non-static.
7479 if (Args.size() > 0 &&
7480 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7481 !isa<CXXConstructorDecl>(FD)))) {
7482 assert(cast<CXXMethodDecl>(FD)->isStatic());
7483 FunctionArgs = Args.slice(1);
7484 }
7485 if (FunTmpl) {
7486 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7487 ExplicitTemplateArgs, FunctionArgs,
7488 CandidateSet, SuppressUserConversions,
7489 PartialOverloading);
7490 } else {
7491 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7492 SuppressUserConversions, PartialOverloading);
7493 }
7494 }
7495 }
7496}
7497
7499 Expr::Classification ObjectClassification,
7500 ArrayRef<Expr *> Args,
7501 OverloadCandidateSet &CandidateSet,
7502 bool SuppressUserConversions,
7504 NamedDecl *Decl = FoundDecl.getDecl();
7505 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
7506
7507 if (isa<UsingShadowDecl>(Decl))
7508 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7509
7510 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7511 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7512 "Expected a member function template");
7513 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7514 /*ExplicitArgs*/ nullptr, ObjectType,
7515 ObjectClassification, Args, CandidateSet,
7516 SuppressUserConversions, false, PO);
7517 } else {
7518 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7519 ObjectType, ObjectClassification, Args, CandidateSet,
7520 SuppressUserConversions, false, {}, PO);
7521 }
7522}
7523
7524void
7526 CXXRecordDecl *ActingContext, QualType ObjectType,
7527 Expr::Classification ObjectClassification,
7528 ArrayRef<Expr *> Args,
7529 OverloadCandidateSet &CandidateSet,
7530 bool SuppressUserConversions,
7531 bool PartialOverloading,
7532 ConversionSequenceList EarlyConversions,
7534 const FunctionProtoType *Proto
7535 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7536 assert(Proto && "Methods without a prototype cannot be overloaded");
7537 assert(!isa<CXXConstructorDecl>(Method) &&
7538 "Use AddOverloadCandidate for constructors");
7539
7540 if (!CandidateSet.isNewCandidate(Method, PO))
7541 return;
7542
7543 // C++11 [class.copy]p23: [DR1402]
7544 // A defaulted move assignment operator that is defined as deleted is
7545 // ignored by overload resolution.
7546 if (Method->isDefaulted() && Method->isDeleted() &&
7547 Method->isMoveAssignmentOperator())
7548 return;
7549
7550 // Overload resolution is always an unevaluated context.
7553
7554 // Add this candidate
7555 OverloadCandidate &Candidate =
7556 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
7557 Candidate.FoundDecl = FoundDecl;
7558 Candidate.Function = Method;
7559 Candidate.RewriteKind =
7560 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7561 Candidate.TookAddressOfOverload =
7563 Candidate.ExplicitCallArguments = Args.size();
7564
7565 bool IgnoreExplicitObject =
7566 (Method->isExplicitObjectMemberFunction() &&
7567 CandidateSet.getKind() ==
7569 bool ImplicitObjectMethodTreatedAsStatic =
7570 CandidateSet.getKind() ==
7573
7574 unsigned ExplicitOffset =
7575 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7576
7577 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7578 int(ImplicitObjectMethodTreatedAsStatic);
7579
7580 // (C++ 13.3.2p2): A candidate function having fewer than m
7581 // parameters is viable only if it has an ellipsis in its parameter
7582 // list (8.3.5).
7583 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7584 !Proto->isVariadic() &&
7585 shouldEnforceArgLimit(PartialOverloading, Method)) {
7586 Candidate.Viable = false;
7588 return;
7589 }
7590
7591 // (C++ 13.3.2p2): A candidate function having more than m parameters
7592 // is viable only if the (m+1)st parameter has a default argument
7593 // (8.3.6). For the purposes of overload resolution, the
7594 // parameter list is truncated on the right, so that there are
7595 // exactly m parameters.
7596 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7597 ExplicitOffset +
7598 int(ImplicitObjectMethodTreatedAsStatic);
7599
7600 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7601 // Not enough arguments.
7602 Candidate.Viable = false;
7604 return;
7605 }
7606
7607 Candidate.Viable = true;
7608
7609 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7610 if (ObjectType.isNull())
7611 Candidate.IgnoreObjectArgument = true;
7612 else if (Method->isStatic()) {
7613 // [over.best.ics.general]p8
7614 // When the parameter is the implicit object parameter of a static member
7615 // function, the implicit conversion sequence is a standard conversion
7616 // sequence that is neither better nor worse than any other standard
7617 // conversion sequence.
7618 //
7619 // This is a rule that was introduced in C++23 to support static lambdas. We
7620 // apply it retroactively because we want to support static lambdas as an
7621 // extension and it doesn't hurt previous code.
7622 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7623 } else {
7624 // Determine the implicit conversion sequence for the object
7625 // parameter.
7626 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7627 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7628 Method, ActingContext, /*InOverloadResolution=*/true);
7629 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7630 Candidate.Viable = false;
7632 return;
7633 }
7634 }
7635
7636 // (CUDA B.1): Check for invalid calls between targets.
7637 if (getLangOpts().CUDA)
7638 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
7639 Method)) {
7640 Candidate.Viable = false;
7641 Candidate.FailureKind = ovl_fail_bad_target;
7642 return;
7643 }
7644
7645 if (Method->getTrailingRequiresClause()) {
7646 ConstraintSatisfaction Satisfaction;
7647 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7648 /*ForOverloadResolution*/ true) ||
7649 !Satisfaction.IsSatisfied) {
7650 Candidate.Viable = false;
7652 return;
7653 }
7654 }
7655
7656 // Determine the implicit conversion sequences for each of the
7657 // arguments.
7658 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7659 unsigned ConvIdx =
7660 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7661 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7662 // We already formed a conversion sequence for this parameter during
7663 // template argument deduction.
7664 } else if (ArgIdx < NumParams) {
7665 // (C++ 13.3.2p3): for F to be a viable function, there shall
7666 // exist for each argument an implicit conversion sequence
7667 // (13.3.3.1) that converts that argument to the corresponding
7668 // parameter of F.
7669 QualType ParamType;
7670 if (ImplicitObjectMethodTreatedAsStatic) {
7671 ParamType = ArgIdx == 0
7673 : Proto->getParamType(ArgIdx - 1);
7674 } else {
7675 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
7676 }
7677 Candidate.Conversions[ConvIdx]
7678 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7679 SuppressUserConversions,
7680 /*InOverloadResolution=*/true,
7681 /*AllowObjCWritebackConversion=*/
7682 getLangOpts().ObjCAutoRefCount);
7683 if (Candidate.Conversions[ConvIdx].isBad()) {
7684 Candidate.Viable = false;
7686 return;
7687 }
7688 } else {
7689 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7690 // argument for which there is no corresponding parameter is
7691 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7692 Candidate.Conversions[ConvIdx].setEllipsis();
7693 }
7694 }
7695
7696 if (EnableIfAttr *FailedAttr =
7697 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7698 Candidate.Viable = false;
7699 Candidate.FailureKind = ovl_fail_enable_if;
7700 Candidate.DeductionFailure.Data = FailedAttr;
7701 return;
7702 }
7703
7704 if (isNonViableMultiVersionOverload(Method)) {
7705 Candidate.Viable = false;
7707 }
7708}
7709
7711 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7712 CXXRecordDecl *ActingContext,
7713 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7714 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7715 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7716 bool PartialOverloading, OverloadCandidateParamOrder PO) {
7717 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7718 return;
7719
7720 // C++ [over.match.funcs]p7:
7721 // In each case where a candidate is a function template, candidate
7722 // function template specializations are generated using template argument
7723 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7724 // candidate functions in the usual way.113) A given name can refer to one
7725 // or more function templates and also to a set of overloaded non-template
7726 // functions. In such a case, the candidate functions generated from each
7727 // function template are combined with the set of non-template candidate
7728 // functions.
7729 TemplateDeductionInfo Info(CandidateSet.getLocation());
7730 FunctionDecl *Specialization = nullptr;
7731 ConversionSequenceList Conversions;
7733 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7734 PartialOverloading, /*AggregateDeductionCandidate=*/false, ObjectType,
7735 ObjectClassification,
7736 [&](ArrayRef<QualType> ParamTypes) {
7737 return CheckNonDependentConversions(
7738 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7739 SuppressUserConversions, ActingContext, ObjectType,
7740 ObjectClassification, PO);
7741 });
7743 OverloadCandidate &Candidate =
7744 CandidateSet.addCandidate(Conversions.size(), Conversions);
7745 Candidate.FoundDecl = FoundDecl;
7746 Candidate.Function = MethodTmpl->getTemplatedDecl();
7747 Candidate.Viable = false;
7748 Candidate.RewriteKind =
7749 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7750 Candidate.IsSurrogate = false;
7751 Candidate.IgnoreObjectArgument =
7752 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7753 ObjectType.isNull();
7754 Candidate.ExplicitCallArguments = Args.size();
7757 else {
7760 Info);
7761 }
7762 return;
7763 }
7764
7765 // Add the function template specialization produced by template argument
7766 // deduction as a candidate.
7767 assert(Specialization && "Missing member function template specialization?");
7768 assert(isa<CXXMethodDecl>(Specialization) &&
7769 "Specialization is not a member function?");
7770 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7771 ActingContext, ObjectType, ObjectClassification, Args,
7772 CandidateSet, SuppressUserConversions, PartialOverloading,
7773 Conversions, PO);
7774}
7775
7776/// Determine whether a given function template has a simple explicit specifier
7777/// or a non-value-dependent explicit-specification that evaluates to true.
7780}
7781
7783 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7784 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7785 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7786 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7787 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
7788 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7789 return;
7790
7791 // If the function template has a non-dependent explicit specification,
7792 // exclude it now if appropriate; we are not permitted to perform deduction
7793 // and substitution in this case.
7794 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7795 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7796 Candidate.FoundDecl = FoundDecl;
7797 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7798 Candidate.Viable = false;
7799 Candidate.FailureKind = ovl_fail_explicit;
7800 return;
7801 }
7802
7803 // C++ [over.match.funcs]p7:
7804 // In each case where a candidate is a function template, candidate
7805 // function template specializations are generated using template argument
7806 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7807 // candidate functions in the usual way.113) A given name can refer to one
7808 // or more function templates and also to a set of overloaded non-template
7809 // functions. In such a case, the candidate functions generated from each
7810 // function template are combined with the set of non-template candidate
7811 // functions.
7812 TemplateDeductionInfo Info(CandidateSet.getLocation(),
7813 FunctionTemplate->getTemplateDepth());
7814 FunctionDecl *Specialization = nullptr;
7815 ConversionSequenceList Conversions;
7817 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7818 PartialOverloading, AggregateCandidateDeduction,
7819 /*ObjectType=*/QualType(),
7820 /*ObjectClassification=*/Expr::Classification(),
7821 [&](ArrayRef<QualType> ParamTypes) {
7822 return CheckNonDependentConversions(
7823 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7824 SuppressUserConversions, nullptr, QualType(), {}, PO);
7825 });
7827 OverloadCandidate &Candidate =
7828 CandidateSet.addCandidate(Conversions.size(), Conversions);
7829 Candidate.FoundDecl = FoundDecl;
7830 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7831 Candidate.Viable = false;
7832 Candidate.RewriteKind =
7833 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7834 Candidate.IsSurrogate = false;
7835 Candidate.IsADLCandidate = IsADLCandidate;
7836 // Ignore the object argument if there is one, since we don't have an object
7837 // type.
7838 Candidate.IgnoreObjectArgument =
7839 isa<CXXMethodDecl>(Candidate.Function) &&
7840 !isa<CXXConstructorDecl>(Candidate.Function);
7841 Candidate.ExplicitCallArguments = Args.size();
7844 else {
7847 Info);
7848 }
7849 return;
7850 }
7851
7852 // Add the function template specialization produced by template argument
7853 // deduction as a candidate.
7854 assert(Specialization && "Missing function template specialization?");
7855 AddOverloadCandidate(
7856 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7857 PartialOverloading, AllowExplicit,
7858 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
7860}
7861
7863 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7864 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7865 ConversionSequenceList &Conversions, bool SuppressUserConversions,
7866 CXXRecordDecl *ActingContext, QualType ObjectType,
7867 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7868 // FIXME: The cases in which we allow explicit conversions for constructor
7869 // arguments never consider calling a constructor template. It's not clear
7870 // that is correct.
7871 const bool AllowExplicit = false;
7872
7873 auto *FD = FunctionTemplate->getTemplatedDecl();
7874 auto *Method = dyn_cast<CXXMethodDecl>(FD);
7875 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7876 unsigned ThisConversions = HasThisConversion ? 1 : 0;
7877
7878 Conversions =
7879 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7880
7881 // Overload resolution is always an unevaluated context.
7884
7885 // For a method call, check the 'this' conversion here too. DR1391 doesn't
7886 // require that, but this check should never result in a hard error, and
7887 // overload resolution is permitted to sidestep instantiations.
7888 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7889 !ObjectType.isNull()) {
7890 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7891 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
7892 !ParamTypes[0]->isDependentType()) {
7893 Conversions[ConvIdx] = TryObjectArgumentInitialization(
7894 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7895 Method, ActingContext, /*InOverloadResolution=*/true,
7896 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
7897 : QualType());
7898 if (Conversions[ConvIdx].isBad())
7899 return true;
7900 }
7901 }
7902
7903 unsigned Offset =
7904 Method && Method->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
7905
7906 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
7907 I != N; ++I) {
7908 QualType ParamType = ParamTypes[I + Offset];
7909 if (!ParamType->isDependentType()) {
7910 unsigned ConvIdx;
7912 ConvIdx = Args.size() - 1 - I;
7913 assert(Args.size() + ThisConversions == 2 &&
7914 "number of args (including 'this') must be exactly 2 for "
7915 "reversed order");
7916 // For members, there would be only one arg 'Args[0]' whose ConvIdx
7917 // would also be 0. 'this' got ConvIdx = 1 previously.
7918 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
7919 } else {
7920 // For members, 'this' got ConvIdx = 0 previously.
7921 ConvIdx = ThisConversions + I;
7922 }
7923 Conversions[ConvIdx]
7924 = TryCopyInitialization(*this, Args[I], ParamType,
7925 SuppressUserConversions,
7926 /*InOverloadResolution=*/true,
7927 /*AllowObjCWritebackConversion=*/
7928 getLangOpts().ObjCAutoRefCount,
7929 AllowExplicit);
7930 if (Conversions[ConvIdx].isBad())
7931 return true;
7932 }
7933 }
7934
7935 return false;
7936}
7937
7938/// Determine whether this is an allowable conversion from the result
7939/// of an explicit conversion operator to the expected type, per C++
7940/// [over.match.conv]p1 and [over.match.ref]p1.
7941///
7942/// \param ConvType The return type of the conversion function.
7943///
7944/// \param ToType The type we are converting to.
7945///
7946/// \param AllowObjCPointerConversion Allow a conversion from one
7947/// Objective-C pointer to another.
7948///
7949/// \returns true if the conversion is allowable, false otherwise.
7951 QualType ConvType, QualType ToType,
7952 bool AllowObjCPointerConversion) {
7953 QualType ToNonRefType = ToType.getNonReferenceType();
7954
7955 // Easy case: the types are the same.
7956 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7957 return true;
7958
7959 // Allow qualification conversions.
7960 bool ObjCLifetimeConversion;
7961 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7962 ObjCLifetimeConversion))
7963 return true;
7964
7965 // If we're not allowed to consider Objective-C pointer conversions,
7966 // we're done.
7967 if (!AllowObjCPointerConversion)
7968 return false;
7969
7970 // Is this an Objective-C pointer conversion?
7971 bool IncompatibleObjC = false;
7972 QualType ConvertedType;
7973 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7974 IncompatibleObjC);
7975}
7976
7978 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7979 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7980 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7981 bool AllowExplicit, bool AllowResultConversion) {
7982 assert(!Conversion->getDescribedFunctionTemplate() &&
7983 "Conversion function templates use AddTemplateConversionCandidate");
7984 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7985 if (!CandidateSet.isNewCandidate(Conversion))
7986 return;
7987
7988 // If the conversion function has an undeduced return type, trigger its
7989 // deduction now.
7990 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7991 if (DeduceReturnType(Conversion, From->getExprLoc()))
7992 return;
7993 ConvType = Conversion->getConversionType().getNonReferenceType();
7994 }
7995
7996 // If we don't allow any conversion of the result type, ignore conversion
7997 // functions that don't convert to exactly (possibly cv-qualified) T.
7998 if (!AllowResultConversion &&
7999 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
8000 return;
8001
8002 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8003 // operator is only a candidate if its return type is the target type or
8004 // can be converted to the target type with a qualification conversion.
8005 //
8006 // FIXME: Include such functions in the candidate list and explain why we
8007 // can't select them.
8008 if (Conversion->isExplicit() &&
8009 !isAllowableExplicitConversion(*this, ConvType, ToType,
8010 AllowObjCConversionOnExplicit))
8011 return;
8012
8013 // Overload resolution is always an unevaluated context.
8016
8017 // Add this candidate
8018 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8019 Candidate.FoundDecl = FoundDecl;
8020 Candidate.Function = Conversion;
8022 Candidate.FinalConversion.setFromType(ConvType);
8023 Candidate.FinalConversion.setAllToTypes(ToType);
8024 Candidate.Viable = true;
8025 Candidate.ExplicitCallArguments = 1;
8026
8027 // Explicit functions are not actually candidates at all if we're not
8028 // allowing them in this context, but keep them around so we can point
8029 // to them in diagnostics.
8030 if (!AllowExplicit && Conversion->isExplicit()) {
8031 Candidate.Viable = false;
8032 Candidate.FailureKind = ovl_fail_explicit;
8033 return;
8034 }
8035
8036 // C++ [over.match.funcs]p4:
8037 // For conversion functions, the function is considered to be a member of
8038 // the class of the implicit implied object argument for the purpose of
8039 // defining the type of the implicit object parameter.
8040 //
8041 // Determine the implicit conversion sequence for the implicit
8042 // object parameter.
8043 QualType ObjectType = From->getType();
8044 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8045 ObjectType = FromPtrType->getPointeeType();
8046 const auto *ConversionContext =
8047 cast<CXXRecordDecl>(ObjectType->castAs<RecordType>()->getDecl());
8048
8049 // C++23 [over.best.ics.general]
8050 // However, if the target is [...]
8051 // - the object parameter of a user-defined conversion function
8052 // [...] user-defined conversion sequences are not considered.
8054 *this, CandidateSet.getLocation(), From->getType(),
8055 From->Classify(Context), Conversion, ConversionContext,
8056 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8057 /*SuppressUserConversion*/ true);
8058
8059 if (Candidate.Conversions[0].isBad()) {
8060 Candidate.Viable = false;
8062 return;
8063 }
8064
8065 if (Conversion->getTrailingRequiresClause()) {
8066 ConstraintSatisfaction Satisfaction;
8067 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8068 !Satisfaction.IsSatisfied) {
8069 Candidate.Viable = false;
8071 return;
8072 }
8073 }
8074
8075 // We won't go through a user-defined type conversion function to convert a
8076 // derived to base as such conversions are given Conversion Rank. They only
8077 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8078 QualType FromCanon
8079 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8080 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8081 if (FromCanon == ToCanon ||
8082 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8083 Candidate.Viable = false;
8085 return;
8086 }
8087
8088 // To determine what the conversion from the result of calling the
8089 // conversion function to the type we're eventually trying to
8090 // convert to (ToType), we need to synthesize a call to the
8091 // conversion function and attempt copy initialization from it. This
8092 // makes sure that we get the right semantics with respect to
8093 // lvalues/rvalues and the type. Fortunately, we can allocate this
8094 // call on the stack and we don't need its arguments to be
8095 // well-formed.
8096 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8097 VK_LValue, From->getBeginLoc());
8099 Context.getPointerType(Conversion->getType()),
8100 CK_FunctionToPointerDecay, &ConversionRef,
8102
8103 QualType ConversionType = Conversion->getConversionType();
8104 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8105 Candidate.Viable = false;
8107 return;
8108 }
8109
8110 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8111
8112 // Note that it is safe to allocate CallExpr on the stack here because
8113 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
8114 // allocator).
8115 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8116
8117 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
8118 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
8119 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
8120
8122 TryCopyInitialization(*this, TheTemporaryCall, ToType,
8123 /*SuppressUserConversions=*/true,
8124 /*InOverloadResolution=*/false,
8125 /*AllowObjCWritebackConversion=*/false);
8126
8127 switch (ICS.getKind()) {
8129 Candidate.FinalConversion = ICS.Standard;
8130
8131 // C++ [over.ics.user]p3:
8132 // If the user-defined conversion is specified by a specialization of a
8133 // conversion function template, the second standard conversion sequence
8134 // shall have exact match rank.
8135 if (Conversion->getPrimaryTemplate() &&
8137 Candidate.Viable = false;
8139 return;
8140 }
8141
8142 // C++0x [dcl.init.ref]p5:
8143 // In the second case, if the reference is an rvalue reference and
8144 // the second standard conversion sequence of the user-defined
8145 // conversion sequence includes an lvalue-to-rvalue conversion, the
8146 // program is ill-formed.
8147 if (ToType->isRValueReferenceType() &&
8149 Candidate.Viable = false;
8151 return;
8152 }
8153 break;
8154
8156 Candidate.Viable = false;
8158 return;
8159
8160 default:
8161 llvm_unreachable(
8162 "Can only end up with a standard conversion sequence or failure");
8163 }
8164
8165 if (EnableIfAttr *FailedAttr =
8166 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8167 Candidate.Viable = false;
8168 Candidate.FailureKind = ovl_fail_enable_if;
8169 Candidate.DeductionFailure.Data = FailedAttr;
8170 return;
8171 }
8172
8173 if (isNonViableMultiVersionOverload(Conversion)) {
8174 Candidate.Viable = false;
8176 }
8177}
8178
8180 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8181 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8182 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8183 bool AllowExplicit, bool AllowResultConversion) {
8184 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8185 "Only conversion function templates permitted here");
8186
8187 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8188 return;
8189
8190 // If the function template has a non-dependent explicit specification,
8191 // exclude it now if appropriate; we are not permitted to perform deduction
8192 // and substitution in this case.
8193 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8194 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8195 Candidate.FoundDecl = FoundDecl;
8196 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8197 Candidate.Viable = false;
8198 Candidate.FailureKind = ovl_fail_explicit;
8199 return;
8200 }
8201
8202 QualType ObjectType = From->getType();
8203 Expr::Classification ObjectClassification = From->Classify(getASTContext());
8204
8205 TemplateDeductionInfo Info(CandidateSet.getLocation());
8208 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8209 Specialization, Info);
8211 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8212 Candidate.FoundDecl = FoundDecl;
8213 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8214 Candidate.Viable = false;
8216 Candidate.ExplicitCallArguments = 1;
8218 Info);
8219 return;
8220 }
8221
8222 // Add the conversion function template specialization produced by
8223 // template argument deduction as a candidate.
8224 assert(Specialization && "Missing function template specialization?");
8225 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
8226 CandidateSet, AllowObjCConversionOnExplicit,
8227 AllowExplicit, AllowResultConversion);
8228}
8229
8231 DeclAccessPair FoundDecl,
8232 CXXRecordDecl *ActingContext,
8233 const FunctionProtoType *Proto,
8234 Expr *Object,
8235 ArrayRef<Expr *> Args,
8236 OverloadCandidateSet& CandidateSet) {
8237 if (!CandidateSet.isNewCandidate(Conversion))
8238 return;
8239
8240 // Overload resolution is always an unevaluated context.
8243
8244 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8245 Candidate.FoundDecl = FoundDecl;
8246 Candidate.Function = nullptr;
8247 Candidate.Surrogate = Conversion;
8248 Candidate.IsSurrogate = true;
8249 Candidate.Viable = true;
8250 Candidate.ExplicitCallArguments = Args.size();
8251
8252 // Determine the implicit conversion sequence for the implicit
8253 // object parameter.
8254 ImplicitConversionSequence ObjectInit;
8255 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8256 ObjectInit = TryCopyInitialization(*this, Object,
8257 Conversion->getParamDecl(0)->getType(),
8258 /*SuppressUserConversions=*/false,
8259 /*InOverloadResolution=*/true, false);
8260 } else {
8262 *this, CandidateSet.getLocation(), Object->getType(),
8263 Object->Classify(Context), Conversion, ActingContext);
8264 }
8265
8266 if (ObjectInit.isBad()) {
8267 Candidate.Viable = false;
8269 Candidate.Conversions[0] = ObjectInit;
8270 return;
8271 }
8272
8273 // The first conversion is actually a user-defined conversion whose
8274 // first conversion is ObjectInit's standard conversion (which is
8275 // effectively a reference binding). Record it as such.
8276 Candidate.Conversions[0].setUserDefined();
8277 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8278 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8279 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8280 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8281 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8282 Candidate.Conversions[0].UserDefined.After
8283 = Candidate.Conversions[0].UserDefined.Before;
8284 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8285
8286 // Find the
8287 unsigned NumParams = Proto->getNumParams();
8288
8289 // (C++ 13.3.2p2): A candidate function having fewer than m
8290 // parameters is viable only if it has an ellipsis in its parameter
8291 // list (8.3.5).
8292 if (Args.size() > NumParams && !Proto->isVariadic()) {
8293 Candidate.Viable = false;
8295 return;
8296 }
8297
8298 // Function types don't have any default arguments, so just check if
8299 // we have enough arguments.
8300 if (Args.size() < NumParams) {
8301 // Not enough arguments.
8302 Candidate.Viable = false;
8304 return;
8305 }
8306
8307 // Determine the implicit conversion sequences for each of the
8308 // arguments.
8309 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8310 if (ArgIdx < NumParams) {
8311 // (C++ 13.3.2p3): for F to be a viable function, there shall
8312 // exist for each argument an implicit conversion sequence
8313 // (13.3.3.1) that converts that argument to the corresponding
8314 // parameter of F.
8315 QualType ParamType = Proto->getParamType(ArgIdx);
8316 Candidate.Conversions[ArgIdx + 1]
8317 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8318 /*SuppressUserConversions=*/false,
8319 /*InOverloadResolution=*/false,
8320 /*AllowObjCWritebackConversion=*/
8321 getLangOpts().ObjCAutoRefCount);
8322 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8323 Candidate.Viable = false;
8325 return;
8326 }
8327 } else {
8328 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8329 // argument for which there is no corresponding parameter is
8330 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8331 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8332 }
8333 }
8334
8335 if (Conversion->getTrailingRequiresClause()) {
8336 ConstraintSatisfaction Satisfaction;
8337 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8338 /*ForOverloadResolution*/ true) ||
8339 !Satisfaction.IsSatisfied) {
8340 Candidate.Viable = false;
8342 return;
8343 }
8344 }
8345
8346 if (EnableIfAttr *FailedAttr =
8347 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8348 Candidate.Viable = false;
8349 Candidate.FailureKind = ovl_fail_enable_if;
8350 Candidate.DeductionFailure.Data = FailedAttr;
8351 return;
8352 }
8353}
8354
8356 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8357 OverloadCandidateSet &CandidateSet,
8358 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8359 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8360 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8361 ArrayRef<Expr *> FunctionArgs = Args;
8362
8363 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8364 FunctionDecl *FD =
8365 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8366
8367 // Don't consider rewritten functions if we're not rewriting.
8368 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8369 continue;
8370
8371 assert(!isa<CXXMethodDecl>(FD) &&
8372 "unqualified operator lookup found a member function");
8373
8374 if (FunTmpl) {
8375 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8376 FunctionArgs, CandidateSet);
8377 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8378 AddTemplateOverloadCandidate(
8379 FunTmpl, F.getPair(), ExplicitTemplateArgs,
8380 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
8381 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
8382 } else {
8383 if (ExplicitTemplateArgs)
8384 continue;
8385 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8386 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8387 AddOverloadCandidate(FD, F.getPair(),
8388 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8389 false, false, true, false, ADLCallKind::NotADL, {},
8391 }
8392 }
8393}
8394
8396 SourceLocation OpLoc,
8397 ArrayRef<Expr *> Args,
8398 OverloadCandidateSet &CandidateSet,
8401
8402 // C++ [over.match.oper]p3:
8403 // For a unary operator @ with an operand of a type whose
8404 // cv-unqualified version is T1, and for a binary operator @ with
8405 // a left operand of a type whose cv-unqualified version is T1 and
8406 // a right operand of a type whose cv-unqualified version is T2,
8407 // three sets of candidate functions, designated member
8408 // candidates, non-member candidates and built-in candidates, are
8409 // constructed as follows:
8410 QualType T1 = Args[0]->getType();
8411
8412 // -- If T1 is a complete class type or a class currently being
8413 // defined, the set of member candidates is the result of the
8414 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8415 // the set of member candidates is empty.
8416 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
8417 // Complete the type if it can be completed.
8418 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
8419 return;
8420 // If the type is neither complete nor being defined, bail out now.
8421 if (!T1Rec->getDecl()->getDefinition())
8422 return;
8423
8424 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8425 LookupQualifiedName(Operators, T1Rec->getDecl());
8426 Operators.suppressAccessDiagnostics();
8427
8428 for (LookupResult::iterator Oper = Operators.begin(),
8429 OperEnd = Operators.end();
8430 Oper != OperEnd; ++Oper) {
8431 if (Oper->getAsFunction() &&
8433 !CandidateSet.getRewriteInfo().shouldAddReversed(
8434 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8435 continue;
8436 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8437 Args[0]->Classify(Context), Args.slice(1),
8438 CandidateSet, /*SuppressUserConversion=*/false, PO);
8439 }
8440 }
8441}
8442
8444 OverloadCandidateSet& CandidateSet,
8445 bool IsAssignmentOperator,
8446 unsigned NumContextualBoolArguments) {
8447 // Overload resolution is always an unevaluated context.
8450
8451 // Add this candidate
8452 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8453 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8454 Candidate.Function = nullptr;
8455 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8456
8457 // Determine the implicit conversion sequences for each of the
8458 // arguments.
8459 Candidate.Viable = true;
8460 Candidate.ExplicitCallArguments = Args.size();
8461 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8462 // C++ [over.match.oper]p4:
8463 // For the built-in assignment operators, conversions of the
8464 // left operand are restricted as follows:
8465 // -- no temporaries are introduced to hold the left operand, and
8466 // -- no user-defined conversions are applied to the left
8467 // operand to achieve a type match with the left-most
8468 // parameter of a built-in candidate.
8469 //
8470 // We block these conversions by turning off user-defined
8471 // conversions, since that is the only way that initialization of
8472 // a reference to a non-class type can occur from something that
8473 // is not of the same type.
8474 if (ArgIdx < NumContextualBoolArguments) {
8475 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8476 "Contextual conversion to bool requires bool type");
8477 Candidate.Conversions[ArgIdx]
8478 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
8479 } else {
8480 Candidate.Conversions[ArgIdx]
8481 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
8482 ArgIdx == 0 && IsAssignmentOperator,
8483 /*InOverloadResolution=*/false,
8484 /*AllowObjCWritebackConversion=*/
8485 getLangOpts().ObjCAutoRefCount);
8486 }
8487 if (Candidate.Conversions[ArgIdx].isBad()) {
8488 Candidate.Viable = false;
8490 break;
8491 }
8492 }
8493}
8494
8495namespace {
8496
8497/// BuiltinCandidateTypeSet - A set of types that will be used for the
8498/// candidate operator functions for built-in operators (C++
8499/// [over.built]). The types are separated into pointer types and
8500/// enumeration types.
8501class BuiltinCandidateTypeSet {
8502 /// TypeSet - A set of types.
8503 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8504
8505 /// PointerTypes - The set of pointer types that will be used in the
8506 /// built-in candidates.
8507 TypeSet PointerTypes;
8508
8509 /// MemberPointerTypes - The set of member pointer types that will be
8510 /// used in the built-in candidates.
8511 TypeSet MemberPointerTypes;
8512
8513 /// EnumerationTypes - The set of enumeration types that will be
8514 /// used in the built-in candidates.
8515 TypeSet EnumerationTypes;
8516
8517 /// The set of vector types that will be used in the built-in
8518 /// candidates.
8519 TypeSet VectorTypes;
8520
8521 /// The set of matrix types that will be used in the built-in
8522 /// candidates.
8523 TypeSet MatrixTypes;
8524
8525 /// The set of _BitInt types that will be used in the built-in candidates.
8526 TypeSet BitIntTypes;
8527
8528 /// A flag indicating non-record types are viable candidates
8529 bool HasNonRecordTypes;
8530
8531 /// A flag indicating whether either arithmetic or enumeration types
8532 /// were present in the candidate set.
8533 bool HasArithmeticOrEnumeralTypes;
8534
8535 /// A flag indicating whether the nullptr type was present in the
8536 /// candidate set.
8537 bool HasNullPtrType;
8538
8539 /// Sema - The semantic analysis instance where we are building the
8540 /// candidate type set.
8541 Sema &SemaRef;
8542
8543 /// Context - The AST context in which we will build the type sets.
8544 ASTContext &Context;
8545
8546 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8547 const Qualifiers &VisibleQuals);
8548 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8549
8550public:
8551 /// iterator - Iterates through the types that are part of the set.
8552 typedef TypeSet::iterator iterator;
8553
8554 BuiltinCandidateTypeSet(Sema &SemaRef)
8555 : HasNonRecordTypes(false),
8556 HasArithmeticOrEnumeralTypes(false),
8557 HasNullPtrType(false),
8558 SemaRef(SemaRef),
8559 Context(SemaRef.Context) { }
8560
8561 void AddTypesConvertedFrom(QualType Ty,
8563 bool AllowUserConversions,
8564 bool AllowExplicitConversions,
8565 const Qualifiers &VisibleTypeConversionsQuals);
8566
8567 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8568 llvm::iterator_range<iterator> member_pointer_types() {
8569 return MemberPointerTypes;
8570 }
8571 llvm::iterator_range<iterator> enumeration_types() {
8572 return EnumerationTypes;
8573 }
8574 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8575 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8576 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8577
8578 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
8579 bool hasNonRecordTypes() { return HasNonRecordTypes; }
8580 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8581 bool hasNullPtrType() const { return HasNullPtrType; }
8582};
8583
8584} // end anonymous namespace
8585
8586/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8587/// the set of pointer types along with any more-qualified variants of
8588/// that type. For example, if @p Ty is "int const *", this routine
8589/// will add "int const *", "int const volatile *", "int const
8590/// restrict *", and "int const volatile restrict *" to the set of
8591/// pointer types. Returns true if the add of @p Ty itself succeeded,
8592/// false otherwise.
8593///
8594/// FIXME: what to do about extended qualifiers?
8595bool
8596BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8597 const Qualifiers &VisibleQuals) {
8598
8599 // Insert this type.
8600 if (!PointerTypes.insert(Ty))
8601 return false;
8602
8603 QualType PointeeTy;
8604 const PointerType *PointerTy = Ty->getAs<PointerType>();
8605 bool buildObjCPtr = false;
8606 if (!PointerTy) {
8608 PointeeTy = PTy->getPointeeType();
8609 buildObjCPtr = true;
8610 } else {
8611 PointeeTy = PointerTy->getPointeeType();
8612 }
8613
8614 // Don't add qualified variants of arrays. For one, they're not allowed
8615 // (the qualifier would sink to the element type), and for another, the
8616 // only overload situation where it matters is subscript or pointer +- int,
8617 // and those shouldn't have qualifier variants anyway.
8618 if (PointeeTy->isArrayType())
8619 return true;
8620
8621 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8622 bool hasVolatile = VisibleQuals.hasVolatile();
8623 bool hasRestrict = VisibleQuals.hasRestrict();
8624
8625 // Iterate through all strict supersets of BaseCVR.
8626 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8627 if ((CVR | BaseCVR) != CVR) continue;
8628 // Skip over volatile if no volatile found anywhere in the types.
8629 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8630
8631 // Skip over restrict if no restrict found anywhere in the types, or if
8632 // the type cannot be restrict-qualified.
8633 if ((CVR & Qualifiers::Restrict) &&
8634 (!hasRestrict ||
8635 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8636 continue;
8637
8638 // Build qualified pointee type.
8639 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8640
8641 // Build qualified pointer type.
8642 QualType QPointerTy;
8643 if (!buildObjCPtr)
8644 QPointerTy = Context.getPointerType(QPointeeTy);
8645 else
8646 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8647
8648 // Insert qualified pointer type.
8649 PointerTypes.insert(QPointerTy);
8650 }
8651
8652 return true;
8653}
8654
8655/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8656/// to the set of pointer types along with any more-qualified variants of
8657/// that type. For example, if @p Ty is "int const *", this routine
8658/// will add "int const *", "int const volatile *", "int const
8659/// restrict *", and "int const volatile restrict *" to the set of
8660/// pointer types. Returns true if the add of @p Ty itself succeeded,
8661/// false otherwise.
8662///
8663/// FIXME: what to do about extended qualifiers?
8664bool
8665BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8666 QualType Ty) {
8667 // Insert this type.
8668 if (!MemberPointerTypes.insert(Ty))
8669 return false;
8670
8671 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8672 assert(PointerTy && "type was not a member pointer type!");
8673
8674 QualType PointeeTy = PointerTy->getPointeeType();
8675 // Don't add qualified variants of arrays. For one, they're not allowed
8676 // (the qualifier would sink to the element type), and for another, the
8677 // only overload situation where it matters is subscript or pointer +- int,
8678 // and those shouldn't have qualifier variants anyway.
8679 if (PointeeTy->isArrayType())
8680 return true;
8681 const Type *ClassTy = PointerTy->getClass();
8682
8683 // Iterate through all strict supersets of the pointee type's CVR
8684 // qualifiers.
8685 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8686 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8687 if ((CVR | BaseCVR) != CVR) continue;
8688
8689 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8690 MemberPointerTypes.insert(
8691 Context.getMemberPointerType(QPointeeTy, ClassTy));
8692 }
8693
8694 return true;
8695}
8696
8697/// AddTypesConvertedFrom - Add each of the types to which the type @p
8698/// Ty can be implicit converted to the given set of @p Types. We're
8699/// primarily interested in pointer types and enumeration types. We also
8700/// take member pointer types, for the conditional operator.
8701/// AllowUserConversions is true if we should look at the conversion
8702/// functions of a class type, and AllowExplicitConversions if we
8703/// should also include the explicit conversion functions of a class
8704/// type.
8705void
8706BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
8707 SourceLocation Loc,
8708 bool AllowUserConversions,
8709 bool AllowExplicitConversions,
8710 const Qualifiers &VisibleQuals) {
8711 // Only deal with canonical types.
8712 Ty = Context.getCanonicalType(Ty);
8713
8714 // Look through reference types; they aren't part of the type of an
8715 // expression for the purposes of conversions.
8716 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8717 Ty = RefTy->getPointeeType();
8718
8719 // If we're dealing with an array type, decay to the pointer.
8720 if (Ty->isArrayType())
8721 Ty = SemaRef.Context.getArrayDecayedType(Ty);
8722
8723 // Otherwise, we don't care about qualifiers on the type.
8724 Ty = Ty.getLocalUnqualifiedType();
8725
8726 // Flag if we ever add a non-record type.
8727 const RecordType *TyRec = Ty->getAs<RecordType>();
8728 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8729
8730 // Flag if we encounter an arithmetic type.
8731 HasArithmeticOrEnumeralTypes =
8732 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8733
8734 if (Ty->isObjCIdType() || Ty->isObjCClassType())
8735 PointerTypes.insert(Ty);
8736 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8737 // Insert our type, and its more-qualified variants, into the set
8738 // of types.
8739 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8740 return;
8741 } else if (Ty->isMemberPointerType()) {
8742 // Member pointers are far easier, since the pointee can't be converted.
8743 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8744 return;
8745 } else if (Ty->isEnumeralType()) {
8746 HasArithmeticOrEnumeralTypes = true;
8747 EnumerationTypes.insert(Ty);
8748 } else if (Ty->isBitIntType()) {
8749 HasArithmeticOrEnumeralTypes = true;
8750 BitIntTypes.insert(Ty);
8751 } else if (Ty->isVectorType()) {
8752 // We treat vector types as arithmetic types in many contexts as an
8753 // extension.
8754 HasArithmeticOrEnumeralTypes = true;
8755 VectorTypes.insert(Ty);
8756 } else if (Ty->isMatrixType()) {
8757 // Similar to vector types, we treat vector types as arithmetic types in
8758 // many contexts as an extension.
8759 HasArithmeticOrEnumeralTypes = true;
8760 MatrixTypes.insert(Ty);
8761 } else if (Ty->isNullPtrType()) {
8762 HasNullPtrType = true;
8763 } else if (AllowUserConversions && TyRec) {
8764 // No conversion functions in incomplete types.
8765 if (!SemaRef.isCompleteType(Loc, Ty))
8766 return;
8767
8768 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8769 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8770 if (isa<UsingShadowDecl>(D))
8771 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8772
8773 // Skip conversion function templates; they don't tell us anything
8774 // about which builtin types we can convert to.
8775 if (isa<FunctionTemplateDecl>(D))
8776 continue;
8777
8778 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8779 if (AllowExplicitConversions || !Conv->isExplicit()) {
8780 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8781 VisibleQuals);
8782 }
8783 }
8784 }
8785}
8786/// Helper function for adjusting address spaces for the pointer or reference
8787/// operands of builtin operators depending on the argument.
8789 Expr *Arg) {
8791}
8792
8793/// Helper function for AddBuiltinOperatorCandidates() that adds
8794/// the volatile- and non-volatile-qualified assignment operators for the
8795/// given type to the candidate set.
8797 QualType T,
8798 ArrayRef<Expr *> Args,
8799 OverloadCandidateSet &CandidateSet) {
8800 QualType ParamTypes[2];
8801
8802 // T& operator=(T&, T)
8803 ParamTypes[0] = S.Context.getLValueReferenceType(
8805 ParamTypes[1] = T;
8806 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8807 /*IsAssignmentOperator=*/true);
8808
8810 // volatile T& operator=(volatile T&, T)
8811 ParamTypes[0] = S.Context.getLValueReferenceType(
8813 Args[0]));
8814 ParamTypes[1] = T;
8815 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8816 /*IsAssignmentOperator=*/true);
8817 }
8818}
8819
8820/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8821/// if any, found in visible type conversion functions found in ArgExpr's type.
8822static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8823 Qualifiers VRQuals;
8824 const RecordType *TyRec;
8825 if (const MemberPointerType *RHSMPType =
8826 ArgExpr->getType()->getAs<MemberPointerType>())
8827 TyRec = RHSMPType->getClass()->getAs<RecordType>();
8828 else
8829 TyRec = ArgExpr->getType()->getAs<RecordType>();
8830 if (!TyRec) {
8831 // Just to be safe, assume the worst case.
8832 VRQuals.addVolatile();
8833 VRQuals.addRestrict();
8834 return VRQuals;
8835 }
8836
8837 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8838 if (!ClassDecl->hasDefinition())
8839 return VRQuals;
8840
8841 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8842 if (isa<UsingShadowDecl>(D))
8843 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8844 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8845 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8846 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8847 CanTy = ResTypeRef->getPointeeType();
8848 // Need to go down the pointer/mempointer chain and add qualifiers
8849 // as see them.
8850 bool done = false;
8851 while (!done) {
8852 if (CanTy.isRestrictQualified())
8853 VRQuals.addRestrict();
8854 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8855 CanTy = ResTypePtr->getPointeeType();
8856 else if (const MemberPointerType *ResTypeMPtr =
8857 CanTy->getAs<MemberPointerType>())
8858 CanTy = ResTypeMPtr->getPointeeType();
8859 else
8860 done = true;
8861 if (CanTy.isVolatileQualified())
8862 VRQuals.addVolatile();
8863 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8864 return VRQuals;
8865 }
8866 }
8867 }
8868 return VRQuals;
8869}
8870
8871// Note: We're currently only handling qualifiers that are meaningful for the
8872// LHS of compound assignment overloading.
8874 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
8875 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8876 // _Atomic
8877 if (Available.hasAtomic()) {
8878 Available.removeAtomic();
8879 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
8880 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8881 return;
8882 }
8883
8884 // volatile
8885 if (Available.hasVolatile()) {
8886 Available.removeVolatile();
8887 assert(!Applied.hasVolatile());
8888 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
8889 Callback);
8890 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8891 return;
8892 }
8893
8894 Callback(Applied);
8895}
8896
8898 QualifiersAndAtomic Quals,
8899 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8901 Callback);
8902}
8903
8905 QualifiersAndAtomic Quals,
8906 Sema &S) {
8907 if (Quals.hasAtomic())
8909 if (Quals.hasVolatile())
8912}
8913
8914namespace {
8915
8916/// Helper class to manage the addition of builtin operator overload
8917/// candidates. It provides shared state and utility methods used throughout
8918/// the process, as well as a helper method to add each group of builtin
8919/// operator overloads from the standard to a candidate set.
8920class BuiltinOperatorOverloadBuilder {
8921 // Common instance state available to all overload candidate addition methods.
8922 Sema &S;
8923 ArrayRef<Expr *> Args;
8924 QualifiersAndAtomic VisibleTypeConversionsQuals;
8925 bool HasArithmeticOrEnumeralCandidateType;
8927 OverloadCandidateSet &CandidateSet;
8928
8929 static constexpr int ArithmeticTypesCap = 26;
8931
8932 // Define some indices used to iterate over the arithmetic types in
8933 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
8934 // types are that preserved by promotion (C++ [over.built]p2).
8935 unsigned FirstIntegralType,
8936 LastIntegralType;
8937 unsigned FirstPromotedIntegralType,
8938 LastPromotedIntegralType;
8939 unsigned FirstPromotedArithmeticType,
8940 LastPromotedArithmeticType;
8941 unsigned NumArithmeticTypes;
8942
8943 void InitArithmeticTypes() {
8944 // Start of promoted types.
8945 FirstPromotedArithmeticType = 0;
8946 ArithmeticTypes.push_back(S.Context.FloatTy);
8947 ArithmeticTypes.push_back(S.Context.DoubleTy);
8948 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8950 ArithmeticTypes.push_back(S.Context.Float128Ty);
8952 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
8953
8954 // Start of integral types.
8955 FirstIntegralType = ArithmeticTypes.size();
8956 FirstPromotedIntegralType = ArithmeticTypes.size();
8957 ArithmeticTypes.push_back(S.Context.IntTy);
8958 ArithmeticTypes.push_back(S.Context.LongTy);
8959 ArithmeticTypes.push_back(S.Context.LongLongTy);
8963 ArithmeticTypes.push_back(S.Context.Int128Ty);
8964 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8965 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8966 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8970 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8971
8972 /// We add candidates for the unique, unqualified _BitInt types present in
8973 /// the candidate type set. The candidate set already handled ensuring the
8974 /// type is unqualified and canonical, but because we're adding from N
8975 /// different sets, we need to do some extra work to unique things. Insert
8976 /// the candidates into a unique set, then move from that set into the list
8977 /// of arithmetic types.
8978 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
8979 llvm::for_each(CandidateTypes, [&BitIntCandidates](
8980 BuiltinCandidateTypeSet &Candidate) {
8981 for (QualType BitTy : Candidate.bitint_types())
8982 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
8983 });
8984 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
8985 LastPromotedIntegralType = ArithmeticTypes.size();
8986 LastPromotedArithmeticType = ArithmeticTypes.size();
8987 // End of promoted types.
8988
8989 ArithmeticTypes.push_back(S.Context.BoolTy);
8990 ArithmeticTypes.push_back(S.Context.CharTy);
8991 ArithmeticTypes.push_back(S.Context.WCharTy);
8992 if (S.Context.getLangOpts().Char8)
8993 ArithmeticTypes.push_back(S.Context.Char8Ty);
8994 ArithmeticTypes.push_back(S.Context.Char16Ty);
8995 ArithmeticTypes.push_back(S.Context.Char32Ty);
8996 ArithmeticTypes.push_back(S.Context.SignedCharTy);
8997 ArithmeticTypes.push_back(S.Context.ShortTy);
8998 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8999 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9000 LastIntegralType = ArithmeticTypes.size();
9001 NumArithmeticTypes = ArithmeticTypes.size();
9002 // End of integral types.
9003 // FIXME: What about complex? What about half?
9004
9005 // We don't know for sure how many bit-precise candidates were involved, so
9006 // we subtract those from the total when testing whether we're under the
9007 // cap or not.
9008 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9009 ArithmeticTypesCap &&
9010 "Enough inline storage for all arithmetic types.");
9011 }
9012
9013 /// Helper method to factor out the common pattern of adding overloads
9014 /// for '++' and '--' builtin operators.
9015 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9016 bool HasVolatile,
9017 bool HasRestrict) {
9018 QualType ParamTypes[2] = {
9019 S.Context.getLValueReferenceType(CandidateTy),
9020 S.Context.IntTy
9021 };
9022
9023 // Non-volatile version.
9024 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9025
9026 // Use a heuristic to reduce number of builtin candidates in the set:
9027 // add volatile version only if there are conversions to a volatile type.
9028 if (HasVolatile) {
9029 ParamTypes[0] =
9031 S.Context.getVolatileType(CandidateTy));
9032 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9033 }
9034
9035 // Add restrict version only if there are conversions to a restrict type
9036 // and our candidate type is a non-restrict-qualified pointer.
9037 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9038 !CandidateTy.isRestrictQualified()) {
9039 ParamTypes[0]
9042 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9043
9044 if (HasVolatile) {
9045 ParamTypes[0]
9047 S.Context.getCVRQualifiedType(CandidateTy,
9050 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9051 }
9052 }
9053
9054 }
9055
9056 /// Helper to add an overload candidate for a binary builtin with types \p L
9057 /// and \p R.
9058 void AddCandidate(QualType L, QualType R) {
9059 QualType LandR[2] = {L, R};
9060 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9061 }
9062
9063public:
9064 BuiltinOperatorOverloadBuilder(
9065 Sema &S, ArrayRef<Expr *> Args,
9066 QualifiersAndAtomic VisibleTypeConversionsQuals,
9067 bool HasArithmeticOrEnumeralCandidateType,
9069 OverloadCandidateSet &CandidateSet)
9070 : S(S), Args(Args),
9071 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9072 HasArithmeticOrEnumeralCandidateType(
9073 HasArithmeticOrEnumeralCandidateType),
9074 CandidateTypes(CandidateTypes),
9075 CandidateSet(CandidateSet) {
9076
9077 InitArithmeticTypes();
9078 }
9079
9080 // Increment is deprecated for bool since C++17.
9081 //
9082 // C++ [over.built]p3:
9083 //
9084 // For every pair (T, VQ), where T is an arithmetic type other
9085 // than bool, and VQ is either volatile or empty, there exist
9086 // candidate operator functions of the form
9087 //
9088 // VQ T& operator++(VQ T&);
9089 // T operator++(VQ T&, int);
9090 //
9091 // C++ [over.built]p4:
9092 //
9093 // For every pair (T, VQ), where T is an arithmetic type other
9094 // than bool, and VQ is either volatile or empty, there exist
9095 // candidate operator functions of the form
9096 //
9097 // VQ T& operator--(VQ T&);
9098 // T operator--(VQ T&, int);
9099 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9100 if (!HasArithmeticOrEnumeralCandidateType)
9101 return;
9102
9103 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9104 const auto TypeOfT = ArithmeticTypes[Arith];
9105 if (TypeOfT == S.Context.BoolTy) {
9106 if (Op == OO_MinusMinus)
9107 continue;
9108 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9109 continue;
9110 }
9111 addPlusPlusMinusMinusStyleOverloads(
9112 TypeOfT,
9113 VisibleTypeConversionsQuals.hasVolatile(),
9114 VisibleTypeConversionsQuals.hasRestrict());
9115 }
9116 }
9117
9118 // C++ [over.built]p5:
9119 //
9120 // For every pair (T, VQ), where T is a cv-qualified or
9121 // cv-unqualified object type, and VQ is either volatile or
9122 // empty, there exist candidate operator functions of the form
9123 //
9124 // T*VQ& operator++(T*VQ&);
9125 // T*VQ& operator--(T*VQ&);
9126 // T* operator++(T*VQ&, int);
9127 // T* operator--(T*VQ&, int);
9128 void addPlusPlusMinusMinusPointerOverloads() {
9129 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9130 // Skip pointer types that aren't pointers to object types.
9131 if (!PtrTy->getPointeeType()->isObjectType())
9132 continue;
9133
9134 addPlusPlusMinusMinusStyleOverloads(
9135 PtrTy,
9136 (!PtrTy.isVolatileQualified() &&
9137 VisibleTypeConversionsQuals.hasVolatile()),
9138 (!PtrTy.isRestrictQualified() &&
9139 VisibleTypeConversionsQuals.hasRestrict()));
9140 }
9141 }
9142
9143 // C++ [over.built]p6:
9144 // For every cv-qualified or cv-unqualified object type T, there
9145 // exist candidate operator functions of the form
9146 //
9147 // T& operator*(T*);
9148 //
9149 // C++ [over.built]p7:
9150 // For every function type T that does not have cv-qualifiers or a
9151 // ref-qualifier, there exist candidate operator functions of the form
9152 // T& operator*(T*);
9153 void addUnaryStarPointerOverloads() {
9154 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9155 QualType PointeeTy = ParamTy->getPointeeType();
9156 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9157 continue;
9158
9159 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9160 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9161 continue;
9162
9163 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9164 }
9165 }
9166
9167 // C++ [over.built]p9:
9168 // For every promoted arithmetic type T, there exist candidate
9169 // operator functions of the form
9170 //
9171 // T operator+(T);
9172 // T operator-(T);
9173 void addUnaryPlusOrMinusArithmeticOverloads() {
9174 if (!HasArithmeticOrEnumeralCandidateType)
9175 return;
9176
9177 for (unsigned Arith = FirstPromotedArithmeticType;
9178 Arith < LastPromotedArithmeticType; ++Arith) {
9179 QualType ArithTy = ArithmeticTypes[Arith];
9180 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9181 }
9182
9183 // Extension: We also add these operators for vector types.
9184 for (QualType VecTy : CandidateTypes[0].vector_types())
9185 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9186 }
9187
9188 // C++ [over.built]p8:
9189 // For every type T, there exist candidate operator functions of
9190 // the form
9191 //
9192 // T* operator+(T*);
9193 void addUnaryPlusPointerOverloads() {
9194 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9195 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9196 }
9197
9198 // C++ [over.built]p10:
9199 // For every promoted integral type T, there exist candidate
9200 // operator functions of the form
9201 //
9202 // T operator~(T);
9203 void addUnaryTildePromotedIntegralOverloads() {
9204 if (!HasArithmeticOrEnumeralCandidateType)
9205 return;
9206
9207 for (unsigned Int = FirstPromotedIntegralType;
9208 Int < LastPromotedIntegralType; ++Int) {
9209 QualType IntTy = ArithmeticTypes[Int];
9210 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9211 }
9212
9213 // Extension: We also add this operator for vector types.
9214 for (QualType VecTy : CandidateTypes[0].vector_types())
9215 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9216 }
9217
9218 // C++ [over.match.oper]p16:
9219 // For every pointer to member type T or type std::nullptr_t, there
9220 // exist candidate operator functions of the form
9221 //
9222 // bool operator==(T,T);
9223 // bool operator!=(T,T);
9224 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9225 /// Set of (canonical) types that we've already handled.
9227
9228 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9229 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9230 // Don't add the same builtin candidate twice.
9231 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9232 continue;
9233
9234 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9235 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9236 }
9237
9238 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9240 if (AddedTypes.insert(NullPtrTy).second) {
9241 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9242 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9243 }
9244 }
9245 }
9246 }
9247
9248 // C++ [over.built]p15:
9249 //
9250 // For every T, where T is an enumeration type or a pointer type,
9251 // there exist candidate operator functions of the form
9252 //
9253 // bool operator<(T, T);
9254 // bool operator>(T, T);
9255 // bool operator<=(T, T);
9256 // bool operator>=(T, T);
9257 // bool operator==(T, T);
9258 // bool operator!=(T, T);
9259 // R operator<=>(T, T)
9260 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9261 // C++ [over.match.oper]p3:
9262 // [...]the built-in candidates include all of the candidate operator
9263 // functions defined in 13.6 that, compared to the given operator, [...]
9264 // do not have the same parameter-type-list as any non-template non-member
9265 // candidate.
9266 //
9267 // Note that in practice, this only affects enumeration types because there
9268 // aren't any built-in candidates of record type, and a user-defined operator
9269 // must have an operand of record or enumeration type. Also, the only other
9270 // overloaded operator with enumeration arguments, operator=,
9271 // cannot be overloaded for enumeration types, so this is the only place
9272 // where we must suppress candidates like this.
9273 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9274 UserDefinedBinaryOperators;
9275
9276 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9277 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9278 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9279 CEnd = CandidateSet.end();
9280 C != CEnd; ++C) {
9281 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9282 continue;
9283
9284 if (C->Function->isFunctionTemplateSpecialization())
9285 continue;
9286
9287 // We interpret "same parameter-type-list" as applying to the
9288 // "synthesized candidate, with the order of the two parameters
9289 // reversed", not to the original function.
9290 bool Reversed = C->isReversed();
9291 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9292 ->getType()
9293 .getUnqualifiedType();
9294 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9295 ->getType()
9296 .getUnqualifiedType();
9297
9298 // Skip if either parameter isn't of enumeral type.
9299 if (!FirstParamType->isEnumeralType() ||
9300 !SecondParamType->isEnumeralType())
9301 continue;
9302
9303 // Add this operator to the set of known user-defined operators.
9304 UserDefinedBinaryOperators.insert(
9305 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9306 S.Context.getCanonicalType(SecondParamType)));
9307 }
9308 }
9309 }
9310
9311 /// Set of (canonical) types that we've already handled.
9313
9314 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9315 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9316 // Don't add the same builtin candidate twice.
9317 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9318 continue;
9319 if (IsSpaceship && PtrTy->isFunctionPointerType())
9320 continue;
9321
9322 QualType ParamTypes[2] = {PtrTy, PtrTy};
9323 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9324 }
9325 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9326 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9327
9328 // Don't add the same builtin candidate twice, or if a user defined
9329 // candidate exists.
9330 if (!AddedTypes.insert(CanonType).second ||
9331 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9332 CanonType)))
9333 continue;
9334 QualType ParamTypes[2] = {EnumTy, EnumTy};
9335 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9336 }
9337 }
9338 }
9339
9340 // C++ [over.built]p13:
9341 //
9342 // For every cv-qualified or cv-unqualified object type T
9343 // there exist candidate operator functions of the form
9344 //
9345 // T* operator+(T*, ptrdiff_t);
9346 // T& operator[](T*, ptrdiff_t); [BELOW]
9347 // T* operator-(T*, ptrdiff_t);
9348 // T* operator+(ptrdiff_t, T*);
9349 // T& operator[](ptrdiff_t, T*); [BELOW]
9350 //
9351 // C++ [over.built]p14:
9352 //
9353 // For every T, where T is a pointer to object type, there
9354 // exist candidate operator functions of the form
9355 //
9356 // ptrdiff_t operator-(T, T);
9357 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9358 /// Set of (canonical) types that we've already handled.
9360
9361 for (int Arg = 0; Arg < 2; ++Arg) {
9362 QualType AsymmetricParamTypes[2] = {
9365 };
9366 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9367 QualType PointeeTy = PtrTy->getPointeeType();
9368 if (!PointeeTy->isObjectType())
9369 continue;
9370
9371 AsymmetricParamTypes[Arg] = PtrTy;
9372 if (Arg == 0 || Op == OO_Plus) {
9373 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9374 // T* operator+(ptrdiff_t, T*);
9375 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9376 }
9377 if (Op == OO_Minus) {
9378 // ptrdiff_t operator-(T, T);
9379 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9380 continue;
9381
9382 QualType ParamTypes[2] = {PtrTy, PtrTy};
9383 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9384 }
9385 }
9386 }
9387 }
9388
9389 // C++ [over.built]p12:
9390 //
9391 // For every pair of promoted arithmetic types L and R, there
9392 // exist candidate operator functions of the form
9393 //
9394 // LR operator*(L, R);
9395 // LR operator/(L, R);
9396 // LR operator+(L, R);
9397 // LR operator-(L, R);
9398 // bool operator<(L, R);
9399 // bool operator>(L, R);
9400 // bool operator<=(L, R);
9401 // bool operator>=(L, R);
9402 // bool operator==(L, R);
9403 // bool operator!=(L, R);
9404 //
9405 // where LR is the result of the usual arithmetic conversions
9406 // between types L and R.
9407 //
9408 // C++ [over.built]p24:
9409 //
9410 // For every pair of promoted arithmetic types L and R, there exist
9411 // candidate operator functions of the form
9412 //
9413 // LR operator?(bool, L, R);
9414 //
9415 // where LR is the result of the usual arithmetic conversions
9416 // between types L and R.
9417 // Our candidates ignore the first parameter.
9418 void addGenericBinaryArithmeticOverloads() {
9419 if (!HasArithmeticOrEnumeralCandidateType)
9420 return;
9421
9422 for (unsigned Left = FirstPromotedArithmeticType;
9423 Left < LastPromotedArithmeticType; ++Left) {
9424 for (unsigned Right = FirstPromotedArithmeticType;
9425 Right < LastPromotedArithmeticType; ++Right) {
9426 QualType LandR[2] = { ArithmeticTypes[Left],
9427 ArithmeticTypes[Right] };
9428 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9429 }
9430 }
9431
9432 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9433 // conditional operator for vector types.
9434 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9435 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9436 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9437 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9438 }
9439 }
9440
9441 /// Add binary operator overloads for each candidate matrix type M1, M2:
9442 /// * (M1, M1) -> M1
9443 /// * (M1, M1.getElementType()) -> M1
9444 /// * (M2.getElementType(), M2) -> M2
9445 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9446 void addMatrixBinaryArithmeticOverloads() {
9447 if (!HasArithmeticOrEnumeralCandidateType)
9448 return;
9449
9450 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9451 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9452 AddCandidate(M1, M1);
9453 }
9454
9455 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9456 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9457 if (!CandidateTypes[0].containsMatrixType(M2))
9458 AddCandidate(M2, M2);
9459 }
9460 }
9461
9462 // C++2a [over.built]p14:
9463 //
9464 // For every integral type T there exists a candidate operator function
9465 // of the form
9466 //
9467 // std::strong_ordering operator<=>(T, T)
9468 //
9469 // C++2a [over.built]p15:
9470 //
9471 // For every pair of floating-point types L and R, there exists a candidate
9472 // operator function of the form
9473 //
9474 // std::partial_ordering operator<=>(L, R);
9475 //
9476 // FIXME: The current specification for integral types doesn't play nice with
9477 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9478 // comparisons. Under the current spec this can lead to ambiguity during
9479 // overload resolution. For example:
9480 //
9481 // enum A : int {a};
9482 // auto x = (a <=> (long)42);
9483 //
9484 // error: call is ambiguous for arguments 'A' and 'long'.
9485 // note: candidate operator<=>(int, int)
9486 // note: candidate operator<=>(long, long)
9487 //
9488 // To avoid this error, this function deviates from the specification and adds
9489 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9490 // arithmetic types (the same as the generic relational overloads).
9491 //
9492 // For now this function acts as a placeholder.
9493 void addThreeWayArithmeticOverloads() {
9494 addGenericBinaryArithmeticOverloads();
9495 }
9496
9497 // C++ [over.built]p17:
9498 //
9499 // For every pair of promoted integral types L and R, there
9500 // exist candidate operator functions of the form
9501 //
9502 // LR operator%(L, R);
9503 // LR operator&(L, R);
9504 // LR operator^(L, R);
9505 // LR operator|(L, R);
9506 // L operator<<(L, R);
9507 // L operator>>(L, R);
9508 //
9509 // where LR is the result of the usual arithmetic conversions
9510 // between types L and R.
9511 void addBinaryBitwiseArithmeticOverloads() {
9512 if (!HasArithmeticOrEnumeralCandidateType)
9513 return;
9514
9515 for (unsigned Left = FirstPromotedIntegralType;
9516 Left < LastPromotedIntegralType; ++Left) {
9517 for (unsigned Right = FirstPromotedIntegralType;
9518 Right < LastPromotedIntegralType; ++Right) {
9519 QualType LandR[2] = { ArithmeticTypes[Left],
9520 ArithmeticTypes[Right] };
9521 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9522 }
9523 }
9524 }
9525
9526 // C++ [over.built]p20:
9527 //
9528 // For every pair (T, VQ), where T is an enumeration or
9529 // pointer to member type and VQ is either volatile or
9530 // empty, there exist candidate operator functions of the form
9531 //
9532 // VQ T& operator=(VQ T&, T);
9533 void addAssignmentMemberPointerOrEnumeralOverloads() {
9534 /// Set of (canonical) types that we've already handled.
9536
9537 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9538 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9539 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9540 continue;
9541
9542 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9543 }
9544
9545 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9546 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9547 continue;
9548
9549 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9550 }
9551 }
9552 }
9553
9554 // C++ [over.built]p19:
9555 //
9556 // For every pair (T, VQ), where T is any type and VQ is either
9557 // volatile or empty, there exist candidate operator functions
9558 // of the form
9559 //
9560 // T*VQ& operator=(T*VQ&, T*);
9561 //
9562 // C++ [over.built]p21:
9563 //
9564 // For every pair (T, VQ), where T is a cv-qualified or
9565 // cv-unqualified object type and VQ is either volatile or
9566 // empty, there exist candidate operator functions of the form
9567 //
9568 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9569 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9570 void addAssignmentPointerOverloads(bool isEqualOp) {
9571 /// Set of (canonical) types that we've already handled.
9573
9574 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9575 // If this is operator=, keep track of the builtin candidates we added.
9576 if (isEqualOp)
9577 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9578 else if (!PtrTy->getPointeeType()->isObjectType())
9579 continue;
9580
9581 // non-volatile version
9582 QualType ParamTypes[2] = {
9584 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9585 };
9586 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9587 /*IsAssignmentOperator=*/ isEqualOp);
9588
9589 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9590 VisibleTypeConversionsQuals.hasVolatile();
9591 if (NeedVolatile) {
9592 // volatile version
9593 ParamTypes[0] =
9595 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9596 /*IsAssignmentOperator=*/isEqualOp);
9597 }
9598
9599 if (!PtrTy.isRestrictQualified() &&
9600 VisibleTypeConversionsQuals.hasRestrict()) {
9601 // restrict version
9602 ParamTypes[0] =
9604 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9605 /*IsAssignmentOperator=*/isEqualOp);
9606
9607 if (NeedVolatile) {
9608 // volatile restrict version
9609 ParamTypes[0] =
9612 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9613 /*IsAssignmentOperator=*/isEqualOp);
9614 }
9615 }
9616 }
9617
9618 if (isEqualOp) {
9619 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9620 // Make sure we don't add the same candidate twice.
9621 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9622 continue;
9623
9624 QualType ParamTypes[2] = {
9626 PtrTy,
9627 };
9628
9629 // non-volatile version
9630 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9631 /*IsAssignmentOperator=*/true);
9632
9633 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9634 VisibleTypeConversionsQuals.hasVolatile();
9635 if (NeedVolatile) {
9636 // volatile version
9637 ParamTypes[0] = S.Context.getLValueReferenceType(
9638 S.Context.getVolatileType(PtrTy));
9639 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9640 /*IsAssignmentOperator=*/true);
9641 }
9642
9643 if (!PtrTy.isRestrictQualified() &&
9644 VisibleTypeConversionsQuals.hasRestrict()) {
9645 // restrict version
9646 ParamTypes[0] = S.Context.getLValueReferenceType(
9647 S.Context.getRestrictType(PtrTy));
9648 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9649 /*IsAssignmentOperator=*/true);
9650
9651 if (NeedVolatile) {
9652 // volatile restrict version
9653 ParamTypes[0] =
9656 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9657 /*IsAssignmentOperator=*/true);
9658 }
9659 }
9660 }
9661 }
9662 }
9663
9664 // C++ [over.built]p18:
9665 //
9666 // For every triple (L, VQ, R), where L is an arithmetic type,
9667 // VQ is either volatile or empty, and R is a promoted
9668 // arithmetic type, there exist candidate operator functions of
9669 // the form
9670 //
9671 // VQ L& operator=(VQ L&, R);
9672 // VQ L& operator*=(VQ L&, R);
9673 // VQ L& operator/=(VQ L&, R);
9674 // VQ L& operator+=(VQ L&, R);
9675 // VQ L& operator-=(VQ L&, R);
9676 void addAssignmentArithmeticOverloads(bool isEqualOp) {
9677 if (!HasArithmeticOrEnumeralCandidateType)
9678 return;
9679
9680 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9681 for (unsigned Right = FirstPromotedArithmeticType;
9682 Right < LastPromotedArithmeticType; ++Right) {
9683 QualType ParamTypes[2];
9684 ParamTypes[1] = ArithmeticTypes[Right];
9686 S, ArithmeticTypes[Left], Args[0]);
9687
9689 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9690 ParamTypes[0] =
9691 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9692 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9693 /*IsAssignmentOperator=*/isEqualOp);
9694 });
9695 }
9696 }
9697
9698 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
9699 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9700 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
9701 QualType ParamTypes[2];
9702 ParamTypes[1] = Vec2Ty;
9703 // Add this built-in operator as a candidate (VQ is empty).
9704 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
9705 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9706 /*IsAssignmentOperator=*/isEqualOp);
9707
9708 // Add this built-in operator as a candidate (VQ is 'volatile').
9709 if (VisibleTypeConversionsQuals.hasVolatile()) {
9710 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
9711 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
9712 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9713 /*IsAssignmentOperator=*/isEqualOp);
9714 }
9715 }
9716 }
9717
9718 // C++ [over.built]p22:
9719 //
9720 // For every triple (L, VQ, R), where L is an integral type, VQ
9721 // is either volatile or empty, and R is a promoted integral
9722 // type, there exist candidate operator functions of the form
9723 //
9724 // VQ L& operator%=(VQ L&, R);
9725 // VQ L& operator<<=(VQ L&, R);
9726 // VQ L& operator>>=(VQ L&, R);
9727 // VQ L& operator&=(VQ L&, R);
9728 // VQ L& operator^=(VQ L&, R);
9729 // VQ L& operator|=(VQ L&, R);
9730 void addAssignmentIntegralOverloads() {
9731 if (!HasArithmeticOrEnumeralCandidateType)
9732 return;
9733
9734 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
9735 for (unsigned Right = FirstPromotedIntegralType;
9736 Right < LastPromotedIntegralType; ++Right) {
9737 QualType ParamTypes[2];
9738 ParamTypes[1] = ArithmeticTypes[Right];
9740 S, ArithmeticTypes[Left], Args[0]);
9741
9743 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9744 ParamTypes[0] =
9745 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9746 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9747 });
9748 }
9749 }
9750 }
9751
9752 // C++ [over.operator]p23:
9753 //
9754 // There also exist candidate operator functions of the form
9755 //
9756 // bool operator!(bool);
9757 // bool operator&&(bool, bool);
9758 // bool operator||(bool, bool);
9759 void addExclaimOverload() {
9760 QualType ParamTy = S.Context.BoolTy;
9761 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
9762 /*IsAssignmentOperator=*/false,
9763 /*NumContextualBoolArguments=*/1);
9764 }
9765 void addAmpAmpOrPipePipeOverload() {
9766 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
9767 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9768 /*IsAssignmentOperator=*/false,
9769 /*NumContextualBoolArguments=*/2);
9770 }
9771
9772 // C++ [over.built]p13:
9773 //
9774 // For every cv-qualified or cv-unqualified object type T there
9775 // exist candidate operator functions of the form
9776 //
9777 // T* operator+(T*, ptrdiff_t); [ABOVE]
9778 // T& operator[](T*, ptrdiff_t);
9779 // T* operator-(T*, ptrdiff_t); [ABOVE]
9780 // T* operator+(ptrdiff_t, T*); [ABOVE]
9781 // T& operator[](ptrdiff_t, T*);
9782 void addSubscriptOverloads() {
9783 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9784 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9785 QualType PointeeType = PtrTy->getPointeeType();
9786 if (!PointeeType->isObjectType())
9787 continue;
9788
9789 // T& operator[](T*, ptrdiff_t)
9790 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9791 }
9792
9793 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9794 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9795 QualType PointeeType = PtrTy->getPointeeType();
9796 if (!PointeeType->isObjectType())
9797 continue;
9798
9799 // T& operator[](ptrdiff_t, T*)
9800 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9801 }
9802 }
9803
9804 // C++ [over.built]p11:
9805 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9806 // C1 is the same type as C2 or is a derived class of C2, T is an object
9807 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9808 // there exist candidate operator functions of the form
9809 //
9810 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9811 //
9812 // where CV12 is the union of CV1 and CV2.
9813 void addArrowStarOverloads() {
9814 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9815 QualType C1Ty = PtrTy;
9816 QualType C1;
9818 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9819 if (!isa<RecordType>(C1))
9820 continue;
9821 // heuristic to reduce number of builtin candidates in the set.
9822 // Add volatile/restrict version only if there are conversions to a
9823 // volatile/restrict type.
9824 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9825 continue;
9826 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9827 continue;
9828 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9829 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
9830 QualType C2 = QualType(mptr->getClass(), 0);
9831 C2 = C2.getUnqualifiedType();
9832 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9833 break;
9834 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9835 // build CV12 T&
9836 QualType T = mptr->getPointeeType();
9837 if (!VisibleTypeConversionsQuals.hasVolatile() &&
9838 T.isVolatileQualified())
9839 continue;
9840 if (!VisibleTypeConversionsQuals.hasRestrict() &&
9841 T.isRestrictQualified())
9842 continue;
9843 T = Q1.apply(S.Context, T);
9844 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9845 }
9846 }
9847 }
9848
9849 // Note that we don't consider the first argument, since it has been
9850 // contextually converted to bool long ago. The candidates below are
9851 // therefore added as binary.
9852 //
9853 // C++ [over.built]p25:
9854 // For every type T, where T is a pointer, pointer-to-member, or scoped
9855 // enumeration type, there exist candidate operator functions of the form
9856 //
9857 // T operator?(bool, T, T);
9858 //
9859 void addConditionalOperatorOverloads() {
9860 /// Set of (canonical) types that we've already handled.
9862
9863 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9864 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9865 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9866 continue;
9867
9868 QualType ParamTypes[2] = {PtrTy, PtrTy};
9869 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9870 }
9871
9872 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9873 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9874 continue;
9875
9876 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9877 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9878 }
9879
9880 if (S.getLangOpts().CPlusPlus11) {
9881 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9882 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9883 continue;
9884
9885 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9886 continue;
9887
9888 QualType ParamTypes[2] = {EnumTy, EnumTy};
9889 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9890 }
9891 }
9892 }
9893 }
9894};
9895
9896} // end anonymous namespace
9897
9899 SourceLocation OpLoc,
9900 ArrayRef<Expr *> Args,
9901 OverloadCandidateSet &CandidateSet) {
9902 // Find all of the types that the arguments can convert to, but only
9903 // if the operator we're looking at has built-in operator candidates
9904 // that make use of these types. Also record whether we encounter non-record
9905 // candidate types or either arithmetic or enumeral candidate types.
9906 QualifiersAndAtomic VisibleTypeConversionsQuals;
9907 VisibleTypeConversionsQuals.addConst();
9908 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9909 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9910 if (Args[ArgIdx]->getType()->isAtomicType())
9911 VisibleTypeConversionsQuals.addAtomic();
9912 }
9913
9914 bool HasNonRecordCandidateType = false;
9915 bool HasArithmeticOrEnumeralCandidateType = false;
9917 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9918 CandidateTypes.emplace_back(*this);
9919 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9920 OpLoc,
9921 true,
9922 (Op == OO_Exclaim ||
9923 Op == OO_AmpAmp ||
9924 Op == OO_PipePipe),
9925 VisibleTypeConversionsQuals);
9926 HasNonRecordCandidateType = HasNonRecordCandidateType ||
9927 CandidateTypes[ArgIdx].hasNonRecordTypes();
9928 HasArithmeticOrEnumeralCandidateType =
9929 HasArithmeticOrEnumeralCandidateType ||
9930 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9931 }
9932
9933 // Exit early when no non-record types have been added to the candidate set
9934 // for any of the arguments to the operator.
9935 //
9936 // We can't exit early for !, ||, or &&, since there we have always have
9937 // 'bool' overloads.
9938 if (!HasNonRecordCandidateType &&
9939 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9940 return;
9941
9942 // Setup an object to manage the common state for building overloads.
9943 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9944 VisibleTypeConversionsQuals,
9945 HasArithmeticOrEnumeralCandidateType,
9946 CandidateTypes, CandidateSet);
9947
9948 // Dispatch over the operation to add in only those overloads which apply.
9949 switch (Op) {
9950 case OO_None:
9952 llvm_unreachable("Expected an overloaded operator");
9953
9954 case OO_New:
9955 case OO_Delete:
9956 case OO_Array_New:
9957 case OO_Array_Delete:
9958 case OO_Call:
9959 llvm_unreachable(
9960 "Special operators don't use AddBuiltinOperatorCandidates");
9961
9962 case OO_Comma:
9963 case OO_Arrow:
9964 case OO_Coawait:
9965 // C++ [over.match.oper]p3:
9966 // -- For the operator ',', the unary operator '&', the
9967 // operator '->', or the operator 'co_await', the
9968 // built-in candidates set is empty.
9969 break;
9970
9971 case OO_Plus: // '+' is either unary or binary
9972 if (Args.size() == 1)
9973 OpBuilder.addUnaryPlusPointerOverloads();
9974 [[fallthrough]];
9975
9976 case OO_Minus: // '-' is either unary or binary
9977 if (Args.size() == 1) {
9978 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9979 } else {
9980 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9981 OpBuilder.addGenericBinaryArithmeticOverloads();
9982 OpBuilder.addMatrixBinaryArithmeticOverloads();
9983 }
9984 break;
9985
9986 case OO_Star: // '*' is either unary or binary
9987 if (Args.size() == 1)
9988 OpBuilder.addUnaryStarPointerOverloads();
9989 else {
9990 OpBuilder.addGenericBinaryArithmeticOverloads();
9991 OpBuilder.addMatrixBinaryArithmeticOverloads();
9992 }
9993 break;
9994
9995 case OO_Slash:
9996 OpBuilder.addGenericBinaryArithmeticOverloads();
9997 break;
9998
9999 case OO_PlusPlus:
10000 case OO_MinusMinus:
10001 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10002 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10003 break;
10004
10005 case OO_EqualEqual:
10006 case OO_ExclaimEqual:
10007 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10008 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10009 OpBuilder.addGenericBinaryArithmeticOverloads();
10010 break;
10011
10012 case OO_Less:
10013 case OO_Greater:
10014 case OO_LessEqual:
10015 case OO_GreaterEqual:
10016 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10017 OpBuilder.addGenericBinaryArithmeticOverloads();
10018 break;
10019
10020 case OO_Spaceship:
10021 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10022 OpBuilder.addThreeWayArithmeticOverloads();
10023 break;
10024
10025 case OO_Percent:
10026 case OO_Caret:
10027 case OO_Pipe:
10028 case OO_LessLess:
10029 case OO_GreaterGreater:
10030 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10031 break;
10032
10033 case OO_Amp: // '&' is either unary or binary
10034 if (Args.size() == 1)
10035 // C++ [over.match.oper]p3:
10036 // -- For the operator ',', the unary operator '&', or the
10037 // operator '->', the built-in candidates set is empty.
10038 break;
10039
10040 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10041 break;
10042
10043 case OO_Tilde:
10044 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10045 break;
10046
10047 case OO_Equal:
10048 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10049 [[fallthrough]];
10050
10051 case OO_PlusEqual:
10052 case OO_MinusEqual:
10053 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10054 [[fallthrough]];
10055
10056 case OO_StarEqual:
10057 case OO_SlashEqual:
10058 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10059 break;
10060
10061 case OO_PercentEqual:
10062 case OO_LessLessEqual:
10063 case OO_GreaterGreaterEqual:
10064 case OO_AmpEqual:
10065 case OO_CaretEqual:
10066 case OO_PipeEqual:
10067 OpBuilder.addAssignmentIntegralOverloads();
10068 break;
10069
10070 case OO_Exclaim:
10071 OpBuilder.addExclaimOverload();
10072 break;
10073
10074 case OO_AmpAmp:
10075 case OO_PipePipe:
10076 OpBuilder.addAmpAmpOrPipePipeOverload();
10077 break;
10078
10079 case OO_Subscript:
10080 if (Args.size() == 2)
10081 OpBuilder.addSubscriptOverloads();
10082 break;
10083
10084 case OO_ArrowStar:
10085 OpBuilder.addArrowStarOverloads();
10086 break;
10087
10088 case OO_Conditional:
10089 OpBuilder.addConditionalOperatorOverloads();
10090 OpBuilder.addGenericBinaryArithmeticOverloads();
10091 break;
10092 }
10093}
10094
10095void
10097 SourceLocation Loc,
10098 ArrayRef<Expr *> Args,
10099 TemplateArgumentListInfo *ExplicitTemplateArgs,
10100 OverloadCandidateSet& CandidateSet,
10101 bool PartialOverloading) {
10102 ADLResult Fns;
10103
10104 // FIXME: This approach for uniquing ADL results (and removing
10105 // redundant candidates from the set) relies on pointer-equality,
10106 // which means we need to key off the canonical decl. However,
10107 // always going back to the canonical decl might not get us the
10108 // right set of default arguments. What default arguments are
10109 // we supposed to consider on ADL candidates, anyway?
10110
10111 // FIXME: Pass in the explicit template arguments?
10112 ArgumentDependentLookup(Name, Loc, Args, Fns);
10113
10114 // Erase all of the candidates we already knew about.
10115 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10116 CandEnd = CandidateSet.end();
10117 Cand != CandEnd; ++Cand)
10118 if (Cand->Function) {
10119 FunctionDecl *Fn = Cand->Function;
10120 Fns.erase(Fn);
10121 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10122 Fns.erase(FunTmpl);
10123 }
10124
10125 // For each of the ADL candidates we found, add it to the overload
10126 // set.
10127 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10129
10130 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10131 if (ExplicitTemplateArgs)
10132 continue;
10133
10134 AddOverloadCandidate(
10135 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10136 PartialOverloading, /*AllowExplicit=*/true,
10137 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10138 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10139 AddOverloadCandidate(
10140 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10141 /*SuppressUserConversions=*/false, PartialOverloading,
10142 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10143 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10144 }
10145 } else {
10146 auto *FTD = cast<FunctionTemplateDecl>(*I);
10147 AddTemplateOverloadCandidate(
10148 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10149 /*SuppressUserConversions=*/false, PartialOverloading,
10150 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10151 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10152 *this, Args, FTD->getTemplatedDecl())) {
10153 AddTemplateOverloadCandidate(
10154 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
10155 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
10156 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10158 }
10159 }
10160 }
10161}
10162
10163namespace {
10164enum class Comparison { Equal, Better, Worse };
10165}
10166
10167/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10168/// overload resolution.
10169///
10170/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10171/// Cand1's first N enable_if attributes have precisely the same conditions as
10172/// Cand2's first N enable_if attributes (where N = the number of enable_if
10173/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10174///
10175/// Note that you can have a pair of candidates such that Cand1's enable_if
10176/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10177/// worse than Cand1's.
10178static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10179 const FunctionDecl *Cand2) {
10180 // Common case: One (or both) decls don't have enable_if attrs.
10181 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10182 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10183 if (!Cand1Attr || !Cand2Attr) {
10184 if (Cand1Attr == Cand2Attr)
10185 return Comparison::Equal;
10186 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10187 }
10188
10189 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10190 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10191
10192 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10193 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10194 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10195 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10196
10197 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10198 // has fewer enable_if attributes than Cand2, and vice versa.
10199 if (!Cand1A)
10200 return Comparison::Worse;
10201 if (!Cand2A)
10202 return Comparison::Better;
10203
10204 Cand1ID.clear();
10205 Cand2ID.clear();
10206
10207 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10208 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10209 if (Cand1ID != Cand2ID)
10210 return Comparison::Worse;
10211 }
10212
10213 return Comparison::Equal;
10214}
10215
10216static Comparison
10218 const OverloadCandidate &Cand2) {
10219 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10220 !Cand2.Function->isMultiVersion())
10221 return Comparison::Equal;
10222
10223 // If both are invalid, they are equal. If one of them is invalid, the other
10224 // is better.
10225 if (Cand1.Function->isInvalidDecl()) {
10226 if (Cand2.Function->isInvalidDecl())
10227 return Comparison::Equal;
10228 return Comparison::Worse;
10229 }
10230 if (Cand2.Function->isInvalidDecl())
10231 return Comparison::Better;
10232
10233 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10234 // cpu_dispatch, else arbitrarily based on the identifiers.
10235 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10236 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10237 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10238 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10239
10240 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10241 return Comparison::Equal;
10242
10243 if (Cand1CPUDisp && !Cand2CPUDisp)
10244 return Comparison::Better;
10245 if (Cand2CPUDisp && !Cand1CPUDisp)
10246 return Comparison::Worse;
10247
10248 if (Cand1CPUSpec && Cand2CPUSpec) {
10249 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10250 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10251 ? Comparison::Better
10252 : Comparison::Worse;
10253
10254 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10255 FirstDiff = std::mismatch(
10256 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10257 Cand2CPUSpec->cpus_begin(),
10258 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10259 return LHS->getName() == RHS->getName();
10260 });
10261
10262 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10263 "Two different cpu-specific versions should not have the same "
10264 "identifier list, otherwise they'd be the same decl!");
10265 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10266 ? Comparison::Better
10267 : Comparison::Worse;
10268 }
10269 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10270}
10271
10272/// Compute the type of the implicit object parameter for the given function,
10273/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10274/// null QualType if there is a 'matches anything' implicit object parameter.
10275static std::optional<QualType>
10277 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
10278 return std::nullopt;
10279
10280 auto *M = cast<CXXMethodDecl>(F);
10281 // Static member functions' object parameters match all types.
10282 if (M->isStatic())
10283 return QualType();
10284 return M->getFunctionObjectParameterReferenceType();
10285}
10286
10287// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10288// represent the same entity.
10289static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10290 const FunctionDecl *F2) {
10291 if (declaresSameEntity(F1, F2))
10292 return true;
10293 auto PT1 = F1->getPrimaryTemplate();
10294 auto PT2 = F2->getPrimaryTemplate();
10295 if (PT1 && PT2) {
10296 if (declaresSameEntity(PT1, PT2) ||
10297 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10298 PT2->getInstantiatedFromMemberTemplate()))
10299 return true;
10300 }
10301 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10302 // different functions with same params). Consider removing this (as no test
10303 // fail w/o it).
10304 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10305 if (First) {
10306 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10307 return *T;
10308 }
10309 assert(I < F->getNumParams());
10310 return F->getParamDecl(I++)->getType();
10311 };
10312
10313 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10314 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10315
10316 if (F1NumParams != F2NumParams)
10317 return false;
10318
10319 unsigned I1 = 0, I2 = 0;
10320 for (unsigned I = 0; I != F1NumParams; ++I) {
10321 QualType T1 = NextParam(F1, I1, I == 0);
10322 QualType T2 = NextParam(F2, I2, I == 0);
10323 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10324 if (!Context.hasSameUnqualifiedType(T1, T2))
10325 return false;
10326 }
10327 return true;
10328}
10329
10330/// We're allowed to use constraints partial ordering only if the candidates
10331/// have the same parameter types:
10332/// [over.match.best.general]p2.6
10333/// F1 and F2 are non-template functions with the same
10334/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10336 const OverloadCandidate &Cand1,
10337 const OverloadCandidate &Cand2) {
10338 if (!Cand1.Function || !Cand2.Function)
10339 return false;
10340
10341 FunctionDecl *Fn1 = Cand1.Function;
10342 FunctionDecl *Fn2 = Cand2.Function;
10343
10344 if (Fn1->isVariadic() != Fn2->isVariadic())
10345 return false;
10346
10348 Fn1, Fn2, nullptr, Cand1.isReversed() ^ Cand2.isReversed()))
10349 return false;
10350
10351 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10352 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10353 if (Mem1 && Mem2) {
10354 // if they are member functions, both are direct members of the same class,
10355 // and
10356 if (Mem1->getParent() != Mem2->getParent())
10357 return false;
10358 // if both are non-static member functions, they have the same types for
10359 // their object parameters
10360 if (Mem1->isInstance() && Mem2->isInstance() &&
10362 Mem1->getFunctionObjectParameterReferenceType(),
10363 Mem1->getFunctionObjectParameterReferenceType()))
10364 return false;
10365 }
10366 return true;
10367}
10368
10369/// isBetterOverloadCandidate - Determines whether the first overload
10370/// candidate is a better candidate than the second (C++ 13.3.3p1).
10372 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10374 // Define viable functions to be better candidates than non-viable
10375 // functions.
10376 if (!Cand2.Viable)
10377 return Cand1.Viable;
10378 else if (!Cand1.Viable)
10379 return false;
10380
10381 // [CUDA] A function with 'never' preference is marked not viable, therefore
10382 // is never shown up here. The worst preference shown up here is 'wrong side',
10383 // e.g. an H function called by a HD function in device compilation. This is
10384 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10385 // function which is called only by an H function. A deferred diagnostic will
10386 // be triggered if it is emitted. However a wrong-sided function is still
10387 // a viable candidate here.
10388 //
10389 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10390 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10391 // can be emitted, Cand1 is not better than Cand2. This rule should have
10392 // precedence over other rules.
10393 //
10394 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10395 // other rules should be used to determine which is better. This is because
10396 // host/device based overloading resolution is mostly for determining
10397 // viability of a function. If two functions are both viable, other factors
10398 // should take precedence in preference, e.g. the standard-defined preferences
10399 // like argument conversion ranks or enable_if partial-ordering. The
10400 // preference for pass-object-size parameters is probably most similar to a
10401 // type-based-overloading decision and so should take priority.
10402 //
10403 // If other rules cannot determine which is better, CUDA preference will be
10404 // used again to determine which is better.
10405 //
10406 // TODO: Currently IdentifyPreference does not return correct values
10407 // for functions called in global variable initializers due to missing
10408 // correct context about device/host. Therefore we can only enforce this
10409 // rule when there is a caller. We should enforce this rule for functions
10410 // in global variable initializers once proper context is added.
10411 //
10412 // TODO: We can only enable the hostness based overloading resolution when
10413 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10414 // overloading resolution diagnostics.
10415 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10416 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10417 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10418 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
10419 bool IsCand1ImplicitHD =
10421 bool IsCand2ImplicitHD =
10423 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
10424 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10425 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10426 // The implicit HD function may be a function in a system header which
10427 // is forced by pragma. In device compilation, if we prefer HD candidates
10428 // over wrong-sided candidates, overloading resolution may change, which
10429 // may result in non-deferrable diagnostics. As a workaround, we let
10430 // implicit HD candidates take equal preference as wrong-sided candidates.
10431 // This will preserve the overloading resolution.
10432 // TODO: We still need special handling of implicit HD functions since
10433 // they may incur other diagnostics to be deferred. We should make all
10434 // host/device related diagnostics deferrable and remove special handling
10435 // of implicit HD functions.
10436 auto EmitThreshold =
10437 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10438 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10441 auto Cand1Emittable = P1 > EmitThreshold;
10442 auto Cand2Emittable = P2 > EmitThreshold;
10443 if (Cand1Emittable && !Cand2Emittable)
10444 return true;
10445 if (!Cand1Emittable && Cand2Emittable)
10446 return false;
10447 }
10448 }
10449
10450 // C++ [over.match.best]p1: (Changed in C++23)
10451 //
10452 // -- if F is a static member function, ICS1(F) is defined such
10453 // that ICS1(F) is neither better nor worse than ICS1(G) for
10454 // any function G, and, symmetrically, ICS1(G) is neither
10455 // better nor worse than ICS1(F).
10456 unsigned StartArg = 0;
10457 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
10458 StartArg = 1;
10459
10460 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10461 // We don't allow incompatible pointer conversions in C++.
10462 if (!S.getLangOpts().CPlusPlus)
10463 return ICS.isStandard() &&
10464 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10465
10466 // The only ill-formed conversion we allow in C++ is the string literal to
10467 // char* conversion, which is only considered ill-formed after C++11.
10468 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10470 };
10471
10472 // Define functions that don't require ill-formed conversions for a given
10473 // argument to be better candidates than functions that do.
10474 unsigned NumArgs = Cand1.Conversions.size();
10475 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10476 bool HasBetterConversion = false;
10477 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10478 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10479 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10480 if (Cand1Bad != Cand2Bad) {
10481 if (Cand1Bad)
10482 return false;
10483 HasBetterConversion = true;
10484 }
10485 }
10486
10487 if (HasBetterConversion)
10488 return true;
10489
10490 // C++ [over.match.best]p1:
10491 // A viable function F1 is defined to be a better function than another
10492 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10493 // conversion sequence than ICSi(F2), and then...
10494 bool HasWorseConversion = false;
10495 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10497 Cand1.Conversions[ArgIdx],
10498 Cand2.Conversions[ArgIdx])) {
10500 // Cand1 has a better conversion sequence.
10501 HasBetterConversion = true;
10502 break;
10503
10505 if (Cand1.Function && Cand2.Function &&
10506 Cand1.isReversed() != Cand2.isReversed() &&
10507 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
10508 // Work around large-scale breakage caused by considering reversed
10509 // forms of operator== in C++20:
10510 //
10511 // When comparing a function against a reversed function, if we have a
10512 // better conversion for one argument and a worse conversion for the
10513 // other, the implicit conversion sequences are treated as being equally
10514 // good.
10515 //
10516 // This prevents a comparison function from being considered ambiguous
10517 // with a reversed form that is written in the same way.
10518 //
10519 // We diagnose this as an extension from CreateOverloadedBinOp.
10520 HasWorseConversion = true;
10521 break;
10522 }
10523
10524 // Cand1 can't be better than Cand2.
10525 return false;
10526
10528 // Do nothing.
10529 break;
10530 }
10531 }
10532
10533 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10534 // ICSj(F2), or, if not that,
10535 if (HasBetterConversion && !HasWorseConversion)
10536 return true;
10537
10538 // -- the context is an initialization by user-defined conversion
10539 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10540 // from the return type of F1 to the destination type (i.e.,
10541 // the type of the entity being initialized) is a better
10542 // conversion sequence than the standard conversion sequence
10543 // from the return type of F2 to the destination type.
10545 Cand1.Function && Cand2.Function &&
10546 isa<CXXConversionDecl>(Cand1.Function) &&
10547 isa<CXXConversionDecl>(Cand2.Function)) {
10548 // First check whether we prefer one of the conversion functions over the
10549 // other. This only distinguishes the results in non-standard, extension
10550 // cases such as the conversion from a lambda closure type to a function
10551 // pointer or block.
10556 Cand1.FinalConversion,
10557 Cand2.FinalConversion);
10558
10561
10562 // FIXME: Compare kind of reference binding if conversion functions
10563 // convert to a reference type used in direct reference binding, per
10564 // C++14 [over.match.best]p1 section 2 bullet 3.
10565 }
10566
10567 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10568 // as combined with the resolution to CWG issue 243.
10569 //
10570 // When the context is initialization by constructor ([over.match.ctor] or
10571 // either phase of [over.match.list]), a constructor is preferred over
10572 // a conversion function.
10573 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10574 Cand1.Function && Cand2.Function &&
10575 isa<CXXConstructorDecl>(Cand1.Function) !=
10576 isa<CXXConstructorDecl>(Cand2.Function))
10577 return isa<CXXConstructorDecl>(Cand1.Function);
10578
10579 // -- F1 is a non-template function and F2 is a function template
10580 // specialization, or, if not that,
10581 bool Cand1IsSpecialization = Cand1.Function &&
10583 bool Cand2IsSpecialization = Cand2.Function &&
10585 if (Cand1IsSpecialization != Cand2IsSpecialization)
10586 return Cand2IsSpecialization;
10587
10588 // -- F1 and F2 are function template specializations, and the function
10589 // template for F1 is more specialized than the template for F2
10590 // according to the partial ordering rules described in 14.5.5.2, or,
10591 // if not that,
10592 if (Cand1IsSpecialization && Cand2IsSpecialization) {
10593 const auto *Obj1Context =
10594 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
10595 const auto *Obj2Context =
10596 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
10597 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10600 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
10601 : TPOC_Call,
10603 Obj1Context ? QualType(Obj1Context->getTypeForDecl(), 0)
10604 : QualType{},
10605 Obj2Context ? QualType(Obj2Context->getTypeForDecl(), 0)
10606 : QualType{},
10607 Cand1.isReversed() ^ Cand2.isReversed())) {
10608 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10609 }
10610 }
10611
10612 // -— F1 and F2 are non-template functions with the same
10613 // parameter-type-lists, and F1 is more constrained than F2 [...],
10614 if (!Cand1IsSpecialization && !Cand2IsSpecialization &&
10615 sameFunctionParameterTypeLists(S, Cand1, Cand2) &&
10617 Cand1.Function)
10618 return true;
10619
10620 // -- F1 is a constructor for a class D, F2 is a constructor for a base
10621 // class B of D, and for all arguments the corresponding parameters of
10622 // F1 and F2 have the same type.
10623 // FIXME: Implement the "all parameters have the same type" check.
10624 bool Cand1IsInherited =
10625 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
10626 bool Cand2IsInherited =
10627 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
10628 if (Cand1IsInherited != Cand2IsInherited)
10629 return Cand2IsInherited;
10630 else if (Cand1IsInherited) {
10631 assert(Cand2IsInherited);
10632 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
10633 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
10634 if (Cand1Class->isDerivedFrom(Cand2Class))
10635 return true;
10636 if (Cand2Class->isDerivedFrom(Cand1Class))
10637 return false;
10638 // Inherited from sibling base classes: still ambiguous.
10639 }
10640
10641 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
10642 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
10643 // with reversed order of parameters and F1 is not
10644 //
10645 // We rank reversed + different operator as worse than just reversed, but
10646 // that comparison can never happen, because we only consider reversing for
10647 // the maximally-rewritten operator (== or <=>).
10648 if (Cand1.RewriteKind != Cand2.RewriteKind)
10649 return Cand1.RewriteKind < Cand2.RewriteKind;
10650
10651 // Check C++17 tie-breakers for deduction guides.
10652 {
10653 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
10654 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
10655 if (Guide1 && Guide2) {
10656 // -- F1 is generated from a deduction-guide and F2 is not
10657 if (Guide1->isImplicit() != Guide2->isImplicit())
10658 return Guide2->isImplicit();
10659
10660 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
10661 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
10662 return true;
10663 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
10664 return false;
10665
10666 // --F1 is generated from a non-template constructor and F2 is generated
10667 // from a constructor template
10668 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
10669 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
10670 if (Constructor1 && Constructor2) {
10671 bool isC1Templated = Constructor1->getTemplatedKind() !=
10673 bool isC2Templated = Constructor2->getTemplatedKind() !=
10675 if (isC1Templated != isC2Templated)
10676 return isC2Templated;
10677 }
10678 }
10679 }
10680
10681 // Check for enable_if value-based overload resolution.
10682 if (Cand1.Function && Cand2.Function) {
10683 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
10684 if (Cmp != Comparison::Equal)
10685 return Cmp == Comparison::Better;
10686 }
10687
10688 bool HasPS1 = Cand1.Function != nullptr &&
10690 bool HasPS2 = Cand2.Function != nullptr &&
10692 if (HasPS1 != HasPS2 && HasPS1)
10693 return true;
10694
10695 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
10696 if (MV == Comparison::Better)
10697 return true;
10698 if (MV == Comparison::Worse)
10699 return false;
10700
10701 // If other rules cannot determine which is better, CUDA preference is used
10702 // to determine which is better.
10703 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
10704 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10705 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
10706 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10707 }
10708
10709 // General member function overloading is handled above, so this only handles
10710 // constructors with address spaces.
10711 // This only handles address spaces since C++ has no other
10712 // qualifier that can be used with constructors.
10713 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
10714 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
10715 if (CD1 && CD2) {
10716 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
10717 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
10718 if (AS1 != AS2) {
10720 return true;
10722 return false;
10723 }
10724 }
10725
10726 return false;
10727}
10728
10729/// Determine whether two declarations are "equivalent" for the purposes of
10730/// name lookup and overload resolution. This applies when the same internal/no
10731/// linkage entity is defined by two modules (probably by textually including
10732/// the same header). In such a case, we don't consider the declarations to
10733/// declare the same entity, but we also don't want lookups with both
10734/// declarations visible to be ambiguous in some cases (this happens when using
10735/// a modularized libstdc++).
10737 const NamedDecl *B) {
10738 auto *VA = dyn_cast_or_null<ValueDecl>(A);
10739 auto *VB = dyn_cast_or_null<ValueDecl>(B);
10740 if (!VA || !VB)
10741 return false;
10742
10743 // The declarations must be declaring the same name as an internal linkage
10744 // entity in different modules.
10745 if (!VA->getDeclContext()->getRedeclContext()->Equals(
10746 VB->getDeclContext()->getRedeclContext()) ||
10747 getOwningModule(VA) == getOwningModule(VB) ||
10748 VA->isExternallyVisible() || VB->isExternallyVisible())
10749 return false;
10750
10751 // Check that the declarations appear to be equivalent.
10752 //
10753 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
10754 // For constants and functions, we should check the initializer or body is
10755 // the same. For non-constant variables, we shouldn't allow it at all.
10756 if (Context.hasSameType(VA->getType(), VB->getType()))
10757 return true;
10758
10759 // Enum constants within unnamed enumerations will have different types, but
10760 // may still be similar enough to be interchangeable for our purposes.
10761 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
10762 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
10763 // Only handle anonymous enums. If the enumerations were named and
10764 // equivalent, they would have been merged to the same type.
10765 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
10766 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
10767 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
10768 !Context.hasSameType(EnumA->getIntegerType(),
10769 EnumB->getIntegerType()))
10770 return false;
10771 // Allow this only if the value is the same for both enumerators.
10772 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
10773 }
10774 }
10775
10776 // Nothing else is sufficiently similar.
10777 return false;
10778}
10779
10782 assert(D && "Unknown declaration");
10783 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
10784
10785 Module *M = getOwningModule(D);
10786 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
10787 << !M << (M ? M->getFullModuleName() : "");
10788
10789 for (auto *E : Equiv) {
10790 Module *M = getOwningModule(E);
10791 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
10792 << !M << (M ? M->getFullModuleName() : "");
10793 }
10794}
10795
10797 return FailureKind == ovl_fail_bad_deduction &&
10798 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
10800 static_cast<CNSInfo *>(DeductionFailure.Data)
10801 ->Satisfaction.ContainsErrors;
10802}
10803
10804/// Computes the best viable function (C++ 13.3.3)
10805/// within an overload candidate set.
10806///
10807/// \param Loc The location of the function name (or operator symbol) for
10808/// which overload resolution occurs.
10809///
10810/// \param Best If overload resolution was successful or found a deleted
10811/// function, \p Best points to the candidate function found.
10812///
10813/// \returns The result of overload resolution.
10816 iterator &Best) {
10818 std::transform(begin(), end(), std::back_inserter(Candidates),
10819 [](OverloadCandidate &Cand) { return &Cand; });
10820
10821 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10822 // are accepted by both clang and NVCC. However, during a particular
10823 // compilation mode only one call variant is viable. We need to
10824 // exclude non-viable overload candidates from consideration based
10825 // only on their host/device attributes. Specifically, if one
10826 // candidate call is WrongSide and the other is SameSide, we ignore
10827 // the WrongSide candidate.
10828 // We only need to remove wrong-sided candidates here if
10829 // -fgpu-exclude-wrong-side-overloads is off. When
10830 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10831 // uniformly in isBetterOverloadCandidate.
10832 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
10833 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10834 bool ContainsSameSideCandidate =
10835 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
10836 // Check viable function only.
10837 return Cand->Viable && Cand->Function &&
10838 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
10840 });
10841 if (ContainsSameSideCandidate) {
10842 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
10843 // Check viable function only to avoid unnecessary data copying/moving.
10844 return Cand->Viable && Cand->Function &&
10845 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
10847 };
10848 llvm::erase_if(Candidates, IsWrongSideCandidate);
10849 }
10850 }
10851
10852 // Find the best viable function.
10853 Best = end();
10854 for (auto *Cand : Candidates) {
10855 Cand->Best = false;
10856 if (Cand->Viable) {
10857 if (Best == end() ||
10858 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
10859 Best = Cand;
10860 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
10861 // This candidate has constraint that we were unable to evaluate because
10862 // it referenced an expression that contained an error. Rather than fall
10863 // back onto a potentially unintended candidate (made worse by
10864 // subsuming constraints), treat this as 'no viable candidate'.
10865 Best = end();
10866 return OR_No_Viable_Function;
10867 }
10868 }
10869
10870 // If we didn't find any viable functions, abort.
10871 if (Best == end())
10872 return OR_No_Viable_Function;
10873
10875
10877 PendingBest.push_back(&*Best);
10878 Best->Best = true;
10879
10880 // Make sure that this function is better than every other viable
10881 // function. If not, we have an ambiguity.
10882 while (!PendingBest.empty()) {
10883 auto *Curr = PendingBest.pop_back_val();
10884 for (auto *Cand : Candidates) {
10885 if (Cand->Viable && !Cand->Best &&
10886 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10887 PendingBest.push_back(Cand);
10888 Cand->Best = true;
10889
10891 Curr->Function))
10892 EquivalentCands.push_back(Cand->Function);
10893 else
10894 Best = end();
10895 }
10896 }
10897 }
10898
10899 // If we found more than one best candidate, this is ambiguous.
10900 if (Best == end())
10901 return OR_Ambiguous;
10902
10903 // Best is the best viable function.
10904 if (Best->Function && Best->Function->isDeleted())
10905 return OR_Deleted;
10906
10907 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
10908 Kind == CSK_AddressOfOverloadSet && M &&
10909 M->isImplicitObjectMemberFunction()) {
10910 return OR_No_Viable_Function;
10911 }
10912
10913 if (!EquivalentCands.empty())
10915 EquivalentCands);
10916
10917 return OR_Success;
10918}
10919
10920namespace {
10921
10922enum OverloadCandidateKind {
10923 oc_function,
10924 oc_method,
10925 oc_reversed_binary_operator,
10926 oc_constructor,
10927 oc_implicit_default_constructor,
10928 oc_implicit_copy_constructor,
10929 oc_implicit_move_constructor,
10930 oc_implicit_copy_assignment,
10931 oc_implicit_move_assignment,
10932 oc_implicit_equality_comparison,
10933 oc_inherited_constructor
10934};
10935
10936enum OverloadCandidateSelect {
10937 ocs_non_template,
10938 ocs_template,
10939 ocs_described_template,
10940};
10941
10942static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10943ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
10944 const FunctionDecl *Fn,
10946 std::string &Description) {
10947
10948 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10949 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10950 isTemplate = true;
10951 Description = S.getTemplateArgumentBindingsText(
10952 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
10953 }
10954
10955 OverloadCandidateSelect Select = [&]() {
10956 if (!Description.empty())
10957 return ocs_described_template;
10958 return isTemplate ? ocs_template : ocs_non_template;
10959 }();
10960
10961 OverloadCandidateKind Kind = [&]() {
10962 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10963 return oc_implicit_equality_comparison;
10964
10965 if (CRK & CRK_Reversed)
10966 return oc_reversed_binary_operator;
10967
10968 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10969 if (!Ctor->isImplicit()) {
10970 if (isa<ConstructorUsingShadowDecl>(Found))
10971 return oc_inherited_constructor;
10972 else
10973 return oc_constructor;
10974 }
10975
10976 if (Ctor->isDefaultConstructor())
10977 return oc_implicit_default_constructor;
10978
10979 if (Ctor->isMoveConstructor())
10980 return oc_implicit_move_constructor;
10981
10982 assert(Ctor->isCopyConstructor() &&
10983 "unexpected sort of implicit constructor");
10984 return oc_implicit_copy_constructor;
10985 }
10986
10987 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
10988 // This actually gets spelled 'candidate function' for now, but
10989 // it doesn't hurt to split it out.
10990 if (!Meth->isImplicit())
10991 return oc_method;
10992
10993 if (Meth->isMoveAssignmentOperator())
10994 return oc_implicit_move_assignment;
10995
10996 if (Meth->isCopyAssignmentOperator())
10997 return oc_implicit_copy_assignment;
10998
10999 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11000 return oc_method;
11001 }
11002
11003 return oc_function;
11004 }();
11005
11006 return std::make_pair(Kind, Select);
11007}
11008
11009void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11010 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11011 // set.
11012 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11013 S.Diag(FoundDecl->getLocation(),
11014 diag::note_ovl_candidate_inherited_constructor)
11015 << Shadow->getNominatedBaseClass();
11016}
11017
11018} // end anonymous namespace
11019
11021 const FunctionDecl *FD) {
11022 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11023 bool AlwaysTrue;
11024 if (EnableIf->getCond()->isValueDependent() ||
11025 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11026 return false;
11027 if (!AlwaysTrue)
11028 return false;
11029 }
11030 return true;
11031}
11032
11033/// Returns true if we can take the address of the function.
11034///
11035/// \param Complain - If true, we'll emit a diagnostic
11036/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11037/// we in overload resolution?
11038/// \param Loc - The location of the statement we're complaining about. Ignored
11039/// if we're not complaining, or if we're in overload resolution.
11041 bool Complain,
11042 bool InOverloadResolution,
11043 SourceLocation Loc) {
11044 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11045 if (Complain) {
11046 if (InOverloadResolution)
11047 S.Diag(FD->getBeginLoc(),
11048 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11049 else
11050 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11051 }
11052 return false;
11053 }
11054
11055 if (FD->getTrailingRequiresClause()) {
11056 ConstraintSatisfaction Satisfaction;
11057 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11058 return false;
11059 if (!Satisfaction.IsSatisfied) {
11060 if (Complain) {
11061 if (InOverloadResolution) {
11062 SmallString<128> TemplateArgString;
11063 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11064 TemplateArgString += " ";
11065 TemplateArgString += S.getTemplateArgumentBindingsText(
11066 FunTmpl->getTemplateParameters(),
11068 }
11069
11070 S.Diag(FD->getBeginLoc(),
11071 diag::note_ovl_candidate_unsatisfied_constraints)
11072 << TemplateArgString;
11073 } else
11074 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11075 << FD;
11076 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11077 }
11078 return false;
11079 }
11080 }
11081
11082 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11083 return P->hasAttr<PassObjectSizeAttr>();
11084 });
11085 if (I == FD->param_end())
11086 return true;
11087
11088 if (Complain) {
11089 // Add one to ParamNo because it's user-facing
11090 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11091 if (InOverloadResolution)
11092 S.Diag(FD->getLocation(),
11093 diag::note_ovl_candidate_has_pass_object_size_params)
11094 << ParamNo;
11095 else
11096 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11097 << FD << ParamNo;
11098 }
11099 return false;
11100}
11101
11103 const FunctionDecl *FD) {
11104 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11105 /*InOverloadResolution=*/true,
11106 /*Loc=*/SourceLocation());
11107}
11108
11110 bool Complain,
11111 SourceLocation Loc) {
11112 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11113 /*InOverloadResolution=*/false,
11114 Loc);
11115}
11116
11117// Don't print candidates other than the one that matches the calling
11118// convention of the call operator, since that is guaranteed to exist.
11120 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11121
11122 if (!ConvD)
11123 return false;
11124 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11125 if (!RD->isLambda())
11126 return false;
11127
11128 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11129 CallingConv CallOpCC =
11130 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11131 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11132 CallingConv ConvToCC =
11133 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11134
11135 return ConvToCC != CallOpCC;
11136}
11137
11138// Notes the location of an overload candidate.
11140 OverloadCandidateRewriteKind RewriteKind,
11141 QualType DestType, bool TakingAddress) {
11142 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11143 return;
11144 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11145 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11146 return;
11147 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11148 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11149 return;
11151 return;
11152
11153 std::string FnDesc;
11154 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11155 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11156 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11157 << (unsigned)KSPair.first << (unsigned)KSPair.second
11158 << Fn << FnDesc;
11159
11160 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11161 Diag(Fn->getLocation(), PD);
11162 MaybeEmitInheritedConstructorNote(*this, Found);
11163}
11164
11165static void
11167 // Perhaps the ambiguity was caused by two atomic constraints that are
11168 // 'identical' but not equivalent:
11169 //
11170 // void foo() requires (sizeof(T) > 4) { } // #1
11171 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11172 //
11173 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11174 // #2 to subsume #1, but these constraint are not considered equivalent
11175 // according to the subsumption rules because they are not the same
11176 // source-level construct. This behavior is quite confusing and we should try
11177 // to help the user figure out what happened.
11178
11179 SmallVector<const Expr *, 3> FirstAC, SecondAC;
11180 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11181 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11182 if (!I->Function)
11183 continue;
11185 if (auto *Template = I->Function->getPrimaryTemplate())
11186 Template->getAssociatedConstraints(AC);
11187 else
11188 I->Function->getAssociatedConstraints(AC);
11189 if (AC.empty())
11190 continue;
11191 if (FirstCand == nullptr) {
11192 FirstCand = I->Function;
11193 FirstAC = AC;
11194 } else if (SecondCand == nullptr) {
11195 SecondCand = I->Function;
11196 SecondAC = AC;
11197 } else {
11198 // We have more than one pair of constrained functions - this check is
11199 // expensive and we'd rather not try to diagnose it.
11200 return;
11201 }
11202 }
11203 if (!SecondCand)
11204 return;
11205 // The diagnostic can only happen if there are associated constraints on
11206 // both sides (there needs to be some identical atomic constraint).
11207 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11208 SecondCand, SecondAC))
11209 // Just show the user one diagnostic, they'll probably figure it out
11210 // from here.
11211 return;
11212}
11213
11214// Notes the location of all overload candidates designated through
11215// OverloadedExpr
11216void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11217 bool TakingAddress) {
11218 assert(OverloadedExpr->getType() == Context.OverloadTy);
11219
11220 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11221 OverloadExpr *OvlExpr = Ovl.Expression;
11222
11223 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11224 IEnd = OvlExpr->decls_end();
11225 I != IEnd; ++I) {
11226 if (FunctionTemplateDecl *FunTmpl =
11227 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11228 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11229 TakingAddress);
11230 } else if (FunctionDecl *Fun
11231 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11232 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11233 }
11234 }
11235}
11236
11237/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11238/// "lead" diagnostic; it will be given two arguments, the source and
11239/// target types of the conversion.
11241 Sema &S,
11242 SourceLocation CaretLoc,
11243 const PartialDiagnostic &PDiag) const {
11244 S.Diag(CaretLoc, PDiag)
11245 << Ambiguous.getFromType() << Ambiguous.getToType();
11246 unsigned CandsShown = 0;
11248 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11249 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11250 break;
11251 ++CandsShown;
11252 S.NoteOverloadCandidate(I->first, I->second);
11253 }
11254 S.Diags.overloadCandidatesShown(CandsShown);
11255 if (I != E)
11256 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11257}
11258
11260 unsigned I, bool TakingCandidateAddress) {
11261 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11262 assert(Conv.isBad());
11263 assert(Cand->Function && "for now, candidate must be a function");
11264 FunctionDecl *Fn = Cand->Function;
11265
11266 // There's a conversion slot for the object argument if this is a
11267 // non-constructor method. Note that 'I' corresponds the
11268 // conversion-slot index.
11269 bool isObjectArgument = false;
11270 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
11271 if (I == 0)
11272 isObjectArgument = true;
11273 else if (!Fn->hasCXXExplicitFunctionObjectParameter())
11274 I--;
11275 }
11276
11277 std::string FnDesc;
11278 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11279 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
11280 FnDesc);
11281
11282 Expr *FromExpr = Conv.Bad.FromExpr;
11283 QualType FromTy = Conv.Bad.getFromType();
11284 QualType ToTy = Conv.Bad.getToType();
11285 SourceRange ToParamRange;
11286
11287 // FIXME: In presence of parameter packs we can't determine parameter range
11288 // reliably, as we don't have access to instantiation.
11289 bool HasParamPack =
11290 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
11291 return Parm->isParameterPack();
11292 });
11293 if (!isObjectArgument && !HasParamPack)
11294 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
11295
11296 if (FromTy == S.Context.OverloadTy) {
11297 assert(FromExpr && "overload set argument came from implicit argument?");
11298 Expr *E = FromExpr->IgnoreParens();
11299 if (isa<UnaryOperator>(E))
11300 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11301 DeclarationName Name = cast<OverloadExpr>(E)->getName();
11302
11303 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
11304 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11305 << ToParamRange << ToTy << Name << I + 1;
11306 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11307 return;
11308 }
11309
11310 // Do some hand-waving analysis to see if the non-viability is due
11311 // to a qualifier mismatch.
11312 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
11313 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
11314 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11315 CToTy = RT->getPointeeType();
11316 else {
11317 // TODO: detect and diagnose the full richness of const mismatches.
11318 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11319 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11320 CFromTy = FromPT->getPointeeType();
11321 CToTy = ToPT->getPointeeType();
11322 }
11323 }
11324
11325 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11326 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
11327 Qualifiers FromQs = CFromTy.getQualifiers();
11328 Qualifiers ToQs = CToTy.getQualifiers();
11329
11330 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11331 if (isObjectArgument)
11332 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
11333 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11334 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11335 else
11336 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
11337 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11338 << FnDesc << ToParamRange << FromQs.getAddressSpace()
11339 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11340 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11341 return;
11342 }
11343
11344 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11345 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
11346 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11347 << ToParamRange << FromTy << FromQs.getObjCLifetime()
11348 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11349 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11350 return;
11351 }
11352
11353 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11354 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
11355 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11356 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11357 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11358 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11359 return;
11360 }
11361
11362 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11363 assert(CVR && "expected qualifiers mismatch");
11364
11365 if (isObjectArgument) {
11366 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
11367 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11368 << FromTy << (CVR - 1);
11369 } else {
11370 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
11371 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11372 << ToParamRange << FromTy << (CVR - 1) << I + 1;
11373 }
11374 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11375 return;
11376 }
11377
11380 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
11381 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11382 << (unsigned)isObjectArgument << I + 1
11384 << ToParamRange;
11385 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11386 return;
11387 }
11388
11389 // Special diagnostic for failure to convert an initializer list, since
11390 // telling the user that it has type void is not useful.
11391 if (FromExpr && isa<InitListExpr>(FromExpr)) {
11392 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
11393 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11394 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11397 ? 2
11398 : 0);
11399 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11400 return;
11401 }
11402
11403 // Diagnose references or pointers to incomplete types differently,
11404 // since it's far from impossible that the incompleteness triggered
11405 // the failure.
11406 QualType TempFromTy = FromTy.getNonReferenceType();
11407 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
11408 TempFromTy = PTy->getPointeeType();
11409 if (TempFromTy->isIncompleteType()) {
11410 // Emit the generic diagnostic and, optionally, add the hints to it.
11411 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
11412 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11413 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11414 << (unsigned)(Cand->Fix.Kind);
11415
11416 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11417 return;
11418 }
11419
11420 // Diagnose base -> derived pointer conversions.
11421 unsigned BaseToDerivedConversion = 0;
11422 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
11423 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
11424 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11425 FromPtrTy->getPointeeType(), S.getASTContext()) &&
11426 !FromPtrTy->getPointeeType()->isIncompleteType() &&
11427 !ToPtrTy->getPointeeType()->isIncompleteType() &&
11428 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
11429 FromPtrTy->getPointeeType()))
11430 BaseToDerivedConversion = 1;
11431 }
11432 } else if (const ObjCObjectPointerType *FromPtrTy
11433 = FromTy->getAs<ObjCObjectPointerType>()) {
11434 if (const ObjCObjectPointerType *ToPtrTy
11435 = ToTy->getAs<ObjCObjectPointerType>())
11436 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
11437 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
11438 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11439 FromPtrTy->getPointeeType(), S.getASTContext()) &&
11440 FromIface->isSuperClassOf(ToIface))
11441 BaseToDerivedConversion = 2;
11442 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
11443 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
11444 S.getASTContext()) &&
11445 !FromTy->isIncompleteType() &&
11446 !ToRefTy->getPointeeType()->isIncompleteType() &&
11447 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
11448 BaseToDerivedConversion = 3;
11449 }
11450 }
11451
11452 if (BaseToDerivedConversion) {
11453 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
11454 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11455 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
11456 << I + 1;
11457 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11458 return;
11459 }
11460
11461 if (isa<ObjCObjectPointerType>(CFromTy) &&
11462 isa<PointerType>(CToTy)) {
11463 Qualifiers FromQs = CFromTy.getQualifiers();
11464 Qualifiers ToQs = CToTy.getQualifiers();
11465 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11466 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
11467 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11468 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
11469 << I + 1;
11470 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11471 return;
11472 }
11473 }
11474
11475 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
11476 return;
11477
11478 // Emit the generic diagnostic and, optionally, add the hints to it.
11479 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
11480 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11481 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11482 << (unsigned)(Cand->Fix.Kind);
11483
11484 // Check that location of Fn is not in system header.
11485 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
11486 // If we can fix the conversion, suggest the FixIts.
11487 for (const FixItHint &HI : Cand->Fix.Hints)
11488 FDiag << HI;
11489 }
11490
11491 S.Diag(Fn->getLocation(), FDiag);
11492
11493 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11494}
11495
11496/// Additional arity mismatch diagnosis specific to a function overload
11497/// candidates. This is not covered by the more general DiagnoseArityMismatch()
11498/// over a candidate in any candidate set.
11500 unsigned NumArgs, bool IsAddressOf = false) {
11501 assert(Cand->Function && "Candidate is required to be a function.");
11502 FunctionDecl *Fn = Cand->Function;
11503 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
11504 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
11505
11506 // With invalid overloaded operators, it's possible that we think we
11507 // have an arity mismatch when in fact it looks like we have the
11508 // right number of arguments, because only overloaded operators have
11509 // the weird behavior of overloading member and non-member functions.
11510 // Just don't report anything.
11511 if (Fn->isInvalidDecl() &&
11512 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
11513 return true;
11514
11515 if (NumArgs < MinParams) {
11516 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
11518 Cand->DeductionFailure.getResult() ==
11520 } else {
11521 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
11523 Cand->DeductionFailure.getResult() ==
11525 }
11526
11527 return false;
11528}
11529
11530/// General arity mismatch diagnosis over a candidate in a candidate set.
11532 unsigned NumFormalArgs,
11533 bool IsAddressOf = false) {
11534 assert(isa<FunctionDecl>(D) &&
11535 "The templated declaration should at least be a function"
11536 " when diagnosing bad template argument deduction due to too many"
11537 " or too few arguments");
11538
11539 FunctionDecl *Fn = cast<FunctionDecl>(D);
11540
11541 // TODO: treat calls to a missing default constructor as a special case
11542 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
11543 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
11544 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
11545
11546 // at least / at most / exactly
11547 bool HasExplicitObjectParam =
11548 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
11549
11550 unsigned ParamCount =
11551 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
11552 unsigned mode, modeCount;
11553
11554 if (NumFormalArgs < MinParams) {
11555 if (MinParams != ParamCount || FnTy->isVariadic() ||
11556 FnTy->isTemplateVariadic())
11557 mode = 0; // "at least"
11558 else
11559 mode = 2; // "exactly"
11560 modeCount = MinParams;
11561 } else {
11562 if (MinParams != ParamCount)
11563 mode = 1; // "at most"
11564 else
11565 mode = 2; // "exactly"
11566 modeCount = ParamCount;
11567 }
11568
11569 std::string Description;
11570 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11571 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
11572
11573 if (modeCount == 1 && !IsAddressOf &&
11574 Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())
11575 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
11576 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11577 << Description << mode
11578 << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
11579 << HasExplicitObjectParam << Fn->getParametersSourceRange();
11580 else
11581 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
11582 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11583 << Description << mode << modeCount << NumFormalArgs
11584 << HasExplicitObjectParam << Fn->getParametersSourceRange();
11585
11586 MaybeEmitInheritedConstructorNote(S, Found);
11587}
11588
11589/// Arity mismatch diagnosis specific to a function overload candidate.
11591 unsigned NumFormalArgs) {
11592 assert(Cand->Function && "Candidate must be a function");
11593 FunctionDecl *Fn = Cand->Function;
11594 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
11595 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
11596 Cand->TookAddressOfOverload);
11597}
11598
11600 if (TemplateDecl *TD = Templated->getDescribedTemplate())
11601 return TD;
11602 llvm_unreachable("Unsupported: Getting the described template declaration"
11603 " for bad deduction diagnosis");
11604}
11605
11606/// Diagnose a failed template-argument deduction.
11607static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
11608 DeductionFailureInfo &DeductionFailure,
11609 unsigned NumArgs,
11610 bool TakingCandidateAddress) {
11611 TemplateParameter Param = DeductionFailure.getTemplateParameter();
11612 NamedDecl *ParamD;
11613 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
11614 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
11615 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
11616 switch (DeductionFailure.getResult()) {
11618 llvm_unreachable(
11619 "TemplateDeductionResult::Success while diagnosing bad deduction");
11621 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
11622 "while diagnosing bad deduction");
11625 return;
11626
11628 assert(ParamD && "no parameter found for incomplete deduction result");
11629 S.Diag(Templated->getLocation(),
11630 diag::note_ovl_candidate_incomplete_deduction)
11631 << ParamD->getDeclName();
11632 MaybeEmitInheritedConstructorNote(S, Found);
11633 return;
11634 }
11635
11637 assert(ParamD && "no parameter found for incomplete deduction result");
11638 S.Diag(Templated->getLocation(),
11639 diag::note_ovl_candidate_incomplete_deduction_pack)
11640 << ParamD->getDeclName()
11641 << (DeductionFailure.getFirstArg()->pack_size() + 1)
11642 << *DeductionFailure.getFirstArg();
11643 MaybeEmitInheritedConstructorNote(S, Found);
11644 return;
11645 }
11646
11648 assert(ParamD && "no parameter found for bad qualifiers deduction result");
11649 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
11650
11651 QualType Param = DeductionFailure.getFirstArg()->getAsType();
11652
11653 // Param will have been canonicalized, but it should just be a
11654 // qualified version of ParamD, so move the qualifiers to that.
11656 Qs.strip(Param);
11657 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
11658 assert(S.Context.hasSameType(Param, NonCanonParam));
11659
11660 // Arg has also been canonicalized, but there's nothing we can do
11661 // about that. It also doesn't matter as much, because it won't
11662 // have any template parameters in it (because deduction isn't
11663 // done on dependent types).
11664 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
11665
11666 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
11667 << ParamD->getDeclName() << Arg << NonCanonParam;
11668 MaybeEmitInheritedConstructorNote(S, Found);
11669 return;
11670 }
11671
11673 assert(ParamD && "no parameter found for inconsistent deduction result");
11674 int which = 0;
11675 if (isa<TemplateTypeParmDecl>(ParamD))
11676 which = 0;
11677 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
11678 // Deduction might have failed because we deduced arguments of two
11679 // different types for a non-type template parameter.
11680 // FIXME: Use a different TDK value for this.
11681 QualType T1 =
11682 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
11683 QualType T2 =
11684 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
11685 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
11686 S.Diag(Templated->getLocation(),
11687 diag::note_ovl_candidate_inconsistent_deduction_types)
11688 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
11689 << *DeductionFailure.getSecondArg() << T2;
11690 MaybeEmitInheritedConstructorNote(S, Found);
11691 return;
11692 }
11693
11694 which = 1;
11695 } else {
11696 which = 2;
11697 }
11698
11699 // Tweak the diagnostic if the problem is that we deduced packs of
11700 // different arities. We'll print the actual packs anyway in case that
11701 // includes additional useful information.
11702 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
11703 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
11704 DeductionFailure.getFirstArg()->pack_size() !=
11705 DeductionFailure.getSecondArg()->pack_size()) {
11706 which = 3;
11707 }
11708
11709 S.Diag(Templated->getLocation(),
11710 diag::note_ovl_candidate_inconsistent_deduction)
11711 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
11712 << *DeductionFailure.getSecondArg();
11713 MaybeEmitInheritedConstructorNote(S, Found);
11714 return;
11715 }
11716
11718 assert(ParamD && "no parameter found for invalid explicit arguments");
11719 if (ParamD->getDeclName())
11720 S.Diag(Templated->getLocation(),
11721 diag::note_ovl_candidate_explicit_arg_mismatch_named)
11722 << ParamD->getDeclName();
11723 else {
11724 int index = 0;
11725 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
11726 index = TTP->getIndex();
11727 else if (NonTypeTemplateParmDecl *NTTP
11728 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
11729 index = NTTP->getIndex();
11730 else
11731 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
11732 S.Diag(Templated->getLocation(),
11733 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
11734 << (index + 1);
11735 }
11736 MaybeEmitInheritedConstructorNote(S, Found);
11737 return;
11738
11740 // Format the template argument list into the argument string.
11741 SmallString<128> TemplateArgString;
11742 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
11743 TemplateArgString = " ";
11744 TemplateArgString += S.getTemplateArgumentBindingsText(
11745 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11746 if (TemplateArgString.size() == 1)
11747 TemplateArgString.clear();
11748 S.Diag(Templated->getLocation(),
11749 diag::note_ovl_candidate_unsatisfied_constraints)
11750 << TemplateArgString;
11751
11753 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
11754 return;
11755 }
11758 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
11759 return;
11760
11762 S.Diag(Templated->getLocation(),
11763 diag::note_ovl_candidate_instantiation_depth);
11764 MaybeEmitInheritedConstructorNote(S, Found);
11765 return;
11766
11768 // Format the template argument list into the argument string.
11769 SmallString<128> TemplateArgString;
11770 if (TemplateArgumentList *Args =
11771 DeductionFailure.getTemplateArgumentList()) {
11772 TemplateArgString = " ";
11773 TemplateArgString += S.getTemplateArgumentBindingsText(
11774 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11775 if (TemplateArgString.size() == 1)
11776 TemplateArgString.clear();
11777 }
11778
11779 // If this candidate was disabled by enable_if, say so.
11780 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
11781 if (PDiag && PDiag->second.getDiagID() ==
11782 diag::err_typename_nested_not_found_enable_if) {
11783 // FIXME: Use the source range of the condition, and the fully-qualified
11784 // name of the enable_if template. These are both present in PDiag.
11785 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
11786 << "'enable_if'" << TemplateArgString;
11787 return;
11788 }
11789
11790 // We found a specific requirement that disabled the enable_if.
11791 if (PDiag && PDiag->second.getDiagID() ==
11792 diag::err_typename_nested_not_found_requirement) {
11793 S.Diag(Templated->getLocation(),
11794 diag::note_ovl_candidate_disabled_by_requirement)
11795 << PDiag->second.getStringArg(0) << TemplateArgString;
11796 return;
11797 }
11798
11799 // Format the SFINAE diagnostic into the argument string.
11800 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
11801 // formatted message in another diagnostic.
11802 SmallString<128> SFINAEArgString;
11803 SourceRange R;
11804 if (PDiag) {
11805 SFINAEArgString = ": ";
11806 R = SourceRange(PDiag->first, PDiag->first);
11807 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
11808 }
11809
11810 S.Diag(Templated->getLocation(),
11811 diag::note_ovl_candidate_substitution_failure)
11812 << TemplateArgString << SFINAEArgString << R;
11813 MaybeEmitInheritedConstructorNote(S, Found);
11814 return;
11815 }
11816
11819 // Format the template argument list into the argument string.
11820 SmallString<128> TemplateArgString;
11821 if (TemplateArgumentList *Args =
11822 DeductionFailure.getTemplateArgumentList()) {
11823 TemplateArgString = " ";
11824 TemplateArgString += S.getTemplateArgumentBindingsText(
11825 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11826 if (TemplateArgString.size() == 1)
11827 TemplateArgString.clear();
11828 }
11829
11830 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
11831 << (*DeductionFailure.getCallArgIndex() + 1)
11832 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
11833 << TemplateArgString
11834 << (DeductionFailure.getResult() ==
11836 break;
11837 }
11838
11840 // FIXME: Provide a source location to indicate what we couldn't match.
11841 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
11842 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
11843 if (FirstTA.getKind() == TemplateArgument::Template &&
11844 SecondTA.getKind() == TemplateArgument::Template) {
11845 TemplateName FirstTN = FirstTA.getAsTemplate();
11846 TemplateName SecondTN = SecondTA.getAsTemplate();
11847 if (FirstTN.getKind() == TemplateName::Template &&
11848 SecondTN.getKind() == TemplateName::Template) {
11849 if (FirstTN.getAsTemplateDecl()->getName() ==
11850 SecondTN.getAsTemplateDecl()->getName()) {
11851 // FIXME: This fixes a bad diagnostic where both templates are named
11852 // the same. This particular case is a bit difficult since:
11853 // 1) It is passed as a string to the diagnostic printer.
11854 // 2) The diagnostic printer only attempts to find a better
11855 // name for types, not decls.
11856 // Ideally, this should folded into the diagnostic printer.
11857 S.Diag(Templated->getLocation(),
11858 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
11859 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
11860 return;
11861 }
11862 }
11863 }
11864
11865 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
11866 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
11867 return;
11868
11869 // FIXME: For generic lambda parameters, check if the function is a lambda
11870 // call operator, and if so, emit a prettier and more informative
11871 // diagnostic that mentions 'auto' and lambda in addition to
11872 // (or instead of?) the canonical template type parameters.
11873 S.Diag(Templated->getLocation(),
11874 diag::note_ovl_candidate_non_deduced_mismatch)
11875 << FirstTA << SecondTA;
11876 return;
11877 }
11878 // TODO: diagnose these individually, then kill off
11879 // note_ovl_candidate_bad_deduction, which is uselessly vague.
11881 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
11882 MaybeEmitInheritedConstructorNote(S, Found);
11883 return;
11885 S.Diag(Templated->getLocation(),
11886 diag::note_cuda_ovl_candidate_target_mismatch);
11887 return;
11888 }
11889}
11890
11891/// Diagnose a failed template-argument deduction, for function calls.
11893 unsigned NumArgs,
11894 bool TakingCandidateAddress) {
11895 assert(Cand->Function && "Candidate must be a function");
11896 FunctionDecl *Fn = Cand->Function;
11900 if (CheckArityMismatch(S, Cand, NumArgs))
11901 return;
11902 }
11903 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
11904 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11905}
11906
11907/// CUDA: diagnose an invalid call across targets.
11909 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11910 assert(Cand->Function && "Candidate must be a Function.");
11911 FunctionDecl *Callee = Cand->Function;
11912
11913 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
11914 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
11915
11916 std::string FnDesc;
11917 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11918 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
11919 Cand->getRewriteKind(), FnDesc);
11920
11921 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11922 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11923 << FnDesc /* Ignored */
11924 << llvm::to_underlying(CalleeTarget) << llvm::to_underlying(CallerTarget);
11925
11926 // This could be an implicit constructor for which we could not infer the
11927 // target due to a collsion. Diagnose that case.
11928 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
11929 if (Meth != nullptr && Meth->isImplicit()) {
11930 CXXRecordDecl *ParentClass = Meth->getParent();
11932
11933 switch (FnKindPair.first) {
11934 default:
11935 return;
11936 case oc_implicit_default_constructor:
11938 break;
11939 case oc_implicit_copy_constructor:
11941 break;
11942 case oc_implicit_move_constructor:
11944 break;
11945 case oc_implicit_copy_assignment:
11947 break;
11948 case oc_implicit_move_assignment:
11950 break;
11951 };
11952
11953 bool ConstRHS = false;
11954 if (Meth->getNumParams()) {
11955 if (const ReferenceType *RT =
11956 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11957 ConstRHS = RT->getPointeeType().isConstQualified();
11958 }
11959 }
11960
11961 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
11962 /* ConstRHS */ ConstRHS,
11963 /* Diagnose */ true);
11964 }
11965}
11966
11968 assert(Cand->Function && "Candidate must be a function");
11969 FunctionDecl *Callee = Cand->Function;
11970 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
11971
11972 S.Diag(Callee->getLocation(),
11973 diag::note_ovl_candidate_disabled_by_function_cond_attr)
11974 << Attr->getCond()->getSourceRange() << Attr->getMessage();
11975}
11976
11978 assert(Cand->Function && "Candidate must be a function");
11979 FunctionDecl *Fn = Cand->Function;
11981 assert(ES.isExplicit() && "not an explicit candidate");
11982
11983 unsigned Kind;
11984 switch (Fn->getDeclKind()) {
11985 case Decl::Kind::CXXConstructor:
11986 Kind = 0;
11987 break;
11988 case Decl::Kind::CXXConversion:
11989 Kind = 1;
11990 break;
11991 case Decl::Kind::CXXDeductionGuide:
11992 Kind = Fn->isImplicit() ? 0 : 2;
11993 break;
11994 default:
11995 llvm_unreachable("invalid Decl");
11996 }
11997
11998 // Note the location of the first (in-class) declaration; a redeclaration
11999 // (particularly an out-of-class definition) will typically lack the
12000 // 'explicit' specifier.
12001 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12002 FunctionDecl *First = Fn->getFirstDecl();
12003 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12004 First = Pattern->getFirstDecl();
12005
12006 S.Diag(First->getLocation(),
12007 diag::note_ovl_candidate_explicit)
12008 << Kind << (ES.getExpr() ? 1 : 0)
12009 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12010}
12011
12013 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
12014 if (!DG)
12015 return;
12016 TemplateDecl *OriginTemplate =
12018 // We want to always print synthesized deduction guides for type aliases.
12019 // They would retain the explicit bit of the corresponding constructor.
12020 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12021 return;
12022 std::string FunctionProto;
12023 llvm::raw_string_ostream OS(FunctionProto);
12024 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12025 if (!Template) {
12026 // This also could be an instantiation. Find out the primary template.
12027 FunctionDecl *Pattern =
12028 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12029 if (!Pattern) {
12030 // The implicit deduction guide is built on an explicit non-template
12031 // deduction guide. Currently, this might be the case only for type
12032 // aliases.
12033 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12034 // gets merged.
12035 assert(OriginTemplate->isTypeAlias() &&
12036 "Non-template implicit deduction guides are only possible for "
12037 "type aliases");
12038 DG->print(OS);
12039 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12040 << FunctionProto;
12041 return;
12042 }
12043 Template = Pattern->getDescribedFunctionTemplate();
12044 assert(Template && "Cannot find the associated function template of "
12045 "CXXDeductionGuideDecl?");
12046 }
12047 Template->print(OS);
12048 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12049 << FunctionProto;
12050}
12051
12052/// Generates a 'note' diagnostic for an overload candidate. We've
12053/// already generated a primary error at the call site.
12054///
12055/// It really does need to be a single diagnostic with its caret
12056/// pointed at the candidate declaration. Yes, this creates some
12057/// major challenges of technical writing. Yes, this makes pointing
12058/// out problems with specific arguments quite awkward. It's still
12059/// better than generating twenty screens of text for every failed
12060/// overload.
12061///
12062/// It would be great to be able to express per-candidate problems
12063/// more richly for those diagnostic clients that cared, but we'd
12064/// still have to be just as careful with the default diagnostics.
12065/// \param CtorDestAS Addr space of object being constructed (for ctor
12066/// candidates only).
12068 unsigned NumArgs,
12069 bool TakingCandidateAddress,
12070 LangAS CtorDestAS = LangAS::Default) {
12071 assert(Cand->Function && "Candidate must be a function");
12072 FunctionDecl *Fn = Cand->Function;
12074 return;
12075
12076 // There is no physical candidate declaration to point to for OpenCL builtins.
12077 // Except for failed conversions, the notes are identical for each candidate,
12078 // so do not generate such notes.
12079 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12081 return;
12082
12083 // Skip implicit member functions when trying to resolve
12084 // the address of a an overload set for a function pointer.
12085 if (Cand->TookAddressOfOverload &&
12086 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12087 return;
12088
12089 // Note deleted candidates, but only if they're viable.
12090 if (Cand->Viable) {
12091 if (Fn->isDeleted()) {
12092 std::string FnDesc;
12093 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12094 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12095 Cand->getRewriteKind(), FnDesc);
12096
12097 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12098 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12099 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12100 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12101 return;
12102 }
12103
12104 // We don't really have anything else to say about viable candidates.
12105 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12106 return;
12107 }
12108
12109 // If this is a synthesized deduction guide we're deducing against, add a note
12110 // for it. These deduction guides are not explicitly spelled in the source
12111 // code, so simply printing a deduction failure note mentioning synthesized
12112 // template parameters or pointing to the header of the surrounding RecordDecl
12113 // would be confusing.
12114 //
12115 // We prefer adding such notes at the end of the deduction failure because
12116 // duplicate code snippets appearing in the diagnostic would likely become
12117 // noisy.
12118 auto _ = llvm::make_scope_exit([&] { NoteImplicitDeductionGuide(S, Fn); });
12119
12120 switch (Cand->FailureKind) {
12123 return DiagnoseArityMismatch(S, Cand, NumArgs);
12124
12126 return DiagnoseBadDeduction(S, Cand, NumArgs,
12127 TakingCandidateAddress);
12128
12130 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12131 << (Fn->getPrimaryTemplate() ? 1 : 0);
12132 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12133 return;
12134 }
12135
12137 Qualifiers QualsForPrinting;
12138 QualsForPrinting.setAddressSpace(CtorDestAS);
12139 S.Diag(Fn->getLocation(),
12140 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12141 << QualsForPrinting;
12142 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12143 return;
12144 }
12145
12149 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12150
12152 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12153 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12154 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12155 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12156
12157 // FIXME: this currently happens when we're called from SemaInit
12158 // when user-conversion overload fails. Figure out how to handle
12159 // those conditions and diagnose them well.
12160 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12161 }
12162
12164 return DiagnoseBadTarget(S, Cand);
12165
12166 case ovl_fail_enable_if:
12167 return DiagnoseFailedEnableIfAttr(S, Cand);
12168
12169 case ovl_fail_explicit:
12170 return DiagnoseFailedExplicitSpec(S, Cand);
12171
12173 // It's generally not interesting to note copy/move constructors here.
12174 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12175 return;
12176 S.Diag(Fn->getLocation(),
12177 diag::note_ovl_candidate_inherited_constructor_slice)
12178 << (Fn->getPrimaryTemplate() ? 1 : 0)
12179 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12180 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12181 return;
12182
12184 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
12185 (void)Available;
12186 assert(!Available);
12187 break;
12188 }
12190 // Do nothing, these should simply be ignored.
12191 break;
12192
12194 std::string FnDesc;
12195 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12196 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12197 Cand->getRewriteKind(), FnDesc);
12198
12199 S.Diag(Fn->getLocation(),
12200 diag::note_ovl_candidate_constraints_not_satisfied)
12201 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12202 << FnDesc /* Ignored */;
12203 ConstraintSatisfaction Satisfaction;
12204 if (S.CheckFunctionConstraints(Fn, Satisfaction))
12205 break;
12206 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12207 }
12208 }
12209}
12210
12213 return;
12214
12215 // Desugar the type of the surrogate down to a function type,
12216 // retaining as many typedefs as possible while still showing
12217 // the function type (and, therefore, its parameter types).
12218 QualType FnType = Cand->Surrogate->getConversionType();
12219 bool isLValueReference = false;
12220 bool isRValueReference = false;
12221 bool isPointer = false;
12222 if (const LValueReferenceType *FnTypeRef =
12223 FnType->getAs<LValueReferenceType>()) {
12224 FnType = FnTypeRef->getPointeeType();
12225 isLValueReference = true;
12226 } else if (const RValueReferenceType *FnTypeRef =
12227 FnType->getAs<RValueReferenceType>()) {
12228 FnType = FnTypeRef->getPointeeType();
12229 isRValueReference = true;
12230 }
12231 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12232 FnType = FnTypePtr->getPointeeType();
12233 isPointer = true;
12234 }
12235 // Desugar down to a function type.
12236 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12237 // Reconstruct the pointer/reference as appropriate.
12238 if (isPointer) FnType = S.Context.getPointerType(FnType);
12239 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
12240 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
12241
12242 if (!Cand->Viable &&
12244 S.Diag(Cand->Surrogate->getLocation(),
12245 diag::note_ovl_surrogate_constraints_not_satisfied)
12246 << Cand->Surrogate;
12247 ConstraintSatisfaction Satisfaction;
12248 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12249 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12250 } else {
12251 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
12252 << FnType;
12253 }
12254}
12255
12256static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12257 SourceLocation OpLoc,
12258 OverloadCandidate *Cand) {
12259 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12260 std::string TypeStr("operator");
12261 TypeStr += Opc;
12262 TypeStr += "(";
12263 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12264 if (Cand->Conversions.size() == 1) {
12265 TypeStr += ")";
12266 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12267 } else {
12268 TypeStr += ", ";
12269 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12270 TypeStr += ")";
12271 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12272 }
12273}
12274
12276 OverloadCandidate *Cand) {
12277 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12278 if (ICS.isBad()) break; // all meaningless after first invalid
12279 if (!ICS.isAmbiguous()) continue;
12280
12282 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
12283 }
12284}
12285
12287 if (Cand->Function)
12288 return Cand->Function->getLocation();
12289 if (Cand->IsSurrogate)
12290 return Cand->Surrogate->getLocation();
12291 return SourceLocation();
12292}
12293
12294static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12295 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12299 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12300
12304 return 1;
12305
12308 return 2;
12309
12317 return 3;
12318
12320 return 4;
12321
12323 return 5;
12324
12327 return 6;
12328 }
12329 llvm_unreachable("Unhandled deduction result");
12330}
12331
12332namespace {
12333
12334struct CompareOverloadCandidatesForDisplay {
12335 Sema &S;
12337 size_t NumArgs;
12339
12340 CompareOverloadCandidatesForDisplay(
12341 Sema &S, SourceLocation Loc, size_t NArgs,
12343 : S(S), NumArgs(NArgs), CSK(CSK) {}
12344
12345 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12346 // If there are too many or too few arguments, that's the high-order bit we
12347 // want to sort by, even if the immediate failure kind was something else.
12348 if (C->FailureKind == ovl_fail_too_many_arguments ||
12349 C->FailureKind == ovl_fail_too_few_arguments)
12350 return static_cast<OverloadFailureKind>(C->FailureKind);
12351
12352 if (C->Function) {
12353 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12355 if (NumArgs < C->Function->getMinRequiredArguments())
12357 }
12358
12359 return static_cast<OverloadFailureKind>(C->FailureKind);
12360 }
12361
12362 bool operator()(const OverloadCandidate *L,
12363 const OverloadCandidate *R) {
12364 // Fast-path this check.
12365 if (L == R) return false;
12366
12367 // Order first by viability.
12368 if (L->Viable) {
12369 if (!R->Viable) return true;
12370
12371 if (int Ord = CompareConversions(*L, *R))
12372 return Ord < 0;
12373 // Use other tie breakers.
12374 } else if (R->Viable)
12375 return false;
12376
12377 assert(L->Viable == R->Viable);
12378
12379 // Criteria by which we can sort non-viable candidates:
12380 if (!L->Viable) {
12381 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
12382 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
12383
12384 // 1. Arity mismatches come after other candidates.
12385 if (LFailureKind == ovl_fail_too_many_arguments ||
12386 LFailureKind == ovl_fail_too_few_arguments) {
12387 if (RFailureKind == ovl_fail_too_many_arguments ||
12388 RFailureKind == ovl_fail_too_few_arguments) {
12389 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
12390 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
12391 if (LDist == RDist) {
12392 if (LFailureKind == RFailureKind)
12393 // Sort non-surrogates before surrogates.
12394 return !L->IsSurrogate && R->IsSurrogate;
12395 // Sort candidates requiring fewer parameters than there were
12396 // arguments given after candidates requiring more parameters
12397 // than there were arguments given.
12398 return LFailureKind == ovl_fail_too_many_arguments;
12399 }
12400 return LDist < RDist;
12401 }
12402 return false;
12403 }
12404 if (RFailureKind == ovl_fail_too_many_arguments ||
12405 RFailureKind == ovl_fail_too_few_arguments)
12406 return true;
12407
12408 // 2. Bad conversions come first and are ordered by the number
12409 // of bad conversions and quality of good conversions.
12410 if (LFailureKind == ovl_fail_bad_conversion) {
12411 if (RFailureKind != ovl_fail_bad_conversion)
12412 return true;
12413
12414 // The conversion that can be fixed with a smaller number of changes,
12415 // comes first.
12416 unsigned numLFixes = L->Fix.NumConversionsFixed;
12417 unsigned numRFixes = R->Fix.NumConversionsFixed;
12418 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
12419 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
12420 if (numLFixes != numRFixes) {
12421 return numLFixes < numRFixes;
12422 }
12423
12424 // If there's any ordering between the defined conversions...
12425 if (int Ord = CompareConversions(*L, *R))
12426 return Ord < 0;
12427 } else if (RFailureKind == ovl_fail_bad_conversion)
12428 return false;
12429
12430 if (LFailureKind == ovl_fail_bad_deduction) {
12431 if (RFailureKind != ovl_fail_bad_deduction)
12432 return true;
12433
12435 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
12436 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
12437 if (LRank != RRank)
12438 return LRank < RRank;
12439 }
12440 } else if (RFailureKind == ovl_fail_bad_deduction)
12441 return false;
12442
12443 // TODO: others?
12444 }
12445
12446 // Sort everything else by location.
12449
12450 // Put candidates without locations (e.g. builtins) at the end.
12451 if (LLoc.isValid() && RLoc.isValid())
12452 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12453 if (LLoc.isValid() && !RLoc.isValid())
12454 return true;
12455 if (RLoc.isValid() && !LLoc.isValid())
12456 return false;
12457 assert(!LLoc.isValid() && !RLoc.isValid());
12458 // For builtins and other functions without locations, fallback to the order
12459 // in which they were added into the candidate set.
12460 return L < R;
12461 }
12462
12463private:
12464 struct ConversionSignals {
12465 unsigned KindRank = 0;
12467
12468 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
12469 ConversionSignals Sig;
12470 Sig.KindRank = Seq.getKindRank();
12471 if (Seq.isStandard())
12472 Sig.Rank = Seq.Standard.getRank();
12473 else if (Seq.isUserDefined())
12474 Sig.Rank = Seq.UserDefined.After.getRank();
12475 // We intend StaticObjectArgumentConversion to compare the same as
12476 // StandardConversion with ICR_ExactMatch rank.
12477 return Sig;
12478 }
12479
12480 static ConversionSignals ForObjectArgument() {
12481 // We intend StaticObjectArgumentConversion to compare the same as
12482 // StandardConversion with ICR_ExactMatch rank. Default give us that.
12483 return {};
12484 }
12485 };
12486
12487 // Returns -1 if conversions in L are considered better.
12488 // 0 if they are considered indistinguishable.
12489 // 1 if conversions in R are better.
12490 int CompareConversions(const OverloadCandidate &L,
12491 const OverloadCandidate &R) {
12492 // We cannot use `isBetterOverloadCandidate` because it is defined
12493 // according to the C++ standard and provides a partial order, but we need
12494 // a total order as this function is used in sort.
12495 assert(L.Conversions.size() == R.Conversions.size());
12496 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
12497 auto LS = L.IgnoreObjectArgument && I == 0
12498 ? ConversionSignals::ForObjectArgument()
12499 : ConversionSignals::ForSequence(L.Conversions[I]);
12500 auto RS = R.IgnoreObjectArgument
12501 ? ConversionSignals::ForObjectArgument()
12502 : ConversionSignals::ForSequence(R.Conversions[I]);
12503 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
12504 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
12505 ? -1
12506 : 1;
12507 }
12508 // FIXME: find a way to compare templates for being more or less
12509 // specialized that provides a strict weak ordering.
12510 return 0;
12511 }
12512};
12513}
12514
12515/// CompleteNonViableCandidate - Normally, overload resolution only
12516/// computes up to the first bad conversion. Produces the FixIt set if
12517/// possible.
12518static void
12520 ArrayRef<Expr *> Args,
12522 assert(!Cand->Viable);
12523
12524 // Don't do anything on failures other than bad conversion.
12526 return;
12527
12528 // We only want the FixIts if all the arguments can be corrected.
12529 bool Unfixable = false;
12530 // Use a implicit copy initialization to check conversion fixes.
12532
12533 // Attempt to fix the bad conversion.
12534 unsigned ConvCount = Cand->Conversions.size();
12535 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
12536 ++ConvIdx) {
12537 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
12538 if (Cand->Conversions[ConvIdx].isInitialized() &&
12539 Cand->Conversions[ConvIdx].isBad()) {
12540 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
12541 break;
12542 }
12543 }
12544
12545 // FIXME: this should probably be preserved from the overload
12546 // operation somehow.
12547 bool SuppressUserConversions = false;
12548
12549 unsigned ConvIdx = 0;
12550 unsigned ArgIdx = 0;
12551 ArrayRef<QualType> ParamTypes;
12552 bool Reversed = Cand->isReversed();
12553
12554 if (Cand->IsSurrogate) {
12555 QualType ConvType
12557 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12558 ConvType = ConvPtrType->getPointeeType();
12559 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
12560 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12561 ConvIdx = 1;
12562 } else if (Cand->Function) {
12563 ParamTypes =
12564 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
12565 if (isa<CXXMethodDecl>(Cand->Function) &&
12566 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
12567 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12568 ConvIdx = 1;
12570 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
12572 OO_Subscript)
12573 // Argument 0 is 'this', which doesn't have a corresponding parameter.
12574 ArgIdx = 1;
12575 }
12576 } else {
12577 // Builtin operator.
12578 assert(ConvCount <= 3);
12579 ParamTypes = Cand->BuiltinParamTypes;
12580 }
12581
12582 // Fill in the rest of the conversions.
12583 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
12584 ConvIdx != ConvCount;
12585 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
12586 assert(ArgIdx < Args.size() && "no argument for this arg conversion");
12587 if (Cand->Conversions[ConvIdx].isInitialized()) {
12588 // We've already checked this conversion.
12589 } else if (ParamIdx < ParamTypes.size()) {
12590 if (ParamTypes[ParamIdx]->isDependentType())
12591 Cand->Conversions[ConvIdx].setAsIdentityConversion(
12592 Args[ArgIdx]->getType());
12593 else {
12594 Cand->Conversions[ConvIdx] =
12595 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
12596 SuppressUserConversions,
12597 /*InOverloadResolution=*/true,
12598 /*AllowObjCWritebackConversion=*/
12599 S.getLangOpts().ObjCAutoRefCount);
12600 // Store the FixIt in the candidate if it exists.
12601 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
12602 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
12603 }
12604 } else
12605 Cand->Conversions[ConvIdx].setEllipsis();
12606 }
12607}
12608
12611 SourceLocation OpLoc,
12612 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12613 // Sort the candidates by viability and position. Sorting directly would
12614 // be prohibitive, so we make a set of pointers and sort those.
12616 if (OCD == OCD_AllCandidates) Cands.reserve(size());
12617 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12618 if (!Filter(*Cand))
12619 continue;
12620 switch (OCD) {
12621 case OCD_AllCandidates:
12622 if (!Cand->Viable) {
12623 if (!Cand->Function && !Cand->IsSurrogate) {
12624 // This a non-viable builtin candidate. We do not, in general,
12625 // want to list every possible builtin candidate.
12626 continue;
12627 }
12628 CompleteNonViableCandidate(S, Cand, Args, Kind);
12629 }
12630 break;
12631
12633 if (!Cand->Viable)
12634 continue;
12635 break;
12636
12638 if (!Cand->Best)
12639 continue;
12640 break;
12641 }
12642
12643 Cands.push_back(Cand);
12644 }
12645
12646 llvm::stable_sort(
12647 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
12648
12649 return Cands;
12650}
12651
12653 SourceLocation OpLoc) {
12654 bool DeferHint = false;
12655 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
12656 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
12657 // host device candidates.
12658 auto WrongSidedCands =
12659 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
12660 return (Cand.Viable == false &&
12661 Cand.FailureKind == ovl_fail_bad_target) ||
12662 (Cand.Function &&
12663 Cand.Function->template hasAttr<CUDAHostAttr>() &&
12664 Cand.Function->template hasAttr<CUDADeviceAttr>());
12665 });
12666 DeferHint = !WrongSidedCands.empty();
12667 }
12668 return DeferHint;
12669}
12670
12671/// When overload resolution fails, prints diagnostic messages containing the
12672/// candidates in the candidate set.
12675 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
12676 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12677
12678 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
12679
12680 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
12681
12682 // In WebAssembly we don't want to emit further diagnostics if a table is
12683 // passed as an argument to a function.
12684 bool NoteCands = true;
12685 for (const Expr *Arg : Args) {
12686 if (Arg->getType()->isWebAssemblyTableType())
12687 NoteCands = false;
12688 }
12689
12690 if (NoteCands)
12691 NoteCandidates(S, Args, Cands, Opc, OpLoc);
12692
12693 if (OCD == OCD_AmbiguousCandidates)
12695}
12696
12699 StringRef Opc, SourceLocation OpLoc) {
12700 bool ReportedAmbiguousConversions = false;
12701
12702 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12703 unsigned CandsShown = 0;
12704 auto I = Cands.begin(), E = Cands.end();
12705 for (; I != E; ++I) {
12706 OverloadCandidate *Cand = *I;
12707
12708 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
12709 ShowOverloads == Ovl_Best) {
12710 break;
12711 }
12712 ++CandsShown;
12713
12714 if (Cand->Function)
12715 NoteFunctionCandidate(S, Cand, Args.size(),
12716 /*TakingCandidateAddress=*/false, DestAS);
12717 else if (Cand->IsSurrogate)
12718 NoteSurrogateCandidate(S, Cand);
12719 else {
12720 assert(Cand->Viable &&
12721 "Non-viable built-in candidates are not added to Cands.");
12722 // Generally we only see ambiguities including viable builtin
12723 // operators if overload resolution got screwed up by an
12724 // ambiguous user-defined conversion.
12725 //
12726 // FIXME: It's quite possible for different conversions to see
12727 // different ambiguities, though.
12728 if (!ReportedAmbiguousConversions) {
12729 NoteAmbiguousUserConversions(S, OpLoc, Cand);
12730 ReportedAmbiguousConversions = true;
12731 }
12732
12733 // If this is a viable builtin, print it.
12734 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
12735 }
12736 }
12737
12738 // Inform S.Diags that we've shown an overload set with N elements. This may
12739 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
12740 S.Diags.overloadCandidatesShown(CandsShown);
12741
12742 if (I != E)
12743 S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
12744 shouldDeferDiags(S, Args, OpLoc))
12745 << int(E - I);
12746}
12747
12748static SourceLocation
12750 return Cand->Specialization ? Cand->Specialization->getLocation()
12751 : SourceLocation();
12752}
12753
12754namespace {
12755struct CompareTemplateSpecCandidatesForDisplay {
12756 Sema &S;
12757 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
12758
12759 bool operator()(const TemplateSpecCandidate *L,
12760 const TemplateSpecCandidate *R) {
12761 // Fast-path this check.
12762 if (L == R)
12763 return false;
12764
12765 // Assuming that both candidates are not matches...
12766
12767 // Sort by the ranking of deduction failures.
12771
12772 // Sort everything else by location.
12775
12776 // Put candidates without locations (e.g. builtins) at the end.
12777 if (LLoc.isInvalid())
12778 return false;
12779 if (RLoc.isInvalid())
12780 return true;
12781
12782 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12783 }
12784};
12785}
12786
12787/// Diagnose a template argument deduction failure.
12788/// We are treating these failures as overload failures due to bad
12789/// deductions.
12791 bool ForTakingAddress) {
12792 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
12793 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
12794}
12795
12796void TemplateSpecCandidateSet::destroyCandidates() {
12797 for (iterator i = begin(), e = end(); i != e; ++i) {
12798 i->DeductionFailure.Destroy();
12799 }
12800}
12801
12803 destroyCandidates();
12804 Candidates.clear();
12805}
12806
12807/// NoteCandidates - When no template specialization match is found, prints
12808/// diagnostic messages containing the non-matching specializations that form
12809/// the candidate set.
12810/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
12811/// OCD == OCD_AllCandidates and Cand->Viable == false.
12813 // Sort the candidates by position (assuming no candidate is a match).
12814 // Sorting directly would be prohibitive, so we make a set of pointers
12815 // and sort those.
12817 Cands.reserve(size());
12818 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12819 if (Cand->Specialization)
12820 Cands.push_back(Cand);
12821 // Otherwise, this is a non-matching builtin candidate. We do not,
12822 // in general, want to list every possible builtin candidate.
12823 }
12824
12825 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
12826
12827 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
12828 // for generalization purposes (?).
12829 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12830
12832 unsigned CandsShown = 0;
12833 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
12834 TemplateSpecCandidate *Cand = *I;
12835
12836 // Set an arbitrary limit on the number of candidates we'll spam
12837 // the user with. FIXME: This limit should depend on details of the
12838 // candidate list.
12839 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
12840 break;
12841 ++CandsShown;
12842
12843 assert(Cand->Specialization &&
12844 "Non-matching built-in candidates are not added to Cands.");
12845 Cand->NoteDeductionFailure(S, ForTakingAddress);
12846 }
12847
12848 if (I != E)
12849 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
12850}
12851
12852// [PossiblyAFunctionType] --> [Return]
12853// NonFunctionType --> NonFunctionType
12854// R (A) --> R(A)
12855// R (*)(A) --> R (A)
12856// R (&)(A) --> R (A)
12857// R (S::*)(A) --> R (A)
12859 QualType Ret = PossiblyAFunctionType;
12860 if (const PointerType *ToTypePtr =
12861 PossiblyAFunctionType->getAs<PointerType>())
12862 Ret = ToTypePtr->getPointeeType();
12863 else if (const ReferenceType *ToTypeRef =
12864 PossiblyAFunctionType->getAs<ReferenceType>())
12865 Ret = ToTypeRef->getPointeeType();
12866 else if (const MemberPointerType *MemTypePtr =
12867 PossiblyAFunctionType->getAs<MemberPointerType>())
12868 Ret = MemTypePtr->getPointeeType();
12869 Ret =
12870 Context.getCanonicalType(Ret).getUnqualifiedType();
12871 return Ret;
12872}
12873
12875 bool Complain = true) {
12876 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
12877 S.DeduceReturnType(FD, Loc, Complain))
12878 return true;
12879
12880 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
12881 if (S.getLangOpts().CPlusPlus17 &&
12882 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
12883 !S.ResolveExceptionSpec(Loc, FPT))
12884 return true;
12885
12886 return false;
12887}
12888
12889namespace {
12890// A helper class to help with address of function resolution
12891// - allows us to avoid passing around all those ugly parameters
12892class AddressOfFunctionResolver {
12893 Sema& S;
12894 Expr* SourceExpr;
12895 const QualType& TargetType;
12896 QualType TargetFunctionType; // Extracted function type from target type
12897
12898 bool Complain;
12899 //DeclAccessPair& ResultFunctionAccessPair;
12900 ASTContext& Context;
12901
12902 bool TargetTypeIsNonStaticMemberFunction;
12903 bool FoundNonTemplateFunction;
12904 bool StaticMemberFunctionFromBoundPointer;
12905 bool HasComplained;
12906
12907 OverloadExpr::FindResult OvlExprInfo;
12908 OverloadExpr *OvlExpr;
12909 TemplateArgumentListInfo OvlExplicitTemplateArgs;
12911 TemplateSpecCandidateSet FailedCandidates;
12912
12913public:
12914 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
12915 const QualType &TargetType, bool Complain)
12916 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
12917 Complain(Complain), Context(S.getASTContext()),
12918 TargetTypeIsNonStaticMemberFunction(
12919 !!TargetType->getAs<MemberPointerType>()),
12920 FoundNonTemplateFunction(false),
12921 StaticMemberFunctionFromBoundPointer(false),
12922 HasComplained(false),
12923 OvlExprInfo(OverloadExpr::find(SourceExpr)),
12924 OvlExpr(OvlExprInfo.Expression),
12925 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
12926 ExtractUnqualifiedFunctionTypeFromTargetType();
12927
12928 if (TargetFunctionType->isFunctionType()) {
12929 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
12930 if (!UME->isImplicitAccess() &&
12932 StaticMemberFunctionFromBoundPointer = true;
12933 } else if (OvlExpr->hasExplicitTemplateArgs()) {
12934 DeclAccessPair dap;
12936 OvlExpr, false, &dap)) {
12937 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
12938 if (!Method->isStatic()) {
12939 // If the target type is a non-function type and the function found
12940 // is a non-static member function, pretend as if that was the
12941 // target, it's the only possible type to end up with.
12942 TargetTypeIsNonStaticMemberFunction = true;
12943
12944 // And skip adding the function if its not in the proper form.
12945 // We'll diagnose this due to an empty set of functions.
12946 if (!OvlExprInfo.HasFormOfMemberPointer)
12947 return;
12948 }
12949
12950 Matches.push_back(std::make_pair(dap, Fn));
12951 }
12952 return;
12953 }
12954
12955 if (OvlExpr->hasExplicitTemplateArgs())
12956 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
12957
12958 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
12959 // C++ [over.over]p4:
12960 // If more than one function is selected, [...]
12961 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12962 if (FoundNonTemplateFunction)
12963 EliminateAllTemplateMatches();
12964 else
12965 EliminateAllExceptMostSpecializedTemplate();
12966 }
12967 }
12968
12969 if (S.getLangOpts().CUDA && Matches.size() > 1)
12970 EliminateSuboptimalCudaMatches();
12971 }
12972
12973 bool hasComplained() const { return HasComplained; }
12974
12975private:
12976 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
12977 QualType Discard;
12978 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
12979 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
12980 }
12981
12982 /// \return true if A is considered a better overload candidate for the
12983 /// desired type than B.
12984 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
12985 // If A doesn't have exactly the correct type, we don't want to classify it
12986 // as "better" than anything else. This way, the user is required to
12987 // disambiguate for us if there are multiple candidates and no exact match.
12988 return candidateHasExactlyCorrectType(A) &&
12989 (!candidateHasExactlyCorrectType(B) ||
12990 compareEnableIfAttrs(S, A, B) == Comparison::Better);
12991 }
12992
12993 /// \return true if we were able to eliminate all but one overload candidate,
12994 /// false otherwise.
12995 bool eliminiateSuboptimalOverloadCandidates() {
12996 // Same algorithm as overload resolution -- one pass to pick the "best",
12997 // another pass to be sure that nothing is better than the best.
12998 auto Best = Matches.begin();
12999 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13000 if (isBetterCandidate(I->second, Best->second))
13001 Best = I;
13002
13003 const FunctionDecl *BestFn = Best->second;
13004 auto IsBestOrInferiorToBest = [this, BestFn](
13005 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13006 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
13007 };
13008
13009 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13010 // option, so we can potentially give the user a better error
13011 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
13012 return false;
13013 Matches[0] = *Best;
13014 Matches.resize(1);
13015 return true;
13016 }
13017
13018 bool isTargetTypeAFunction() const {
13019 return TargetFunctionType->isFunctionType();
13020 }
13021
13022 // [ToType] [Return]
13023
13024 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13025 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13026 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13027 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13028 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13029 }
13030
13031 // return true if any matching specializations were found
13032 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13033 const DeclAccessPair& CurAccessFunPair) {
13034 if (CXXMethodDecl *Method
13035 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13036 // Skip non-static function templates when converting to pointer, and
13037 // static when converting to member pointer.
13038 bool CanConvertToFunctionPointer =
13039 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13040 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13041 return false;
13042 }
13043 else if (TargetTypeIsNonStaticMemberFunction)
13044 return false;
13045
13046 // C++ [over.over]p2:
13047 // If the name is a function template, template argument deduction is
13048 // done (14.8.2.2), and if the argument deduction succeeds, the
13049 // resulting template argument list is used to generate a single
13050 // function template specialization, which is added to the set of
13051 // overloaded functions considered.
13052 FunctionDecl *Specialization = nullptr;
13053 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13055 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13056 Specialization, Info, /*IsAddressOfFunction*/ true);
13057 Result != TemplateDeductionResult::Success) {
13058 // Make a note of the failed deduction for diagnostics.
13059 FailedCandidates.addCandidate()
13060 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13061 MakeDeductionFailureInfo(Context, Result, Info));
13062 return false;
13063 }
13064
13065 // Template argument deduction ensures that we have an exact match or
13066 // compatible pointer-to-function arguments that would be adjusted by ICS.
13067 // This function template specicalization works.
13069 Context.getCanonicalType(Specialization->getType()),
13070 Context.getCanonicalType(TargetFunctionType)));
13071
13073 return false;
13074
13075 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13076 return true;
13077 }
13078
13079 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13080 const DeclAccessPair& CurAccessFunPair) {
13081 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13082 // Skip non-static functions when converting to pointer, and static
13083 // when converting to member pointer.
13084 bool CanConvertToFunctionPointer =
13085 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13086 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13087 return false;
13088 }
13089 else if (TargetTypeIsNonStaticMemberFunction)
13090 return false;
13091
13092 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13093 if (S.getLangOpts().CUDA) {
13094 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13095 if (!(Caller && Caller->isImplicit()) &&
13096 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13097 return false;
13098 }
13099 if (FunDecl->isMultiVersion()) {
13100 const auto *TA = FunDecl->getAttr<TargetAttr>();
13101 if (TA && !TA->isDefaultVersion())
13102 return false;
13103 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13104 if (TVA && !TVA->isDefaultVersion())
13105 return false;
13106 }
13107
13108 // If any candidate has a placeholder return type, trigger its deduction
13109 // now.
13110 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13111 Complain)) {
13112 HasComplained |= Complain;
13113 return false;
13114 }
13115
13116 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13117 return false;
13118
13119 // If we're in C, we need to support types that aren't exactly identical.
13120 if (!S.getLangOpts().CPlusPlus ||
13121 candidateHasExactlyCorrectType(FunDecl)) {
13122 Matches.push_back(std::make_pair(
13123 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13124 FoundNonTemplateFunction = true;
13125 return true;
13126 }
13127 }
13128
13129 return false;
13130 }
13131
13132 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13133 bool Ret = false;
13134
13135 // If the overload expression doesn't have the form of a pointer to
13136 // member, don't try to convert it to a pointer-to-member type.
13137 if (IsInvalidFormOfPointerToMemberFunction())
13138 return false;
13139
13140 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13141 E = OvlExpr->decls_end();
13142 I != E; ++I) {
13143 // Look through any using declarations to find the underlying function.
13144 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13145
13146 // C++ [over.over]p3:
13147 // Non-member functions and static member functions match
13148 // targets of type "pointer-to-function" or "reference-to-function."
13149 // Nonstatic member functions match targets of
13150 // type "pointer-to-member-function."
13151 // Note that according to DR 247, the containing class does not matter.
13152 if (FunctionTemplateDecl *FunctionTemplate
13153 = dyn_cast<FunctionTemplateDecl>(Fn)) {
13154 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13155 Ret = true;
13156 }
13157 // If we have explicit template arguments supplied, skip non-templates.
13158 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13159 AddMatchingNonTemplateFunction(Fn, I.getPair()))
13160 Ret = true;
13161 }
13162 assert(Ret || Matches.empty());
13163 return Ret;
13164 }
13165
13166 void EliminateAllExceptMostSpecializedTemplate() {
13167 // [...] and any given function template specialization F1 is
13168 // eliminated if the set contains a second function template
13169 // specialization whose function template is more specialized
13170 // than the function template of F1 according to the partial
13171 // ordering rules of 14.5.5.2.
13172
13173 // The algorithm specified above is quadratic. We instead use a
13174 // two-pass algorithm (similar to the one used to identify the
13175 // best viable function in an overload set) that identifies the
13176 // best function template (if it exists).
13177
13178 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13179 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13180 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13181
13182 // TODO: It looks like FailedCandidates does not serve much purpose
13183 // here, since the no_viable diagnostic has index 0.
13185 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13186 SourceExpr->getBeginLoc(), S.PDiag(),
13187 S.PDiag(diag::err_addr_ovl_ambiguous)
13188 << Matches[0].second->getDeclName(),
13189 S.PDiag(diag::note_ovl_candidate)
13190 << (unsigned)oc_function << (unsigned)ocs_described_template,
13191 Complain, TargetFunctionType);
13192
13193 if (Result != MatchesCopy.end()) {
13194 // Make it the first and only element
13195 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13196 Matches[0].second = cast<FunctionDecl>(*Result);
13197 Matches.resize(1);
13198 } else
13199 HasComplained |= Complain;
13200 }
13201
13202 void EliminateAllTemplateMatches() {
13203 // [...] any function template specializations in the set are
13204 // eliminated if the set also contains a non-template function, [...]
13205 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13206 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13207 ++I;
13208 else {
13209 Matches[I] = Matches[--N];
13210 Matches.resize(N);
13211 }
13212 }
13213 }
13214
13215 void EliminateSuboptimalCudaMatches() {
13216 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
13217 Matches);
13218 }
13219
13220public:
13221 void ComplainNoMatchesFound() const {
13222 assert(Matches.empty());
13223 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
13224 << OvlExpr->getName() << TargetFunctionType
13225 << OvlExpr->getSourceRange();
13226 if (FailedCandidates.empty())
13227 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13228 /*TakingAddress=*/true);
13229 else {
13230 // We have some deduction failure messages. Use them to diagnose
13231 // the function templates, and diagnose the non-template candidates
13232 // normally.
13233 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13234 IEnd = OvlExpr->decls_end();
13235 I != IEnd; ++I)
13236 if (FunctionDecl *Fun =
13237 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
13239 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
13240 /*TakingAddress=*/true);
13241 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
13242 }
13243 }
13244
13245 bool IsInvalidFormOfPointerToMemberFunction() const {
13246 return TargetTypeIsNonStaticMemberFunction &&
13247 !OvlExprInfo.HasFormOfMemberPointer;
13248 }
13249
13250 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13251 // TODO: Should we condition this on whether any functions might
13252 // have matched, or is it more appropriate to do that in callers?
13253 // TODO: a fixit wouldn't hurt.
13254 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
13255 << TargetType << OvlExpr->getSourceRange();
13256 }
13257
13258 bool IsStaticMemberFunctionFromBoundPointer() const {
13259 return StaticMemberFunctionFromBoundPointer;
13260 }
13261
13262 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13263 S.Diag(OvlExpr->getBeginLoc(),
13264 diag::err_invalid_form_pointer_member_function)
13265 << OvlExpr->getSourceRange();
13266 }
13267
13268 void ComplainOfInvalidConversion() const {
13269 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
13270 << OvlExpr->getName() << TargetType;
13271 }
13272
13273 void ComplainMultipleMatchesFound() const {
13274 assert(Matches.size() > 1);
13275 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
13276 << OvlExpr->getName() << OvlExpr->getSourceRange();
13277 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13278 /*TakingAddress=*/true);
13279 }
13280
13281 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13282
13283 int getNumMatches() const { return Matches.size(); }
13284
13285 FunctionDecl* getMatchingFunctionDecl() const {
13286 if (Matches.size() != 1) return nullptr;
13287 return Matches[0].second;
13288 }
13289
13290 const DeclAccessPair* getMatchingFunctionAccessPair() const {
13291 if (Matches.size() != 1) return nullptr;
13292 return &Matches[0].first;
13293 }
13294};
13295}
13296
13299 QualType TargetType,
13300 bool Complain,
13301 DeclAccessPair &FoundResult,
13302 bool *pHadMultipleCandidates) {
13303 assert(AddressOfExpr->getType() == Context.OverloadTy);
13304
13305 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13306 Complain);
13307 int NumMatches = Resolver.getNumMatches();
13308 FunctionDecl *Fn = nullptr;
13309 bool ShouldComplain = Complain && !Resolver.hasComplained();
13310 if (NumMatches == 0 && ShouldComplain) {
13311 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13312 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13313 else
13314 Resolver.ComplainNoMatchesFound();
13315 }
13316 else if (NumMatches > 1 && ShouldComplain)
13317 Resolver.ComplainMultipleMatchesFound();
13318 else if (NumMatches == 1) {
13319 Fn = Resolver.getMatchingFunctionDecl();
13320 assert(Fn);
13321 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13322 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
13323 FoundResult = *Resolver.getMatchingFunctionAccessPair();
13324 if (Complain) {
13325 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13326 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13327 else
13328 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
13329 }
13330 }
13331
13332 if (pHadMultipleCandidates)
13333 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13334 return Fn;
13335}
13336
13340 OverloadExpr *Ovl = R.Expression;
13341 bool IsResultAmbiguous = false;
13342 FunctionDecl *Result = nullptr;
13343 DeclAccessPair DAP;
13344 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
13345
13346 // Return positive for better, negative for worse, 0 for equal preference.
13347 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
13348 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
13349 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
13350 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
13351 };
13352
13353 // Don't use the AddressOfResolver because we're specifically looking for
13354 // cases where we have one overload candidate that lacks
13355 // enable_if/pass_object_size/...
13356 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
13357 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
13358 if (!FD)
13359 return nullptr;
13360
13362 continue;
13363
13364 // If we found a better result, update Result.
13365 auto FoundBetter = [&]() {
13366 IsResultAmbiguous = false;
13367 DAP = I.getPair();
13368 Result = FD;
13369 };
13370
13371 // We have more than one result - see if it is more constrained than the
13372 // previous one.
13373 if (Result) {
13374 // Check CUDA preference first. If the candidates have differennt CUDA
13375 // preference, choose the one with higher CUDA preference. Otherwise,
13376 // choose the one with more constraints.
13377 if (getLangOpts().CUDA) {
13378 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
13379 // FD has different preference than Result.
13380 if (PreferenceByCUDA != 0) {
13381 // FD is more preferable than Result.
13382 if (PreferenceByCUDA > 0)
13383 FoundBetter();
13384 continue;
13385 }
13386 }
13387 // FD has the same CUDA prefernece than Result. Continue check
13388 // constraints.
13389 FunctionDecl *MoreConstrained = getMoreConstrainedFunction(FD, Result);
13390 if (MoreConstrained != FD) {
13391 if (!MoreConstrained) {
13392 IsResultAmbiguous = true;
13393 AmbiguousDecls.push_back(FD);
13394 }
13395 continue;
13396 }
13397 // FD is more constrained - replace Result with it.
13398 }
13399 FoundBetter();
13400 }
13401
13402 if (IsResultAmbiguous)
13403 return nullptr;
13404
13405 if (Result) {
13407 // We skipped over some ambiguous declarations which might be ambiguous with
13408 // the selected result.
13409 for (FunctionDecl *Skipped : AmbiguousDecls) {
13410 // If skipped candidate has different CUDA preference than the result,
13411 // there is no ambiguity. Otherwise check whether they have different
13412 // constraints.
13413 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
13414 continue;
13415 if (!getMoreConstrainedFunction(Skipped, Result))
13416 return nullptr;
13417 }
13418 Pair = DAP;
13419 }
13420 return Result;
13421}
13422
13424 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
13425 Expr *E = SrcExpr.get();
13426 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
13427
13428 DeclAccessPair DAP;
13429 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
13430 if (!Found || Found->isCPUDispatchMultiVersion() ||
13431 Found->isCPUSpecificMultiVersion())
13432 return false;
13433
13434 // Emitting multiple diagnostics for a function that is both inaccessible and
13435 // unavailable is consistent with our behavior elsewhere. So, always check
13436 // for both.
13437 DiagnoseUseOfDecl(Found, E->getExprLoc());
13438 CheckAddressOfMemberAccess(E, DAP);
13439 ExprResult Res = FixOverloadedFunctionReference(E, DAP, Found);
13440 if (Res.isInvalid())
13441 return false;
13442 Expr *Fixed = Res.get();
13443 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
13444 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
13445 else
13446 SrcExpr = Fixed;
13447 return true;
13448}
13449
13451 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
13452 TemplateSpecCandidateSet *FailedTSC) {
13453 // C++ [over.over]p1:
13454 // [...] [Note: any redundant set of parentheses surrounding the
13455 // overloaded function name is ignored (5.1). ]
13456 // C++ [over.over]p1:
13457 // [...] The overloaded function name can be preceded by the &
13458 // operator.
13459
13460 // If we didn't actually find any template-ids, we're done.
13461 if (!ovl->hasExplicitTemplateArgs())
13462 return nullptr;
13463
13464 TemplateArgumentListInfo ExplicitTemplateArgs;
13465 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
13466
13467 // Look through all of the overloaded functions, searching for one
13468 // whose type matches exactly.
13469 FunctionDecl *Matched = nullptr;
13470 for (UnresolvedSetIterator I = ovl->decls_begin(),
13471 E = ovl->decls_end(); I != E; ++I) {
13472 // C++0x [temp.arg.explicit]p3:
13473 // [...] In contexts where deduction is done and fails, or in contexts
13474 // where deduction is not done, if a template argument list is
13475 // specified and it, along with any default template arguments,
13476 // identifies a single function template specialization, then the
13477 // template-id is an lvalue for the function template specialization.
13478 FunctionTemplateDecl *FunctionTemplate
13479 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
13480
13481 // C++ [over.over]p2:
13482 // If the name is a function template, template argument deduction is
13483 // done (14.8.2.2), and if the argument deduction succeeds, the
13484 // resulting template argument list is used to generate a single
13485 // function template specialization, which is added to the set of
13486 // overloaded functions considered.
13487 FunctionDecl *Specialization = nullptr;
13488 TemplateDeductionInfo Info(ovl->getNameLoc());
13490 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
13491 /*IsAddressOfFunction*/ true);
13493 // Make a note of the failed deduction for diagnostics.
13494 if (FailedTSC)
13495 FailedTSC->addCandidate().set(
13496 I.getPair(), FunctionTemplate->getTemplatedDecl(),
13497 MakeDeductionFailureInfo(Context, Result, Info));
13498 continue;
13499 }
13500
13501 assert(Specialization && "no specialization and no error?");
13502
13503 // Multiple matches; we can't resolve to a single declaration.
13504 if (Matched) {
13505 if (Complain) {
13506 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
13507 << ovl->getName();
13508 NoteAllOverloadCandidates(ovl);
13509 }
13510 return nullptr;
13511 }
13512
13513 Matched = Specialization;
13514 if (FoundResult) *FoundResult = I.getPair();
13515 }
13516
13517 if (Matched &&
13518 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
13519 return nullptr;
13520
13521 return Matched;
13522}
13523
13525 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
13526 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
13527 unsigned DiagIDForComplaining) {
13528 assert(SrcExpr.get()->getType() == Context.OverloadTy);
13529
13531
13532 DeclAccessPair found;
13533 ExprResult SingleFunctionExpression;
13534 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
13535 ovl.Expression, /*complain*/ false, &found)) {
13536 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
13537 SrcExpr = ExprError();
13538 return true;
13539 }
13540
13541 // It is only correct to resolve to an instance method if we're
13542 // resolving a form that's permitted to be a pointer to member.
13543 // Otherwise we'll end up making a bound member expression, which
13544 // is illegal in all the contexts we resolve like this.
13545 if (!ovl.HasFormOfMemberPointer &&
13546 isa<CXXMethodDecl>(fn) &&
13547 cast<CXXMethodDecl>(fn)->isInstance()) {
13548 if (!complain) return false;
13549
13550 Diag(ovl.Expression->getExprLoc(),
13551 diag::err_bound_member_function)
13552 << 0 << ovl.Expression->getSourceRange();
13553
13554 // TODO: I believe we only end up here if there's a mix of
13555 // static and non-static candidates (otherwise the expression
13556 // would have 'bound member' type, not 'overload' type).
13557 // Ideally we would note which candidate was chosen and why
13558 // the static candidates were rejected.
13559 SrcExpr = ExprError();
13560 return true;
13561 }
13562
13563 // Fix the expression to refer to 'fn'.
13564 SingleFunctionExpression =
13565 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
13566
13567 // If desired, do function-to-pointer decay.
13568 if (doFunctionPointerConversion) {
13569 SingleFunctionExpression =
13570 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
13571 if (SingleFunctionExpression.isInvalid()) {
13572 SrcExpr = ExprError();
13573 return true;
13574 }
13575 }
13576 }
13577
13578 if (!SingleFunctionExpression.isUsable()) {
13579 if (complain) {
13580 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
13581 << ovl.Expression->getName()
13582 << DestTypeForComplaining
13583 << OpRangeForComplaining
13585 NoteAllOverloadCandidates(SrcExpr.get());
13586
13587 SrcExpr = ExprError();
13588 return true;
13589 }
13590
13591 return false;
13592 }
13593
13594 SrcExpr = SingleFunctionExpression;
13595 return true;
13596}
13597
13598/// Add a single candidate to the overload set.
13600 DeclAccessPair FoundDecl,
13601 TemplateArgumentListInfo *ExplicitTemplateArgs,
13602 ArrayRef<Expr *> Args,
13603 OverloadCandidateSet &CandidateSet,
13604 bool PartialOverloading,
13605 bool KnownValid) {
13606 NamedDecl *Callee = FoundDecl.getDecl();
13607 if (isa<UsingShadowDecl>(Callee))
13608 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
13609
13610 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
13611 if (ExplicitTemplateArgs) {
13612 assert(!KnownValid && "Explicit template arguments?");
13613 return;
13614 }
13615 // Prevent ill-formed function decls to be added as overload candidates.
13616 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
13617 return;
13618
13619 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
13620 /*SuppressUserConversions=*/false,
13621 PartialOverloading);
13622 return;
13623 }
13624
13625 if (FunctionTemplateDecl *FuncTemplate
13626 = dyn_cast<FunctionTemplateDecl>(Callee)) {
13627 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
13628 ExplicitTemplateArgs, Args, CandidateSet,
13629 /*SuppressUserConversions=*/false,
13630 PartialOverloading);
13631 return;
13632 }
13633
13634 assert(!KnownValid && "unhandled case in overloaded call candidate");
13635}
13636
13638 ArrayRef<Expr *> Args,
13639 OverloadCandidateSet &CandidateSet,
13640 bool PartialOverloading) {
13641
13642#ifndef NDEBUG
13643 // Verify that ArgumentDependentLookup is consistent with the rules
13644 // in C++0x [basic.lookup.argdep]p3:
13645 //
13646 // Let X be the lookup set produced by unqualified lookup (3.4.1)
13647 // and let Y be the lookup set produced by argument dependent
13648 // lookup (defined as follows). If X contains
13649 //
13650 // -- a declaration of a class member, or
13651 //
13652 // -- a block-scope function declaration that is not a
13653 // using-declaration, or
13654 //
13655 // -- a declaration that is neither a function or a function
13656 // template
13657 //
13658 // then Y is empty.
13659
13660 if (ULE->requiresADL()) {
13662 E = ULE->decls_end(); I != E; ++I) {
13663 assert(!(*I)->getDeclContext()->isRecord());
13664 assert(isa<UsingShadowDecl>(*I) ||
13665 !(*I)->getDeclContext()->isFunctionOrMethod());
13666 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
13667 }
13668 }
13669#endif
13670
13671 // It would be nice to avoid this copy.
13672 TemplateArgumentListInfo TABuffer;
13673 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13674 if (ULE->hasExplicitTemplateArgs()) {
13675 ULE->copyTemplateArgumentsInto(TABuffer);
13676 ExplicitTemplateArgs = &TABuffer;
13677 }
13678
13680 E = ULE->decls_end(); I != E; ++I)
13681 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13682 CandidateSet, PartialOverloading,
13683 /*KnownValid*/ true);
13684
13685 if (ULE->requiresADL())
13686 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
13687 Args, ExplicitTemplateArgs,
13688 CandidateSet, PartialOverloading);
13689}
13690
13692 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
13693 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
13694 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13695 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13696 CandidateSet, false, /*KnownValid*/ false);
13697}
13698
13699/// Determine whether a declaration with the specified name could be moved into
13700/// a different namespace.
13702 switch (Name.getCXXOverloadedOperator()) {
13703 case OO_New: case OO_Array_New:
13704 case OO_Delete: case OO_Array_Delete:
13705 return false;
13706
13707 default:
13708 return true;
13709 }
13710}
13711
13712/// Attempt to recover from an ill-formed use of a non-dependent name in a
13713/// template, where the non-dependent name was declared after the template
13714/// was defined. This is common in code written for a compilers which do not
13715/// correctly implement two-stage name lookup.
13716///
13717/// Returns true if a viable candidate was found and a diagnostic was issued.
13719 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
13721 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
13722 CXXRecordDecl **FoundInClass = nullptr) {
13723 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
13724 return false;
13725
13726 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
13727 if (DC->isTransparentContext())
13728 continue;
13729
13730 SemaRef.LookupQualifiedName(R, DC);
13731
13732 if (!R.empty()) {
13734
13735 OverloadCandidateSet Candidates(FnLoc, CSK);
13736 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
13737 Candidates);
13738
13741 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
13742
13743 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
13744 // We either found non-function declarations or a best viable function
13745 // at class scope. A class-scope lookup result disables ADL. Don't
13746 // look past this, but let the caller know that we found something that
13747 // either is, or might be, usable in this class.
13748 if (FoundInClass) {
13749 *FoundInClass = RD;
13750 if (OR == OR_Success) {
13751 R.clear();
13752 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
13753 R.resolveKind();
13754 }
13755 }
13756 return false;
13757 }
13758
13759 if (OR != OR_Success) {
13760 // There wasn't a unique best function or function template.
13761 return false;
13762 }
13763
13764 // Find the namespaces where ADL would have looked, and suggest
13765 // declaring the function there instead.
13766 Sema::AssociatedNamespaceSet AssociatedNamespaces;
13767 Sema::AssociatedClassSet AssociatedClasses;
13768 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
13769 AssociatedNamespaces,
13770 AssociatedClasses);
13771 Sema::AssociatedNamespaceSet SuggestedNamespaces;
13773 DeclContext *Std = SemaRef.getStdNamespace();
13774 for (Sema::AssociatedNamespaceSet::iterator
13775 it = AssociatedNamespaces.begin(),
13776 end = AssociatedNamespaces.end(); it != end; ++it) {
13777 // Never suggest declaring a function within namespace 'std'.
13778 if (Std && Std->Encloses(*it))
13779 continue;
13780
13781 // Never suggest declaring a function within a namespace with a
13782 // reserved name, like __gnu_cxx.
13783 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
13784 if (NS &&
13785 NS->getQualifiedNameAsString().find("__") != std::string::npos)
13786 continue;
13787
13788 SuggestedNamespaces.insert(*it);
13789 }
13790 }
13791
13792 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
13793 << R.getLookupName();
13794 if (SuggestedNamespaces.empty()) {
13795 SemaRef.Diag(Best->Function->getLocation(),
13796 diag::note_not_found_by_two_phase_lookup)
13797 << R.getLookupName() << 0;
13798 } else if (SuggestedNamespaces.size() == 1) {
13799 SemaRef.Diag(Best->Function->getLocation(),
13800 diag::note_not_found_by_two_phase_lookup)
13801 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
13802 } else {
13803 // FIXME: It would be useful to list the associated namespaces here,
13804 // but the diagnostics infrastructure doesn't provide a way to produce
13805 // a localized representation of a list of items.
13806 SemaRef.Diag(Best->Function->getLocation(),
13807 diag::note_not_found_by_two_phase_lookup)
13808 << R.getLookupName() << 2;
13809 }
13810
13811 // Try to recover by calling this function.
13812 return true;
13813 }
13814
13815 R.clear();
13816 }
13817
13818 return false;
13819}
13820
13821/// Attempt to recover from ill-formed use of a non-dependent operator in a
13822/// template, where the non-dependent operator was declared after the template
13823/// was defined.
13824///
13825/// Returns true if a viable candidate was found and a diagnostic was issued.
13826static bool
13828 SourceLocation OpLoc,
13829 ArrayRef<Expr *> Args) {
13830 DeclarationName OpName =
13832 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
13833 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
13835 /*ExplicitTemplateArgs=*/nullptr, Args);
13836}
13837
13838namespace {
13839class BuildRecoveryCallExprRAII {
13840 Sema &SemaRef;
13842
13843public:
13844 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
13845 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
13846 SemaRef.IsBuildingRecoveryCallExpr = true;
13847 }
13848
13849 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
13850};
13851}
13852
13853/// Attempts to recover from a call where no functions were found.
13854///
13855/// This function will do one of three things:
13856/// * Diagnose, recover, and return a recovery expression.
13857/// * Diagnose, fail to recover, and return ExprError().
13858/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
13859/// expected to diagnose as appropriate.
13860static ExprResult
13863 SourceLocation LParenLoc,
13865 SourceLocation RParenLoc,
13866 bool EmptyLookup, bool AllowTypoCorrection) {
13867 // Do not try to recover if it is already building a recovery call.
13868 // This stops infinite loops for template instantiations like
13869 //
13870 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
13871 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
13872 if (SemaRef.IsBuildingRecoveryCallExpr)
13873 return ExprResult();
13874 BuildRecoveryCallExprRAII RCE(SemaRef);
13875
13876 CXXScopeSpec SS;
13877 SS.Adopt(ULE->getQualifierLoc());
13878 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
13879
13880 TemplateArgumentListInfo TABuffer;
13881 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13882 if (ULE->hasExplicitTemplateArgs()) {
13883 ULE->copyTemplateArgumentsInto(TABuffer);
13884 ExplicitTemplateArgs = &TABuffer;
13885 }
13886
13887 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
13889 CXXRecordDecl *FoundInClass = nullptr;
13890 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
13892 ExplicitTemplateArgs, Args, &FoundInClass)) {
13893 // OK, diagnosed a two-phase lookup issue.
13894 } else if (EmptyLookup) {
13895 // Try to recover from an empty lookup with typo correction.
13896 R.clear();
13897 NoTypoCorrectionCCC NoTypoValidator{};
13898 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
13899 ExplicitTemplateArgs != nullptr,
13900 dyn_cast<MemberExpr>(Fn));
13901 CorrectionCandidateCallback &Validator =
13902 AllowTypoCorrection
13903 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
13904 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
13905 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
13906 Args))
13907 return ExprError();
13908 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
13909 // We found a usable declaration of the name in a dependent base of some
13910 // enclosing class.
13911 // FIXME: We should also explain why the candidates found by name lookup
13912 // were not viable.
13913 if (SemaRef.DiagnoseDependentMemberLookup(R))
13914 return ExprError();
13915 } else {
13916 // We had viable candidates and couldn't recover; let the caller diagnose
13917 // this.
13918 return ExprResult();
13919 }
13920
13921 // If we get here, we should have issued a diagnostic and formed a recovery
13922 // lookup result.
13923 assert(!R.empty() && "lookup results empty despite recovery");
13924
13925 // If recovery created an ambiguity, just bail out.
13926 if (R.isAmbiguous()) {
13928 return ExprError();
13929 }
13930
13931 // Build an implicit member call if appropriate. Just drop the
13932 // casts and such from the call, we don't really care.
13933 ExprResult NewFn = ExprError();
13934 if ((*R.begin())->isCXXClassMember())
13935 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
13936 ExplicitTemplateArgs, S);
13937 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
13938 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
13939 ExplicitTemplateArgs);
13940 else
13941 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
13942
13943 if (NewFn.isInvalid())
13944 return ExprError();
13945
13946 // This shouldn't cause an infinite loop because we're giving it
13947 // an expression with viable lookup results, which should never
13948 // end up here.
13949 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
13950 MultiExprArg(Args.data(), Args.size()),
13951 RParenLoc);
13952}
13953
13956 MultiExprArg Args,
13957 SourceLocation RParenLoc,
13958 OverloadCandidateSet *CandidateSet,
13959 ExprResult *Result) {
13960#ifndef NDEBUG
13961 if (ULE->requiresADL()) {
13962 // To do ADL, we must have found an unqualified name.
13963 assert(!ULE->getQualifier() && "qualified name with ADL");
13964
13965 // We don't perform ADL for implicit declarations of builtins.
13966 // Verify that this was correctly set up.
13967 FunctionDecl *F;
13968 if (ULE->decls_begin() != ULE->decls_end() &&
13969 ULE->decls_begin() + 1 == ULE->decls_end() &&
13970 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
13971 F->getBuiltinID() && F->isImplicit())
13972 llvm_unreachable("performing ADL for builtin");
13973
13974 // We don't perform ADL in C.
13975 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
13976 }
13977#endif
13978
13979 UnbridgedCastsSet UnbridgedCasts;
13980 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
13981 *Result = ExprError();
13982 return true;
13983 }
13984
13985 // Add the functions denoted by the callee to the set of candidate
13986 // functions, including those from argument-dependent lookup.
13987 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
13988
13989 if (getLangOpts().MSVCCompat &&
13990 CurContext->isDependentContext() && !isSFINAEContext() &&
13991 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
13992
13994 if (CandidateSet->empty() ||
13995 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
13997 // In Microsoft mode, if we are inside a template class member function
13998 // then create a type dependent CallExpr. The goal is to postpone name
13999 // lookup to instantiation time to be able to search into type dependent
14000 // base classes.
14001 CallExpr *CE =
14002 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
14003 RParenLoc, CurFPFeatureOverrides());
14005 *Result = CE;
14006 return true;
14007 }
14008 }
14009
14010 if (CandidateSet->empty())
14011 return false;
14012
14013 UnbridgedCasts.restore();
14014 return false;
14015}
14016
14017// Guess at what the return type for an unresolvable overload should be.
14020 std::optional<QualType> Result;
14021 // Adjust Type after seeing a candidate.
14022 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14023 if (!Candidate.Function)
14024 return;
14025 if (Candidate.Function->isInvalidDecl())
14026 return;
14027 QualType T = Candidate.Function->getReturnType();
14028 if (T.isNull())
14029 return;
14030 if (!Result)
14031 Result = T;
14032 else if (Result != T)
14033 Result = QualType();
14034 };
14035
14036 // Look for an unambiguous type from a progressively larger subset.
14037 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14038 //
14039 // First, consider only the best candidate.
14040 if (Best && *Best != CS.end())
14041 ConsiderCandidate(**Best);
14042 // Next, consider only viable candidates.
14043 if (!Result)
14044 for (const auto &C : CS)
14045 if (C.Viable)
14046 ConsiderCandidate(C);
14047 // Finally, consider all candidates.
14048 if (!Result)
14049 for (const auto &C : CS)
14050 ConsiderCandidate(C);
14051
14052 if (!Result)
14053 return QualType();
14054 auto Value = *Result;
14055 if (Value.isNull() || Value->isUndeducedType())
14056 return QualType();
14057 return Value;
14058}
14059
14060/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14061/// the completed call expression. If overload resolution fails, emits
14062/// diagnostics and returns ExprError()
14065 SourceLocation LParenLoc,
14066 MultiExprArg Args,
14067 SourceLocation RParenLoc,
14068 Expr *ExecConfig,
14069 OverloadCandidateSet *CandidateSet,
14071 OverloadingResult OverloadResult,
14072 bool AllowTypoCorrection) {
14073 switch (OverloadResult) {
14074 case OR_Success: {
14075 FunctionDecl *FDecl = (*Best)->Function;
14076 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14077 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14078 return ExprError();
14079 ExprResult Res =
14080 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14081 if (Res.isInvalid())
14082 return ExprError();
14083 return SemaRef.BuildResolvedCallExpr(
14084 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14085 /*IsExecConfig=*/false, (*Best)->IsADLCandidate);
14086 }
14087
14088 case OR_No_Viable_Function: {
14089 if (*Best != CandidateSet->end() &&
14090 CandidateSet->getKind() ==
14092 if (CXXMethodDecl *M =
14093 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
14095 CandidateSet->NoteCandidates(
14097 Fn->getBeginLoc(),
14098 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
14099 SemaRef, OCD_AmbiguousCandidates, Args);
14100 return ExprError();
14101 }
14102 }
14103
14104 // Try to recover by looking for viable functions which the user might
14105 // have meant to call.
14106 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14107 Args, RParenLoc,
14108 CandidateSet->empty(),
14109 AllowTypoCorrection);
14110 if (Recovery.isInvalid() || Recovery.isUsable())
14111 return Recovery;
14112
14113 // If the user passes in a function that we can't take the address of, we
14114 // generally end up emitting really bad error messages. Here, we attempt to
14115 // emit better ones.
14116 for (const Expr *Arg : Args) {
14117 if (!Arg->getType()->isFunctionType())
14118 continue;
14119 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14120 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14121 if (FD &&
14122 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14123 Arg->getExprLoc()))
14124 return ExprError();
14125 }
14126 }
14127
14128 CandidateSet->NoteCandidates(
14130 Fn->getBeginLoc(),
14131 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14132 << ULE->getName() << Fn->getSourceRange()),
14133 SemaRef, OCD_AllCandidates, Args);
14134 break;
14135 }
14136
14137 case OR_Ambiguous:
14138 CandidateSet->NoteCandidates(
14139 PartialDiagnosticAt(Fn->getBeginLoc(),
14140 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14141 << ULE->getName() << Fn->getSourceRange()),
14142 SemaRef, OCD_AmbiguousCandidates, Args);
14143 break;
14144
14145 case OR_Deleted: {
14146 FunctionDecl *FDecl = (*Best)->Function;
14147 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
14148 Fn->getSourceRange(), ULE->getName(),
14149 *CandidateSet, FDecl, Args);
14150
14151 // We emitted an error for the unavailable/deleted function call but keep
14152 // the call in the AST.
14153 ExprResult Res =
14154 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14155 if (Res.isInvalid())
14156 return ExprError();
14157 return SemaRef.BuildResolvedCallExpr(
14158 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14159 /*IsExecConfig=*/false, (*Best)->IsADLCandidate);
14160 }
14161 }
14162
14163 // Overload resolution failed, try to recover.
14164 SmallVector<Expr *, 8> SubExprs = {Fn};
14165 SubExprs.append(Args.begin(), Args.end());
14166 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
14167 chooseRecoveryType(*CandidateSet, Best));
14168}
14169
14172 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14173 if (I->Viable &&
14174 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
14175 I->Viable = false;
14176 I->FailureKind = ovl_fail_addr_not_available;
14177 }
14178 }
14179}
14180
14183 SourceLocation LParenLoc,
14184 MultiExprArg Args,
14185 SourceLocation RParenLoc,
14186 Expr *ExecConfig,
14187 bool AllowTypoCorrection,
14188 bool CalleesAddressIsTaken) {
14189 OverloadCandidateSet CandidateSet(
14190 Fn->getExprLoc(), CalleesAddressIsTaken
14193 ExprResult result;
14194
14195 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
14196 &result))
14197 return result;
14198
14199 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14200 // functions that aren't addressible are considered unviable.
14201 if (CalleesAddressIsTaken)
14202 markUnaddressableCandidatesUnviable(*this, CandidateSet);
14203
14205 OverloadingResult OverloadResult =
14206 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
14207
14208 // Model the case with a call to a templated function whose definition
14209 // encloses the call and whose return type contains a placeholder type as if
14210 // the UnresolvedLookupExpr was type-dependent.
14211 if (OverloadResult == OR_Success) {
14212 const FunctionDecl *FDecl = Best->Function;
14213 if (FDecl && FDecl->isTemplateInstantiation() &&
14214 FDecl->getReturnType()->isUndeducedType()) {
14215 if (const auto *TP =
14216 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14217 TP && TP->willHaveBody()) {
14218 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
14219 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
14220 }
14221 }
14222 }
14223
14224 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14225 ExecConfig, &CandidateSet, &Best,
14226 OverloadResult, AllowTypoCorrection);
14227}
14228
14232 const UnresolvedSetImpl &Fns,
14233 bool PerformADL) {
14235 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
14236 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
14237}
14238
14240 CXXConversionDecl *Method,
14241 bool HadMultipleCandidates) {
14242 // Convert the expression to match the conversion function's implicit object
14243 // parameter.
14244 ExprResult Exp;
14245 if (Method->isExplicitObjectMemberFunction())
14246 Exp = InitializeExplicitObjectArgument(*this, E, Method);
14247 else
14248 Exp = PerformImplicitObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
14249 FoundDecl, Method);
14250 if (Exp.isInvalid())
14251 return true;
14252
14253 if (Method->getParent()->isLambda() &&
14255 // This is a lambda conversion to block pointer; check if the argument
14256 // was a LambdaExpr.
14257 Expr *SubE = E;
14258 auto *CE = dyn_cast<CastExpr>(SubE);
14259 if (CE && CE->getCastKind() == CK_NoOp)
14260 SubE = CE->getSubExpr();
14261 SubE = SubE->IgnoreParens();
14262 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
14263 SubE = BE->getSubExpr();
14264 if (isa<LambdaExpr>(SubE)) {
14265 // For the conversion to block pointer on a lambda expression, we
14266 // construct a special BlockLiteral instead; this doesn't really make
14267 // a difference in ARC, but outside of ARC the resulting block literal
14268 // follows the normal lifetime rules for block literals instead of being
14269 // autoreleased.
14270 PushExpressionEvaluationContext(
14271 ExpressionEvaluationContext::PotentiallyEvaluated);
14272 ExprResult BlockExp = BuildBlockForLambdaConversion(
14273 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
14274 PopExpressionEvaluationContext();
14275
14276 // FIXME: This note should be produced by a CodeSynthesisContext.
14277 if (BlockExp.isInvalid())
14278 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
14279 return BlockExp;
14280 }
14281 }
14282 CallExpr *CE;
14283 QualType ResultType = Method->getReturnType();
14285 ResultType = ResultType.getNonLValueExprType(Context);
14286 if (Method->isExplicitObjectMemberFunction()) {
14287 ExprResult FnExpr =
14288 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
14289 HadMultipleCandidates, E->getBeginLoc());
14290 if (FnExpr.isInvalid())
14291 return ExprError();
14292 Expr *ObjectParam = Exp.get();
14293 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
14294 ResultType, VK, Exp.get()->getEndLoc(),
14295 CurFPFeatureOverrides());
14296 } else {
14297 MemberExpr *ME =
14298 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
14300 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
14301 HadMultipleCandidates, DeclarationNameInfo(),
14303
14304 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
14305 Exp.get()->getEndLoc(),
14306 CurFPFeatureOverrides());
14307 }
14308
14309 if (CheckFunctionCall(Method, CE,
14310 Method->getType()->castAs<FunctionProtoType>()))
14311 return ExprError();
14312
14313 return CheckForImmediateInvocation(CE, CE->getDirectCallee());
14314}
14315
14318 const UnresolvedSetImpl &Fns,
14319 Expr *Input, bool PerformADL) {
14321 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
14323 // TODO: provide better source location info.
14324 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14325
14326 if (checkPlaceholderForOverload(*this, Input))
14327 return ExprError();
14328
14329 Expr *Args[2] = { Input, nullptr };
14330 unsigned NumArgs = 1;
14331
14332 // For post-increment and post-decrement, add the implicit '0' as
14333 // the second argument, so that we know this is a post-increment or
14334 // post-decrement.
14335 if (Opc == UO_PostInc || Opc == UO_PostDec) {
14336 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14337 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
14338 SourceLocation());
14339 NumArgs = 2;
14340 }
14341
14342 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
14343
14344 if (Input->isTypeDependent()) {
14346 // [C++26][expr.unary.op][expr.pre.incr]
14347 // The * operator yields an lvalue of type
14348 // The pre/post increment operators yied an lvalue.
14349 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
14350 VK = VK_LValue;
14351
14352 if (Fns.empty())
14353 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
14354 OK_Ordinary, OpLoc, false,
14355 CurFPFeatureOverrides());
14356
14357 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14358 ExprResult Fn = CreateUnresolvedLookupExpr(
14359 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
14360 if (Fn.isInvalid())
14361 return ExprError();
14362 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
14363 Context.DependentTy, VK_PRValue, OpLoc,
14364 CurFPFeatureOverrides());
14365 }
14366
14367 // Build an empty overload set.
14369
14370 // Add the candidates from the given function set.
14371 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
14372
14373 // Add operator candidates that are member functions.
14374 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14375
14376 // Add candidates from ADL.
14377 if (PerformADL) {
14378 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
14379 /*ExplicitTemplateArgs*/nullptr,
14380 CandidateSet);
14381 }
14382
14383 // Add builtin operator candidates.
14384 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14385
14386 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14387
14388 // Perform overload resolution.
14390 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14391 case OR_Success: {
14392 // We found a built-in operator or an overloaded operator.
14393 FunctionDecl *FnDecl = Best->Function;
14394
14395 if (FnDecl) {
14396 Expr *Base = nullptr;
14397 // We matched an overloaded operator. Build a call to that
14398 // operator.
14399
14400 // Convert the arguments.
14401 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14402 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
14403
14404 ExprResult InputInit;
14405 if (Method->isExplicitObjectMemberFunction())
14406 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
14407 else
14408 InputInit = PerformImplicitObjectArgumentInitialization(
14409 Input, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14410 if (InputInit.isInvalid())
14411 return ExprError();
14412 Base = Input = InputInit.get();
14413 } else {
14414 // Convert the arguments.
14415 ExprResult InputInit
14416 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14417 Context,
14418 FnDecl->getParamDecl(0)),
14420 Input);
14421 if (InputInit.isInvalid())
14422 return ExprError();
14423 Input = InputInit.get();
14424 }
14425
14426 // Build the actual expression node.
14427 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
14428 Base, HadMultipleCandidates,
14429 OpLoc);
14430 if (FnExpr.isInvalid())
14431 return ExprError();
14432
14433 // Determine the result type.
14434 QualType ResultTy = FnDecl->getReturnType();
14436 ResultTy = ResultTy.getNonLValueExprType(Context);
14437
14438 Args[0] = Input;
14440 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
14441 CurFPFeatureOverrides(), Best->IsADLCandidate);
14442
14443 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
14444 return ExprError();
14445
14446 if (CheckFunctionCall(FnDecl, TheCall,
14447 FnDecl->getType()->castAs<FunctionProtoType>()))
14448 return ExprError();
14449 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
14450 } else {
14451 // We matched a built-in operator. Convert the arguments, then
14452 // break out so that we will build the appropriate built-in
14453 // operator node.
14454 ExprResult InputRes = PerformImplicitConversion(
14455 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
14458 if (InputRes.isInvalid())
14459 return ExprError();
14460 Input = InputRes.get();
14461 break;
14462 }
14463 }
14464
14466 // This is an erroneous use of an operator which can be overloaded by
14467 // a non-member function. Check for non-member operators which were
14468 // defined too late to be candidates.
14469 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
14470 // FIXME: Recover by calling the found function.
14471 return ExprError();
14472
14473 // No viable function; fall through to handling this as a
14474 // built-in operator, which will produce an error message for us.
14475 break;
14476
14477 case OR_Ambiguous:
14478 CandidateSet.NoteCandidates(
14479 PartialDiagnosticAt(OpLoc,
14480 PDiag(diag::err_ovl_ambiguous_oper_unary)
14482 << Input->getType() << Input->getSourceRange()),
14483 *this, OCD_AmbiguousCandidates, ArgsArray,
14484 UnaryOperator::getOpcodeStr(Opc), OpLoc);
14485 return ExprError();
14486
14487 case OR_Deleted: {
14488 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
14489 // object whose method was called. Later in NoteCandidates size of ArgsArray
14490 // is passed further and it eventually ends up compared to number of
14491 // function candidate parameters which never includes the object parameter,
14492 // so slice ArgsArray to make sure apples are compared to apples.
14493 StringLiteral *Msg = Best->Function->getDeletedMessage();
14494 CandidateSet.NoteCandidates(
14495 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14497 << (Msg != nullptr)
14498 << (Msg ? Msg->getString() : StringRef())
14499 << Input->getSourceRange()),
14500 *this, OCD_AllCandidates, ArgsArray.drop_front(),
14501 UnaryOperator::getOpcodeStr(Opc), OpLoc);
14502 return ExprError();
14503 }
14504 }
14505
14506 // Either we found no viable overloaded operator or we matched a
14507 // built-in operator. In either case, fall through to trying to
14508 // build a built-in operation.
14509 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14510}
14511
14514 const UnresolvedSetImpl &Fns,
14515 ArrayRef<Expr *> Args, bool PerformADL) {
14516 SourceLocation OpLoc = CandidateSet.getLocation();
14517
14518 OverloadedOperatorKind ExtraOp =
14521 : OO_None;
14522
14523 // Add the candidates from the given function set. This also adds the
14524 // rewritten candidates using these functions if necessary.
14525 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
14526
14527 // Add operator candidates that are member functions.
14528 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14529 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
14530 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
14532
14533 // In C++20, also add any rewritten member candidates.
14534 if (ExtraOp) {
14535 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
14536 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
14537 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
14538 CandidateSet,
14540 }
14541
14542 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
14543 // performed for an assignment operator (nor for operator[] nor operator->,
14544 // which don't get here).
14545 if (Op != OO_Equal && PerformADL) {
14547 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
14548 /*ExplicitTemplateArgs*/ nullptr,
14549 CandidateSet);
14550 if (ExtraOp) {
14551 DeclarationName ExtraOpName =
14552 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
14553 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
14554 /*ExplicitTemplateArgs*/ nullptr,
14555 CandidateSet);
14556 }
14557 }
14558
14559 // Add builtin operator candidates.
14560 //
14561 // FIXME: We don't add any rewritten candidates here. This is strictly
14562 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
14563 // resulting in our selecting a rewritten builtin candidate. For example:
14564 //
14565 // enum class E { e };
14566 // bool operator!=(E, E) requires false;
14567 // bool k = E::e != E::e;
14568 //
14569 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
14570 // it seems unreasonable to consider rewritten builtin candidates. A core
14571 // issue has been filed proposing to removed this requirement.
14572 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14573}
14574
14577 const UnresolvedSetImpl &Fns, Expr *LHS,
14578 Expr *RHS, bool PerformADL,
14579 bool AllowRewrittenCandidates,
14580 FunctionDecl *DefaultedFn) {
14581 Expr *Args[2] = { LHS, RHS };
14582 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
14583
14584 if (!getLangOpts().CPlusPlus20)
14585 AllowRewrittenCandidates = false;
14586
14588
14589 // If either side is type-dependent, create an appropriate dependent
14590 // expression.
14591 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
14592 if (Fns.empty()) {
14593 // If there are no functions to store, just build a dependent
14594 // BinaryOperator or CompoundAssignment.
14597 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
14598 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
14599 Context.DependentTy);
14601 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
14602 OK_Ordinary, OpLoc, CurFPFeatureOverrides());
14603 }
14604
14605 // FIXME: save results of ADL from here?
14606 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14607 // TODO: provide better source location info in DNLoc component.
14609 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14610 ExprResult Fn = CreateUnresolvedLookupExpr(
14611 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
14612 if (Fn.isInvalid())
14613 return ExprError();
14614 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
14615 Context.DependentTy, VK_PRValue, OpLoc,
14616 CurFPFeatureOverrides());
14617 }
14618
14619 // If this is the .* operator, which is not overloadable, just
14620 // create a built-in binary operator.
14621 if (Opc == BO_PtrMemD) {
14622 auto CheckPlaceholder = [&](Expr *&Arg) {
14623 ExprResult Res = CheckPlaceholderExpr(Arg);
14624 if (Res.isUsable())
14625 Arg = Res.get();
14626 return !Res.isUsable();
14627 };
14628
14629 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
14630 // expression that contains placeholders (in either the LHS or RHS).
14631 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
14632 return ExprError();
14633 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14634 }
14635
14636 // Always do placeholder-like conversions on the RHS.
14637 if (checkPlaceholderForOverload(*this, Args[1]))
14638 return ExprError();
14639
14640 // Do placeholder-like conversion on the LHS; note that we should
14641 // not get here with a PseudoObject LHS.
14642 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
14643 if (checkPlaceholderForOverload(*this, Args[0]))
14644 return ExprError();
14645
14646 // If this is the assignment operator, we only perform overload resolution
14647 // if the left-hand side is a class or enumeration type. This is actually
14648 // a hack. The standard requires that we do overload resolution between the
14649 // various built-in candidates, but as DR507 points out, this can lead to
14650 // problems. So we do it this way, which pretty much follows what GCC does.
14651 // Note that we go the traditional code path for compound assignment forms.
14652 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
14653 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14654
14655 // Build the overload set.
14658 Op, OpLoc, AllowRewrittenCandidates));
14659 if (DefaultedFn)
14660 CandidateSet.exclude(DefaultedFn);
14661 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
14662
14663 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14664
14665 // Perform overload resolution.
14667 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14668 case OR_Success: {
14669 // We found a built-in operator or an overloaded operator.
14670 FunctionDecl *FnDecl = Best->Function;
14671
14672 bool IsReversed = Best->isReversed();
14673 if (IsReversed)
14674 std::swap(Args[0], Args[1]);
14675
14676 if (FnDecl) {
14677
14678 if (FnDecl->isInvalidDecl())
14679 return ExprError();
14680
14681 Expr *Base = nullptr;
14682 // We matched an overloaded operator. Build a call to that
14683 // operator.
14684
14685 OverloadedOperatorKind ChosenOp =
14687
14688 // C++2a [over.match.oper]p9:
14689 // If a rewritten operator== candidate is selected by overload
14690 // resolution for an operator@, its return type shall be cv bool
14691 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
14692 !FnDecl->getReturnType()->isBooleanType()) {
14693 bool IsExtension =
14695 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
14696 : diag::err_ovl_rewrite_equalequal_not_bool)
14697 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
14698 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14699 Diag(FnDecl->getLocation(), diag::note_declared_at);
14700 if (!IsExtension)
14701 return ExprError();
14702 }
14703
14704 if (AllowRewrittenCandidates && !IsReversed &&
14705 CandidateSet.getRewriteInfo().isReversible()) {
14706 // We could have reversed this operator, but didn't. Check if some
14707 // reversed form was a viable candidate, and if so, if it had a
14708 // better conversion for either parameter. If so, this call is
14709 // formally ambiguous, and allowing it is an extension.
14711 for (OverloadCandidate &Cand : CandidateSet) {
14712 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
14713 allowAmbiguity(Context, Cand.Function, FnDecl)) {
14714 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
14716 *this, OpLoc, Cand.Conversions[ArgIdx],
14717 Best->Conversions[ArgIdx]) ==
14719 AmbiguousWith.push_back(Cand.Function);
14720 break;
14721 }
14722 }
14723 }
14724 }
14725
14726 if (!AmbiguousWith.empty()) {
14727 bool AmbiguousWithSelf =
14728 AmbiguousWith.size() == 1 &&
14729 declaresSameEntity(AmbiguousWith.front(), FnDecl);
14730 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
14732 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
14733 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14734 if (AmbiguousWithSelf) {
14735 Diag(FnDecl->getLocation(),
14736 diag::note_ovl_ambiguous_oper_binary_reversed_self);
14737 // Mark member== const or provide matching != to disallow reversed
14738 // args. Eg.
14739 // struct S { bool operator==(const S&); };
14740 // S()==S();
14741 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
14742 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
14743 !MD->isConst() &&
14744 !MD->hasCXXExplicitFunctionObjectParameter() &&
14745 Context.hasSameUnqualifiedType(
14746 MD->getFunctionObjectParameterType(),
14747 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
14748 Context.hasSameUnqualifiedType(
14749 MD->getFunctionObjectParameterType(),
14750 Args[0]->getType()) &&
14751 Context.hasSameUnqualifiedType(
14752 MD->getFunctionObjectParameterType(),
14753 Args[1]->getType()))
14754 Diag(FnDecl->getLocation(),
14755 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
14756 } else {
14757 Diag(FnDecl->getLocation(),
14758 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
14759 for (auto *F : AmbiguousWith)
14760 Diag(F->getLocation(),
14761 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
14762 }
14763 }
14764 }
14765
14766 // Check for nonnull = nullable.
14767 // This won't be caught in the arg's initialization: the parameter to
14768 // the assignment operator is not marked nonnull.
14769 if (Op == OO_Equal)
14770 diagnoseNullableToNonnullConversion(Args[0]->getType(),
14771 Args[1]->getType(), OpLoc);
14772
14773 // Convert the arguments.
14774 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14775 // Best->Access is only meaningful for class members.
14776 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
14777
14778 ExprResult Arg0, Arg1;
14779 unsigned ParamIdx = 0;
14780 if (Method->isExplicitObjectMemberFunction()) {
14781 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
14782 ParamIdx = 1;
14783 } else {
14784 Arg0 = PerformImplicitObjectArgumentInitialization(
14785 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14786 }
14787 Arg1 = PerformCopyInitialization(
14789 Context, FnDecl->getParamDecl(ParamIdx)),
14790 SourceLocation(), Args[1]);
14791 if (Arg0.isInvalid() || Arg1.isInvalid())
14792 return ExprError();
14793
14794 Base = Args[0] = Arg0.getAs<Expr>();
14795 Args[1] = RHS = Arg1.getAs<Expr>();
14796 } else {
14797 // Convert the arguments.
14798 ExprResult Arg0 = PerformCopyInitialization(
14800 FnDecl->getParamDecl(0)),
14801 SourceLocation(), Args[0]);
14802 if (Arg0.isInvalid())
14803 return ExprError();
14804
14805 ExprResult Arg1 =
14806 PerformCopyInitialization(
14808 FnDecl->getParamDecl(1)),
14809 SourceLocation(), Args[1]);
14810 if (Arg1.isInvalid())
14811 return ExprError();
14812 Args[0] = LHS = Arg0.getAs<Expr>();
14813 Args[1] = RHS = Arg1.getAs<Expr>();
14814 }
14815
14816 // Build the actual expression node.
14817 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
14818 Best->FoundDecl, Base,
14819 HadMultipleCandidates, OpLoc);
14820 if (FnExpr.isInvalid())
14821 return ExprError();
14822
14823 // Determine the result type.
14824 QualType ResultTy = FnDecl->getReturnType();
14826 ResultTy = ResultTy.getNonLValueExprType(Context);
14827
14828 CallExpr *TheCall;
14829 ArrayRef<const Expr *> ArgsArray(Args, 2);
14830 const Expr *ImplicitThis = nullptr;
14831
14832 // We always create a CXXOperatorCallExpr, even for explicit object
14833 // members; CodeGen should take care not to emit the this pointer.
14835 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
14836 CurFPFeatureOverrides(), Best->IsADLCandidate);
14837
14838 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
14839 Method && Method->isImplicitObjectMemberFunction()) {
14840 // Cut off the implicit 'this'.
14841 ImplicitThis = ArgsArray[0];
14842 ArgsArray = ArgsArray.slice(1);
14843 }
14844
14845 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
14846 FnDecl))
14847 return ExprError();
14848
14849 if (Op == OO_Equal) {
14850 // Check for a self move.
14851 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
14852 // lifetime check.
14854 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
14855 Args[1]);
14856 }
14857 if (ImplicitThis) {
14858 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
14859 QualType ThisTypeFromDecl = Context.getPointerType(
14860 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
14861
14862 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
14863 ThisTypeFromDecl);
14864 }
14865
14866 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
14867 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
14868 VariadicDoesNotApply);
14869
14870 ExprResult R = MaybeBindToTemporary(TheCall);
14871 if (R.isInvalid())
14872 return ExprError();
14873
14874 R = CheckForImmediateInvocation(R, FnDecl);
14875 if (R.isInvalid())
14876 return ExprError();
14877
14878 // For a rewritten candidate, we've already reversed the arguments
14879 // if needed. Perform the rest of the rewrite now.
14880 if ((Best->RewriteKind & CRK_DifferentOperator) ||
14881 (Op == OO_Spaceship && IsReversed)) {
14882 if (Op == OO_ExclaimEqual) {
14883 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
14884 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
14885 } else {
14886 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
14887 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14888 Expr *ZeroLiteral =
14889 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
14890
14893 Ctx.Entity = FnDecl;
14894 pushCodeSynthesisContext(Ctx);
14895
14896 R = CreateOverloadedBinOp(
14897 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
14898 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
14899 /*AllowRewrittenCandidates=*/false);
14900
14901 popCodeSynthesisContext();
14902 }
14903 if (R.isInvalid())
14904 return ExprError();
14905 } else {
14906 assert(ChosenOp == Op && "unexpected operator name");
14907 }
14908
14909 // Make a note in the AST if we did any rewriting.
14910 if (Best->RewriteKind != CRK_None)
14911 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
14912
14913 return R;
14914 } else {
14915 // We matched a built-in operator. Convert the arguments, then
14916 // break out so that we will build the appropriate built-in
14917 // operator node.
14918 ExprResult ArgsRes0 = PerformImplicitConversion(
14919 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14922 if (ArgsRes0.isInvalid())
14923 return ExprError();
14924 Args[0] = ArgsRes0.get();
14925
14926 ExprResult ArgsRes1 = PerformImplicitConversion(
14927 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14930 if (ArgsRes1.isInvalid())
14931 return ExprError();
14932 Args[1] = ArgsRes1.get();
14933 break;
14934 }
14935 }
14936
14937 case OR_No_Viable_Function: {
14938 // C++ [over.match.oper]p9:
14939 // If the operator is the operator , [...] and there are no
14940 // viable functions, then the operator is assumed to be the
14941 // built-in operator and interpreted according to clause 5.
14942 if (Opc == BO_Comma)
14943 break;
14944
14945 // When defaulting an 'operator<=>', we can try to synthesize a three-way
14946 // compare result using '==' and '<'.
14947 if (DefaultedFn && Opc == BO_Cmp) {
14948 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
14949 Args[1], DefaultedFn);
14950 if (E.isInvalid() || E.isUsable())
14951 return E;
14952 }
14953
14954 // For class as left operand for assignment or compound assignment
14955 // operator do not fall through to handling in built-in, but report that
14956 // no overloaded assignment operator found
14958 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
14959 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
14960 Args, OpLoc);
14961 DeferDiagsRAII DDR(*this,
14962 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
14963 if (Args[0]->getType()->isRecordType() &&
14964 Opc >= BO_Assign && Opc <= BO_OrAssign) {
14965 Diag(OpLoc, diag::err_ovl_no_viable_oper)
14967 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14968 if (Args[0]->getType()->isIncompleteType()) {
14969 Diag(OpLoc, diag::note_assign_lhs_incomplete)
14970 << Args[0]->getType()
14971 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14972 }
14973 } else {
14974 // This is an erroneous use of an operator which can be overloaded by
14975 // a non-member function. Check for non-member operators which were
14976 // defined too late to be candidates.
14977 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
14978 // FIXME: Recover by calling the found function.
14979 return ExprError();
14980
14981 // No viable function; try to create a built-in operation, which will
14982 // produce an error. Then, show the non-viable candidates.
14983 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14984 }
14985 assert(Result.isInvalid() &&
14986 "C++ binary operator overloading is missing candidates!");
14987 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
14988 return Result;
14989 }
14990
14991 case OR_Ambiguous:
14992 CandidateSet.NoteCandidates(
14993 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14995 << Args[0]->getType()
14996 << Args[1]->getType()
14997 << Args[0]->getSourceRange()
14998 << Args[1]->getSourceRange()),
15000 OpLoc);
15001 return ExprError();
15002
15003 case OR_Deleted: {
15004 if (isImplicitlyDeleted(Best->Function)) {
15005 FunctionDecl *DeletedFD = Best->Function;
15006 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
15007 if (DFK.isSpecialMember()) {
15008 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15009 << Args[0]->getType()
15010 << llvm::to_underlying(DFK.asSpecialMember());
15011 } else {
15012 assert(DFK.isComparison());
15013 Diag(OpLoc, diag::err_ovl_deleted_comparison)
15014 << Args[0]->getType() << DeletedFD;
15015 }
15016
15017 // The user probably meant to call this special member. Just
15018 // explain why it's deleted.
15019 NoteDeletedFunction(DeletedFD);
15020 return ExprError();
15021 }
15022
15023 StringLiteral *Msg = Best->Function->getDeletedMessage();
15024 CandidateSet.NoteCandidates(
15026 OpLoc,
15027 PDiag(diag::err_ovl_deleted_oper)
15028 << getOperatorSpelling(Best->Function->getDeclName()
15029 .getCXXOverloadedOperator())
15030 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15031 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15033 OpLoc);
15034 return ExprError();
15035 }
15036 }
15037
15038 // We matched a built-in operator; build it.
15039 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15040}
15041
15043 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15044 FunctionDecl *DefaultedFn) {
15045 const ComparisonCategoryInfo *Info =
15046 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
15047 // If we're not producing a known comparison category type, we can't
15048 // synthesize a three-way comparison. Let the caller diagnose this.
15049 if (!Info)
15050 return ExprResult((Expr*)nullptr);
15051
15052 // If we ever want to perform this synthesis more generally, we will need to
15053 // apply the temporary materialization conversion to the operands.
15054 assert(LHS->isGLValue() && RHS->isGLValue() &&
15055 "cannot use prvalue expressions more than once");
15056 Expr *OrigLHS = LHS;
15057 Expr *OrigRHS = RHS;
15058
15059 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15060 // each of them multiple times below.
15061 LHS = new (Context)
15062 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15063 LHS->getObjectKind(), LHS);
15064 RHS = new (Context)
15065 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15066 RHS->getObjectKind(), RHS);
15067
15068 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
15069 DefaultedFn);
15070 if (Eq.isInvalid())
15071 return ExprError();
15072
15073 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
15074 true, DefaultedFn);
15075 if (Less.isInvalid())
15076 return ExprError();
15077
15079 if (Info->isPartial()) {
15080 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
15081 DefaultedFn);
15082 if (Greater.isInvalid())
15083 return ExprError();
15084 }
15085
15086 // Form the list of comparisons we're going to perform.
15087 struct Comparison {
15088 ExprResult Cmp;
15090 } Comparisons[4] =
15096 };
15097
15098 int I = Info->isPartial() ? 3 : 2;
15099
15100 // Combine the comparisons with suitable conditional expressions.
15102 for (; I >= 0; --I) {
15103 // Build a reference to the comparison category constant.
15104 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
15105 // FIXME: Missing a constant for a comparison category. Diagnose this?
15106 if (!VI)
15107 return ExprResult((Expr*)nullptr);
15108 ExprResult ThisResult =
15109 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
15110 if (ThisResult.isInvalid())
15111 return ExprError();
15112
15113 // Build a conditional unless this is the final case.
15114 if (Result.get()) {
15115 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
15116 ThisResult.get(), Result.get());
15117 if (Result.isInvalid())
15118 return ExprError();
15119 } else {
15120 Result = ThisResult;
15121 }
15122 }
15123
15124 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15125 // bind the OpaqueValueExprs before they're (repeatedly) used.
15126 Expr *SyntacticForm = BinaryOperator::Create(
15127 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
15128 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
15129 CurFPFeatureOverrides());
15130 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15131 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
15132}
15133
15135 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15136 MultiExprArg Args, SourceLocation LParenLoc) {
15137
15138 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15139 unsigned NumParams = Proto->getNumParams();
15140 unsigned NumArgsSlots =
15141 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
15142 // Build the full argument list for the method call (the implicit object
15143 // parameter is placed at the beginning of the list).
15144 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
15145 bool IsError = false;
15146 // Initialize the implicit object parameter.
15147 // Check the argument types.
15148 for (unsigned i = 0; i != NumParams; i++) {
15149 Expr *Arg;
15150 if (i < Args.size()) {
15151 Arg = Args[i];
15152 ExprResult InputInit =
15154 S.Context, Method->getParamDecl(i)),
15155 SourceLocation(), Arg);
15156 IsError |= InputInit.isInvalid();
15157 Arg = InputInit.getAs<Expr>();
15158 } else {
15159 ExprResult DefArg =
15160 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
15161 if (DefArg.isInvalid()) {
15162 IsError = true;
15163 break;
15164 }
15165 Arg = DefArg.getAs<Expr>();
15166 }
15167
15168 MethodArgs.push_back(Arg);
15169 }
15170 return IsError;
15171}
15172
15174 SourceLocation RLoc,
15175 Expr *Base,
15176 MultiExprArg ArgExpr) {
15178 Args.push_back(Base);
15179 for (auto *e : ArgExpr) {
15180 Args.push_back(e);
15181 }
15182 DeclarationName OpName =
15183 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
15184
15185 SourceRange Range = ArgExpr.empty()
15186 ? SourceRange{}
15187 : SourceRange(ArgExpr.front()->getBeginLoc(),
15188 ArgExpr.back()->getEndLoc());
15189
15190 // If either side is type-dependent, create an appropriate dependent
15191 // expression.
15193
15194 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15195 // CHECKME: no 'operator' keyword?
15196 DeclarationNameInfo OpNameInfo(OpName, LLoc);
15197 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15198 ExprResult Fn = CreateUnresolvedLookupExpr(
15199 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
15200 if (Fn.isInvalid())
15201 return ExprError();
15202 // Can't add any actual overloads yet
15203
15204 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
15205 Context.DependentTy, VK_PRValue, RLoc,
15206 CurFPFeatureOverrides());
15207 }
15208
15209 // Handle placeholders
15210 UnbridgedCastsSet UnbridgedCasts;
15211 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
15212 return ExprError();
15213 }
15214 // Build an empty overload set.
15216
15217 // Subscript can only be overloaded as a member function.
15218
15219 // Add operator candidates that are member functions.
15220 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15221
15222 // Add builtin operator candidates.
15223 if (Args.size() == 2)
15224 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15225
15226 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15227
15228 // Perform overload resolution.
15230 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
15231 case OR_Success: {
15232 // We found a built-in operator or an overloaded operator.
15233 FunctionDecl *FnDecl = Best->Function;
15234
15235 if (FnDecl) {
15236 // We matched an overloaded operator. Build a call to that
15237 // operator.
15238
15239 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
15240
15241 // Convert the arguments.
15242 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
15243 SmallVector<Expr *, 2> MethodArgs;
15244
15245 // Initialize the object parameter.
15246 if (Method->isExplicitObjectMemberFunction()) {
15247 ExprResult Res =
15248 InitializeExplicitObjectArgument(*this, Args[0], Method);
15249 if (Res.isInvalid())
15250 return ExprError();
15251 Args[0] = Res.get();
15252 ArgExpr = Args;
15253 } else {
15254 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
15255 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15256 if (Arg0.isInvalid())
15257 return ExprError();
15258
15259 MethodArgs.push_back(Arg0.get());
15260 }
15261
15263 *this, MethodArgs, Method, ArgExpr, LLoc);
15264 if (IsError)
15265 return ExprError();
15266
15267 // Build the actual expression node.
15268 DeclarationNameInfo OpLocInfo(OpName, LLoc);
15269 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15271 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
15272 OpLocInfo.getLoc(), OpLocInfo.getInfo());
15273 if (FnExpr.isInvalid())
15274 return ExprError();
15275
15276 // Determine the result type
15277 QualType ResultTy = FnDecl->getReturnType();
15279 ResultTy = ResultTy.getNonLValueExprType(Context);
15280
15282 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
15283 CurFPFeatureOverrides());
15284
15285 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
15286 return ExprError();
15287
15288 if (CheckFunctionCall(Method, TheCall,
15289 Method->getType()->castAs<FunctionProtoType>()))
15290 return ExprError();
15291
15292 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
15293 FnDecl);
15294 } else {
15295 // We matched a built-in operator. Convert the arguments, then
15296 // break out so that we will build the appropriate built-in
15297 // operator node.
15298 ExprResult ArgsRes0 = PerformImplicitConversion(
15299 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15302 if (ArgsRes0.isInvalid())
15303 return ExprError();
15304 Args[0] = ArgsRes0.get();
15305
15306 ExprResult ArgsRes1 = PerformImplicitConversion(
15307 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15310 if (ArgsRes1.isInvalid())
15311 return ExprError();
15312 Args[1] = ArgsRes1.get();
15313
15314 break;
15315 }
15316 }
15317
15318 case OR_No_Viable_Function: {
15320 CandidateSet.empty()
15321 ? (PDiag(diag::err_ovl_no_oper)
15322 << Args[0]->getType() << /*subscript*/ 0
15323 << Args[0]->getSourceRange() << Range)
15324 : (PDiag(diag::err_ovl_no_viable_subscript)
15325 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
15326 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
15327 OCD_AllCandidates, ArgExpr, "[]", LLoc);
15328 return ExprError();
15329 }
15330
15331 case OR_Ambiguous:
15332 if (Args.size() == 2) {
15333 CandidateSet.NoteCandidates(
15335 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15336 << "[]" << Args[0]->getType() << Args[1]->getType()
15337 << Args[0]->getSourceRange() << Range),
15338 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15339 } else {
15340 CandidateSet.NoteCandidates(
15342 PDiag(diag::err_ovl_ambiguous_subscript_call)
15343 << Args[0]->getType()
15344 << Args[0]->getSourceRange() << Range),
15345 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15346 }
15347 return ExprError();
15348
15349 case OR_Deleted: {
15350 StringLiteral *Msg = Best->Function->getDeletedMessage();
15351 CandidateSet.NoteCandidates(
15353 PDiag(diag::err_ovl_deleted_oper)
15354 << "[]" << (Msg != nullptr)
15355 << (Msg ? Msg->getString() : StringRef())
15356 << Args[0]->getSourceRange() << Range),
15357 *this, OCD_AllCandidates, Args, "[]", LLoc);
15358 return ExprError();
15359 }
15360 }
15361
15362 // We matched a built-in operator; build it.
15363 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
15364}
15365
15367 SourceLocation LParenLoc,
15368 MultiExprArg Args,
15369 SourceLocation RParenLoc,
15370 Expr *ExecConfig, bool IsExecConfig,
15371 bool AllowRecovery) {
15372 assert(MemExprE->getType() == Context.BoundMemberTy ||
15373 MemExprE->getType() == Context.OverloadTy);
15374
15375 // Dig out the member expression. This holds both the object
15376 // argument and the member function we're referring to.
15377 Expr *NakedMemExpr = MemExprE->IgnoreParens();
15378
15379 // Determine whether this is a call to a pointer-to-member function.
15380 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
15381 assert(op->getType() == Context.BoundMemberTy);
15382 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
15383
15384 QualType fnType =
15385 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
15386
15387 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
15388 QualType resultType = proto->getCallResultType(Context);
15390
15391 // Check that the object type isn't more qualified than the
15392 // member function we're calling.
15393 Qualifiers funcQuals = proto->getMethodQuals();
15394
15395 QualType objectType = op->getLHS()->getType();
15396 if (op->getOpcode() == BO_PtrMemI)
15397 objectType = objectType->castAs<PointerType>()->getPointeeType();
15398 Qualifiers objectQuals = objectType.getQualifiers();
15399
15400 Qualifiers difference = objectQuals - funcQuals;
15401 difference.removeObjCGCAttr();
15402 difference.removeAddressSpace();
15403 if (difference) {
15404 std::string qualsString = difference.getAsString();
15405 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
15406 << fnType.getUnqualifiedType()
15407 << qualsString
15408 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
15409 }
15410
15412 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
15413 CurFPFeatureOverrides(), proto->getNumParams());
15414
15415 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
15416 call, nullptr))
15417 return ExprError();
15418
15419 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
15420 return ExprError();
15421
15422 if (CheckOtherCall(call, proto))
15423 return ExprError();
15424
15425 return MaybeBindToTemporary(call);
15426 }
15427
15428 // We only try to build a recovery expr at this level if we can preserve
15429 // the return type, otherwise we return ExprError() and let the caller
15430 // recover.
15431 auto BuildRecoveryExpr = [&](QualType Type) {
15432 if (!AllowRecovery)
15433 return ExprError();
15434 std::vector<Expr *> SubExprs = {MemExprE};
15435 llvm::append_range(SubExprs, Args);
15436 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
15437 Type);
15438 };
15439 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
15440 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
15441 RParenLoc, CurFPFeatureOverrides());
15442
15443 UnbridgedCastsSet UnbridgedCasts;
15444 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
15445 return ExprError();
15446
15447 MemberExpr *MemExpr;
15448 CXXMethodDecl *Method = nullptr;
15449 bool HadMultipleCandidates = false;
15450 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
15451 NestedNameSpecifier *Qualifier = nullptr;
15452 if (isa<MemberExpr>(NakedMemExpr)) {
15453 MemExpr = cast<MemberExpr>(NakedMemExpr);
15454 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
15455 FoundDecl = MemExpr->getFoundDecl();
15456 Qualifier = MemExpr->getQualifier();
15457 UnbridgedCasts.restore();
15458 } else {
15459 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
15460 Qualifier = UnresExpr->getQualifier();
15461
15462 QualType ObjectType = UnresExpr->getBaseType();
15463 Expr::Classification ObjectClassification
15465 : UnresExpr->getBase()->Classify(Context);
15466
15467 // Add overload candidates
15468 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
15470
15471 // FIXME: avoid copy.
15472 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15473 if (UnresExpr->hasExplicitTemplateArgs()) {
15474 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15475 TemplateArgs = &TemplateArgsBuffer;
15476 }
15477
15479 E = UnresExpr->decls_end(); I != E; ++I) {
15480
15481 QualType ExplicitObjectType = ObjectType;
15482
15483 NamedDecl *Func = *I;
15484 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
15485 if (isa<UsingShadowDecl>(Func))
15486 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
15487
15488 bool HasExplicitParameter = false;
15489 if (const auto *M = dyn_cast<FunctionDecl>(Func);
15490 M && M->hasCXXExplicitFunctionObjectParameter())
15491 HasExplicitParameter = true;
15492 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
15493 M &&
15494 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
15495 HasExplicitParameter = true;
15496
15497 if (HasExplicitParameter)
15498 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
15499
15500 // Microsoft supports direct constructor calls.
15501 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
15502 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
15503 CandidateSet,
15504 /*SuppressUserConversions*/ false);
15505 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
15506 // If explicit template arguments were provided, we can't call a
15507 // non-template member function.
15508 if (TemplateArgs)
15509 continue;
15510
15511 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
15512 ObjectClassification, Args, CandidateSet,
15513 /*SuppressUserConversions=*/false);
15514 } else {
15515 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
15516 I.getPair(), ActingDC, TemplateArgs,
15517 ExplicitObjectType, ObjectClassification,
15518 Args, CandidateSet,
15519 /*SuppressUserConversions=*/false);
15520 }
15521 }
15522
15523 HadMultipleCandidates = (CandidateSet.size() > 1);
15524
15525 DeclarationName DeclName = UnresExpr->getMemberName();
15526
15527 UnbridgedCasts.restore();
15528
15530 bool Succeeded = false;
15531 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
15532 Best)) {
15533 case OR_Success:
15534 Method = cast<CXXMethodDecl>(Best->Function);
15535 FoundDecl = Best->FoundDecl;
15536 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
15537 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
15538 break;
15539 // If FoundDecl is different from Method (such as if one is a template
15540 // and the other a specialization), make sure DiagnoseUseOfDecl is
15541 // called on both.
15542 // FIXME: This would be more comprehensively addressed by modifying
15543 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
15544 // being used.
15545 if (Method != FoundDecl.getDecl() &&
15546 DiagnoseUseOfOverloadedDecl(Method, UnresExpr->getNameLoc()))
15547 break;
15548 Succeeded = true;
15549 break;
15550
15552 CandidateSet.NoteCandidates(
15554 UnresExpr->getMemberLoc(),
15555 PDiag(diag::err_ovl_no_viable_member_function_in_call)
15556 << DeclName << MemExprE->getSourceRange()),
15557 *this, OCD_AllCandidates, Args);
15558 break;
15559 case OR_Ambiguous:
15560 CandidateSet.NoteCandidates(
15561 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
15562 PDiag(diag::err_ovl_ambiguous_member_call)
15563 << DeclName << MemExprE->getSourceRange()),
15564 *this, OCD_AmbiguousCandidates, Args);
15565 break;
15566 case OR_Deleted:
15567 DiagnoseUseOfDeletedFunction(
15568 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
15569 CandidateSet, Best->Function, Args, /*IsMember=*/true);
15570 break;
15571 }
15572 // Overload resolution fails, try to recover.
15573 if (!Succeeded)
15574 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
15575
15576 ExprResult Res =
15577 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
15578 if (Res.isInvalid())
15579 return ExprError();
15580 MemExprE = Res.get();
15581
15582 // If overload resolution picked a static member
15583 // build a non-member call based on that function.
15584 if (Method->isStatic()) {
15585 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
15586 ExecConfig, IsExecConfig);
15587 }
15588
15589 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
15590 }
15591
15592 QualType ResultType = Method->getReturnType();
15594 ResultType = ResultType.getNonLValueExprType(Context);
15595
15596 assert(Method && "Member call to something that isn't a method?");
15597 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15598
15599 CallExpr *TheCall = nullptr;
15601 if (Method->isExplicitObjectMemberFunction()) {
15602 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
15603 NewArgs))
15604 return ExprError();
15605
15606 // Build the actual expression node.
15607 ExprResult FnExpr =
15608 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
15609 HadMultipleCandidates, MemExpr->getExprLoc());
15610 if (FnExpr.isInvalid())
15611 return ExprError();
15612
15613 TheCall =
15614 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
15615 CurFPFeatureOverrides(), Proto->getNumParams());
15616 } else {
15617 // Convert the object argument (for a non-static member function call).
15618 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
15619 MemExpr->getBase(), Qualifier, FoundDecl, Method);
15620 if (ObjectArg.isInvalid())
15621 return ExprError();
15622 MemExpr->setBase(ObjectArg.get());
15623 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
15624 RParenLoc, CurFPFeatureOverrides(),
15625 Proto->getNumParams());
15626 }
15627
15628 // Check for a valid return type.
15629 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
15630 TheCall, Method))
15631 return BuildRecoveryExpr(ResultType);
15632
15633 // Convert the rest of the arguments
15634 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
15635 RParenLoc))
15636 return BuildRecoveryExpr(ResultType);
15637
15638 DiagnoseSentinelCalls(Method, LParenLoc, Args);
15639
15640 if (CheckFunctionCall(Method, TheCall, Proto))
15641 return ExprError();
15642
15643 // In the case the method to call was not selected by the overloading
15644 // resolution process, we still need to handle the enable_if attribute. Do
15645 // that here, so it will not hide previous -- and more relevant -- errors.
15646 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
15647 if (const EnableIfAttr *Attr =
15648 CheckEnableIf(Method, LParenLoc, Args, true)) {
15649 Diag(MemE->getMemberLoc(),
15650 diag::err_ovl_no_viable_member_function_in_call)
15651 << Method << Method->getSourceRange();
15652 Diag(Method->getLocation(),
15653 diag::note_ovl_candidate_disabled_by_function_cond_attr)
15654 << Attr->getCond()->getSourceRange() << Attr->getMessage();
15655 return ExprError();
15656 }
15657 }
15658
15659 if (isa<CXXConstructorDecl, CXXDestructorDecl>(CurContext) &&
15660 TheCall->getDirectCallee()->isPureVirtual()) {
15661 const FunctionDecl *MD = TheCall->getDirectCallee();
15662
15663 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
15664 MemExpr->performsVirtualDispatch(getLangOpts())) {
15665 Diag(MemExpr->getBeginLoc(),
15666 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
15667 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
15668 << MD->getParent();
15669
15670 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
15671 if (getLangOpts().AppleKext)
15672 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
15673 << MD->getParent() << MD->getDeclName();
15674 }
15675 }
15676
15677 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
15678 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
15679 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
15680 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
15681 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
15682 MemExpr->getMemberLoc());
15683 }
15684
15685 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
15686 TheCall->getDirectCallee());
15687}
15688
15691 SourceLocation LParenLoc,
15692 MultiExprArg Args,
15693 SourceLocation RParenLoc) {
15694 if (checkPlaceholderForOverload(*this, Obj))
15695 return ExprError();
15696 ExprResult Object = Obj;
15697
15698 UnbridgedCastsSet UnbridgedCasts;
15699 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
15700 return ExprError();
15701
15702 assert(Object.get()->getType()->isRecordType() &&
15703 "Requires object type argument");
15704
15705 // C++ [over.call.object]p1:
15706 // If the primary-expression E in the function call syntax
15707 // evaluates to a class object of type "cv T", then the set of
15708 // candidate functions includes at least the function call
15709 // operators of T. The function call operators of T are obtained by
15710 // ordinary lookup of the name operator() in the context of
15711 // (E).operator().
15712 OverloadCandidateSet CandidateSet(LParenLoc,
15714 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
15715
15716 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
15717 diag::err_incomplete_object_call, Object.get()))
15718 return true;
15719
15720 const auto *Record = Object.get()->getType()->castAs<RecordType>();
15721 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
15722 LookupQualifiedName(R, Record->getDecl());
15723 R.suppressAccessDiagnostics();
15724
15725 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15726 Oper != OperEnd; ++Oper) {
15727 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
15728 Object.get()->Classify(Context), Args, CandidateSet,
15729 /*SuppressUserConversion=*/false);
15730 }
15731
15732 // When calling a lambda, both the call operator, and
15733 // the conversion operator to function pointer
15734 // are considered. But when constraint checking
15735 // on the call operator fails, it will also fail on the
15736 // conversion operator as the constraints are always the same.
15737 // As the user probably does not intend to perform a surrogate call,
15738 // we filter them out to produce better error diagnostics, ie to avoid
15739 // showing 2 failed overloads instead of one.
15740 bool IgnoreSurrogateFunctions = false;
15741 if (CandidateSet.size() == 1 && Record->getAsCXXRecordDecl()->isLambda()) {
15742 const OverloadCandidate &Candidate = *CandidateSet.begin();
15743 if (!Candidate.Viable &&
15745 IgnoreSurrogateFunctions = true;
15746 }
15747
15748 // C++ [over.call.object]p2:
15749 // In addition, for each (non-explicit in C++0x) conversion function
15750 // declared in T of the form
15751 //
15752 // operator conversion-type-id () cv-qualifier;
15753 //
15754 // where cv-qualifier is the same cv-qualification as, or a
15755 // greater cv-qualification than, cv, and where conversion-type-id
15756 // denotes the type "pointer to function of (P1,...,Pn) returning
15757 // R", or the type "reference to pointer to function of
15758 // (P1,...,Pn) returning R", or the type "reference to function
15759 // of (P1,...,Pn) returning R", a surrogate call function [...]
15760 // is also considered as a candidate function. Similarly,
15761 // surrogate call functions are added to the set of candidate
15762 // functions for each conversion function declared in an
15763 // accessible base class provided the function is not hidden
15764 // within T by another intervening declaration.
15765 const auto &Conversions =
15766 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
15767 for (auto I = Conversions.begin(), E = Conversions.end();
15768 !IgnoreSurrogateFunctions && I != E; ++I) {
15769 NamedDecl *D = *I;
15770 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
15771 if (isa<UsingShadowDecl>(D))
15772 D = cast<UsingShadowDecl>(D)->getTargetDecl();
15773
15774 // Skip over templated conversion functions; they aren't
15775 // surrogates.
15776 if (isa<FunctionTemplateDecl>(D))
15777 continue;
15778
15779 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
15780 if (!Conv->isExplicit()) {
15781 // Strip the reference type (if any) and then the pointer type (if
15782 // any) to get down to what might be a function type.
15783 QualType ConvType = Conv->getConversionType().getNonReferenceType();
15784 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
15785 ConvType = ConvPtrType->getPointeeType();
15786
15787 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
15788 {
15789 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
15790 Object.get(), Args, CandidateSet);
15791 }
15792 }
15793 }
15794
15795 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15796
15797 // Perform overload resolution.
15799 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
15800 Best)) {
15801 case OR_Success:
15802 // Overload resolution succeeded; we'll build the appropriate call
15803 // below.
15804 break;
15805
15806 case OR_No_Viable_Function: {
15808 CandidateSet.empty()
15809 ? (PDiag(diag::err_ovl_no_oper)
15810 << Object.get()->getType() << /*call*/ 1
15811 << Object.get()->getSourceRange())
15812 : (PDiag(diag::err_ovl_no_viable_object_call)
15813 << Object.get()->getType() << Object.get()->getSourceRange());
15814 CandidateSet.NoteCandidates(
15815 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
15816 OCD_AllCandidates, Args);
15817 break;
15818 }
15819 case OR_Ambiguous:
15820 if (!R.isAmbiguous())
15821 CandidateSet.NoteCandidates(
15822 PartialDiagnosticAt(Object.get()->getBeginLoc(),
15823 PDiag(diag::err_ovl_ambiguous_object_call)
15824 << Object.get()->getType()
15825 << Object.get()->getSourceRange()),
15826 *this, OCD_AmbiguousCandidates, Args);
15827 break;
15828
15829 case OR_Deleted: {
15830 // FIXME: Is this diagnostic here really necessary? It seems that
15831 // 1. we don't have any tests for this diagnostic, and
15832 // 2. we already issue err_deleted_function_use for this later on anyway.
15833 StringLiteral *Msg = Best->Function->getDeletedMessage();
15834 CandidateSet.NoteCandidates(
15835 PartialDiagnosticAt(Object.get()->getBeginLoc(),
15836 PDiag(diag::err_ovl_deleted_object_call)
15837 << Object.get()->getType() << (Msg != nullptr)
15838 << (Msg ? Msg->getString() : StringRef())
15839 << Object.get()->getSourceRange()),
15840 *this, OCD_AllCandidates, Args);
15841 break;
15842 }
15843 }
15844
15845 if (Best == CandidateSet.end())
15846 return true;
15847
15848 UnbridgedCasts.restore();
15849
15850 if (Best->Function == nullptr) {
15851 // Since there is no function declaration, this is one of the
15852 // surrogate candidates. Dig out the conversion function.
15853 CXXConversionDecl *Conv
15854 = cast<CXXConversionDecl>(
15855 Best->Conversions[0].UserDefined.ConversionFunction);
15856
15857 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
15858 Best->FoundDecl);
15859 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
15860 return ExprError();
15861 assert(Conv == Best->FoundDecl.getDecl() &&
15862 "Found Decl & conversion-to-functionptr should be same, right?!");
15863 // We selected one of the surrogate functions that converts the
15864 // object parameter to a function pointer. Perform the conversion
15865 // on the object argument, then let BuildCallExpr finish the job.
15866
15867 // Create an implicit member expr to refer to the conversion operator.
15868 // and then call it.
15869 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
15870 Conv, HadMultipleCandidates);
15871 if (Call.isInvalid())
15872 return ExprError();
15873 // Record usage of conversion in an implicit cast.
15875 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
15876 nullptr, VK_PRValue, CurFPFeatureOverrides());
15877
15878 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
15879 }
15880
15881 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
15882
15883 // We found an overloaded operator(). Build a CXXOperatorCallExpr
15884 // that calls this method, using Object for the implicit object
15885 // parameter and passing along the remaining arguments.
15886 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
15887
15888 // An error diagnostic has already been printed when parsing the declaration.
15889 if (Method->isInvalidDecl())
15890 return ExprError();
15891
15892 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15893 unsigned NumParams = Proto->getNumParams();
15894
15895 DeclarationNameInfo OpLocInfo(
15896 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
15897 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
15898 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15899 Obj, HadMultipleCandidates,
15900 OpLocInfo.getLoc(),
15901 OpLocInfo.getInfo());
15902 if (NewFn.isInvalid())
15903 return true;
15904
15905 SmallVector<Expr *, 8> MethodArgs;
15906 MethodArgs.reserve(NumParams + 1);
15907
15908 bool IsError = false;
15909
15910 // Initialize the object parameter.
15912 if (Method->isExplicitObjectMemberFunction()) {
15913 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
15914 } else {
15915 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
15916 Object.get(), /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15917 if (ObjRes.isInvalid())
15918 IsError = true;
15919 else
15920 Object = ObjRes;
15921 MethodArgs.push_back(Object.get());
15922 }
15923
15925 *this, MethodArgs, Method, Args, LParenLoc);
15926
15927 // If this is a variadic call, handle args passed through "...".
15928 if (Proto->isVariadic()) {
15929 // Promote the arguments (C99 6.5.2.2p7).
15930 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
15931 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
15932 nullptr);
15933 IsError |= Arg.isInvalid();
15934 MethodArgs.push_back(Arg.get());
15935 }
15936 }
15937
15938 if (IsError)
15939 return true;
15940
15941 DiagnoseSentinelCalls(Method, LParenLoc, Args);
15942
15943 // Once we've built TheCall, all of the expressions are properly owned.
15944 QualType ResultTy = Method->getReturnType();
15946 ResultTy = ResultTy.getNonLValueExprType(Context);
15947
15949 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
15950 CurFPFeatureOverrides());
15951
15952 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
15953 return true;
15954
15955 if (CheckFunctionCall(Method, TheCall, Proto))
15956 return true;
15957
15958 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
15959}
15960
15963 bool *NoArrowOperatorFound) {
15964 assert(Base->getType()->isRecordType() &&
15965 "left-hand side must have class type");
15966
15968 return ExprError();
15969
15970 SourceLocation Loc = Base->getExprLoc();
15971
15972 // C++ [over.ref]p1:
15973 //
15974 // [...] An expression x->m is interpreted as (x.operator->())->m
15975 // for a class object x of type T if T::operator->() exists and if
15976 // the operator is selected as the best match function by the
15977 // overload resolution mechanism (13.3).
15978 DeclarationName OpName =
15979 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
15981
15982 if (RequireCompleteType(Loc, Base->getType(),
15983 diag::err_typecheck_incomplete_tag, Base))
15984 return ExprError();
15985
15986 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
15987 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
15989
15990 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15991 Oper != OperEnd; ++Oper) {
15992 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
15993 {}, CandidateSet,
15994 /*SuppressUserConversion=*/false);
15995 }
15996
15997 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15998
15999 // Perform overload resolution.
16001 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
16002 case OR_Success:
16003 // Overload resolution succeeded; we'll build the call below.
16004 break;
16005
16006 case OR_No_Viable_Function: {
16007 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
16008 if (CandidateSet.empty()) {
16009 QualType BaseType = Base->getType();
16010 if (NoArrowOperatorFound) {
16011 // Report this specific error to the caller instead of emitting a
16012 // diagnostic, as requested.
16013 *NoArrowOperatorFound = true;
16014 return ExprError();
16015 }
16016 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16017 << BaseType << Base->getSourceRange();
16018 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16019 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16020 << FixItHint::CreateReplacement(OpLoc, ".");
16021 }
16022 } else
16023 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16024 << "operator->" << Base->getSourceRange();
16025 CandidateSet.NoteCandidates(*this, Base, Cands);
16026 return ExprError();
16027 }
16028 case OR_Ambiguous:
16029 if (!R.isAmbiguous())
16030 CandidateSet.NoteCandidates(
16031 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16032 << "->" << Base->getType()
16033 << Base->getSourceRange()),
16035 return ExprError();
16036
16037 case OR_Deleted: {
16038 StringLiteral *Msg = Best->Function->getDeletedMessage();
16039 CandidateSet.NoteCandidates(
16040 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16041 << "->" << (Msg != nullptr)
16042 << (Msg ? Msg->getString() : StringRef())
16043 << Base->getSourceRange()),
16044 *this, OCD_AllCandidates, Base);
16045 return ExprError();
16046 }
16047 }
16048
16049 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
16050
16051 // Convert the object parameter.
16052 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16053
16054 if (Method->isExplicitObjectMemberFunction()) {
16055 ExprResult R = InitializeExplicitObjectArgument(*this, Base, Method);
16056 if (R.isInvalid())
16057 return ExprError();
16058 Base = R.get();
16059 } else {
16060 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
16061 Base, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
16062 if (BaseResult.isInvalid())
16063 return ExprError();
16064 Base = BaseResult.get();
16065 }
16066
16067 // Build the operator call.
16068 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16069 Base, HadMultipleCandidates, OpLoc);
16070 if (FnExpr.isInvalid())
16071 return ExprError();
16072
16073 QualType ResultTy = Method->getReturnType();
16075 ResultTy = ResultTy.getNonLValueExprType(Context);
16076
16077 CallExpr *TheCall =
16078 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
16079 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
16080
16081 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
16082 return ExprError();
16083
16084 if (CheckFunctionCall(Method, TheCall,
16085 Method->getType()->castAs<FunctionProtoType>()))
16086 return ExprError();
16087
16088 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
16089}
16090
16092 DeclarationNameInfo &SuffixInfo,
16093 ArrayRef<Expr*> Args,
16094 SourceLocation LitEndLoc,
16095 TemplateArgumentListInfo *TemplateArgs) {
16096 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16097
16098 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16100 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
16101 TemplateArgs);
16102
16103 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16104
16105 // Perform overload resolution. This will usually be trivial, but might need
16106 // to perform substitutions for a literal operator template.
16108 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
16109 case OR_Success:
16110 case OR_Deleted:
16111 break;
16112
16114 CandidateSet.NoteCandidates(
16115 PartialDiagnosticAt(UDSuffixLoc,
16116 PDiag(diag::err_ovl_no_viable_function_in_call)
16117 << R.getLookupName()),
16118 *this, OCD_AllCandidates, Args);
16119 return ExprError();
16120
16121 case OR_Ambiguous:
16122 CandidateSet.NoteCandidates(
16123 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
16124 << R.getLookupName()),
16125 *this, OCD_AmbiguousCandidates, Args);
16126 return ExprError();
16127 }
16128
16129 FunctionDecl *FD = Best->Function;
16130 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
16131 nullptr, HadMultipleCandidates,
16132 SuffixInfo.getLoc(),
16133 SuffixInfo.getInfo());
16134 if (Fn.isInvalid())
16135 return true;
16136
16137 // Check the argument types. This should almost always be a no-op, except
16138 // that array-to-pointer decay is applied to string literals.
16139 Expr *ConvArgs[2];
16140 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16141 ExprResult InputInit = PerformCopyInitialization(
16143 SourceLocation(), Args[ArgIdx]);
16144 if (InputInit.isInvalid())
16145 return true;
16146 ConvArgs[ArgIdx] = InputInit.get();
16147 }
16148
16149 QualType ResultTy = FD->getReturnType();
16151 ResultTy = ResultTy.getNonLValueExprType(Context);
16152
16154 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
16155 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
16156
16157 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
16158 return ExprError();
16159
16160 if (CheckFunctionCall(FD, UDL, nullptr))
16161 return ExprError();
16162
16163 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
16164}
16165
16168 SourceLocation RangeLoc,
16169 const DeclarationNameInfo &NameInfo,
16170 LookupResult &MemberLookup,
16171 OverloadCandidateSet *CandidateSet,
16173 Scope *S = nullptr;
16174
16176 if (!MemberLookup.empty()) {
16177 ExprResult MemberRef =
16178 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
16179 /*IsPtr=*/false, CXXScopeSpec(),
16180 /*TemplateKWLoc=*/SourceLocation(),
16181 /*FirstQualifierInScope=*/nullptr,
16182 MemberLookup,
16183 /*TemplateArgs=*/nullptr, S);
16184 if (MemberRef.isInvalid()) {
16185 *CallExpr = ExprError();
16186 return FRS_DiagnosticIssued;
16187 }
16188 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
16189 if (CallExpr->isInvalid()) {
16190 *CallExpr = ExprError();
16191 return FRS_DiagnosticIssued;
16192 }
16193 } else {
16194 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16196 NameInfo, UnresolvedSet<0>());
16197 if (FnR.isInvalid())
16198 return FRS_DiagnosticIssued;
16199 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
16200
16201 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
16202 CandidateSet, CallExpr);
16203 if (CandidateSet->empty() || CandidateSetError) {
16204 *CallExpr = ExprError();
16205 return FRS_NoViableFunction;
16206 }
16208 OverloadingResult OverloadResult =
16209 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
16210
16211 if (OverloadResult == OR_No_Viable_Function) {
16212 *CallExpr = ExprError();
16213 return FRS_NoViableFunction;
16214 }
16215 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
16216 Loc, nullptr, CandidateSet, &Best,
16217 OverloadResult,
16218 /*AllowTypoCorrection=*/false);
16219 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16220 *CallExpr = ExprError();
16221 return FRS_DiagnosticIssued;
16222 }
16223 }
16224 return FRS_Success;
16225}
16226
16228 FunctionDecl *Fn) {
16229 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
16230 ExprResult SubExpr =
16231 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
16232 if (SubExpr.isInvalid())
16233 return ExprError();
16234 if (SubExpr.get() == PE->getSubExpr())
16235 return PE;
16236
16237 return new (Context)
16238 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16239 }
16240
16241 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
16242 ExprResult SubExpr =
16243 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
16244 if (SubExpr.isInvalid())
16245 return ExprError();
16246 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16247 SubExpr.get()->getType()) &&
16248 "Implicit cast type cannot be determined from overload");
16249 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16250 if (SubExpr.get() == ICE->getSubExpr())
16251 return ICE;
16252
16253 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
16254 SubExpr.get(), nullptr, ICE->getValueKind(),
16255 CurFPFeatureOverrides());
16256 }
16257
16258 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
16259 if (!GSE->isResultDependent()) {
16260 ExprResult SubExpr =
16261 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
16262 if (SubExpr.isInvalid())
16263 return ExprError();
16264 if (SubExpr.get() == GSE->getResultExpr())
16265 return GSE;
16266
16267 // Replace the resulting type information before rebuilding the generic
16268 // selection expression.
16269 ArrayRef<Expr *> A = GSE->getAssocExprs();
16270 SmallVector<Expr *, 4> AssocExprs(A);
16271 unsigned ResultIdx = GSE->getResultIndex();
16272 AssocExprs[ResultIdx] = SubExpr.get();
16273
16274 if (GSE->isExprPredicate())
16276 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
16277 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16278 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16279 ResultIdx);
16281 Context, GSE->getGenericLoc(), GSE->getControllingType(),
16282 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16283 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16284 ResultIdx);
16285 }
16286 // Rather than fall through to the unreachable, return the original generic
16287 // selection expression.
16288 return GSE;
16289 }
16290
16291 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
16292 assert(UnOp->getOpcode() == UO_AddrOf &&
16293 "Can only take the address of an overloaded function");
16294 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
16295 if (!Method->isImplicitObjectMemberFunction()) {
16296 // Do nothing: the address of static and
16297 // explicit object member functions is a (non-member) function pointer.
16298 } else {
16299 // Fix the subexpression, which really has to be an
16300 // UnresolvedLookupExpr holding an overloaded member function
16301 // or template.
16302 ExprResult SubExpr =
16303 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16304 if (SubExpr.isInvalid())
16305 return ExprError();
16306 if (SubExpr.get() == UnOp->getSubExpr())
16307 return UnOp;
16308
16309 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
16310 SubExpr.get(), Method))
16311 return ExprError();
16312
16313 assert(isa<DeclRefExpr>(SubExpr.get()) &&
16314 "fixed to something other than a decl ref");
16315 assert(cast<DeclRefExpr>(SubExpr.get())->getQualifier() &&
16316 "fixed to a member ref with no nested name qualifier");
16317
16318 // We have taken the address of a pointer to member
16319 // function. Perform the computation here so that we get the
16320 // appropriate pointer to member type.
16321 QualType ClassType
16322 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
16323 QualType MemPtrType
16324 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
16325 // Under the MS ABI, lock down the inheritance model now.
16326 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
16327 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
16328
16329 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
16330 MemPtrType, VK_PRValue, OK_Ordinary,
16331 UnOp->getOperatorLoc(), false,
16332 CurFPFeatureOverrides());
16333 }
16334 }
16335 ExprResult SubExpr =
16336 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16337 if (SubExpr.isInvalid())
16338 return ExprError();
16339 if (SubExpr.get() == UnOp->getSubExpr())
16340 return UnOp;
16341
16342 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
16343 SubExpr.get());
16344 }
16345
16346 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16347 // FIXME: avoid copy.
16348 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16349 if (ULE->hasExplicitTemplateArgs()) {
16350 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
16351 TemplateArgs = &TemplateArgsBuffer;
16352 }
16353
16354 QualType Type = Fn->getType();
16355 ExprValueKind ValueKind =
16356 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
16357 ? VK_LValue
16358 : VK_PRValue;
16359
16360 // FIXME: Duplicated from BuildDeclarationNameExpr.
16361 if (unsigned BID = Fn->getBuiltinID()) {
16362 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
16363 Type = Context.BuiltinFnTy;
16364 ValueKind = VK_PRValue;
16365 }
16366 }
16367
16368 DeclRefExpr *DRE = BuildDeclRefExpr(
16369 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
16370 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
16371 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
16372 return DRE;
16373 }
16374
16375 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
16376 // FIXME: avoid copy.
16377 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16378 if (MemExpr->hasExplicitTemplateArgs()) {
16379 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16380 TemplateArgs = &TemplateArgsBuffer;
16381 }
16382
16383 Expr *Base;
16384
16385 // If we're filling in a static method where we used to have an
16386 // implicit member access, rewrite to a simple decl ref.
16387 if (MemExpr->isImplicitAccess()) {
16388 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
16389 DeclRefExpr *DRE = BuildDeclRefExpr(
16390 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
16391 MemExpr->getQualifierLoc(), Found.getDecl(),
16392 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
16393 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
16394 return DRE;
16395 } else {
16396 SourceLocation Loc = MemExpr->getMemberLoc();
16397 if (MemExpr->getQualifier())
16398 Loc = MemExpr->getQualifierLoc().getBeginLoc();
16399 Base =
16400 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
16401 }
16402 } else
16403 Base = MemExpr->getBase();
16404
16405 ExprValueKind valueKind;
16406 QualType type;
16407 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
16408 valueKind = VK_LValue;
16409 type = Fn->getType();
16410 } else {
16411 valueKind = VK_PRValue;
16412 type = Context.BoundMemberTy;
16413 }
16414
16415 return BuildMemberExpr(
16416 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
16417 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
16418 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
16419 type, valueKind, OK_Ordinary, TemplateArgs);
16420 }
16421
16422 llvm_unreachable("Invalid reference to overloaded function");
16423}
16424
16427 FunctionDecl *Fn) {
16428 return FixOverloadedFunctionReference(E.get(), Found, Fn);
16429}
16430
16431bool clang::shouldEnforceArgLimit(bool PartialOverloading,
16433 if (!PartialOverloading || !Function)
16434 return true;
16435 if (Function->isVariadic())
16436 return false;
16437 if (const auto *Proto =
16438 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
16439 if (Proto->isTemplateVariadic())
16440 return false;
16441 if (auto *Pattern = Function->getTemplateInstantiationPattern())
16442 if (const auto *Proto =
16443 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
16444 if (Proto->isTemplateVariadic())
16445 return false;
16446 return true;
16447}
16448
16450 DeclarationName Name,
16451 OverloadCandidateSet &CandidateSet,
16452 FunctionDecl *Fn, MultiExprArg Args,
16453 bool IsMember) {
16454 StringLiteral *Msg = Fn->getDeletedMessage();
16455 CandidateSet.NoteCandidates(
16456 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
16457 << IsMember << Name << (Msg != nullptr)
16458 << (Msg ? Msg->getString() : StringRef())
16459 << Range),
16460 *this, OCD_AllCandidates, Args);
16461}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3453
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)
static bool hasExplicitAttr(const VarDecl *D)
Definition: SemaCUDA.cpp:31
This file declares semantic analysis for CUDA constructs.
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
static bool isRecordType(QualType T)
static void TryUserDefinedConversion(Sema &S, QualType DestType, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence, bool TopLevelOfInitList)
Attempt a user-defined conversion between two types (C++ [dcl.init]), which enumerates all conversion...
Definition: SemaInit.cpp:5929
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...
@ ft_different_class
@ ft_parameter_mismatch
@ ft_noexcept
@ ft_return_type
@ ft_parameter_arity
@ ft_default
@ ft_qualifer_mismatch
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)
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:7766
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:2196
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:4902
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:189
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:2885
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition: DeclCXX.h:2921
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2925
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:1499
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:1513
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:4924
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:349
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:3861
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4066
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6103
EnumDecl * getDecl() const
Definition: Type.h:6110
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:3102
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:3093
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:3317
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition: Expr.cpp:4131
@ 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:3970
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:276
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:5107
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5573
unsigned getNumParams() const
Definition: Type.h:5360
Qualifiers getMethodQuals() const
Definition: Type.h:5502
QualType getParamType(unsigned i) const
Definition: Type.h:5362
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5484
ArrayRef< QualType > param_types() const
Definition: Type.h:5516
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:4660
CallingConv getCallConv() const
Definition: Type.h:4659
QualType getReturnType() const
Definition: Type.h:4648
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition: Type.h:4672
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:4522
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:2089
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:2501
const Expr * getInit(unsigned Init) const
Definition: Expr.h:5134
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.cpp:2519
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:980
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:1813
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:7529
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:7585
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition: Type.h:7674
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition: Type.h:7643
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7597
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition: Type.h:7637
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:7649
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:4996
A (possibly-)qualified type.
Definition: Type.h:929
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:8020
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition: Type.h:8014
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:8025
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:7936
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:8062
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7976
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:8139
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8030
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:8108
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:8009
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:8057
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7982
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:8119
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:7968
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7876
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7883
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:4162
field_range fields() const
Definition: Decl.h:4368
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6077
RecordDecl * getDecl() const
Definition: Type.h:6087
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:10031
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:5891
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:5920
RAII class to control scope of DeferDiags.
Definition: Sema.h:9758
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:12086
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12116
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:464
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:9774
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:8990
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition: Sema.h:9002
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:8998
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:1071
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:10114
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition: Sema.h:10117
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition: Sema.h:10123
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition: Sema.h:10121
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:1665
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:1570
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:909
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:529
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:1111
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:532
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:692
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:10479
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:9834
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:817
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:11789
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:82
const LangOptions & getLangOpts() const
Definition: Sema.h:525
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:907
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:14990
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:1044
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:7580
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition: Sema.h:7619
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition: Sema.h:7598
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:7582
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition: Sema.h:7615
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:20015
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20971
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:13490
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:14945
bool CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity &Entity, InitListExpr *From)
Determine whether we can perform aggregate initialization for the purposes of overload resolution.
Definition: SemaInit.cpp:3454
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:9998
@ CCEK_ExplicitBool
Condition in an explicit(bool) specifier.
Definition: Sema.h:10003
@ CCEK_Noexcept
Condition in a noexcept(bool) specifier.
Definition: Sema.h:10004
@ CCEK_ArrayBound
Array bound in array declarator or new-expression.
Definition: Sema.h:10002
@ CCEK_TemplateArg
Value of a non-type template parameter.
Definition: Sema.h:10001
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:9776
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:912
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:911
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9713
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:21168
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:9698
bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method, SourceLocation CallLoc)
Returns true if the explicit object parameter was invalid.
Definition: SemaLambda.cpp:395
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:8268
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:6666
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Declaration of a template type parameter.
const Type * getTypeForDecl() const
Definition: Decl.h:3409
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:8205
bool isVoidType() const
Definition: Type.h:8515
bool isBooleanType() const
Definition: Type.h:8643
bool isObjCBuiltinType() const
Definition: Type.h:8384
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:8271
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:8524
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:8217
bool isConstantArrayType() const
Definition: Type.h:8267
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8673
bool isArrayType() const
Definition: Type.h:8263
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:8580
bool isArithmeticType() const
Definition: Type.cpp:2315
bool isPointerType() const
Definition: Type.h:8191
bool isArrayParameterType() const
Definition: Type.h:8279
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8555
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:8805
bool isReferenceType() const
Definition: Type.h:8209
bool isEnumeralType() const
Definition: Type.h:8295
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2092
bool isObjCQualifiedIdType() const
Definition: Type.h:8354
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:8630
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:8341
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:8213
bool isBitIntType() const
Definition: Type.h:8429
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:8299
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8568
bool isHalfType() const
Definition: Type.h:8519
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:8497
bool isQueueT() const
Definition: Type.h:8410
bool isMemberPointerType() const
Definition: Type.h:8245
bool isObjCIdType() const
Definition: Type.h:8366
bool isMatrixType() const
Definition: Type.h:8321
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8649
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2446
bool isEventT() const
Definition: Type.h:8402
bool isBFloat16Type() const
Definition: Type.h:8536
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:8187
bool isObjCObjectPointerType() const
Definition: Type.h:8333
bool isVectorType() const
Definition: Type.h:8303
bool isObjCClassType() const
Definition: Type.h:8372
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:8476
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:8199
TypeClass getTypeClass() const
Definition: Type.h:2341
bool isSamplerT() const
Definition: Type.h:8398
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8736
bool isNullPtrType() const
Definition: Type.h:8548
bool isRecordType() const
Definition: Type.h:8291
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:1432
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:4959
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition: Expr.cpp:1408
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:211
CXXSpecialMemberKind
Kinds of C++ special members.
Definition: Sema.h:423
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:365
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
@ CUDATargetMismatch
CUDA Target attributes do not match.
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
@ Invalid
The declaration was invalid; do nothing.
@ Success
Template argument deduction was successful.
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
@ AlreadyDiagnosed
Some error which was already diagnosed.
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:278
const char * getOperatorSpelling(OverloadedOperatorKind Operator)
Retrieve the spelling of the given overloaded operator, without the preceding "operator" keyword.
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition: Overload.h: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:5192
FunctionEffectsRef FunctionEffects
Definition: Type.h:5202
const ExtParameterInfo * ExtParameterInfos
Definition: Type.h:5200
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:12660
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition: Sema.h:12748
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:12780
ReferenceConversions
The conversions that would be performed on an lvalue of type T2 when binding a reference of type T1 t...
Definition: Sema.h:10131
Abstract class used to diagnose incomplete types.
Definition: Sema.h:7858
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.