1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file provides Sema routines for C++ overloading.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/Overload.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/TypeOrdering.h"
22 #include "clang/Basic/Diagnostic.h"
23 #include "clang/Basic/DiagnosticOptions.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/SemaInternal.h"
29 #include "clang/Sema/Template.h"
30 #include "clang/Sema/TemplateDeduction.h"
31 #include "llvm/ADT/DenseSet.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
38 using namespace clang;
41 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
42 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
43 return P->hasAttr<PassObjectSizeAttr>();
47 /// A convenience routine for creating a decayed reference to a function.
49 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
50 bool HadMultipleCandidates,
51 SourceLocation Loc = SourceLocation(),
52 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
53 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
55 // If FoundDecl is different from Fn (such as if one is a template
56 // and the other a specialization), make sure DiagnoseUseOfDecl is
58 // FIXME: This would be more comprehensively addressed by modifying
59 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
61 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
63 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
64 S.ResolveExceptionSpec(Loc, FPT);
65 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
66 VK_LValue, Loc, LocInfo);
67 if (HadMultipleCandidates)
68 DRE->setHadMultipleCandidates(true);
70 S.MarkDeclRefReferenced(DRE);
71 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
72 CK_FunctionToPointerDecay);
75 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
76 bool InOverloadResolution,
77 StandardConversionSequence &SCS,
79 bool AllowObjCWritebackConversion);
81 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
83 bool InOverloadResolution,
84 StandardConversionSequence &SCS,
86 static OverloadingResult
87 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
88 UserDefinedConversionSequence& User,
89 OverloadCandidateSet& Conversions,
91 bool AllowObjCConversionOnExplicit);
94 static ImplicitConversionSequence::CompareKind
95 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
96 const StandardConversionSequence& SCS1,
97 const StandardConversionSequence& SCS2);
99 static ImplicitConversionSequence::CompareKind
100 CompareQualificationConversions(Sema &S,
101 const StandardConversionSequence& SCS1,
102 const StandardConversionSequence& SCS2);
104 static ImplicitConversionSequence::CompareKind
105 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
106 const StandardConversionSequence& SCS1,
107 const StandardConversionSequence& SCS2);
109 /// GetConversionRank - Retrieve the implicit conversion rank
110 /// corresponding to the given implicit conversion kind.
111 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
112 static const ImplicitConversionRank
113 Rank[(int)ICK_Num_Conversion_Kinds] = {
134 ICR_Complex_Real_Conversion,
137 ICR_Writeback_Conversion,
138 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
139 // it was omitted by the patch that added
140 // ICK_Zero_Event_Conversion
142 ICR_C_Conversion_Extension
144 return Rank[(int)Kind];
147 /// GetImplicitConversionName - Return the name of this kind of
148 /// implicit conversion.
149 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
150 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
154 "Function-to-pointer",
155 "Function pointer conversion",
157 "Integral promotion",
158 "Floating point promotion",
160 "Integral conversion",
161 "Floating conversion",
162 "Complex conversion",
163 "Floating-integral conversion",
164 "Pointer conversion",
165 "Pointer-to-member conversion",
166 "Boolean conversion",
167 "Compatible-types conversion",
168 "Derived-to-base conversion",
171 "Complex-real conversion",
172 "Block Pointer conversion",
173 "Transparent Union Conversion",
174 "Writeback conversion",
175 "OpenCL Zero Event Conversion",
176 "C specific type conversion",
177 "Incompatible pointer conversion"
182 /// StandardConversionSequence - Set the standard conversion
183 /// sequence to the identity conversion.
184 void StandardConversionSequence::setAsIdentityConversion() {
185 First = ICK_Identity;
186 Second = ICK_Identity;
187 Third = ICK_Identity;
188 DeprecatedStringLiteralToCharPtr = false;
189 QualificationIncludesObjCLifetime = false;
190 ReferenceBinding = false;
191 DirectBinding = false;
192 IsLvalueReference = true;
193 BindsToFunctionLvalue = false;
194 BindsToRvalue = false;
195 BindsImplicitObjectArgumentWithoutRefQualifier = false;
196 ObjCLifetimeConversionBinding = false;
197 CopyConstructor = nullptr;
200 /// getRank - Retrieve the rank of this standard conversion sequence
201 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
202 /// implicit conversions.
203 ImplicitConversionRank StandardConversionSequence::getRank() const {
204 ImplicitConversionRank Rank = ICR_Exact_Match;
205 if (GetConversionRank(First) > Rank)
206 Rank = GetConversionRank(First);
207 if (GetConversionRank(Second) > Rank)
208 Rank = GetConversionRank(Second);
209 if (GetConversionRank(Third) > Rank)
210 Rank = GetConversionRank(Third);
214 /// isPointerConversionToBool - Determines whether this conversion is
215 /// a conversion of a pointer or pointer-to-member to bool. This is
216 /// used as part of the ranking of standard conversion sequences
217 /// (C++ 13.3.3.2p4).
218 bool StandardConversionSequence::isPointerConversionToBool() const {
219 // Note that FromType has not necessarily been transformed by the
220 // array-to-pointer or function-to-pointer implicit conversions, so
221 // check for their presence as well as checking whether FromType is
223 if (getToType(1)->isBooleanType() &&
224 (getFromType()->isPointerType() ||
225 getFromType()->isObjCObjectPointerType() ||
226 getFromType()->isBlockPointerType() ||
227 getFromType()->isNullPtrType() ||
228 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
234 /// isPointerConversionToVoidPointer - Determines whether this
235 /// conversion is a conversion of a pointer to a void pointer. This is
236 /// used as part of the ranking of standard conversion sequences (C++
239 StandardConversionSequence::
240 isPointerConversionToVoidPointer(ASTContext& Context) const {
241 QualType FromType = getFromType();
242 QualType ToType = getToType(1);
244 // Note that FromType has not necessarily been transformed by the
245 // array-to-pointer implicit conversion, so check for its presence
246 // and redo the conversion to get a pointer.
247 if (First == ICK_Array_To_Pointer)
248 FromType = Context.getArrayDecayedType(FromType);
250 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
251 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
252 return ToPtrType->getPointeeType()->isVoidType();
257 /// Skip any implicit casts which could be either part of a narrowing conversion
258 /// or after one in an implicit conversion.
259 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
260 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
261 switch (ICE->getCastKind()) {
263 case CK_IntegralCast:
264 case CK_IntegralToBoolean:
265 case CK_IntegralToFloating:
266 case CK_BooleanToSignedIntegral:
267 case CK_FloatingToIntegral:
268 case CK_FloatingToBoolean:
269 case CK_FloatingCast:
270 Converted = ICE->getSubExpr();
281 /// Check if this standard conversion sequence represents a narrowing
282 /// conversion, according to C++11 [dcl.init.list]p7.
284 /// \param Ctx The AST context.
285 /// \param Converted The result of applying this standard conversion sequence.
286 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
287 /// value of the expression prior to the narrowing conversion.
288 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
289 /// type of the expression prior to the narrowing conversion.
291 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
292 const Expr *Converted,
293 APValue &ConstantValue,
294 QualType &ConstantType) const {
295 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
297 // C++11 [dcl.init.list]p7:
298 // A narrowing conversion is an implicit conversion ...
299 QualType FromType = getToType(0);
300 QualType ToType = getToType(1);
302 // A conversion to an enumeration type is narrowing if the conversion to
303 // the underlying type is narrowing. This only arises for expressions of
304 // the form 'Enum{init}'.
305 if (auto *ET = ToType->getAs<EnumType>())
306 ToType = ET->getDecl()->getIntegerType();
309 // 'bool' is an integral type; dispatch to the right place to handle it.
310 case ICK_Boolean_Conversion:
311 if (FromType->isRealFloatingType())
312 goto FloatingIntegralConversion;
313 if (FromType->isIntegralOrUnscopedEnumerationType())
314 goto IntegralConversion;
315 // Boolean conversions can be from pointers and pointers to members
316 // [conv.bool], and those aren't considered narrowing conversions.
317 return NK_Not_Narrowing;
319 // -- from a floating-point type to an integer type, or
321 // -- from an integer type or unscoped enumeration type to a floating-point
322 // type, except where the source is a constant expression and the actual
323 // value after conversion will fit into the target type and will produce
324 // the original value when converted back to the original type, or
325 case ICK_Floating_Integral:
326 FloatingIntegralConversion:
327 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
328 return NK_Type_Narrowing;
329 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
330 llvm::APSInt IntConstantValue;
331 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
333 // If it's value-dependent, we can't tell whether it's narrowing.
334 if (Initializer->isValueDependent())
335 return NK_Dependent_Narrowing;
338 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
339 // Convert the integer to the floating type.
340 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
341 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
342 llvm::APFloat::rmNearestTiesToEven);
344 llvm::APSInt ConvertedValue = IntConstantValue;
346 Result.convertToInteger(ConvertedValue,
347 llvm::APFloat::rmTowardZero, &ignored);
348 // If the resulting value is different, this was a narrowing conversion.
349 if (IntConstantValue != ConvertedValue) {
350 ConstantValue = APValue(IntConstantValue);
351 ConstantType = Initializer->getType();
352 return NK_Constant_Narrowing;
355 // Variables are always narrowings.
356 return NK_Variable_Narrowing;
359 return NK_Not_Narrowing;
361 // -- from long double to double or float, or from double to float, except
362 // where the source is a constant expression and the actual value after
363 // conversion is within the range of values that can be represented (even
364 // if it cannot be represented exactly), or
365 case ICK_Floating_Conversion:
366 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
367 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
368 // FromType is larger than ToType.
369 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
371 // If it's value-dependent, we can't tell whether it's narrowing.
372 if (Initializer->isValueDependent())
373 return NK_Dependent_Narrowing;
375 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
377 assert(ConstantValue.isFloat());
378 llvm::APFloat FloatVal = ConstantValue.getFloat();
379 // Convert the source value into the target type.
381 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
382 Ctx.getFloatTypeSemantics(ToType),
383 llvm::APFloat::rmNearestTiesToEven, &ignored);
384 // If there was no overflow, the source value is within the range of
385 // values that can be represented.
386 if (ConvertStatus & llvm::APFloat::opOverflow) {
387 ConstantType = Initializer->getType();
388 return NK_Constant_Narrowing;
391 return NK_Variable_Narrowing;
394 return NK_Not_Narrowing;
396 // -- from an integer type or unscoped enumeration type to an integer type
397 // that cannot represent all the values of the original type, except where
398 // the source is a constant expression and the actual value after
399 // conversion will fit into the target type and will produce the original
400 // value when converted back to the original type.
401 case ICK_Integral_Conversion:
402 IntegralConversion: {
403 assert(FromType->isIntegralOrUnscopedEnumerationType());
404 assert(ToType->isIntegralOrUnscopedEnumerationType());
405 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
406 const unsigned FromWidth = Ctx.getIntWidth(FromType);
407 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
408 const unsigned ToWidth = Ctx.getIntWidth(ToType);
410 if (FromWidth > ToWidth ||
411 (FromWidth == ToWidth && FromSigned != ToSigned) ||
412 (FromSigned && !ToSigned)) {
413 // Not all values of FromType can be represented in ToType.
414 llvm::APSInt InitializerValue;
415 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
417 // If it's value-dependent, we can't tell whether it's narrowing.
418 if (Initializer->isValueDependent())
419 return NK_Dependent_Narrowing;
421 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
422 // Such conversions on variables are always narrowing.
423 return NK_Variable_Narrowing;
425 bool Narrowing = false;
426 if (FromWidth < ToWidth) {
427 // Negative -> unsigned is narrowing. Otherwise, more bits is never
429 if (InitializerValue.isSigned() && InitializerValue.isNegative())
432 // Add a bit to the InitializerValue so we don't have to worry about
433 // signed vs. unsigned comparisons.
434 InitializerValue = InitializerValue.extend(
435 InitializerValue.getBitWidth() + 1);
436 // Convert the initializer to and from the target width and signed-ness.
437 llvm::APSInt ConvertedValue = InitializerValue;
438 ConvertedValue = ConvertedValue.trunc(ToWidth);
439 ConvertedValue.setIsSigned(ToSigned);
440 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
441 ConvertedValue.setIsSigned(InitializerValue.isSigned());
442 // If the result is different, this was a narrowing conversion.
443 if (ConvertedValue != InitializerValue)
447 ConstantType = Initializer->getType();
448 ConstantValue = APValue(InitializerValue);
449 return NK_Constant_Narrowing;
452 return NK_Not_Narrowing;
456 // Other kinds of conversions are not narrowings.
457 return NK_Not_Narrowing;
461 /// dump - Print this standard conversion sequence to standard
462 /// error. Useful for debugging overloading issues.
463 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
464 raw_ostream &OS = llvm::errs();
465 bool PrintedSomething = false;
466 if (First != ICK_Identity) {
467 OS << GetImplicitConversionName(First);
468 PrintedSomething = true;
471 if (Second != ICK_Identity) {
472 if (PrintedSomething) {
475 OS << GetImplicitConversionName(Second);
477 if (CopyConstructor) {
478 OS << " (by copy constructor)";
479 } else if (DirectBinding) {
480 OS << " (direct reference binding)";
481 } else if (ReferenceBinding) {
482 OS << " (reference binding)";
484 PrintedSomething = true;
487 if (Third != ICK_Identity) {
488 if (PrintedSomething) {
491 OS << GetImplicitConversionName(Third);
492 PrintedSomething = true;
495 if (!PrintedSomething) {
496 OS << "No conversions required";
500 /// dump - Print this user-defined conversion sequence to standard
501 /// error. Useful for debugging overloading issues.
502 void UserDefinedConversionSequence::dump() const {
503 raw_ostream &OS = llvm::errs();
504 if (Before.First || Before.Second || Before.Third) {
508 if (ConversionFunction)
509 OS << '\'' << *ConversionFunction << '\'';
511 OS << "aggregate initialization";
512 if (After.First || After.Second || After.Third) {
518 /// dump - Print this implicit conversion sequence to standard
519 /// error. Useful for debugging overloading issues.
520 void ImplicitConversionSequence::dump() const {
521 raw_ostream &OS = llvm::errs();
522 if (isStdInitializerListElement())
523 OS << "Worst std::initializer_list element conversion: ";
524 switch (ConversionKind) {
525 case StandardConversion:
526 OS << "Standard conversion: ";
529 case UserDefinedConversion:
530 OS << "User-defined conversion: ";
533 case EllipsisConversion:
534 OS << "Ellipsis conversion";
536 case AmbiguousConversion:
537 OS << "Ambiguous conversion";
540 OS << "Bad conversion";
547 void AmbiguousConversionSequence::construct() {
548 new (&conversions()) ConversionSet();
551 void AmbiguousConversionSequence::destruct() {
552 conversions().~ConversionSet();
556 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
557 FromTypePtr = O.FromTypePtr;
558 ToTypePtr = O.ToTypePtr;
559 new (&conversions()) ConversionSet(O.conversions());
563 // Structure used by DeductionFailureInfo to store
564 // template argument information.
565 struct DFIArguments {
566 TemplateArgument FirstArg;
567 TemplateArgument SecondArg;
569 // Structure used by DeductionFailureInfo to store
570 // template parameter and template argument information.
571 struct DFIParamWithArguments : DFIArguments {
572 TemplateParameter Param;
574 // Structure used by DeductionFailureInfo to store template argument
575 // information and the index of the problematic call argument.
576 struct DFIDeducedMismatchArgs : DFIArguments {
577 TemplateArgumentList *TemplateArgs;
578 unsigned CallArgIndex;
582 /// \brief Convert from Sema's representation of template deduction information
583 /// to the form used in overload-candidate information.
585 clang::MakeDeductionFailureInfo(ASTContext &Context,
586 Sema::TemplateDeductionResult TDK,
587 TemplateDeductionInfo &Info) {
588 DeductionFailureInfo Result;
589 Result.Result = static_cast<unsigned>(TDK);
590 Result.HasDiagnostic = false;
592 case Sema::TDK_Success:
593 case Sema::TDK_Invalid:
594 case Sema::TDK_InstantiationDepth:
595 case Sema::TDK_TooManyArguments:
596 case Sema::TDK_TooFewArguments:
597 case Sema::TDK_MiscellaneousDeductionFailure:
598 case Sema::TDK_CUDATargetMismatch:
599 Result.Data = nullptr;
602 case Sema::TDK_Incomplete:
603 case Sema::TDK_InvalidExplicitArguments:
604 Result.Data = Info.Param.getOpaqueValue();
607 case Sema::TDK_DeducedMismatch: {
608 // FIXME: Should allocate from normal heap so that we can free this later.
609 auto *Saved = new (Context) DFIDeducedMismatchArgs;
610 Saved->FirstArg = Info.FirstArg;
611 Saved->SecondArg = Info.SecondArg;
612 Saved->TemplateArgs = Info.take();
613 Saved->CallArgIndex = Info.CallArgIndex;
618 case Sema::TDK_NonDeducedMismatch: {
619 // FIXME: Should allocate from normal heap so that we can free this later.
620 DFIArguments *Saved = new (Context) DFIArguments;
621 Saved->FirstArg = Info.FirstArg;
622 Saved->SecondArg = Info.SecondArg;
627 case Sema::TDK_Inconsistent:
628 case Sema::TDK_Underqualified: {
629 // FIXME: Should allocate from normal heap so that we can free this later.
630 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
631 Saved->Param = Info.Param;
632 Saved->FirstArg = Info.FirstArg;
633 Saved->SecondArg = Info.SecondArg;
638 case Sema::TDK_SubstitutionFailure:
639 Result.Data = Info.take();
640 if (Info.hasSFINAEDiagnostic()) {
641 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
642 SourceLocation(), PartialDiagnostic::NullDiagnostic());
643 Info.takeSFINAEDiagnostic(*Diag);
644 Result.HasDiagnostic = true;
648 case Sema::TDK_FailedOverloadResolution:
649 Result.Data = Info.Expression;
656 void DeductionFailureInfo::Destroy() {
657 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
658 case Sema::TDK_Success:
659 case Sema::TDK_Invalid:
660 case Sema::TDK_InstantiationDepth:
661 case Sema::TDK_Incomplete:
662 case Sema::TDK_TooManyArguments:
663 case Sema::TDK_TooFewArguments:
664 case Sema::TDK_InvalidExplicitArguments:
665 case Sema::TDK_FailedOverloadResolution:
666 case Sema::TDK_CUDATargetMismatch:
669 case Sema::TDK_Inconsistent:
670 case Sema::TDK_Underqualified:
671 case Sema::TDK_DeducedMismatch:
672 case Sema::TDK_NonDeducedMismatch:
673 // FIXME: Destroy the data?
677 case Sema::TDK_SubstitutionFailure:
678 // FIXME: Destroy the template argument list?
680 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
681 Diag->~PartialDiagnosticAt();
682 HasDiagnostic = false;
687 case Sema::TDK_MiscellaneousDeductionFailure:
692 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
694 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
698 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
699 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
700 case Sema::TDK_Success:
701 case Sema::TDK_Invalid:
702 case Sema::TDK_InstantiationDepth:
703 case Sema::TDK_TooManyArguments:
704 case Sema::TDK_TooFewArguments:
705 case Sema::TDK_SubstitutionFailure:
706 case Sema::TDK_DeducedMismatch:
707 case Sema::TDK_NonDeducedMismatch:
708 case Sema::TDK_FailedOverloadResolution:
709 case Sema::TDK_CUDATargetMismatch:
710 return TemplateParameter();
712 case Sema::TDK_Incomplete:
713 case Sema::TDK_InvalidExplicitArguments:
714 return TemplateParameter::getFromOpaqueValue(Data);
716 case Sema::TDK_Inconsistent:
717 case Sema::TDK_Underqualified:
718 return static_cast<DFIParamWithArguments*>(Data)->Param;
721 case Sema::TDK_MiscellaneousDeductionFailure:
725 return TemplateParameter();
728 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
729 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
730 case Sema::TDK_Success:
731 case Sema::TDK_Invalid:
732 case Sema::TDK_InstantiationDepth:
733 case Sema::TDK_TooManyArguments:
734 case Sema::TDK_TooFewArguments:
735 case Sema::TDK_Incomplete:
736 case Sema::TDK_InvalidExplicitArguments:
737 case Sema::TDK_Inconsistent:
738 case Sema::TDK_Underqualified:
739 case Sema::TDK_NonDeducedMismatch:
740 case Sema::TDK_FailedOverloadResolution:
741 case Sema::TDK_CUDATargetMismatch:
744 case Sema::TDK_DeducedMismatch:
745 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
747 case Sema::TDK_SubstitutionFailure:
748 return static_cast<TemplateArgumentList*>(Data);
751 case Sema::TDK_MiscellaneousDeductionFailure:
758 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
759 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
760 case Sema::TDK_Success:
761 case Sema::TDK_Invalid:
762 case Sema::TDK_InstantiationDepth:
763 case Sema::TDK_Incomplete:
764 case Sema::TDK_TooManyArguments:
765 case Sema::TDK_TooFewArguments:
766 case Sema::TDK_InvalidExplicitArguments:
767 case Sema::TDK_SubstitutionFailure:
768 case Sema::TDK_FailedOverloadResolution:
769 case Sema::TDK_CUDATargetMismatch:
772 case Sema::TDK_Inconsistent:
773 case Sema::TDK_Underqualified:
774 case Sema::TDK_DeducedMismatch:
775 case Sema::TDK_NonDeducedMismatch:
776 return &static_cast<DFIArguments*>(Data)->FirstArg;
779 case Sema::TDK_MiscellaneousDeductionFailure:
786 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
787 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
788 case Sema::TDK_Success:
789 case Sema::TDK_Invalid:
790 case Sema::TDK_InstantiationDepth:
791 case Sema::TDK_Incomplete:
792 case Sema::TDK_TooManyArguments:
793 case Sema::TDK_TooFewArguments:
794 case Sema::TDK_InvalidExplicitArguments:
795 case Sema::TDK_SubstitutionFailure:
796 case Sema::TDK_FailedOverloadResolution:
797 case Sema::TDK_CUDATargetMismatch:
800 case Sema::TDK_Inconsistent:
801 case Sema::TDK_Underqualified:
802 case Sema::TDK_DeducedMismatch:
803 case Sema::TDK_NonDeducedMismatch:
804 return &static_cast<DFIArguments*>(Data)->SecondArg;
807 case Sema::TDK_MiscellaneousDeductionFailure:
814 Expr *DeductionFailureInfo::getExpr() {
815 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
816 Sema::TDK_FailedOverloadResolution)
817 return static_cast<Expr*>(Data);
822 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
823 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
824 Sema::TDK_DeducedMismatch)
825 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
830 void OverloadCandidateSet::destroyCandidates() {
831 for (iterator i = begin(), e = end(); i != e; ++i) {
832 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
833 i->Conversions[ii].~ImplicitConversionSequence();
834 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
835 i->DeductionFailure.Destroy();
839 void OverloadCandidateSet::clear() {
841 ConversionSequenceAllocator.Reset();
842 NumInlineSequences = 0;
848 class UnbridgedCastsSet {
853 SmallVector<Entry, 2> Entries;
856 void save(Sema &S, Expr *&E) {
857 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
858 Entry entry = { &E, E };
859 Entries.push_back(entry);
860 E = S.stripARCUnbridgedCast(E);
864 for (SmallVectorImpl<Entry>::iterator
865 i = Entries.begin(), e = Entries.end(); i != e; ++i)
871 /// checkPlaceholderForOverload - Do any interesting placeholder-like
872 /// preprocessing on the given expression.
874 /// \param unbridgedCasts a collection to which to add unbridged casts;
875 /// without this, they will be immediately diagnosed as errors
877 /// Return true on unrecoverable error.
879 checkPlaceholderForOverload(Sema &S, Expr *&E,
880 UnbridgedCastsSet *unbridgedCasts = nullptr) {
881 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
882 // We can't handle overloaded expressions here because overload
883 // resolution might reasonably tweak them.
884 if (placeholder->getKind() == BuiltinType::Overload) return false;
886 // If the context potentially accepts unbridged ARC casts, strip
887 // the unbridged cast and add it to the collection for later restoration.
888 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
890 unbridgedCasts->save(S, E);
894 // Go ahead and check everything else.
895 ExprResult result = S.CheckPlaceholderExpr(E);
896 if (result.isInvalid())
907 /// checkArgPlaceholdersForOverload - Check a set of call operands for
909 static bool checkArgPlaceholdersForOverload(Sema &S,
911 UnbridgedCastsSet &unbridged) {
912 for (unsigned i = 0, e = Args.size(); i != e; ++i)
913 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
919 // IsOverload - Determine whether the given New declaration is an
920 // overload of the declarations in Old. This routine returns false if
921 // New and Old cannot be overloaded, e.g., if New has the same
922 // signature as some function in Old (C++ 1.3.10) or if the Old
923 // declarations aren't functions (or function templates) at all. When
924 // it does return false, MatchedDecl will point to the decl that New
925 // cannot be overloaded with. This decl may be a UsingShadowDecl on
926 // top of the underlying declaration.
928 // Example: Given the following input:
930 // void f(int, float); // #1
931 // void f(int, int); // #2
932 // int f(int, int); // #3
934 // When we process #1, there is no previous declaration of "f",
935 // so IsOverload will not be used.
937 // When we process #2, Old contains only the FunctionDecl for #1. By
938 // comparing the parameter types, we see that #1 and #2 are overloaded
939 // (since they have different signatures), so this routine returns
940 // false; MatchedDecl is unchanged.
942 // When we process #3, Old is an overload set containing #1 and #2. We
943 // compare the signatures of #3 to #1 (they're overloaded, so we do
944 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
945 // identical (return types of functions are not part of the
946 // signature), IsOverload returns false and MatchedDecl will be set to
947 // point to the FunctionDecl for #2.
949 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
950 // into a class by a using declaration. The rules for whether to hide
951 // shadow declarations ignore some properties which otherwise figure
952 // into a function template's signature.
954 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
955 NamedDecl *&Match, bool NewIsUsingDecl) {
956 for (LookupResult::iterator I = Old.begin(), E = Old.end();
958 NamedDecl *OldD = *I;
960 bool OldIsUsingDecl = false;
961 if (isa<UsingShadowDecl>(OldD)) {
962 OldIsUsingDecl = true;
964 // We can always introduce two using declarations into the same
965 // context, even if they have identical signatures.
966 if (NewIsUsingDecl) continue;
968 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
971 // A using-declaration does not conflict with another declaration
972 // if one of them is hidden.
973 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
976 // If either declaration was introduced by a using declaration,
977 // we'll need to use slightly different rules for matching.
978 // Essentially, these rules are the normal rules, except that
979 // function templates hide function templates with different
980 // return types or template parameter lists.
981 bool UseMemberUsingDeclRules =
982 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
983 !New->getFriendObjectKind();
985 if (FunctionDecl *OldF = OldD->getAsFunction()) {
986 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
987 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
988 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
992 if (!isa<FunctionTemplateDecl>(OldD) &&
993 !shouldLinkPossiblyHiddenDecl(*I, New))
999 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1000 // We can overload with these, which can show up when doing
1001 // redeclaration checks for UsingDecls.
1002 assert(Old.getLookupKind() == LookupUsingDeclName);
1003 } else if (isa<TagDecl>(OldD)) {
1004 // We can always overload with tags by hiding them.
1005 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1006 // Optimistically assume that an unresolved using decl will
1007 // overload; if it doesn't, we'll have to diagnose during
1008 // template instantiation.
1010 // Exception: if the scope is dependent and this is not a class
1011 // member, the using declaration can only introduce an enumerator.
1012 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1014 return Ovl_NonFunction;
1018 // Only function declarations can be overloaded; object and type
1019 // declarations cannot be overloaded.
1021 return Ovl_NonFunction;
1025 return Ovl_Overload;
1028 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1029 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1030 // C++ [basic.start.main]p2: This function shall not be overloaded.
1034 // MSVCRT user defined entry points cannot be overloaded.
1035 if (New->isMSVCRTEntryPoint())
1038 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1039 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1041 // C++ [temp.fct]p2:
1042 // A function template can be overloaded with other function templates
1043 // and with normal (non-template) functions.
1044 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1047 // Is the function New an overload of the function Old?
1048 QualType OldQType = Context.getCanonicalType(Old->getType());
1049 QualType NewQType = Context.getCanonicalType(New->getType());
1051 // Compare the signatures (C++ 1.3.10) of the two functions to
1052 // determine whether they are overloads. If we find any mismatch
1053 // in the signature, they are overloads.
1055 // If either of these functions is a K&R-style function (no
1056 // prototype), then we consider them to have matching signatures.
1057 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1058 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1061 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1062 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1064 // The signature of a function includes the types of its
1065 // parameters (C++ 1.3.10), which includes the presence or absence
1066 // of the ellipsis; see C++ DR 357).
1067 if (OldQType != NewQType &&
1068 (OldType->getNumParams() != NewType->getNumParams() ||
1069 OldType->isVariadic() != NewType->isVariadic() ||
1070 !FunctionParamTypesAreEqual(OldType, NewType)))
1073 // C++ [temp.over.link]p4:
1074 // The signature of a function template consists of its function
1075 // signature, its return type and its template parameter list. The names
1076 // of the template parameters are significant only for establishing the
1077 // relationship between the template parameters and the rest of the
1080 // We check the return type and template parameter lists for function
1081 // templates first; the remaining checks follow.
1083 // However, we don't consider either of these when deciding whether
1084 // a member introduced by a shadow declaration is hidden.
1085 if (!UseMemberUsingDeclRules && NewTemplate &&
1086 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1087 OldTemplate->getTemplateParameters(),
1088 false, TPL_TemplateMatch) ||
1089 OldType->getReturnType() != NewType->getReturnType()))
1092 // If the function is a class member, its signature includes the
1093 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1095 // As part of this, also check whether one of the member functions
1096 // is static, in which case they are not overloads (C++
1097 // 13.1p2). While not part of the definition of the signature,
1098 // this check is important to determine whether these functions
1099 // can be overloaded.
1100 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1101 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1102 if (OldMethod && NewMethod &&
1103 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1104 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1105 if (!UseMemberUsingDeclRules &&
1106 (OldMethod->getRefQualifier() == RQ_None ||
1107 NewMethod->getRefQualifier() == RQ_None)) {
1108 // C++0x [over.load]p2:
1109 // - Member function declarations with the same name and the same
1110 // parameter-type-list as well as member function template
1111 // declarations with the same name, the same parameter-type-list, and
1112 // the same template parameter lists cannot be overloaded if any of
1113 // them, but not all, have a ref-qualifier (8.3.5).
1114 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1115 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1116 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1121 // We may not have applied the implicit const for a constexpr member
1122 // function yet (because we haven't yet resolved whether this is a static
1123 // or non-static member function). Add it now, on the assumption that this
1124 // is a redeclaration of OldMethod.
1125 unsigned OldQuals = OldMethod->getTypeQualifiers();
1126 unsigned NewQuals = NewMethod->getTypeQualifiers();
1127 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1128 !isa<CXXConstructorDecl>(NewMethod))
1129 NewQuals |= Qualifiers::Const;
1131 // We do not allow overloading based off of '__restrict'.
1132 OldQuals &= ~Qualifiers::Restrict;
1133 NewQuals &= ~Qualifiers::Restrict;
1134 if (OldQuals != NewQuals)
1138 // Though pass_object_size is placed on parameters and takes an argument, we
1139 // consider it to be a function-level modifier for the sake of function
1140 // identity. Either the function has one or more parameters with
1141 // pass_object_size or it doesn't.
1142 if (functionHasPassObjectSizeParams(New) !=
1143 functionHasPassObjectSizeParams(Old))
1146 // enable_if attributes are an order-sensitive part of the signature.
1147 for (specific_attr_iterator<EnableIfAttr>
1148 NewI = New->specific_attr_begin<EnableIfAttr>(),
1149 NewE = New->specific_attr_end<EnableIfAttr>(),
1150 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1151 OldE = Old->specific_attr_end<EnableIfAttr>();
1152 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1153 if (NewI == NewE || OldI == OldE)
1155 llvm::FoldingSetNodeID NewID, OldID;
1156 NewI->getCond()->Profile(NewID, Context, true);
1157 OldI->getCond()->Profile(OldID, Context, true);
1162 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1163 // Don't allow overloading of destructors. (In theory we could, but it
1164 // would be a giant change to clang.)
1165 if (isa<CXXDestructorDecl>(New))
1168 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1169 OldTarget = IdentifyCUDATarget(Old);
1170 if (NewTarget == CFT_InvalidTarget)
1173 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1175 // Allow overloading of functions with same signature and different CUDA
1176 // target attributes.
1177 return NewTarget != OldTarget;
1180 // The signatures match; this is not an overload.
1184 /// \brief Checks availability of the function depending on the current
1185 /// function context. Inside an unavailable function, unavailability is ignored.
1187 /// \returns true if \arg FD is unavailable and current context is inside
1188 /// an available function, false otherwise.
1189 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1190 if (!FD->isUnavailable())
1193 // Walk up the context of the caller.
1194 Decl *C = cast<Decl>(CurContext);
1196 if (C->isUnavailable())
1198 } while ((C = cast_or_null<Decl>(C->getDeclContext())));
1202 /// \brief Tries a user-defined conversion from From to ToType.
1204 /// Produces an implicit conversion sequence for when a standard conversion
1205 /// is not an option. See TryImplicitConversion for more information.
1206 static ImplicitConversionSequence
1207 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1208 bool SuppressUserConversions,
1210 bool InOverloadResolution,
1212 bool AllowObjCWritebackConversion,
1213 bool AllowObjCConversionOnExplicit) {
1214 ImplicitConversionSequence ICS;
1216 if (SuppressUserConversions) {
1217 // We're not in the case above, so there is no conversion that
1219 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1223 // Attempt user-defined conversion.
1224 OverloadCandidateSet Conversions(From->getExprLoc(),
1225 OverloadCandidateSet::CSK_Normal);
1226 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1227 Conversions, AllowExplicit,
1228 AllowObjCConversionOnExplicit)) {
1231 ICS.setUserDefined();
1232 // C++ [over.ics.user]p4:
1233 // A conversion of an expression of class type to the same class
1234 // type is given Exact Match rank, and a conversion of an
1235 // expression of class type to a base class of that type is
1236 // given Conversion rank, in spite of the fact that a copy
1237 // constructor (i.e., a user-defined conversion function) is
1238 // called for those cases.
1239 if (CXXConstructorDecl *Constructor
1240 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1242 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1244 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1245 if (Constructor->isCopyConstructor() &&
1246 (FromCanon == ToCanon ||
1247 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) {
1248 // Turn this into a "standard" conversion sequence, so that it
1249 // gets ranked with standard conversion sequences.
1250 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1252 ICS.Standard.setAsIdentityConversion();
1253 ICS.Standard.setFromType(From->getType());
1254 ICS.Standard.setAllToTypes(ToType);
1255 ICS.Standard.CopyConstructor = Constructor;
1256 ICS.Standard.FoundCopyConstructor = Found;
1257 if (ToCanon != FromCanon)
1258 ICS.Standard.Second = ICK_Derived_To_Base;
1265 ICS.Ambiguous.setFromType(From->getType());
1266 ICS.Ambiguous.setToType(ToType);
1267 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1268 Cand != Conversions.end(); ++Cand)
1270 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1274 case OR_No_Viable_Function:
1275 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1282 /// TryImplicitConversion - Attempt to perform an implicit conversion
1283 /// from the given expression (Expr) to the given type (ToType). This
1284 /// function returns an implicit conversion sequence that can be used
1285 /// to perform the initialization. Given
1287 /// void f(float f);
1288 /// void g(int i) { f(i); }
1290 /// this routine would produce an implicit conversion sequence to
1291 /// describe the initialization of f from i, which will be a standard
1292 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1293 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1295 /// Note that this routine only determines how the conversion can be
1296 /// performed; it does not actually perform the conversion. As such,
1297 /// it will not produce any diagnostics if no conversion is available,
1298 /// but will instead return an implicit conversion sequence of kind
1299 /// "BadConversion".
1301 /// If @p SuppressUserConversions, then user-defined conversions are
1303 /// If @p AllowExplicit, then explicit user-defined conversions are
1306 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1307 /// writeback conversion, which allows __autoreleasing id* parameters to
1308 /// be initialized with __strong id* or __weak id* arguments.
1309 static ImplicitConversionSequence
1310 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1311 bool SuppressUserConversions,
1313 bool InOverloadResolution,
1315 bool AllowObjCWritebackConversion,
1316 bool AllowObjCConversionOnExplicit) {
1317 ImplicitConversionSequence ICS;
1318 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1319 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1324 if (!S.getLangOpts().CPlusPlus) {
1325 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1329 // C++ [over.ics.user]p4:
1330 // A conversion of an expression of class type to the same class
1331 // type is given Exact Match rank, and a conversion of an
1332 // expression of class type to a base class of that type is
1333 // given Conversion rank, in spite of the fact that a copy/move
1334 // constructor (i.e., a user-defined conversion function) is
1335 // called for those cases.
1336 QualType FromType = From->getType();
1337 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1338 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1339 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) {
1341 ICS.Standard.setAsIdentityConversion();
1342 ICS.Standard.setFromType(FromType);
1343 ICS.Standard.setAllToTypes(ToType);
1345 // We don't actually check at this point whether there is a valid
1346 // copy/move constructor, since overloading just assumes that it
1347 // exists. When we actually perform initialization, we'll find the
1348 // appropriate constructor to copy the returned object, if needed.
1349 ICS.Standard.CopyConstructor = nullptr;
1351 // Determine whether this is considered a derived-to-base conversion.
1352 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1353 ICS.Standard.Second = ICK_Derived_To_Base;
1358 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1359 AllowExplicit, InOverloadResolution, CStyle,
1360 AllowObjCWritebackConversion,
1361 AllowObjCConversionOnExplicit);
1364 ImplicitConversionSequence
1365 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1366 bool SuppressUserConversions,
1368 bool InOverloadResolution,
1370 bool AllowObjCWritebackConversion) {
1371 return ::TryImplicitConversion(*this, From, ToType,
1372 SuppressUserConversions, AllowExplicit,
1373 InOverloadResolution, CStyle,
1374 AllowObjCWritebackConversion,
1375 /*AllowObjCConversionOnExplicit=*/false);
1378 /// PerformImplicitConversion - Perform an implicit conversion of the
1379 /// expression From to the type ToType. Returns the
1380 /// converted expression. Flavor is the kind of conversion we're
1381 /// performing, used in the error message. If @p AllowExplicit,
1382 /// explicit user-defined conversions are permitted.
1384 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1385 AssignmentAction Action, bool AllowExplicit) {
1386 ImplicitConversionSequence ICS;
1387 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1391 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1392 AssignmentAction Action, bool AllowExplicit,
1393 ImplicitConversionSequence& ICS) {
1394 if (checkPlaceholderForOverload(*this, From))
1397 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1398 bool AllowObjCWritebackConversion
1399 = getLangOpts().ObjCAutoRefCount &&
1400 (Action == AA_Passing || Action == AA_Sending);
1401 if (getLangOpts().ObjC1)
1402 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1403 ToType, From->getType(), From);
1404 ICS = ::TryImplicitConversion(*this, From, ToType,
1405 /*SuppressUserConversions=*/false,
1407 /*InOverloadResolution=*/false,
1409 AllowObjCWritebackConversion,
1410 /*AllowObjCConversionOnExplicit=*/false);
1411 return PerformImplicitConversion(From, ToType, ICS, Action);
1414 /// \brief Determine whether the conversion from FromType to ToType is a valid
1415 /// conversion that strips "noexcept" or "noreturn" off the nested function
1417 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1418 QualType &ResultTy) {
1419 if (Context.hasSameUnqualifiedType(FromType, ToType))
1422 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1423 // or F(t noexcept) -> F(t)
1424 // where F adds one of the following at most once:
1426 // - a member pointer
1427 // - a block pointer
1428 // Changes here need matching changes in FindCompositePointerType.
1429 CanQualType CanTo = Context.getCanonicalType(ToType);
1430 CanQualType CanFrom = Context.getCanonicalType(FromType);
1431 Type::TypeClass TyClass = CanTo->getTypeClass();
1432 if (TyClass != CanFrom->getTypeClass()) return false;
1433 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1434 if (TyClass == Type::Pointer) {
1435 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1436 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1437 } else if (TyClass == Type::BlockPointer) {
1438 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1439 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1440 } else if (TyClass == Type::MemberPointer) {
1441 auto ToMPT = CanTo.getAs<MemberPointerType>();
1442 auto FromMPT = CanFrom.getAs<MemberPointerType>();
1443 // A function pointer conversion cannot change the class of the function.
1444 if (ToMPT->getClass() != FromMPT->getClass())
1446 CanTo = ToMPT->getPointeeType();
1447 CanFrom = FromMPT->getPointeeType();
1452 TyClass = CanTo->getTypeClass();
1453 if (TyClass != CanFrom->getTypeClass()) return false;
1454 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1458 const auto *FromFn = cast<FunctionType>(CanFrom);
1459 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1461 const auto *ToFn = cast<FunctionType>(CanTo);
1462 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1464 bool Changed = false;
1466 // Drop 'noreturn' if not present in target type.
1467 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1468 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1472 // Drop 'noexcept' if not present in target type.
1473 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1474 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1475 if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) {
1476 FromFn = cast<FunctionType>(
1477 Context.getFunctionType(FromFPT->getReturnType(),
1478 FromFPT->getParamTypes(),
1479 FromFPT->getExtProtoInfo().withExceptionSpec(
1480 FunctionProtoType::ExceptionSpecInfo()))
1489 assert(QualType(FromFn, 0).isCanonical());
1490 if (QualType(FromFn, 0) != CanTo) return false;
1496 /// \brief Determine whether the conversion from FromType to ToType is a valid
1497 /// vector conversion.
1499 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1501 static bool IsVectorConversion(Sema &S, QualType FromType,
1502 QualType ToType, ImplicitConversionKind &ICK) {
1503 // We need at least one of these types to be a vector type to have a vector
1505 if (!ToType->isVectorType() && !FromType->isVectorType())
1508 // Identical types require no conversions.
1509 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1512 // There are no conversions between extended vector types, only identity.
1513 if (ToType->isExtVectorType()) {
1514 // There are no conversions between extended vector types other than the
1515 // identity conversion.
1516 if (FromType->isExtVectorType())
1519 // Vector splat from any arithmetic type to a vector.
1520 if (FromType->isArithmeticType()) {
1521 ICK = ICK_Vector_Splat;
1526 // We can perform the conversion between vector types in the following cases:
1527 // 1)vector types are equivalent AltiVec and GCC vector types
1528 // 2)lax vector conversions are permitted and the vector types are of the
1530 if (ToType->isVectorType() && FromType->isVectorType()) {
1531 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1532 S.isLaxVectorConversion(FromType, ToType)) {
1533 ICK = ICK_Vector_Conversion;
1541 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1542 bool InOverloadResolution,
1543 StandardConversionSequence &SCS,
1546 /// IsStandardConversion - Determines whether there is a standard
1547 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1548 /// expression From to the type ToType. Standard conversion sequences
1549 /// only consider non-class types; for conversions that involve class
1550 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1551 /// contain the standard conversion sequence required to perform this
1552 /// conversion and this routine will return true. Otherwise, this
1553 /// routine will return false and the value of SCS is unspecified.
1554 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1555 bool InOverloadResolution,
1556 StandardConversionSequence &SCS,
1558 bool AllowObjCWritebackConversion) {
1559 QualType FromType = From->getType();
1561 // Standard conversions (C++ [conv])
1562 SCS.setAsIdentityConversion();
1563 SCS.IncompatibleObjC = false;
1564 SCS.setFromType(FromType);
1565 SCS.CopyConstructor = nullptr;
1567 // There are no standard conversions for class types in C++, so
1568 // abort early. When overloading in C, however, we do permit them.
1569 if (S.getLangOpts().CPlusPlus &&
1570 (FromType->isRecordType() || ToType->isRecordType()))
1573 // The first conversion can be an lvalue-to-rvalue conversion,
1574 // array-to-pointer conversion, or function-to-pointer conversion
1577 if (FromType == S.Context.OverloadTy) {
1578 DeclAccessPair AccessPair;
1579 if (FunctionDecl *Fn
1580 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1582 // We were able to resolve the address of the overloaded function,
1583 // so we can convert to the type of that function.
1584 FromType = Fn->getType();
1585 SCS.setFromType(FromType);
1587 // we can sometimes resolve &foo<int> regardless of ToType, so check
1588 // if the type matches (identity) or we are converting to bool
1589 if (!S.Context.hasSameUnqualifiedType(
1590 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1592 // if the function type matches except for [[noreturn]], it's ok
1593 if (!S.IsFunctionConversion(FromType,
1594 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1595 // otherwise, only a boolean conversion is standard
1596 if (!ToType->isBooleanType())
1600 // Check if the "from" expression is taking the address of an overloaded
1601 // function and recompute the FromType accordingly. Take advantage of the
1602 // fact that non-static member functions *must* have such an address-of
1604 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1605 if (Method && !Method->isStatic()) {
1606 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1607 "Non-unary operator on non-static member address");
1608 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1610 "Non-address-of operator on non-static member address");
1611 const Type *ClassType
1612 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1613 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1614 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1615 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1617 "Non-address-of operator for overloaded function expression");
1618 FromType = S.Context.getPointerType(FromType);
1621 // Check that we've computed the proper type after overload resolution.
1622 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1623 // be calling it from within an NDEBUG block.
1624 assert(S.Context.hasSameType(
1626 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1631 // Lvalue-to-rvalue conversion (C++11 4.1):
1632 // A glvalue (3.10) of a non-function, non-array type T can
1633 // be converted to a prvalue.
1634 bool argIsLValue = From->isGLValue();
1636 !FromType->isFunctionType() && !FromType->isArrayType() &&
1637 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1638 SCS.First = ICK_Lvalue_To_Rvalue;
1641 // ... if the lvalue has atomic type, the value has the non-atomic version
1642 // of the type of the lvalue ...
1643 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1644 FromType = Atomic->getValueType();
1646 // If T is a non-class type, the type of the rvalue is the
1647 // cv-unqualified version of T. Otherwise, the type of the rvalue
1648 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1649 // just strip the qualifiers because they don't matter.
1650 FromType = FromType.getUnqualifiedType();
1651 } else if (FromType->isArrayType()) {
1652 // Array-to-pointer conversion (C++ 4.2)
1653 SCS.First = ICK_Array_To_Pointer;
1655 // An lvalue or rvalue of type "array of N T" or "array of unknown
1656 // bound of T" can be converted to an rvalue of type "pointer to
1658 FromType = S.Context.getArrayDecayedType(FromType);
1660 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1661 // This conversion is deprecated in C++03 (D.4)
1662 SCS.DeprecatedStringLiteralToCharPtr = true;
1664 // For the purpose of ranking in overload resolution
1665 // (13.3.3.1.1), this conversion is considered an
1666 // array-to-pointer conversion followed by a qualification
1667 // conversion (4.4). (C++ 4.2p2)
1668 SCS.Second = ICK_Identity;
1669 SCS.Third = ICK_Qualification;
1670 SCS.QualificationIncludesObjCLifetime = false;
1671 SCS.setAllToTypes(FromType);
1674 } else if (FromType->isFunctionType() && argIsLValue) {
1675 // Function-to-pointer conversion (C++ 4.3).
1676 SCS.First = ICK_Function_To_Pointer;
1678 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1679 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1680 if (!S.checkAddressOfFunctionIsAvailable(FD))
1683 // An lvalue of function type T can be converted to an rvalue of
1684 // type "pointer to T." The result is a pointer to the
1685 // function. (C++ 4.3p1).
1686 FromType = S.Context.getPointerType(FromType);
1688 // We don't require any conversions for the first step.
1689 SCS.First = ICK_Identity;
1691 SCS.setToType(0, FromType);
1693 // The second conversion can be an integral promotion, floating
1694 // point promotion, integral conversion, floating point conversion,
1695 // floating-integral conversion, pointer conversion,
1696 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1697 // For overloading in C, this can also be a "compatible-type"
1699 bool IncompatibleObjC = false;
1700 ImplicitConversionKind SecondICK = ICK_Identity;
1701 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1702 // The unqualified versions of the types are the same: there's no
1703 // conversion to do.
1704 SCS.Second = ICK_Identity;
1705 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1706 // Integral promotion (C++ 4.5).
1707 SCS.Second = ICK_Integral_Promotion;
1708 FromType = ToType.getUnqualifiedType();
1709 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1710 // Floating point promotion (C++ 4.6).
1711 SCS.Second = ICK_Floating_Promotion;
1712 FromType = ToType.getUnqualifiedType();
1713 } else if (S.IsComplexPromotion(FromType, ToType)) {
1714 // Complex promotion (Clang extension)
1715 SCS.Second = ICK_Complex_Promotion;
1716 FromType = ToType.getUnqualifiedType();
1717 } else if (ToType->isBooleanType() &&
1718 (FromType->isArithmeticType() ||
1719 FromType->isAnyPointerType() ||
1720 FromType->isBlockPointerType() ||
1721 FromType->isMemberPointerType() ||
1722 FromType->isNullPtrType())) {
1723 // Boolean conversions (C++ 4.12).
1724 SCS.Second = ICK_Boolean_Conversion;
1725 FromType = S.Context.BoolTy;
1726 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1727 ToType->isIntegralType(S.Context)) {
1728 // Integral conversions (C++ 4.7).
1729 SCS.Second = ICK_Integral_Conversion;
1730 FromType = ToType.getUnqualifiedType();
1731 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1732 // Complex conversions (C99 6.3.1.6)
1733 SCS.Second = ICK_Complex_Conversion;
1734 FromType = ToType.getUnqualifiedType();
1735 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1736 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1737 // Complex-real conversions (C99 6.3.1.7)
1738 SCS.Second = ICK_Complex_Real;
1739 FromType = ToType.getUnqualifiedType();
1740 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1741 // FIXME: disable conversions between long double and __float128 if
1742 // their representation is different until there is back end support
1743 // We of course allow this conversion if long double is really double.
1744 if (&S.Context.getFloatTypeSemantics(FromType) !=
1745 &S.Context.getFloatTypeSemantics(ToType)) {
1746 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1747 ToType == S.Context.LongDoubleTy) ||
1748 (FromType == S.Context.LongDoubleTy &&
1749 ToType == S.Context.Float128Ty));
1750 if (Float128AndLongDouble &&
1751 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1752 &llvm::APFloat::IEEEdouble()))
1755 // Floating point conversions (C++ 4.8).
1756 SCS.Second = ICK_Floating_Conversion;
1757 FromType = ToType.getUnqualifiedType();
1758 } else if ((FromType->isRealFloatingType() &&
1759 ToType->isIntegralType(S.Context)) ||
1760 (FromType->isIntegralOrUnscopedEnumerationType() &&
1761 ToType->isRealFloatingType())) {
1762 // Floating-integral conversions (C++ 4.9).
1763 SCS.Second = ICK_Floating_Integral;
1764 FromType = ToType.getUnqualifiedType();
1765 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1766 SCS.Second = ICK_Block_Pointer_Conversion;
1767 } else if (AllowObjCWritebackConversion &&
1768 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1769 SCS.Second = ICK_Writeback_Conversion;
1770 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1771 FromType, IncompatibleObjC)) {
1772 // Pointer conversions (C++ 4.10).
1773 SCS.Second = ICK_Pointer_Conversion;
1774 SCS.IncompatibleObjC = IncompatibleObjC;
1775 FromType = FromType.getUnqualifiedType();
1776 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1777 InOverloadResolution, FromType)) {
1778 // Pointer to member conversions (4.11).
1779 SCS.Second = ICK_Pointer_Member;
1780 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1781 SCS.Second = SecondICK;
1782 FromType = ToType.getUnqualifiedType();
1783 } else if (!S.getLangOpts().CPlusPlus &&
1784 S.Context.typesAreCompatible(ToType, FromType)) {
1785 // Compatible conversions (Clang extension for C function overloading)
1786 SCS.Second = ICK_Compatible_Conversion;
1787 FromType = ToType.getUnqualifiedType();
1788 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1789 InOverloadResolution,
1791 SCS.Second = ICK_TransparentUnionConversion;
1793 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1795 // tryAtomicConversion has updated the standard conversion sequence
1798 } else if (ToType->isEventT() &&
1799 From->isIntegerConstantExpr(S.getASTContext()) &&
1800 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1801 SCS.Second = ICK_Zero_Event_Conversion;
1803 } else if (ToType->isQueueT() &&
1804 From->isIntegerConstantExpr(S.getASTContext()) &&
1805 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1806 SCS.Second = ICK_Zero_Queue_Conversion;
1809 // No second conversion required.
1810 SCS.Second = ICK_Identity;
1812 SCS.setToType(1, FromType);
1814 // The third conversion can be a function pointer conversion or a
1815 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1816 bool ObjCLifetimeConversion;
1817 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1818 // Function pointer conversions (removing 'noexcept') including removal of
1819 // 'noreturn' (Clang extension).
1820 SCS.Third = ICK_Function_Conversion;
1821 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1822 ObjCLifetimeConversion)) {
1823 SCS.Third = ICK_Qualification;
1824 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1827 // No conversion required
1828 SCS.Third = ICK_Identity;
1831 // C++ [over.best.ics]p6:
1832 // [...] Any difference in top-level cv-qualification is
1833 // subsumed by the initialization itself and does not constitute
1834 // a conversion. [...]
1835 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1836 QualType CanonTo = S.Context.getCanonicalType(ToType);
1837 if (CanonFrom.getLocalUnqualifiedType()
1838 == CanonTo.getLocalUnqualifiedType() &&
1839 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1841 CanonFrom = CanonTo;
1844 SCS.setToType(2, FromType);
1846 if (CanonFrom == CanonTo)
1849 // If we have not converted the argument type to the parameter type,
1850 // this is a bad conversion sequence, unless we're resolving an overload in C.
1851 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1854 ExprResult ER = ExprResult{From};
1855 Sema::AssignConvertType Conv =
1856 S.CheckSingleAssignmentConstraints(ToType, ER,
1858 /*DiagnoseCFAudited=*/false,
1859 /*ConvertRHS=*/false);
1860 ImplicitConversionKind SecondConv;
1862 case Sema::Compatible:
1863 SecondConv = ICK_C_Only_Conversion;
1865 // For our purposes, discarding qualifiers is just as bad as using an
1866 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1867 // qualifiers, as well.
1868 case Sema::CompatiblePointerDiscardsQualifiers:
1869 case Sema::IncompatiblePointer:
1870 case Sema::IncompatiblePointerSign:
1871 SecondConv = ICK_Incompatible_Pointer_Conversion;
1877 // First can only be an lvalue conversion, so we pretend that this was the
1878 // second conversion. First should already be valid from earlier in the
1880 SCS.Second = SecondConv;
1881 SCS.setToType(1, ToType);
1883 // Third is Identity, because Second should rank us worse than any other
1884 // conversion. This could also be ICK_Qualification, but it's simpler to just
1885 // lump everything in with the second conversion, and we don't gain anything
1886 // from making this ICK_Qualification.
1887 SCS.Third = ICK_Identity;
1888 SCS.setToType(2, ToType);
1893 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1895 bool InOverloadResolution,
1896 StandardConversionSequence &SCS,
1899 const RecordType *UT = ToType->getAsUnionType();
1900 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1902 // The field to initialize within the transparent union.
1903 RecordDecl *UD = UT->getDecl();
1904 // It's compatible if the expression matches any of the fields.
1905 for (const auto *it : UD->fields()) {
1906 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1907 CStyle, /*ObjCWritebackConversion=*/false)) {
1908 ToType = it->getType();
1915 /// IsIntegralPromotion - Determines whether the conversion from the
1916 /// expression From (whose potentially-adjusted type is FromType) to
1917 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1918 /// sets PromotedType to the promoted type.
1919 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1920 const BuiltinType *To = ToType->getAs<BuiltinType>();
1921 // All integers are built-in.
1926 // An rvalue of type char, signed char, unsigned char, short int, or
1927 // unsigned short int can be converted to an rvalue of type int if
1928 // int can represent all the values of the source type; otherwise,
1929 // the source rvalue can be converted to an rvalue of type unsigned
1931 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1932 !FromType->isEnumeralType()) {
1933 if (// We can promote any signed, promotable integer type to an int
1934 (FromType->isSignedIntegerType() ||
1935 // We can promote any unsigned integer type whose size is
1936 // less than int to an int.
1937 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
1938 return To->getKind() == BuiltinType::Int;
1941 return To->getKind() == BuiltinType::UInt;
1944 // C++11 [conv.prom]p3:
1945 // A prvalue of an unscoped enumeration type whose underlying type is not
1946 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1947 // following types that can represent all the values of the enumeration
1948 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1949 // unsigned int, long int, unsigned long int, long long int, or unsigned
1950 // long long int. If none of the types in that list can represent all the
1951 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1952 // type can be converted to an rvalue a prvalue of the extended integer type
1953 // with lowest integer conversion rank (4.13) greater than the rank of long
1954 // long in which all the values of the enumeration can be represented. If
1955 // there are two such extended types, the signed one is chosen.
1956 // C++11 [conv.prom]p4:
1957 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1958 // can be converted to a prvalue of its underlying type. Moreover, if
1959 // integral promotion can be applied to its underlying type, a prvalue of an
1960 // unscoped enumeration type whose underlying type is fixed can also be
1961 // converted to a prvalue of the promoted underlying type.
1962 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1963 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1964 // provided for a scoped enumeration.
1965 if (FromEnumType->getDecl()->isScoped())
1968 // We can perform an integral promotion to the underlying type of the enum,
1969 // even if that's not the promoted type. Note that the check for promoting
1970 // the underlying type is based on the type alone, and does not consider
1971 // the bitfield-ness of the actual source expression.
1972 if (FromEnumType->getDecl()->isFixed()) {
1973 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1974 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1975 IsIntegralPromotion(nullptr, Underlying, ToType);
1978 // We have already pre-calculated the promotion type, so this is trivial.
1979 if (ToType->isIntegerType() &&
1980 isCompleteType(From->getLocStart(), FromType))
1981 return Context.hasSameUnqualifiedType(
1982 ToType, FromEnumType->getDecl()->getPromotionType());
1985 // C++0x [conv.prom]p2:
1986 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1987 // to an rvalue a prvalue of the first of the following types that can
1988 // represent all the values of its underlying type: int, unsigned int,
1989 // long int, unsigned long int, long long int, or unsigned long long int.
1990 // If none of the types in that list can represent all the values of its
1991 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1992 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1994 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1995 ToType->isIntegerType()) {
1996 // Determine whether the type we're converting from is signed or
1998 bool FromIsSigned = FromType->isSignedIntegerType();
1999 uint64_t FromSize = Context.getTypeSize(FromType);
2001 // The types we'll try to promote to, in the appropriate
2002 // order. Try each of these types.
2003 QualType PromoteTypes[6] = {
2004 Context.IntTy, Context.UnsignedIntTy,
2005 Context.LongTy, Context.UnsignedLongTy ,
2006 Context.LongLongTy, Context.UnsignedLongLongTy
2008 for (int Idx = 0; Idx < 6; ++Idx) {
2009 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2010 if (FromSize < ToSize ||
2011 (FromSize == ToSize &&
2012 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2013 // We found the type that we can promote to. If this is the
2014 // type we wanted, we have a promotion. Otherwise, no
2016 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2021 // An rvalue for an integral bit-field (9.6) can be converted to an
2022 // rvalue of type int if int can represent all the values of the
2023 // bit-field; otherwise, it can be converted to unsigned int if
2024 // unsigned int can represent all the values of the bit-field. If
2025 // the bit-field is larger yet, no integral promotion applies to
2026 // it. If the bit-field has an enumerated type, it is treated as any
2027 // other value of that type for promotion purposes (C++ 4.5p3).
2028 // FIXME: We should delay checking of bit-fields until we actually perform the
2031 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2032 llvm::APSInt BitWidth;
2033 if (FromType->isIntegralType(Context) &&
2034 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2035 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2036 ToSize = Context.getTypeSize(ToType);
2038 // Are we promoting to an int from a bitfield that fits in an int?
2039 if (BitWidth < ToSize ||
2040 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2041 return To->getKind() == BuiltinType::Int;
2044 // Are we promoting to an unsigned int from an unsigned bitfield
2045 // that fits into an unsigned int?
2046 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2047 return To->getKind() == BuiltinType::UInt;
2055 // An rvalue of type bool can be converted to an rvalue of type int,
2056 // with false becoming zero and true becoming one (C++ 4.5p4).
2057 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2064 /// IsFloatingPointPromotion - Determines whether the conversion from
2065 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2066 /// returns true and sets PromotedType to the promoted type.
2067 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2068 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2069 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2070 /// An rvalue of type float can be converted to an rvalue of type
2071 /// double. (C++ 4.6p1).
2072 if (FromBuiltin->getKind() == BuiltinType::Float &&
2073 ToBuiltin->getKind() == BuiltinType::Double)
2077 // When a float is promoted to double or long double, or a
2078 // double is promoted to long double [...].
2079 if (!getLangOpts().CPlusPlus &&
2080 (FromBuiltin->getKind() == BuiltinType::Float ||
2081 FromBuiltin->getKind() == BuiltinType::Double) &&
2082 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2083 ToBuiltin->getKind() == BuiltinType::Float128))
2086 // Half can be promoted to float.
2087 if (!getLangOpts().NativeHalfType &&
2088 FromBuiltin->getKind() == BuiltinType::Half &&
2089 ToBuiltin->getKind() == BuiltinType::Float)
2096 /// \brief Determine if a conversion is a complex promotion.
2098 /// A complex promotion is defined as a complex -> complex conversion
2099 /// where the conversion between the underlying real types is a
2100 /// floating-point or integral promotion.
2101 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2102 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2106 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2110 return IsFloatingPointPromotion(FromComplex->getElementType(),
2111 ToComplex->getElementType()) ||
2112 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2113 ToComplex->getElementType());
2116 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2117 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2118 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2119 /// if non-empty, will be a pointer to ToType that may or may not have
2120 /// the right set of qualifiers on its pointee.
2123 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2124 QualType ToPointee, QualType ToType,
2125 ASTContext &Context,
2126 bool StripObjCLifetime = false) {
2127 assert((FromPtr->getTypeClass() == Type::Pointer ||
2128 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2129 "Invalid similarly-qualified pointer type");
2131 /// Conversions to 'id' subsume cv-qualifier conversions.
2132 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2133 return ToType.getUnqualifiedType();
2135 QualType CanonFromPointee
2136 = Context.getCanonicalType(FromPtr->getPointeeType());
2137 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2138 Qualifiers Quals = CanonFromPointee.getQualifiers();
2140 if (StripObjCLifetime)
2141 Quals.removeObjCLifetime();
2143 // Exact qualifier match -> return the pointer type we're converting to.
2144 if (CanonToPointee.getLocalQualifiers() == Quals) {
2145 // ToType is exactly what we need. Return it.
2146 if (!ToType.isNull())
2147 return ToType.getUnqualifiedType();
2149 // Build a pointer to ToPointee. It has the right qualifiers
2151 if (isa<ObjCObjectPointerType>(ToType))
2152 return Context.getObjCObjectPointerType(ToPointee);
2153 return Context.getPointerType(ToPointee);
2156 // Just build a canonical type that has the right qualifiers.
2157 QualType QualifiedCanonToPointee
2158 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2160 if (isa<ObjCObjectPointerType>(ToType))
2161 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2162 return Context.getPointerType(QualifiedCanonToPointee);
2165 static bool isNullPointerConstantForConversion(Expr *Expr,
2166 bool InOverloadResolution,
2167 ASTContext &Context) {
2168 // Handle value-dependent integral null pointer constants correctly.
2169 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2170 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2171 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2172 return !InOverloadResolution;
2174 return Expr->isNullPointerConstant(Context,
2175 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2176 : Expr::NPC_ValueDependentIsNull);
2179 /// IsPointerConversion - Determines whether the conversion of the
2180 /// expression From, which has the (possibly adjusted) type FromType,
2181 /// can be converted to the type ToType via a pointer conversion (C++
2182 /// 4.10). If so, returns true and places the converted type (that
2183 /// might differ from ToType in its cv-qualifiers at some level) into
2186 /// This routine also supports conversions to and from block pointers
2187 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2188 /// pointers to interfaces. FIXME: Once we've determined the
2189 /// appropriate overloading rules for Objective-C, we may want to
2190 /// split the Objective-C checks into a different routine; however,
2191 /// GCC seems to consider all of these conversions to be pointer
2192 /// conversions, so for now they live here. IncompatibleObjC will be
2193 /// set if the conversion is an allowed Objective-C conversion that
2194 /// should result in a warning.
2195 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2196 bool InOverloadResolution,
2197 QualType& ConvertedType,
2198 bool &IncompatibleObjC) {
2199 IncompatibleObjC = false;
2200 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2204 // Conversion from a null pointer constant to any Objective-C pointer type.
2205 if (ToType->isObjCObjectPointerType() &&
2206 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2207 ConvertedType = ToType;
2211 // Blocks: Block pointers can be converted to void*.
2212 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2213 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2214 ConvertedType = ToType;
2217 // Blocks: A null pointer constant can be converted to a block
2219 if (ToType->isBlockPointerType() &&
2220 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2221 ConvertedType = ToType;
2225 // If the left-hand-side is nullptr_t, the right side can be a null
2226 // pointer constant.
2227 if (ToType->isNullPtrType() &&
2228 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2229 ConvertedType = ToType;
2233 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2237 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2238 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2239 ConvertedType = ToType;
2243 // Beyond this point, both types need to be pointers
2244 // , including objective-c pointers.
2245 QualType ToPointeeType = ToTypePtr->getPointeeType();
2246 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2247 !getLangOpts().ObjCAutoRefCount) {
2248 ConvertedType = BuildSimilarlyQualifiedPointerType(
2249 FromType->getAs<ObjCObjectPointerType>(),
2254 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2258 QualType FromPointeeType = FromTypePtr->getPointeeType();
2260 // If the unqualified pointee types are the same, this can't be a
2261 // pointer conversion, so don't do all of the work below.
2262 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2265 // An rvalue of type "pointer to cv T," where T is an object type,
2266 // can be converted to an rvalue of type "pointer to cv void" (C++
2268 if (FromPointeeType->isIncompleteOrObjectType() &&
2269 ToPointeeType->isVoidType()) {
2270 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2273 /*StripObjCLifetime=*/true);
2277 // MSVC allows implicit function to void* type conversion.
2278 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2279 ToPointeeType->isVoidType()) {
2280 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2286 // When we're overloading in C, we allow a special kind of pointer
2287 // conversion for compatible-but-not-identical pointee types.
2288 if (!getLangOpts().CPlusPlus &&
2289 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2290 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2296 // C++ [conv.ptr]p3:
2298 // An rvalue of type "pointer to cv D," where D is a class type,
2299 // can be converted to an rvalue of type "pointer to cv B," where
2300 // B is a base class (clause 10) of D. If B is an inaccessible
2301 // (clause 11) or ambiguous (10.2) base class of D, a program that
2302 // necessitates this conversion is ill-formed. The result of the
2303 // conversion is a pointer to the base class sub-object of the
2304 // derived class object. The null pointer value is converted to
2305 // the null pointer value of the destination type.
2307 // Note that we do not check for ambiguity or inaccessibility
2308 // here. That is handled by CheckPointerConversion.
2309 if (getLangOpts().CPlusPlus &&
2310 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2311 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2312 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) {
2313 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2319 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2320 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2321 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2330 /// \brief Adopt the given qualifiers for the given type.
2331 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2332 Qualifiers TQs = T.getQualifiers();
2334 // Check whether qualifiers already match.
2338 if (Qs.compatiblyIncludes(TQs))
2339 return Context.getQualifiedType(T, Qs);
2341 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2344 /// isObjCPointerConversion - Determines whether this is an
2345 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2346 /// with the same arguments and return values.
2347 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2348 QualType& ConvertedType,
2349 bool &IncompatibleObjC) {
2350 if (!getLangOpts().ObjC1)
2353 // The set of qualifiers on the type we're converting from.
2354 Qualifiers FromQualifiers = FromType.getQualifiers();
2356 // First, we handle all conversions on ObjC object pointer types.
2357 const ObjCObjectPointerType* ToObjCPtr =
2358 ToType->getAs<ObjCObjectPointerType>();
2359 const ObjCObjectPointerType *FromObjCPtr =
2360 FromType->getAs<ObjCObjectPointerType>();
2362 if (ToObjCPtr && FromObjCPtr) {
2363 // If the pointee types are the same (ignoring qualifications),
2364 // then this is not a pointer conversion.
2365 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2366 FromObjCPtr->getPointeeType()))
2369 // Conversion between Objective-C pointers.
2370 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2371 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2372 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2373 if (getLangOpts().CPlusPlus && LHS && RHS &&
2374 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2375 FromObjCPtr->getPointeeType()))
2377 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2378 ToObjCPtr->getPointeeType(),
2380 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2384 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2385 // Okay: this is some kind of implicit downcast of Objective-C
2386 // interfaces, which is permitted. However, we're going to
2387 // complain about it.
2388 IncompatibleObjC = true;
2389 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2390 ToObjCPtr->getPointeeType(),
2392 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2396 // Beyond this point, both types need to be C pointers or block pointers.
2397 QualType ToPointeeType;
2398 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2399 ToPointeeType = ToCPtr->getPointeeType();
2400 else if (const BlockPointerType *ToBlockPtr =
2401 ToType->getAs<BlockPointerType>()) {
2402 // Objective C++: We're able to convert from a pointer to any object
2403 // to a block pointer type.
2404 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2405 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2408 ToPointeeType = ToBlockPtr->getPointeeType();
2410 else if (FromType->getAs<BlockPointerType>() &&
2411 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2412 // Objective C++: We're able to convert from a block pointer type to a
2413 // pointer to any object.
2414 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2420 QualType FromPointeeType;
2421 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2422 FromPointeeType = FromCPtr->getPointeeType();
2423 else if (const BlockPointerType *FromBlockPtr =
2424 FromType->getAs<BlockPointerType>())
2425 FromPointeeType = FromBlockPtr->getPointeeType();
2429 // If we have pointers to pointers, recursively check whether this
2430 // is an Objective-C conversion.
2431 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2432 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2433 IncompatibleObjC)) {
2434 // We always complain about this conversion.
2435 IncompatibleObjC = true;
2436 ConvertedType = Context.getPointerType(ConvertedType);
2437 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2440 // Allow conversion of pointee being objective-c pointer to another one;
2442 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2443 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2444 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2445 IncompatibleObjC)) {
2447 ConvertedType = Context.getPointerType(ConvertedType);
2448 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2452 // If we have pointers to functions or blocks, check whether the only
2453 // differences in the argument and result types are in Objective-C
2454 // pointer conversions. If so, we permit the conversion (but
2455 // complain about it).
2456 const FunctionProtoType *FromFunctionType
2457 = FromPointeeType->getAs<FunctionProtoType>();
2458 const FunctionProtoType *ToFunctionType
2459 = ToPointeeType->getAs<FunctionProtoType>();
2460 if (FromFunctionType && ToFunctionType) {
2461 // If the function types are exactly the same, this isn't an
2462 // Objective-C pointer conversion.
2463 if (Context.getCanonicalType(FromPointeeType)
2464 == Context.getCanonicalType(ToPointeeType))
2467 // Perform the quick checks that will tell us whether these
2468 // function types are obviously different.
2469 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2470 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2471 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2474 bool HasObjCConversion = false;
2475 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2476 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2477 // Okay, the types match exactly. Nothing to do.
2478 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2479 ToFunctionType->getReturnType(),
2480 ConvertedType, IncompatibleObjC)) {
2481 // Okay, we have an Objective-C pointer conversion.
2482 HasObjCConversion = true;
2484 // Function types are too different. Abort.
2488 // Check argument types.
2489 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2490 ArgIdx != NumArgs; ++ArgIdx) {
2491 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2492 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2493 if (Context.getCanonicalType(FromArgType)
2494 == Context.getCanonicalType(ToArgType)) {
2495 // Okay, the types match exactly. Nothing to do.
2496 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2497 ConvertedType, IncompatibleObjC)) {
2498 // Okay, we have an Objective-C pointer conversion.
2499 HasObjCConversion = true;
2501 // Argument types are too different. Abort.
2506 if (HasObjCConversion) {
2507 // We had an Objective-C conversion. Allow this pointer
2508 // conversion, but complain about it.
2509 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2510 IncompatibleObjC = true;
2518 /// \brief Determine whether this is an Objective-C writeback conversion,
2519 /// used for parameter passing when performing automatic reference counting.
2521 /// \param FromType The type we're converting form.
2523 /// \param ToType The type we're converting to.
2525 /// \param ConvertedType The type that will be produced after applying
2526 /// this conversion.
2527 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2528 QualType &ConvertedType) {
2529 if (!getLangOpts().ObjCAutoRefCount ||
2530 Context.hasSameUnqualifiedType(FromType, ToType))
2533 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2535 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2536 ToPointee = ToPointer->getPointeeType();
2540 Qualifiers ToQuals = ToPointee.getQualifiers();
2541 if (!ToPointee->isObjCLifetimeType() ||
2542 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2543 !ToQuals.withoutObjCLifetime().empty())
2546 // Argument must be a pointer to __strong to __weak.
2547 QualType FromPointee;
2548 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2549 FromPointee = FromPointer->getPointeeType();
2553 Qualifiers FromQuals = FromPointee.getQualifiers();
2554 if (!FromPointee->isObjCLifetimeType() ||
2555 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2556 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2559 // Make sure that we have compatible qualifiers.
2560 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2561 if (!ToQuals.compatiblyIncludes(FromQuals))
2564 // Remove qualifiers from the pointee type we're converting from; they
2565 // aren't used in the compatibility check belong, and we'll be adding back
2566 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2567 FromPointee = FromPointee.getUnqualifiedType();
2569 // The unqualified form of the pointee types must be compatible.
2570 ToPointee = ToPointee.getUnqualifiedType();
2571 bool IncompatibleObjC;
2572 if (Context.typesAreCompatible(FromPointee, ToPointee))
2573 FromPointee = ToPointee;
2574 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2578 /// \brief Construct the type we're converting to, which is a pointer to
2579 /// __autoreleasing pointee.
2580 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2581 ConvertedType = Context.getPointerType(FromPointee);
2585 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2586 QualType& ConvertedType) {
2587 QualType ToPointeeType;
2588 if (const BlockPointerType *ToBlockPtr =
2589 ToType->getAs<BlockPointerType>())
2590 ToPointeeType = ToBlockPtr->getPointeeType();
2594 QualType FromPointeeType;
2595 if (const BlockPointerType *FromBlockPtr =
2596 FromType->getAs<BlockPointerType>())
2597 FromPointeeType = FromBlockPtr->getPointeeType();
2600 // We have pointer to blocks, check whether the only
2601 // differences in the argument and result types are in Objective-C
2602 // pointer conversions. If so, we permit the conversion.
2604 const FunctionProtoType *FromFunctionType
2605 = FromPointeeType->getAs<FunctionProtoType>();
2606 const FunctionProtoType *ToFunctionType
2607 = ToPointeeType->getAs<FunctionProtoType>();
2609 if (!FromFunctionType || !ToFunctionType)
2612 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2615 // Perform the quick checks that will tell us whether these
2616 // function types are obviously different.
2617 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2618 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2621 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2622 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2623 if (FromEInfo != ToEInfo)
2626 bool IncompatibleObjC = false;
2627 if (Context.hasSameType(FromFunctionType->getReturnType(),
2628 ToFunctionType->getReturnType())) {
2629 // Okay, the types match exactly. Nothing to do.
2631 QualType RHS = FromFunctionType->getReturnType();
2632 QualType LHS = ToFunctionType->getReturnType();
2633 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2634 !RHS.hasQualifiers() && LHS.hasQualifiers())
2635 LHS = LHS.getUnqualifiedType();
2637 if (Context.hasSameType(RHS,LHS)) {
2639 } else if (isObjCPointerConversion(RHS, LHS,
2640 ConvertedType, IncompatibleObjC)) {
2641 if (IncompatibleObjC)
2643 // Okay, we have an Objective-C pointer conversion.
2649 // Check argument types.
2650 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2651 ArgIdx != NumArgs; ++ArgIdx) {
2652 IncompatibleObjC = false;
2653 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2654 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2655 if (Context.hasSameType(FromArgType, ToArgType)) {
2656 // Okay, the types match exactly. Nothing to do.
2657 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2658 ConvertedType, IncompatibleObjC)) {
2659 if (IncompatibleObjC)
2661 // Okay, we have an Objective-C pointer conversion.
2663 // Argument types are too different. Abort.
2666 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType,
2670 ConvertedType = ToType;
2678 ft_parameter_mismatch,
2680 ft_qualifer_mismatch,
2684 /// Attempts to get the FunctionProtoType from a Type. Handles
2685 /// MemberFunctionPointers properly.
2686 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2687 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2690 if (auto *MPT = FromType->getAs<MemberPointerType>())
2691 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2696 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2697 /// function types. Catches different number of parameter, mismatch in
2698 /// parameter types, and different return types.
2699 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2700 QualType FromType, QualType ToType) {
2701 // If either type is not valid, include no extra info.
2702 if (FromType.isNull() || ToType.isNull()) {
2703 PDiag << ft_default;
2707 // Get the function type from the pointers.
2708 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2709 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2710 *ToMember = ToType->getAs<MemberPointerType>();
2711 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2712 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2713 << QualType(FromMember->getClass(), 0);
2716 FromType = FromMember->getPointeeType();
2717 ToType = ToMember->getPointeeType();
2720 if (FromType->isPointerType())
2721 FromType = FromType->getPointeeType();
2722 if (ToType->isPointerType())
2723 ToType = ToType->getPointeeType();
2725 // Remove references.
2726 FromType = FromType.getNonReferenceType();
2727 ToType = ToType.getNonReferenceType();
2729 // Don't print extra info for non-specialized template functions.
2730 if (FromType->isInstantiationDependentType() &&
2731 !FromType->getAs<TemplateSpecializationType>()) {
2732 PDiag << ft_default;
2736 // No extra info for same types.
2737 if (Context.hasSameType(FromType, ToType)) {
2738 PDiag << ft_default;
2742 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2743 *ToFunction = tryGetFunctionProtoType(ToType);
2745 // Both types need to be function types.
2746 if (!FromFunction || !ToFunction) {
2747 PDiag << ft_default;
2751 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2752 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2753 << FromFunction->getNumParams();
2757 // Handle different parameter types.
2759 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2760 PDiag << ft_parameter_mismatch << ArgPos + 1
2761 << ToFunction->getParamType(ArgPos)
2762 << FromFunction->getParamType(ArgPos);
2766 // Handle different return type.
2767 if (!Context.hasSameType(FromFunction->getReturnType(),
2768 ToFunction->getReturnType())) {
2769 PDiag << ft_return_type << ToFunction->getReturnType()
2770 << FromFunction->getReturnType();
2774 unsigned FromQuals = FromFunction->getTypeQuals(),
2775 ToQuals = ToFunction->getTypeQuals();
2776 if (FromQuals != ToQuals) {
2777 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2781 // Handle exception specification differences on canonical type (in C++17
2783 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2784 ->isNothrow(Context) !=
2785 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2786 ->isNothrow(Context)) {
2787 PDiag << ft_noexcept;
2791 // Unable to find a difference, so add no extra info.
2792 PDiag << ft_default;
2795 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2796 /// for equality of their argument types. Caller has already checked that
2797 /// they have same number of arguments. If the parameters are different,
2798 /// ArgPos will have the parameter index of the first different parameter.
2799 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2800 const FunctionProtoType *NewType,
2802 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2803 N = NewType->param_type_begin(),
2804 E = OldType->param_type_end();
2805 O && (O != E); ++O, ++N) {
2806 if (!Context.hasSameType(O->getUnqualifiedType(),
2807 N->getUnqualifiedType())) {
2809 *ArgPos = O - OldType->param_type_begin();
2816 /// CheckPointerConversion - Check the pointer conversion from the
2817 /// expression From to the type ToType. This routine checks for
2818 /// ambiguous or inaccessible derived-to-base pointer
2819 /// conversions for which IsPointerConversion has already returned
2820 /// true. It returns true and produces a diagnostic if there was an
2821 /// error, or returns false otherwise.
2822 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2824 CXXCastPath& BasePath,
2825 bool IgnoreBaseAccess,
2827 QualType FromType = From->getType();
2828 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2832 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2833 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2834 Expr::NPCK_ZeroExpression) {
2835 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2836 DiagRuntimeBehavior(From->getExprLoc(), From,
2837 PDiag(diag::warn_impcast_bool_to_null_pointer)
2838 << ToType << From->getSourceRange());
2839 else if (!isUnevaluatedContext())
2840 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2841 << ToType << From->getSourceRange();
2843 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2844 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2845 QualType FromPointeeType = FromPtrType->getPointeeType(),
2846 ToPointeeType = ToPtrType->getPointeeType();
2848 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2849 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2850 // We must have a derived-to-base conversion. Check an
2851 // ambiguous or inaccessible conversion.
2852 unsigned InaccessibleID = 0;
2853 unsigned AmbigiousID = 0;
2855 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2856 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2858 if (CheckDerivedToBaseConversion(
2859 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2860 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2861 &BasePath, IgnoreBaseAccess))
2864 // The conversion was successful.
2865 Kind = CK_DerivedToBase;
2868 if (Diagnose && !IsCStyleOrFunctionalCast &&
2869 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2870 assert(getLangOpts().MSVCCompat &&
2871 "this should only be possible with MSVCCompat!");
2872 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2873 << From->getSourceRange();
2876 } else if (const ObjCObjectPointerType *ToPtrType =
2877 ToType->getAs<ObjCObjectPointerType>()) {
2878 if (const ObjCObjectPointerType *FromPtrType =
2879 FromType->getAs<ObjCObjectPointerType>()) {
2880 // Objective-C++ conversions are always okay.
2881 // FIXME: We should have a different class of conversions for the
2882 // Objective-C++ implicit conversions.
2883 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2885 } else if (FromType->isBlockPointerType()) {
2886 Kind = CK_BlockPointerToObjCPointerCast;
2888 Kind = CK_CPointerToObjCPointerCast;
2890 } else if (ToType->isBlockPointerType()) {
2891 if (!FromType->isBlockPointerType())
2892 Kind = CK_AnyPointerToBlockPointerCast;
2895 // We shouldn't fall into this case unless it's valid for other
2897 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2898 Kind = CK_NullToPointer;
2903 /// IsMemberPointerConversion - Determines whether the conversion of the
2904 /// expression From, which has the (possibly adjusted) type FromType, can be
2905 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2906 /// If so, returns true and places the converted type (that might differ from
2907 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2908 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2910 bool InOverloadResolution,
2911 QualType &ConvertedType) {
2912 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2916 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2917 if (From->isNullPointerConstant(Context,
2918 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2919 : Expr::NPC_ValueDependentIsNull)) {
2920 ConvertedType = ToType;
2924 // Otherwise, both types have to be member pointers.
2925 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2929 // A pointer to member of B can be converted to a pointer to member of D,
2930 // where D is derived from B (C++ 4.11p2).
2931 QualType FromClass(FromTypePtr->getClass(), 0);
2932 QualType ToClass(ToTypePtr->getClass(), 0);
2934 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2935 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) {
2936 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2937 ToClass.getTypePtr());
2944 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2945 /// expression From to the type ToType. This routine checks for ambiguous or
2946 /// virtual or inaccessible base-to-derived member pointer conversions
2947 /// for which IsMemberPointerConversion has already returned true. It returns
2948 /// true and produces a diagnostic if there was an error, or returns false
2950 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2952 CXXCastPath &BasePath,
2953 bool IgnoreBaseAccess) {
2954 QualType FromType = From->getType();
2955 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2957 // This must be a null pointer to member pointer conversion
2958 assert(From->isNullPointerConstant(Context,
2959 Expr::NPC_ValueDependentIsNull) &&
2960 "Expr must be null pointer constant!");
2961 Kind = CK_NullToMemberPointer;
2965 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2966 assert(ToPtrType && "No member pointer cast has a target type "
2967 "that is not a member pointer.");
2969 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2970 QualType ToClass = QualType(ToPtrType->getClass(), 0);
2972 // FIXME: What about dependent types?
2973 assert(FromClass->isRecordType() && "Pointer into non-class.");
2974 assert(ToClass->isRecordType() && "Pointer into non-class.");
2976 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2977 /*DetectVirtual=*/true);
2978 bool DerivationOkay =
2979 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths);
2980 assert(DerivationOkay &&
2981 "Should not have been called if derivation isn't OK.");
2982 (void)DerivationOkay;
2984 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2985 getUnqualifiedType())) {
2986 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2987 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2988 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2992 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2993 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2994 << FromClass << ToClass << QualType(VBase, 0)
2995 << From->getSourceRange();
2999 if (!IgnoreBaseAccess)
3000 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3002 diag::err_downcast_from_inaccessible_base);
3004 // Must be a base to derived member conversion.
3005 BuildBasePathArray(Paths, BasePath);
3006 Kind = CK_BaseToDerivedMemberPointer;
3010 /// Determine whether the lifetime conversion between the two given
3011 /// qualifiers sets is nontrivial.
3012 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3013 Qualifiers ToQuals) {
3014 // Converting anything to const __unsafe_unretained is trivial.
3015 if (ToQuals.hasConst() &&
3016 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3022 /// IsQualificationConversion - Determines whether the conversion from
3023 /// an rvalue of type FromType to ToType is a qualification conversion
3026 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3027 /// when the qualification conversion involves a change in the Objective-C
3028 /// object lifetime.
3030 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3031 bool CStyle, bool &ObjCLifetimeConversion) {
3032 FromType = Context.getCanonicalType(FromType);
3033 ToType = Context.getCanonicalType(ToType);
3034 ObjCLifetimeConversion = false;
3036 // If FromType and ToType are the same type, this is not a
3037 // qualification conversion.
3038 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3042 // A conversion can add cv-qualifiers at levels other than the first
3043 // in multi-level pointers, subject to the following rules: [...]
3044 bool PreviousToQualsIncludeConst = true;
3045 bool UnwrappedAnyPointer = false;
3046 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
3047 // Within each iteration of the loop, we check the qualifiers to
3048 // determine if this still looks like a qualification
3049 // conversion. Then, if all is well, we unwrap one more level of
3050 // pointers or pointers-to-members and do it all again
3051 // until there are no more pointers or pointers-to-members left to
3053 UnwrappedAnyPointer = true;
3055 Qualifiers FromQuals = FromType.getQualifiers();
3056 Qualifiers ToQuals = ToType.getQualifiers();
3058 // Ignore __unaligned qualifier if this type is void.
3059 if (ToType.getUnqualifiedType()->isVoidType())
3060 FromQuals.removeUnaligned();
3063 // Check Objective-C lifetime conversions.
3064 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3065 UnwrappedAnyPointer) {
3066 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3067 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3068 ObjCLifetimeConversion = true;
3069 FromQuals.removeObjCLifetime();
3070 ToQuals.removeObjCLifetime();
3072 // Qualification conversions cannot cast between different
3073 // Objective-C lifetime qualifiers.
3078 // Allow addition/removal of GC attributes but not changing GC attributes.
3079 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3080 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3081 FromQuals.removeObjCGCAttr();
3082 ToQuals.removeObjCGCAttr();
3085 // -- for every j > 0, if const is in cv 1,j then const is in cv
3086 // 2,j, and similarly for volatile.
3087 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3090 // -- if the cv 1,j and cv 2,j are different, then const is in
3091 // every cv for 0 < k < j.
3092 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3093 && !PreviousToQualsIncludeConst)
3096 // Keep track of whether all prior cv-qualifiers in the "to" type
3098 PreviousToQualsIncludeConst
3099 = PreviousToQualsIncludeConst && ToQuals.hasConst();
3102 // We are left with FromType and ToType being the pointee types
3103 // after unwrapping the original FromType and ToType the same number
3104 // of types. If we unwrapped any pointers, and if FromType and
3105 // ToType have the same unqualified type (since we checked
3106 // qualifiers above), then this is a qualification conversion.
3107 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3110 /// \brief - Determine whether this is a conversion from a scalar type to an
3113 /// If successful, updates \c SCS's second and third steps in the conversion
3114 /// sequence to finish the conversion.
3115 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3116 bool InOverloadResolution,
3117 StandardConversionSequence &SCS,
3119 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3123 StandardConversionSequence InnerSCS;
3124 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3125 InOverloadResolution, InnerSCS,
3126 CStyle, /*AllowObjCWritebackConversion=*/false))
3129 SCS.Second = InnerSCS.Second;
3130 SCS.setToType(1, InnerSCS.getToType(1));
3131 SCS.Third = InnerSCS.Third;
3132 SCS.QualificationIncludesObjCLifetime
3133 = InnerSCS.QualificationIncludesObjCLifetime;
3134 SCS.setToType(2, InnerSCS.getToType(2));
3138 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3139 CXXConstructorDecl *Constructor,
3141 const FunctionProtoType *CtorType =
3142 Constructor->getType()->getAs<FunctionProtoType>();
3143 if (CtorType->getNumParams() > 0) {
3144 QualType FirstArg = CtorType->getParamType(0);
3145 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3151 static OverloadingResult
3152 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3154 UserDefinedConversionSequence &User,
3155 OverloadCandidateSet &CandidateSet,
3156 bool AllowExplicit) {
3157 for (auto *D : S.LookupConstructors(To)) {
3158 auto Info = getConstructorInfo(D);
3162 bool Usable = !Info.Constructor->isInvalidDecl() &&
3163 S.isInitListConstructor(Info.Constructor) &&
3164 (AllowExplicit || !Info.Constructor->isExplicit());
3166 // If the first argument is (a reference to) the target type,
3167 // suppress conversions.
3168 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3169 S.Context, Info.Constructor, ToType);
3170 if (Info.ConstructorTmpl)
3171 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3172 /*ExplicitArgs*/ nullptr, From,
3173 CandidateSet, SuppressUserConversions);
3175 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3176 CandidateSet, SuppressUserConversions);
3180 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3182 OverloadCandidateSet::iterator Best;
3183 switch (auto Result =
3184 CandidateSet.BestViableFunction(S, From->getLocStart(),
3188 // Record the standard conversion we used and the conversion function.
3189 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3190 QualType ThisType = Constructor->getThisType(S.Context);
3191 // Initializer lists don't have conversions as such.
3192 User.Before.setAsIdentityConversion();
3193 User.HadMultipleCandidates = HadMultipleCandidates;
3194 User.ConversionFunction = Constructor;
3195 User.FoundConversionFunction = Best->FoundDecl;
3196 User.After.setAsIdentityConversion();
3197 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3198 User.After.setAllToTypes(ToType);
3202 case OR_No_Viable_Function:
3203 return OR_No_Viable_Function;
3205 return OR_Ambiguous;
3208 llvm_unreachable("Invalid OverloadResult!");
3211 /// Determines whether there is a user-defined conversion sequence
3212 /// (C++ [over.ics.user]) that converts expression From to the type
3213 /// ToType. If such a conversion exists, User will contain the
3214 /// user-defined conversion sequence that performs such a conversion
3215 /// and this routine will return true. Otherwise, this routine returns
3216 /// false and User is unspecified.
3218 /// \param AllowExplicit true if the conversion should consider C++0x
3219 /// "explicit" conversion functions as well as non-explicit conversion
3220 /// functions (C++0x [class.conv.fct]p2).
3222 /// \param AllowObjCConversionOnExplicit true if the conversion should
3223 /// allow an extra Objective-C pointer conversion on uses of explicit
3224 /// constructors. Requires \c AllowExplicit to also be set.
3225 static OverloadingResult
3226 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3227 UserDefinedConversionSequence &User,
3228 OverloadCandidateSet &CandidateSet,
3230 bool AllowObjCConversionOnExplicit) {
3231 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3233 // Whether we will only visit constructors.
3234 bool ConstructorsOnly = false;
3236 // If the type we are conversion to is a class type, enumerate its
3238 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3239 // C++ [over.match.ctor]p1:
3240 // When objects of class type are direct-initialized (8.5), or
3241 // copy-initialized from an expression of the same or a
3242 // derived class type (8.5), overload resolution selects the
3243 // constructor. [...] For copy-initialization, the candidate
3244 // functions are all the converting constructors (12.3.1) of
3245 // that class. The argument list is the expression-list within
3246 // the parentheses of the initializer.
3247 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3248 (From->getType()->getAs<RecordType>() &&
3249 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType)))
3250 ConstructorsOnly = true;
3252 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3253 // We're not going to find any constructors.
3254 } else if (CXXRecordDecl *ToRecordDecl
3255 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3257 Expr **Args = &From;
3258 unsigned NumArgs = 1;
3259 bool ListInitializing = false;
3260 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3261 // But first, see if there is an init-list-constructor that will work.
3262 OverloadingResult Result = IsInitializerListConstructorConversion(
3263 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3264 if (Result != OR_No_Viable_Function)
3267 CandidateSet.clear();
3269 // If we're list-initializing, we pass the individual elements as
3270 // arguments, not the entire list.
3271 Args = InitList->getInits();
3272 NumArgs = InitList->getNumInits();
3273 ListInitializing = true;
3276 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3277 auto Info = getConstructorInfo(D);
3281 bool Usable = !Info.Constructor->isInvalidDecl();
3282 if (ListInitializing)
3283 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3286 Info.Constructor->isConvertingConstructor(AllowExplicit);
3288 bool SuppressUserConversions = !ConstructorsOnly;
3289 if (SuppressUserConversions && ListInitializing) {
3290 SuppressUserConversions = false;
3292 // If the first argument is (a reference to) the target type,
3293 // suppress conversions.
3294 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3295 S.Context, Info.Constructor, ToType);
3298 if (Info.ConstructorTmpl)
3299 S.AddTemplateOverloadCandidate(
3300 Info.ConstructorTmpl, Info.FoundDecl,
3301 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3302 CandidateSet, SuppressUserConversions);
3304 // Allow one user-defined conversion when user specifies a
3305 // From->ToType conversion via an static cast (c-style, etc).
3306 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3307 llvm::makeArrayRef(Args, NumArgs),
3308 CandidateSet, SuppressUserConversions);
3314 // Enumerate conversion functions, if we're allowed to.
3315 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3316 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) {
3317 // No conversion functions from incomplete types.
3318 } else if (const RecordType *FromRecordType
3319 = From->getType()->getAs<RecordType>()) {
3320 if (CXXRecordDecl *FromRecordDecl
3321 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3322 // Add all of the conversion functions as candidates.
3323 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3324 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3325 DeclAccessPair FoundDecl = I.getPair();
3326 NamedDecl *D = FoundDecl.getDecl();
3327 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3328 if (isa<UsingShadowDecl>(D))
3329 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3331 CXXConversionDecl *Conv;
3332 FunctionTemplateDecl *ConvTemplate;
3333 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3334 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3336 Conv = cast<CXXConversionDecl>(D);
3338 if (AllowExplicit || !Conv->isExplicit()) {
3340 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3341 ActingContext, From, ToType,
3343 AllowObjCConversionOnExplicit);
3345 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3346 From, ToType, CandidateSet,
3347 AllowObjCConversionOnExplicit);
3353 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3355 OverloadCandidateSet::iterator Best;
3356 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3360 // Record the standard conversion we used and the conversion function.
3361 if (CXXConstructorDecl *Constructor
3362 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3363 // C++ [over.ics.user]p1:
3364 // If the user-defined conversion is specified by a
3365 // constructor (12.3.1), the initial standard conversion
3366 // sequence converts the source type to the type required by
3367 // the argument of the constructor.
3369 QualType ThisType = Constructor->getThisType(S.Context);
3370 if (isa<InitListExpr>(From)) {
3371 // Initializer lists don't have conversions as such.
3372 User.Before.setAsIdentityConversion();
3374 if (Best->Conversions[0].isEllipsis())
3375 User.EllipsisConversion = true;
3377 User.Before = Best->Conversions[0].Standard;
3378 User.EllipsisConversion = false;
3381 User.HadMultipleCandidates = HadMultipleCandidates;
3382 User.ConversionFunction = Constructor;
3383 User.FoundConversionFunction = Best->FoundDecl;
3384 User.After.setAsIdentityConversion();
3385 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3386 User.After.setAllToTypes(ToType);
3389 if (CXXConversionDecl *Conversion
3390 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3391 // C++ [over.ics.user]p1:
3393 // [...] If the user-defined conversion is specified by a
3394 // conversion function (12.3.2), the initial standard
3395 // conversion sequence converts the source type to the
3396 // implicit object parameter of the conversion function.
3397 User.Before = Best->Conversions[0].Standard;
3398 User.HadMultipleCandidates = HadMultipleCandidates;
3399 User.ConversionFunction = Conversion;
3400 User.FoundConversionFunction = Best->FoundDecl;
3401 User.EllipsisConversion = false;
3403 // C++ [over.ics.user]p2:
3404 // The second standard conversion sequence converts the
3405 // result of the user-defined conversion to the target type
3406 // for the sequence. Since an implicit conversion sequence
3407 // is an initialization, the special rules for
3408 // initialization by user-defined conversion apply when
3409 // selecting the best user-defined conversion for a
3410 // user-defined conversion sequence (see 13.3.3 and
3412 User.After = Best->FinalConversion;
3415 llvm_unreachable("Not a constructor or conversion function?");
3417 case OR_No_Viable_Function:
3418 return OR_No_Viable_Function;
3421 return OR_Ambiguous;
3424 llvm_unreachable("Invalid OverloadResult!");
3428 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3429 ImplicitConversionSequence ICS;
3430 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3431 OverloadCandidateSet::CSK_Normal);
3432 OverloadingResult OvResult =
3433 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3434 CandidateSet, false, false);
3435 if (OvResult == OR_Ambiguous)
3436 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3437 << From->getType() << ToType << From->getSourceRange();
3438 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3439 if (!RequireCompleteType(From->getLocStart(), ToType,
3440 diag::err_typecheck_nonviable_condition_incomplete,
3441 From->getType(), From->getSourceRange()))
3442 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3443 << false << From->getType() << From->getSourceRange() << ToType;
3446 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3450 /// \brief Compare the user-defined conversion functions or constructors
3451 /// of two user-defined conversion sequences to determine whether any ordering
3453 static ImplicitConversionSequence::CompareKind
3454 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3455 FunctionDecl *Function2) {
3456 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3457 return ImplicitConversionSequence::Indistinguishable;
3460 // If both conversion functions are implicitly-declared conversions from
3461 // a lambda closure type to a function pointer and a block pointer,
3462 // respectively, always prefer the conversion to a function pointer,
3463 // because the function pointer is more lightweight and is more likely
3464 // to keep code working.
3465 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3467 return ImplicitConversionSequence::Indistinguishable;
3469 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3471 return ImplicitConversionSequence::Indistinguishable;
3473 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3474 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3475 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3476 if (Block1 != Block2)
3477 return Block1 ? ImplicitConversionSequence::Worse
3478 : ImplicitConversionSequence::Better;
3481 return ImplicitConversionSequence::Indistinguishable;
3484 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3485 const ImplicitConversionSequence &ICS) {
3486 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3487 (ICS.isUserDefined() &&
3488 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3491 /// CompareImplicitConversionSequences - Compare two implicit
3492 /// conversion sequences to determine whether one is better than the
3493 /// other or if they are indistinguishable (C++ 13.3.3.2).
3494 static ImplicitConversionSequence::CompareKind
3495 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3496 const ImplicitConversionSequence& ICS1,
3497 const ImplicitConversionSequence& ICS2)
3499 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3500 // conversion sequences (as defined in 13.3.3.1)
3501 // -- a standard conversion sequence (13.3.3.1.1) is a better
3502 // conversion sequence than a user-defined conversion sequence or
3503 // an ellipsis conversion sequence, and
3504 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3505 // conversion sequence than an ellipsis conversion sequence
3508 // C++0x [over.best.ics]p10:
3509 // For the purpose of ranking implicit conversion sequences as
3510 // described in 13.3.3.2, the ambiguous conversion sequence is
3511 // treated as a user-defined sequence that is indistinguishable
3512 // from any other user-defined conversion sequence.
3514 // String literal to 'char *' conversion has been deprecated in C++03. It has
3515 // been removed from C++11. We still accept this conversion, if it happens at
3516 // the best viable function. Otherwise, this conversion is considered worse
3517 // than ellipsis conversion. Consider this as an extension; this is not in the
3518 // standard. For example:
3520 // int &f(...); // #1
3521 // void f(char*); // #2
3522 // void g() { int &r = f("foo"); }
3524 // In C++03, we pick #2 as the best viable function.
3525 // In C++11, we pick #1 as the best viable function, because ellipsis
3526 // conversion is better than string-literal to char* conversion (since there
3527 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3528 // convert arguments, #2 would be the best viable function in C++11.
3529 // If the best viable function has this conversion, a warning will be issued
3530 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3532 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3533 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3534 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3535 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3536 ? ImplicitConversionSequence::Worse
3537 : ImplicitConversionSequence::Better;
3539 if (ICS1.getKindRank() < ICS2.getKindRank())
3540 return ImplicitConversionSequence::Better;
3541 if (ICS2.getKindRank() < ICS1.getKindRank())
3542 return ImplicitConversionSequence::Worse;
3544 // The following checks require both conversion sequences to be of
3546 if (ICS1.getKind() != ICS2.getKind())
3547 return ImplicitConversionSequence::Indistinguishable;
3549 ImplicitConversionSequence::CompareKind Result =
3550 ImplicitConversionSequence::Indistinguishable;
3552 // Two implicit conversion sequences of the same form are
3553 // indistinguishable conversion sequences unless one of the
3554 // following rules apply: (C++ 13.3.3.2p3):
3556 // List-initialization sequence L1 is a better conversion sequence than
3557 // list-initialization sequence L2 if:
3558 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3560 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3561 // and N1 is smaller than N2.,
3562 // even if one of the other rules in this paragraph would otherwise apply.
3563 if (!ICS1.isBad()) {
3564 if (ICS1.isStdInitializerListElement() &&
3565 !ICS2.isStdInitializerListElement())
3566 return ImplicitConversionSequence::Better;
3567 if (!ICS1.isStdInitializerListElement() &&
3568 ICS2.isStdInitializerListElement())
3569 return ImplicitConversionSequence::Worse;
3572 if (ICS1.isStandard())
3573 // Standard conversion sequence S1 is a better conversion sequence than
3574 // standard conversion sequence S2 if [...]
3575 Result = CompareStandardConversionSequences(S, Loc,
3576 ICS1.Standard, ICS2.Standard);
3577 else if (ICS1.isUserDefined()) {
3578 // User-defined conversion sequence U1 is a better conversion
3579 // sequence than another user-defined conversion sequence U2 if
3580 // they contain the same user-defined conversion function or
3581 // constructor and if the second standard conversion sequence of
3582 // U1 is better than the second standard conversion sequence of
3583 // U2 (C++ 13.3.3.2p3).
3584 if (ICS1.UserDefined.ConversionFunction ==
3585 ICS2.UserDefined.ConversionFunction)
3586 Result = CompareStandardConversionSequences(S, Loc,
3587 ICS1.UserDefined.After,
3588 ICS2.UserDefined.After);
3590 Result = compareConversionFunctions(S,
3591 ICS1.UserDefined.ConversionFunction,
3592 ICS2.UserDefined.ConversionFunction);
3598 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3599 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3601 T1 = Context.getUnqualifiedArrayType(T1, Quals);
3602 T2 = Context.getUnqualifiedArrayType(T2, Quals);
3605 return Context.hasSameUnqualifiedType(T1, T2);
3608 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3609 // determine if one is a proper subset of the other.
3610 static ImplicitConversionSequence::CompareKind
3611 compareStandardConversionSubsets(ASTContext &Context,
3612 const StandardConversionSequence& SCS1,
3613 const StandardConversionSequence& SCS2) {
3614 ImplicitConversionSequence::CompareKind Result
3615 = ImplicitConversionSequence::Indistinguishable;
3617 // the identity conversion sequence is considered to be a subsequence of
3618 // any non-identity conversion sequence
3619 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3620 return ImplicitConversionSequence::Better;
3621 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3622 return ImplicitConversionSequence::Worse;
3624 if (SCS1.Second != SCS2.Second) {
3625 if (SCS1.Second == ICK_Identity)
3626 Result = ImplicitConversionSequence::Better;
3627 else if (SCS2.Second == ICK_Identity)
3628 Result = ImplicitConversionSequence::Worse;
3630 return ImplicitConversionSequence::Indistinguishable;
3631 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3632 return ImplicitConversionSequence::Indistinguishable;
3634 if (SCS1.Third == SCS2.Third) {
3635 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3636 : ImplicitConversionSequence::Indistinguishable;
3639 if (SCS1.Third == ICK_Identity)
3640 return Result == ImplicitConversionSequence::Worse
3641 ? ImplicitConversionSequence::Indistinguishable
3642 : ImplicitConversionSequence::Better;
3644 if (SCS2.Third == ICK_Identity)
3645 return Result == ImplicitConversionSequence::Better
3646 ? ImplicitConversionSequence::Indistinguishable
3647 : ImplicitConversionSequence::Worse;
3649 return ImplicitConversionSequence::Indistinguishable;
3652 /// \brief Determine whether one of the given reference bindings is better
3653 /// than the other based on what kind of bindings they are.
3655 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3656 const StandardConversionSequence &SCS2) {
3657 // C++0x [over.ics.rank]p3b4:
3658 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3659 // implicit object parameter of a non-static member function declared
3660 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3661 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3662 // lvalue reference to a function lvalue and S2 binds an rvalue
3665 // FIXME: Rvalue references. We're going rogue with the above edits,
3666 // because the semantics in the current C++0x working paper (N3225 at the
3667 // time of this writing) break the standard definition of std::forward
3668 // and std::reference_wrapper when dealing with references to functions.
3669 // Proposed wording changes submitted to CWG for consideration.
3670 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3671 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3674 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3675 SCS2.IsLvalueReference) ||
3676 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3677 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3680 /// CompareStandardConversionSequences - Compare two standard
3681 /// conversion sequences to determine whether one is better than the
3682 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3683 static ImplicitConversionSequence::CompareKind
3684 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3685 const StandardConversionSequence& SCS1,
3686 const StandardConversionSequence& SCS2)
3688 // Standard conversion sequence S1 is a better conversion sequence
3689 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3691 // -- S1 is a proper subsequence of S2 (comparing the conversion
3692 // sequences in the canonical form defined by 13.3.3.1.1,
3693 // excluding any Lvalue Transformation; the identity conversion
3694 // sequence is considered to be a subsequence of any
3695 // non-identity conversion sequence) or, if not that,
3696 if (ImplicitConversionSequence::CompareKind CK
3697 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3700 // -- the rank of S1 is better than the rank of S2 (by the rules
3701 // defined below), or, if not that,
3702 ImplicitConversionRank Rank1 = SCS1.getRank();
3703 ImplicitConversionRank Rank2 = SCS2.getRank();
3705 return ImplicitConversionSequence::Better;
3706 else if (Rank2 < Rank1)
3707 return ImplicitConversionSequence::Worse;
3709 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3710 // are indistinguishable unless one of the following rules
3713 // A conversion that is not a conversion of a pointer, or
3714 // pointer to member, to bool is better than another conversion
3715 // that is such a conversion.
3716 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3717 return SCS2.isPointerConversionToBool()
3718 ? ImplicitConversionSequence::Better
3719 : ImplicitConversionSequence::Worse;
3721 // C++ [over.ics.rank]p4b2:
3723 // If class B is derived directly or indirectly from class A,
3724 // conversion of B* to A* is better than conversion of B* to
3725 // void*, and conversion of A* to void* is better than conversion
3727 bool SCS1ConvertsToVoid
3728 = SCS1.isPointerConversionToVoidPointer(S.Context);
3729 bool SCS2ConvertsToVoid
3730 = SCS2.isPointerConversionToVoidPointer(S.Context);
3731 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3732 // Exactly one of the conversion sequences is a conversion to
3733 // a void pointer; it's the worse conversion.
3734 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3735 : ImplicitConversionSequence::Worse;
3736 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3737 // Neither conversion sequence converts to a void pointer; compare
3738 // their derived-to-base conversions.
3739 if (ImplicitConversionSequence::CompareKind DerivedCK
3740 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3742 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3743 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3744 // Both conversion sequences are conversions to void
3745 // pointers. Compare the source types to determine if there's an
3746 // inheritance relationship in their sources.
3747 QualType FromType1 = SCS1.getFromType();
3748 QualType FromType2 = SCS2.getFromType();
3750 // Adjust the types we're converting from via the array-to-pointer
3751 // conversion, if we need to.
3752 if (SCS1.First == ICK_Array_To_Pointer)
3753 FromType1 = S.Context.getArrayDecayedType(FromType1);
3754 if (SCS2.First == ICK_Array_To_Pointer)
3755 FromType2 = S.Context.getArrayDecayedType(FromType2);
3757 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3758 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3760 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3761 return ImplicitConversionSequence::Better;
3762 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3763 return ImplicitConversionSequence::Worse;
3765 // Objective-C++: If one interface is more specific than the
3766 // other, it is the better one.
3767 const ObjCObjectPointerType* FromObjCPtr1
3768 = FromType1->getAs<ObjCObjectPointerType>();
3769 const ObjCObjectPointerType* FromObjCPtr2
3770 = FromType2->getAs<ObjCObjectPointerType>();
3771 if (FromObjCPtr1 && FromObjCPtr2) {
3772 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3774 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3776 if (AssignLeft != AssignRight) {
3777 return AssignLeft? ImplicitConversionSequence::Better
3778 : ImplicitConversionSequence::Worse;
3783 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3785 if (ImplicitConversionSequence::CompareKind QualCK
3786 = CompareQualificationConversions(S, SCS1, SCS2))
3789 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3790 // Check for a better reference binding based on the kind of bindings.
3791 if (isBetterReferenceBindingKind(SCS1, SCS2))
3792 return ImplicitConversionSequence::Better;
3793 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3794 return ImplicitConversionSequence::Worse;
3796 // C++ [over.ics.rank]p3b4:
3797 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3798 // which the references refer are the same type except for
3799 // top-level cv-qualifiers, and the type to which the reference
3800 // initialized by S2 refers is more cv-qualified than the type
3801 // to which the reference initialized by S1 refers.
3802 QualType T1 = SCS1.getToType(2);
3803 QualType T2 = SCS2.getToType(2);
3804 T1 = S.Context.getCanonicalType(T1);
3805 T2 = S.Context.getCanonicalType(T2);
3806 Qualifiers T1Quals, T2Quals;
3807 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3808 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3809 if (UnqualT1 == UnqualT2) {
3810 // Objective-C++ ARC: If the references refer to objects with different
3811 // lifetimes, prefer bindings that don't change lifetime.
3812 if (SCS1.ObjCLifetimeConversionBinding !=
3813 SCS2.ObjCLifetimeConversionBinding) {
3814 return SCS1.ObjCLifetimeConversionBinding
3815 ? ImplicitConversionSequence::Worse
3816 : ImplicitConversionSequence::Better;
3819 // If the type is an array type, promote the element qualifiers to the
3820 // type for comparison.
3821 if (isa<ArrayType>(T1) && T1Quals)
3822 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3823 if (isa<ArrayType>(T2) && T2Quals)
3824 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3825 if (T2.isMoreQualifiedThan(T1))
3826 return ImplicitConversionSequence::Better;
3827 else if (T1.isMoreQualifiedThan(T2))
3828 return ImplicitConversionSequence::Worse;
3832 // In Microsoft mode, prefer an integral conversion to a
3833 // floating-to-integral conversion if the integral conversion
3834 // is between types of the same size.
3842 // Here, MSVC will call f(int) instead of generating a compile error
3843 // as clang will do in standard mode.
3844 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3845 SCS2.Second == ICK_Floating_Integral &&
3846 S.Context.getTypeSize(SCS1.getFromType()) ==
3847 S.Context.getTypeSize(SCS1.getToType(2)))
3848 return ImplicitConversionSequence::Better;
3850 return ImplicitConversionSequence::Indistinguishable;
3853 /// CompareQualificationConversions - Compares two standard conversion
3854 /// sequences to determine whether they can be ranked based on their
3855 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3856 static ImplicitConversionSequence::CompareKind
3857 CompareQualificationConversions(Sema &S,
3858 const StandardConversionSequence& SCS1,
3859 const StandardConversionSequence& SCS2) {
3861 // -- S1 and S2 differ only in their qualification conversion and
3862 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3863 // cv-qualification signature of type T1 is a proper subset of
3864 // the cv-qualification signature of type T2, and S1 is not the
3865 // deprecated string literal array-to-pointer conversion (4.2).
3866 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3867 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3868 return ImplicitConversionSequence::Indistinguishable;
3870 // FIXME: the example in the standard doesn't use a qualification
3872 QualType T1 = SCS1.getToType(2);
3873 QualType T2 = SCS2.getToType(2);
3874 T1 = S.Context.getCanonicalType(T1);
3875 T2 = S.Context.getCanonicalType(T2);
3876 Qualifiers T1Quals, T2Quals;
3877 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3878 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3880 // If the types are the same, we won't learn anything by unwrapped
3882 if (UnqualT1 == UnqualT2)
3883 return ImplicitConversionSequence::Indistinguishable;
3885 // If the type is an array type, promote the element qualifiers to the type
3887 if (isa<ArrayType>(T1) && T1Quals)
3888 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3889 if (isa<ArrayType>(T2) && T2Quals)
3890 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3892 ImplicitConversionSequence::CompareKind Result
3893 = ImplicitConversionSequence::Indistinguishable;
3895 // Objective-C++ ARC:
3896 // Prefer qualification conversions not involving a change in lifetime
3897 // to qualification conversions that do not change lifetime.
3898 if (SCS1.QualificationIncludesObjCLifetime !=
3899 SCS2.QualificationIncludesObjCLifetime) {
3900 Result = SCS1.QualificationIncludesObjCLifetime
3901 ? ImplicitConversionSequence::Worse
3902 : ImplicitConversionSequence::Better;
3905 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3906 // Within each iteration of the loop, we check the qualifiers to
3907 // determine if this still looks like a qualification
3908 // conversion. Then, if all is well, we unwrap one more level of
3909 // pointers or pointers-to-members and do it all again
3910 // until there are no more pointers or pointers-to-members left
3911 // to unwrap. This essentially mimics what
3912 // IsQualificationConversion does, but here we're checking for a
3913 // strict subset of qualifiers.
3914 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3915 // The qualifiers are the same, so this doesn't tell us anything
3916 // about how the sequences rank.
3918 else if (T2.isMoreQualifiedThan(T1)) {
3919 // T1 has fewer qualifiers, so it could be the better sequence.
3920 if (Result == ImplicitConversionSequence::Worse)
3921 // Neither has qualifiers that are a subset of the other's
3923 return ImplicitConversionSequence::Indistinguishable;
3925 Result = ImplicitConversionSequence::Better;
3926 } else if (T1.isMoreQualifiedThan(T2)) {
3927 // T2 has fewer qualifiers, so it could be the better sequence.
3928 if (Result == ImplicitConversionSequence::Better)
3929 // Neither has qualifiers that are a subset of the other's
3931 return ImplicitConversionSequence::Indistinguishable;
3933 Result = ImplicitConversionSequence::Worse;
3935 // Qualifiers are disjoint.
3936 return ImplicitConversionSequence::Indistinguishable;
3939 // If the types after this point are equivalent, we're done.
3940 if (S.Context.hasSameUnqualifiedType(T1, T2))
3944 // Check that the winning standard conversion sequence isn't using
3945 // the deprecated string literal array to pointer conversion.
3947 case ImplicitConversionSequence::Better:
3948 if (SCS1.DeprecatedStringLiteralToCharPtr)
3949 Result = ImplicitConversionSequence::Indistinguishable;
3952 case ImplicitConversionSequence::Indistinguishable:
3955 case ImplicitConversionSequence::Worse:
3956 if (SCS2.DeprecatedStringLiteralToCharPtr)
3957 Result = ImplicitConversionSequence::Indistinguishable;
3964 /// CompareDerivedToBaseConversions - Compares two standard conversion
3965 /// sequences to determine whether they can be ranked based on their
3966 /// various kinds of derived-to-base conversions (C++
3967 /// [over.ics.rank]p4b3). As part of these checks, we also look at
3968 /// conversions between Objective-C interface types.
3969 static ImplicitConversionSequence::CompareKind
3970 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
3971 const StandardConversionSequence& SCS1,
3972 const StandardConversionSequence& SCS2) {
3973 QualType FromType1 = SCS1.getFromType();
3974 QualType ToType1 = SCS1.getToType(1);
3975 QualType FromType2 = SCS2.getFromType();
3976 QualType ToType2 = SCS2.getToType(1);
3978 // Adjust the types we're converting from via the array-to-pointer
3979 // conversion, if we need to.
3980 if (SCS1.First == ICK_Array_To_Pointer)
3981 FromType1 = S.Context.getArrayDecayedType(FromType1);
3982 if (SCS2.First == ICK_Array_To_Pointer)
3983 FromType2 = S.Context.getArrayDecayedType(FromType2);
3985 // Canonicalize all of the types.
3986 FromType1 = S.Context.getCanonicalType(FromType1);
3987 ToType1 = S.Context.getCanonicalType(ToType1);
3988 FromType2 = S.Context.getCanonicalType(FromType2);
3989 ToType2 = S.Context.getCanonicalType(ToType2);
3991 // C++ [over.ics.rank]p4b3:
3993 // If class B is derived directly or indirectly from class A and
3994 // class C is derived directly or indirectly from B,
3996 // Compare based on pointer conversions.
3997 if (SCS1.Second == ICK_Pointer_Conversion &&
3998 SCS2.Second == ICK_Pointer_Conversion &&
3999 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4000 FromType1->isPointerType() && FromType2->isPointerType() &&
4001 ToType1->isPointerType() && ToType2->isPointerType()) {
4002 QualType FromPointee1
4003 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4005 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4006 QualType FromPointee2
4007 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4009 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4011 // -- conversion of C* to B* is better than conversion of C* to A*,
4012 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4013 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4014 return ImplicitConversionSequence::Better;
4015 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4016 return ImplicitConversionSequence::Worse;
4019 // -- conversion of B* to A* is better than conversion of C* to A*,
4020 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4021 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4022 return ImplicitConversionSequence::Better;
4023 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4024 return ImplicitConversionSequence::Worse;
4026 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4027 SCS2.Second == ICK_Pointer_Conversion) {
4028 const ObjCObjectPointerType *FromPtr1
4029 = FromType1->getAs<ObjCObjectPointerType>();
4030 const ObjCObjectPointerType *FromPtr2
4031 = FromType2->getAs<ObjCObjectPointerType>();
4032 const ObjCObjectPointerType *ToPtr1
4033 = ToType1->getAs<ObjCObjectPointerType>();
4034 const ObjCObjectPointerType *ToPtr2
4035 = ToType2->getAs<ObjCObjectPointerType>();
4037 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4038 // Apply the same conversion ranking rules for Objective-C pointer types
4039 // that we do for C++ pointers to class types. However, we employ the
4040 // Objective-C pseudo-subtyping relationship used for assignment of
4041 // Objective-C pointer types.
4043 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4044 bool FromAssignRight
4045 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4047 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4049 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4051 // A conversion to an a non-id object pointer type or qualified 'id'
4052 // type is better than a conversion to 'id'.
4053 if (ToPtr1->isObjCIdType() &&
4054 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4055 return ImplicitConversionSequence::Worse;
4056 if (ToPtr2->isObjCIdType() &&
4057 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4058 return ImplicitConversionSequence::Better;
4060 // A conversion to a non-id object pointer type is better than a
4061 // conversion to a qualified 'id' type
4062 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4063 return ImplicitConversionSequence::Worse;
4064 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4065 return ImplicitConversionSequence::Better;
4067 // A conversion to an a non-Class object pointer type or qualified 'Class'
4068 // type is better than a conversion to 'Class'.
4069 if (ToPtr1->isObjCClassType() &&
4070 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4071 return ImplicitConversionSequence::Worse;
4072 if (ToPtr2->isObjCClassType() &&
4073 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4074 return ImplicitConversionSequence::Better;
4076 // A conversion to a non-Class object pointer type is better than a
4077 // conversion to a qualified 'Class' type.
4078 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4079 return ImplicitConversionSequence::Worse;
4080 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4081 return ImplicitConversionSequence::Better;
4083 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4084 if (S.Context.hasSameType(FromType1, FromType2) &&
4085 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4086 (ToAssignLeft != ToAssignRight))
4087 return ToAssignLeft? ImplicitConversionSequence::Worse
4088 : ImplicitConversionSequence::Better;
4090 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4091 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4092 (FromAssignLeft != FromAssignRight))
4093 return FromAssignLeft? ImplicitConversionSequence::Better
4094 : ImplicitConversionSequence::Worse;
4098 // Ranking of member-pointer types.
4099 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4100 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4101 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4102 const MemberPointerType * FromMemPointer1 =
4103 FromType1->getAs<MemberPointerType>();
4104 const MemberPointerType * ToMemPointer1 =
4105 ToType1->getAs<MemberPointerType>();
4106 const MemberPointerType * FromMemPointer2 =
4107 FromType2->getAs<MemberPointerType>();
4108 const MemberPointerType * ToMemPointer2 =
4109 ToType2->getAs<MemberPointerType>();
4110 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4111 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4112 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4113 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4114 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4115 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4116 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4117 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4118 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4119 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4120 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4121 return ImplicitConversionSequence::Worse;
4122 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4123 return ImplicitConversionSequence::Better;
4125 // conversion of B::* to C::* is better than conversion of A::* to C::*
4126 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4127 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4128 return ImplicitConversionSequence::Better;
4129 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4130 return ImplicitConversionSequence::Worse;
4134 if (SCS1.Second == ICK_Derived_To_Base) {
4135 // -- conversion of C to B is better than conversion of C to A,
4136 // -- binding of an expression of type C to a reference of type
4137 // B& is better than binding an expression of type C to a
4138 // reference of type A&,
4139 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4140 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4141 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4142 return ImplicitConversionSequence::Better;
4143 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4144 return ImplicitConversionSequence::Worse;
4147 // -- conversion of B to A is better than conversion of C to A.
4148 // -- binding of an expression of type B to a reference of type
4149 // A& is better than binding an expression of type C to a
4150 // reference of type A&,
4151 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4152 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4153 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4154 return ImplicitConversionSequence::Better;
4155 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4156 return ImplicitConversionSequence::Worse;
4160 return ImplicitConversionSequence::Indistinguishable;
4163 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
4165 static bool isTypeValid(QualType T) {
4166 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4167 return !Record->isInvalidDecl();
4172 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4173 /// determine whether they are reference-related,
4174 /// reference-compatible, reference-compatible with added
4175 /// qualification, or incompatible, for use in C++ initialization by
4176 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4177 /// type, and the first type (T1) is the pointee type of the reference
4178 /// type being initialized.
4179 Sema::ReferenceCompareResult
4180 Sema::CompareReferenceRelationship(SourceLocation Loc,
4181 QualType OrigT1, QualType OrigT2,
4182 bool &DerivedToBase,
4183 bool &ObjCConversion,
4184 bool &ObjCLifetimeConversion) {
4185 assert(!OrigT1->isReferenceType() &&
4186 "T1 must be the pointee type of the reference type");
4187 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4189 QualType T1 = Context.getCanonicalType(OrigT1);
4190 QualType T2 = Context.getCanonicalType(OrigT2);
4191 Qualifiers T1Quals, T2Quals;
4192 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4193 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4195 // C++ [dcl.init.ref]p4:
4196 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4197 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4198 // T1 is a base class of T2.
4199 DerivedToBase = false;
4200 ObjCConversion = false;
4201 ObjCLifetimeConversion = false;
4202 QualType ConvertedT2;
4203 if (UnqualT1 == UnqualT2) {
4205 } else if (isCompleteType(Loc, OrigT2) &&
4206 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4207 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4208 DerivedToBase = true;
4209 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4210 UnqualT2->isObjCObjectOrInterfaceType() &&
4211 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4212 ObjCConversion = true;
4213 else if (UnqualT2->isFunctionType() &&
4214 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4215 // C++1z [dcl.init.ref]p4:
4216 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4217 // function" and T1 is "function"
4219 // We extend this to also apply to 'noreturn', so allow any function
4220 // conversion between function types.
4221 return Ref_Compatible;
4223 return Ref_Incompatible;
4225 // At this point, we know that T1 and T2 are reference-related (at
4228 // If the type is an array type, promote the element qualifiers to the type
4230 if (isa<ArrayType>(T1) && T1Quals)
4231 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4232 if (isa<ArrayType>(T2) && T2Quals)
4233 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4235 // C++ [dcl.init.ref]p4:
4236 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4237 // reference-related to T2 and cv1 is the same cv-qualification
4238 // as, or greater cv-qualification than, cv2. For purposes of
4239 // overload resolution, cases for which cv1 is greater
4240 // cv-qualification than cv2 are identified as
4241 // reference-compatible with added qualification (see 13.3.3.2).
4243 // Note that we also require equivalence of Objective-C GC and address-space
4244 // qualifiers when performing these computations, so that e.g., an int in
4245 // address space 1 is not reference-compatible with an int in address
4247 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4248 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4249 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4250 ObjCLifetimeConversion = true;
4252 T1Quals.removeObjCLifetime();
4253 T2Quals.removeObjCLifetime();
4256 // MS compiler ignores __unaligned qualifier for references; do the same.
4257 T1Quals.removeUnaligned();
4258 T2Quals.removeUnaligned();
4260 if (T1Quals.compatiblyIncludes(T2Quals))
4261 return Ref_Compatible;
4266 /// \brief Look for a user-defined conversion to an value reference-compatible
4267 /// with DeclType. Return true if something definite is found.
4269 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4270 QualType DeclType, SourceLocation DeclLoc,
4271 Expr *Init, QualType T2, bool AllowRvalues,
4272 bool AllowExplicit) {
4273 assert(T2->isRecordType() && "Can only find conversions of record types.");
4274 CXXRecordDecl *T2RecordDecl
4275 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4277 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4278 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4279 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4281 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4282 if (isa<UsingShadowDecl>(D))
4283 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4285 FunctionTemplateDecl *ConvTemplate
4286 = dyn_cast<FunctionTemplateDecl>(D);
4287 CXXConversionDecl *Conv;
4289 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4291 Conv = cast<CXXConversionDecl>(D);
4293 // If this is an explicit conversion, and we're not allowed to consider
4294 // explicit conversions, skip it.
4295 if (!AllowExplicit && Conv->isExplicit())
4299 bool DerivedToBase = false;
4300 bool ObjCConversion = false;
4301 bool ObjCLifetimeConversion = false;
4303 // If we are initializing an rvalue reference, don't permit conversion
4304 // functions that return lvalues.
4305 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4306 const ReferenceType *RefType
4307 = Conv->getConversionType()->getAs<LValueReferenceType>();
4308 if (RefType && !RefType->getPointeeType()->isFunctionType())
4312 if (!ConvTemplate &&
4313 S.CompareReferenceRelationship(
4315 Conv->getConversionType().getNonReferenceType()
4316 .getUnqualifiedType(),
4317 DeclType.getNonReferenceType().getUnqualifiedType(),
4318 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4319 Sema::Ref_Incompatible)
4322 // If the conversion function doesn't return a reference type,
4323 // it can't be considered for this conversion. An rvalue reference
4324 // is only acceptable if its referencee is a function type.
4326 const ReferenceType *RefType =
4327 Conv->getConversionType()->getAs<ReferenceType>();
4329 (!RefType->isLValueReferenceType() &&
4330 !RefType->getPointeeType()->isFunctionType()))
4335 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4336 Init, DeclType, CandidateSet,
4337 /*AllowObjCConversionOnExplicit=*/false);
4339 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4340 DeclType, CandidateSet,
4341 /*AllowObjCConversionOnExplicit=*/false);
4344 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4346 OverloadCandidateSet::iterator Best;
4347 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4349 // C++ [over.ics.ref]p1:
4351 // [...] If the parameter binds directly to the result of
4352 // applying a conversion function to the argument
4353 // expression, the implicit conversion sequence is a
4354 // user-defined conversion sequence (13.3.3.1.2), with the
4355 // second standard conversion sequence either an identity
4356 // conversion or, if the conversion function returns an
4357 // entity of a type that is a derived class of the parameter
4358 // type, a derived-to-base Conversion.
4359 if (!Best->FinalConversion.DirectBinding)
4362 ICS.setUserDefined();
4363 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4364 ICS.UserDefined.After = Best->FinalConversion;
4365 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4366 ICS.UserDefined.ConversionFunction = Best->Function;
4367 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4368 ICS.UserDefined.EllipsisConversion = false;
4369 assert(ICS.UserDefined.After.ReferenceBinding &&
4370 ICS.UserDefined.After.DirectBinding &&
4371 "Expected a direct reference binding!");
4376 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4377 Cand != CandidateSet.end(); ++Cand)
4379 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4382 case OR_No_Viable_Function:
4384 // There was no suitable conversion, or we found a deleted
4385 // conversion; continue with other checks.
4389 llvm_unreachable("Invalid OverloadResult!");
4392 /// \brief Compute an implicit conversion sequence for reference
4394 static ImplicitConversionSequence
4395 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4396 SourceLocation DeclLoc,
4397 bool SuppressUserConversions,
4398 bool AllowExplicit) {
4399 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4401 // Most paths end in a failed conversion.
4402 ImplicitConversionSequence ICS;
4403 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4405 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4406 QualType T2 = Init->getType();
4408 // If the initializer is the address of an overloaded function, try
4409 // to resolve the overloaded function. If all goes well, T2 is the
4410 // type of the resulting function.
4411 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4412 DeclAccessPair Found;
4413 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4418 // Compute some basic properties of the types and the initializer.
4419 bool isRValRef = DeclType->isRValueReferenceType();
4420 bool DerivedToBase = false;
4421 bool ObjCConversion = false;
4422 bool ObjCLifetimeConversion = false;
4423 Expr::Classification InitCategory = Init->Classify(S.Context);
4424 Sema::ReferenceCompareResult RefRelationship
4425 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4426 ObjCConversion, ObjCLifetimeConversion);
4429 // C++0x [dcl.init.ref]p5:
4430 // A reference to type "cv1 T1" is initialized by an expression
4431 // of type "cv2 T2" as follows:
4433 // -- If reference is an lvalue reference and the initializer expression
4435 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4436 // reference-compatible with "cv2 T2," or
4438 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4439 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4440 // C++ [over.ics.ref]p1:
4441 // When a parameter of reference type binds directly (8.5.3)
4442 // to an argument expression, the implicit conversion sequence
4443 // is the identity conversion, unless the argument expression
4444 // has a type that is a derived class of the parameter type,
4445 // in which case the implicit conversion sequence is a
4446 // derived-to-base Conversion (13.3.3.1).
4448 ICS.Standard.First = ICK_Identity;
4449 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4450 : ObjCConversion? ICK_Compatible_Conversion
4452 ICS.Standard.Third = ICK_Identity;
4453 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4454 ICS.Standard.setToType(0, T2);
4455 ICS.Standard.setToType(1, T1);
4456 ICS.Standard.setToType(2, T1);
4457 ICS.Standard.ReferenceBinding = true;
4458 ICS.Standard.DirectBinding = true;
4459 ICS.Standard.IsLvalueReference = !isRValRef;
4460 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4461 ICS.Standard.BindsToRvalue = false;
4462 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4463 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4464 ICS.Standard.CopyConstructor = nullptr;
4465 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4467 // Nothing more to do: the inaccessibility/ambiguity check for
4468 // derived-to-base conversions is suppressed when we're
4469 // computing the implicit conversion sequence (C++
4470 // [over.best.ics]p2).
4474 // -- has a class type (i.e., T2 is a class type), where T1 is
4475 // not reference-related to T2, and can be implicitly
4476 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4477 // is reference-compatible with "cv3 T3" 92) (this
4478 // conversion is selected by enumerating the applicable
4479 // conversion functions (13.3.1.6) and choosing the best
4480 // one through overload resolution (13.3)),
4481 if (!SuppressUserConversions && T2->isRecordType() &&
4482 S.isCompleteType(DeclLoc, T2) &&
4483 RefRelationship == Sema::Ref_Incompatible) {
4484 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4485 Init, T2, /*AllowRvalues=*/false,
4491 // -- Otherwise, the reference shall be an lvalue reference to a
4492 // non-volatile const type (i.e., cv1 shall be const), or the reference
4493 // shall be an rvalue reference.
4494 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4497 // -- If the initializer expression
4499 // -- is an xvalue, class prvalue, array prvalue or function
4500 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4501 if (RefRelationship == Sema::Ref_Compatible &&
4502 (InitCategory.isXValue() ||
4503 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4504 (InitCategory.isLValue() && T2->isFunctionType()))) {
4506 ICS.Standard.First = ICK_Identity;
4507 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4508 : ObjCConversion? ICK_Compatible_Conversion
4510 ICS.Standard.Third = ICK_Identity;
4511 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4512 ICS.Standard.setToType(0, T2);
4513 ICS.Standard.setToType(1, T1);
4514 ICS.Standard.setToType(2, T1);
4515 ICS.Standard.ReferenceBinding = true;
4516 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4517 // binding unless we're binding to a class prvalue.
4518 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4519 // allow the use of rvalue references in C++98/03 for the benefit of
4520 // standard library implementors; therefore, we need the xvalue check here.
4521 ICS.Standard.DirectBinding =
4522 S.getLangOpts().CPlusPlus11 ||
4523 !(InitCategory.isPRValue() || T2->isRecordType());
4524 ICS.Standard.IsLvalueReference = !isRValRef;
4525 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4526 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4527 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4528 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4529 ICS.Standard.CopyConstructor = nullptr;
4530 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4534 // -- has a class type (i.e., T2 is a class type), where T1 is not
4535 // reference-related to T2, and can be implicitly converted to
4536 // an xvalue, class prvalue, or function lvalue of type
4537 // "cv3 T3", where "cv1 T1" is reference-compatible with
4540 // then the reference is bound to the value of the initializer
4541 // expression in the first case and to the result of the conversion
4542 // in the second case (or, in either case, to an appropriate base
4543 // class subobject).
4544 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4545 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4546 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4547 Init, T2, /*AllowRvalues=*/true,
4549 // In the second case, if the reference is an rvalue reference
4550 // and the second standard conversion sequence of the
4551 // user-defined conversion sequence includes an lvalue-to-rvalue
4552 // conversion, the program is ill-formed.
4553 if (ICS.isUserDefined() && isRValRef &&
4554 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4555 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4560 // A temporary of function type cannot be created; don't even try.
4561 if (T1->isFunctionType())
4564 // -- Otherwise, a temporary of type "cv1 T1" is created and
4565 // initialized from the initializer expression using the
4566 // rules for a non-reference copy initialization (8.5). The
4567 // reference is then bound to the temporary. If T1 is
4568 // reference-related to T2, cv1 must be the same
4569 // cv-qualification as, or greater cv-qualification than,
4570 // cv2; otherwise, the program is ill-formed.
4571 if (RefRelationship == Sema::Ref_Related) {
4572 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4573 // we would be reference-compatible or reference-compatible with
4574 // added qualification. But that wasn't the case, so the reference
4575 // initialization fails.
4577 // Note that we only want to check address spaces and cvr-qualifiers here.
4578 // ObjC GC, lifetime and unaligned qualifiers aren't important.
4579 Qualifiers T1Quals = T1.getQualifiers();
4580 Qualifiers T2Quals = T2.getQualifiers();
4581 T1Quals.removeObjCGCAttr();
4582 T1Quals.removeObjCLifetime();
4583 T2Quals.removeObjCGCAttr();
4584 T2Quals.removeObjCLifetime();
4585 // MS compiler ignores __unaligned qualifier for references; do the same.
4586 T1Quals.removeUnaligned();
4587 T2Quals.removeUnaligned();
4588 if (!T1Quals.compatiblyIncludes(T2Quals))
4592 // If at least one of the types is a class type, the types are not
4593 // related, and we aren't allowed any user conversions, the
4594 // reference binding fails. This case is important for breaking
4595 // recursion, since TryImplicitConversion below will attempt to
4596 // create a temporary through the use of a copy constructor.
4597 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4598 (T1->isRecordType() || T2->isRecordType()))
4601 // If T1 is reference-related to T2 and the reference is an rvalue
4602 // reference, the initializer expression shall not be an lvalue.
4603 if (RefRelationship >= Sema::Ref_Related &&
4604 isRValRef && Init->Classify(S.Context).isLValue())
4607 // C++ [over.ics.ref]p2:
4608 // When a parameter of reference type is not bound directly to
4609 // an argument expression, the conversion sequence is the one
4610 // required to convert the argument expression to the
4611 // underlying type of the reference according to
4612 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4613 // to copy-initializing a temporary of the underlying type with
4614 // the argument expression. Any difference in top-level
4615 // cv-qualification is subsumed by the initialization itself
4616 // and does not constitute a conversion.
4617 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4618 /*AllowExplicit=*/false,
4619 /*InOverloadResolution=*/false,
4621 /*AllowObjCWritebackConversion=*/false,
4622 /*AllowObjCConversionOnExplicit=*/false);
4624 // Of course, that's still a reference binding.
4625 if (ICS.isStandard()) {
4626 ICS.Standard.ReferenceBinding = true;
4627 ICS.Standard.IsLvalueReference = !isRValRef;
4628 ICS.Standard.BindsToFunctionLvalue = false;
4629 ICS.Standard.BindsToRvalue = true;
4630 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4631 ICS.Standard.ObjCLifetimeConversionBinding = false;
4632 } else if (ICS.isUserDefined()) {
4633 const ReferenceType *LValRefType =
4634 ICS.UserDefined.ConversionFunction->getReturnType()
4635 ->getAs<LValueReferenceType>();
4637 // C++ [over.ics.ref]p3:
4638 // Except for an implicit object parameter, for which see 13.3.1, a
4639 // standard conversion sequence cannot be formed if it requires [...]
4640 // binding an rvalue reference to an lvalue other than a function
4642 // Note that the function case is not possible here.
4643 if (DeclType->isRValueReferenceType() && LValRefType) {
4644 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4645 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4646 // reference to an rvalue!
4647 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4651 ICS.UserDefined.After.ReferenceBinding = true;
4652 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4653 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4654 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4655 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4656 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4662 static ImplicitConversionSequence
4663 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4664 bool SuppressUserConversions,
4665 bool InOverloadResolution,
4666 bool AllowObjCWritebackConversion,
4667 bool AllowExplicit = false);
4669 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4670 /// initializer list From.
4671 static ImplicitConversionSequence
4672 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4673 bool SuppressUserConversions,
4674 bool InOverloadResolution,
4675 bool AllowObjCWritebackConversion) {
4676 // C++11 [over.ics.list]p1:
4677 // When an argument is an initializer list, it is not an expression and
4678 // special rules apply for converting it to a parameter type.
4680 ImplicitConversionSequence Result;
4681 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4683 // We need a complete type for what follows. Incomplete types can never be
4684 // initialized from init lists.
4685 if (!S.isCompleteType(From->getLocStart(), ToType))
4689 // If the parameter type is a class X and the initializer list has a single
4690 // element of type cv U, where U is X or a class derived from X, the
4691 // implicit conversion sequence is the one required to convert the element
4692 // to the parameter type.
4694 // Otherwise, if the parameter type is a character array [... ]
4695 // and the initializer list has a single element that is an
4696 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4697 // implicit conversion sequence is the identity conversion.
4698 if (From->getNumInits() == 1) {
4699 if (ToType->isRecordType()) {
4700 QualType InitType = From->getInit(0)->getType();
4701 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4702 S.IsDerivedFrom(From->getLocStart(), InitType, ToType))
4703 return TryCopyInitialization(S, From->getInit(0), ToType,
4704 SuppressUserConversions,
4705 InOverloadResolution,
4706 AllowObjCWritebackConversion);
4708 // FIXME: Check the other conditions here: array of character type,
4709 // initializer is a string literal.
4710 if (ToType->isArrayType()) {
4711 InitializedEntity Entity =
4712 InitializedEntity::InitializeParameter(S.Context, ToType,
4713 /*Consumed=*/false);
4714 if (S.CanPerformCopyInitialization(Entity, From)) {
4715 Result.setStandard();
4716 Result.Standard.setAsIdentityConversion();
4717 Result.Standard.setFromType(ToType);
4718 Result.Standard.setAllToTypes(ToType);
4724 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4725 // C++11 [over.ics.list]p2:
4726 // If the parameter type is std::initializer_list<X> or "array of X" and
4727 // all the elements can be implicitly converted to X, the implicit
4728 // conversion sequence is the worst conversion necessary to convert an
4729 // element of the list to X.
4731 // C++14 [over.ics.list]p3:
4732 // Otherwise, if the parameter type is "array of N X", if the initializer
4733 // list has exactly N elements or if it has fewer than N elements and X is
4734 // default-constructible, and if all the elements of the initializer list
4735 // can be implicitly converted to X, the implicit conversion sequence is
4736 // the worst conversion necessary to convert an element of the list to X.
4738 // FIXME: We're missing a lot of these checks.
4739 bool toStdInitializerList = false;
4741 if (ToType->isArrayType())
4742 X = S.Context.getAsArrayType(ToType)->getElementType();
4744 toStdInitializerList = S.isStdInitializerList(ToType, &X);
4746 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4747 Expr *Init = From->getInit(i);
4748 ImplicitConversionSequence ICS =
4749 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4750 InOverloadResolution,
4751 AllowObjCWritebackConversion);
4752 // If a single element isn't convertible, fail.
4757 // Otherwise, look for the worst conversion.
4758 if (Result.isBad() ||
4759 CompareImplicitConversionSequences(S, From->getLocStart(), ICS,
4761 ImplicitConversionSequence::Worse)
4765 // For an empty list, we won't have computed any conversion sequence.
4766 // Introduce the identity conversion sequence.
4767 if (From->getNumInits() == 0) {
4768 Result.setStandard();
4769 Result.Standard.setAsIdentityConversion();
4770 Result.Standard.setFromType(ToType);
4771 Result.Standard.setAllToTypes(ToType);
4774 Result.setStdInitializerListElement(toStdInitializerList);
4778 // C++14 [over.ics.list]p4:
4779 // C++11 [over.ics.list]p3:
4780 // Otherwise, if the parameter is a non-aggregate class X and overload
4781 // resolution chooses a single best constructor [...] the implicit
4782 // conversion sequence is a user-defined conversion sequence. If multiple
4783 // constructors are viable but none is better than the others, the
4784 // implicit conversion sequence is a user-defined conversion sequence.
4785 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4786 // This function can deal with initializer lists.
4787 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4788 /*AllowExplicit=*/false,
4789 InOverloadResolution, /*CStyle=*/false,
4790 AllowObjCWritebackConversion,
4791 /*AllowObjCConversionOnExplicit=*/false);
4794 // C++14 [over.ics.list]p5:
4795 // C++11 [over.ics.list]p4:
4796 // Otherwise, if the parameter has an aggregate type which can be
4797 // initialized from the initializer list [...] the implicit conversion
4798 // sequence is a user-defined conversion sequence.
4799 if (ToType->isAggregateType()) {
4800 // Type is an aggregate, argument is an init list. At this point it comes
4801 // down to checking whether the initialization works.
4802 // FIXME: Find out whether this parameter is consumed or not.
4803 // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4804 // need to call into the initialization code here; overload resolution
4805 // should not be doing that.
4806 InitializedEntity Entity =
4807 InitializedEntity::InitializeParameter(S.Context, ToType,
4808 /*Consumed=*/false);
4809 if (S.CanPerformCopyInitialization(Entity, From)) {
4810 Result.setUserDefined();
4811 Result.UserDefined.Before.setAsIdentityConversion();
4812 // Initializer lists don't have a type.
4813 Result.UserDefined.Before.setFromType(QualType());
4814 Result.UserDefined.Before.setAllToTypes(QualType());
4816 Result.UserDefined.After.setAsIdentityConversion();
4817 Result.UserDefined.After.setFromType(ToType);
4818 Result.UserDefined.After.setAllToTypes(ToType);
4819 Result.UserDefined.ConversionFunction = nullptr;
4824 // C++14 [over.ics.list]p6:
4825 // C++11 [over.ics.list]p5:
4826 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4827 if (ToType->isReferenceType()) {
4828 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4829 // mention initializer lists in any way. So we go by what list-
4830 // initialization would do and try to extrapolate from that.
4832 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4834 // If the initializer list has a single element that is reference-related
4835 // to the parameter type, we initialize the reference from that.
4836 if (From->getNumInits() == 1) {
4837 Expr *Init = From->getInit(0);
4839 QualType T2 = Init->getType();
4841 // If the initializer is the address of an overloaded function, try
4842 // to resolve the overloaded function. If all goes well, T2 is the
4843 // type of the resulting function.
4844 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4845 DeclAccessPair Found;
4846 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4847 Init, ToType, false, Found))
4851 // Compute some basic properties of the types and the initializer.
4852 bool dummy1 = false;
4853 bool dummy2 = false;
4854 bool dummy3 = false;
4855 Sema::ReferenceCompareResult RefRelationship
4856 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4859 if (RefRelationship >= Sema::Ref_Related) {
4860 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4861 SuppressUserConversions,
4862 /*AllowExplicit=*/false);
4866 // Otherwise, we bind the reference to a temporary created from the
4867 // initializer list.
4868 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4869 InOverloadResolution,
4870 AllowObjCWritebackConversion);
4871 if (Result.isFailure())
4873 assert(!Result.isEllipsis() &&
4874 "Sub-initialization cannot result in ellipsis conversion.");
4876 // Can we even bind to a temporary?
4877 if (ToType->isRValueReferenceType() ||
4878 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4879 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4880 Result.UserDefined.After;
4881 SCS.ReferenceBinding = true;
4882 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4883 SCS.BindsToRvalue = true;
4884 SCS.BindsToFunctionLvalue = false;
4885 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4886 SCS.ObjCLifetimeConversionBinding = false;
4888 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4893 // C++14 [over.ics.list]p7:
4894 // C++11 [over.ics.list]p6:
4895 // Otherwise, if the parameter type is not a class:
4896 if (!ToType->isRecordType()) {
4897 // - if the initializer list has one element that is not itself an
4898 // initializer list, the implicit conversion sequence is the one
4899 // required to convert the element to the parameter type.
4900 unsigned NumInits = From->getNumInits();
4901 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
4902 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4903 SuppressUserConversions,
4904 InOverloadResolution,
4905 AllowObjCWritebackConversion);
4906 // - if the initializer list has no elements, the implicit conversion
4907 // sequence is the identity conversion.
4908 else if (NumInits == 0) {
4909 Result.setStandard();
4910 Result.Standard.setAsIdentityConversion();
4911 Result.Standard.setFromType(ToType);
4912 Result.Standard.setAllToTypes(ToType);
4917 // C++14 [over.ics.list]p8:
4918 // C++11 [over.ics.list]p7:
4919 // In all cases other than those enumerated above, no conversion is possible
4923 /// TryCopyInitialization - Try to copy-initialize a value of type
4924 /// ToType from the expression From. Return the implicit conversion
4925 /// sequence required to pass this argument, which may be a bad
4926 /// conversion sequence (meaning that the argument cannot be passed to
4927 /// a parameter of this type). If @p SuppressUserConversions, then we
4928 /// do not permit any user-defined conversion sequences.
4929 static ImplicitConversionSequence
4930 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4931 bool SuppressUserConversions,
4932 bool InOverloadResolution,
4933 bool AllowObjCWritebackConversion,
4934 bool AllowExplicit) {
4935 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4936 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4937 InOverloadResolution,AllowObjCWritebackConversion);
4939 if (ToType->isReferenceType())
4940 return TryReferenceInit(S, From, ToType,
4941 /*FIXME:*/From->getLocStart(),
4942 SuppressUserConversions,
4945 return TryImplicitConversion(S, From, ToType,
4946 SuppressUserConversions,
4947 /*AllowExplicit=*/false,
4948 InOverloadResolution,
4950 AllowObjCWritebackConversion,
4951 /*AllowObjCConversionOnExplicit=*/false);
4954 static bool TryCopyInitialization(const CanQualType FromQTy,
4955 const CanQualType ToQTy,
4958 ExprValueKind FromVK) {
4959 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4960 ImplicitConversionSequence ICS =
4961 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4963 return !ICS.isBad();
4966 /// TryObjectArgumentInitialization - Try to initialize the object
4967 /// parameter of the given member function (@c Method) from the
4968 /// expression @p From.
4969 static ImplicitConversionSequence
4970 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
4971 Expr::Classification FromClassification,
4972 CXXMethodDecl *Method,
4973 CXXRecordDecl *ActingContext) {
4974 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4975 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4976 // const volatile object.
4977 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4978 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4979 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
4981 // Set up the conversion sequence as a "bad" conversion, to allow us
4983 ImplicitConversionSequence ICS;
4985 // We need to have an object of class type.
4986 if (const PointerType *PT = FromType->getAs<PointerType>()) {
4987 FromType = PT->getPointeeType();
4989 // When we had a pointer, it's implicitly dereferenced, so we
4990 // better have an lvalue.
4991 assert(FromClassification.isLValue());
4994 assert(FromType->isRecordType());
4996 // C++0x [over.match.funcs]p4:
4997 // For non-static member functions, the type of the implicit object
5000 // - "lvalue reference to cv X" for functions declared without a
5001 // ref-qualifier or with the & ref-qualifier
5002 // - "rvalue reference to cv X" for functions declared with the &&
5005 // where X is the class of which the function is a member and cv is the
5006 // cv-qualification on the member function declaration.
5008 // However, when finding an implicit conversion sequence for the argument, we
5009 // are not allowed to perform user-defined conversions
5010 // (C++ [over.match.funcs]p5). We perform a simplified version of
5011 // reference binding here, that allows class rvalues to bind to
5012 // non-constant references.
5014 // First check the qualifiers.
5015 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5016 if (ImplicitParamType.getCVRQualifiers()
5017 != FromTypeCanon.getLocalCVRQualifiers() &&
5018 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5019 ICS.setBad(BadConversionSequence::bad_qualifiers,
5020 FromType, ImplicitParamType);
5024 // Check that we have either the same type or a derived type. It
5025 // affects the conversion rank.
5026 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5027 ImplicitConversionKind SecondKind;
5028 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5029 SecondKind = ICK_Identity;
5030 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5031 SecondKind = ICK_Derived_To_Base;
5033 ICS.setBad(BadConversionSequence::unrelated_class,
5034 FromType, ImplicitParamType);
5038 // Check the ref-qualifier.
5039 switch (Method->getRefQualifier()) {
5041 // Do nothing; we don't care about lvalueness or rvalueness.
5045 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
5046 // non-const lvalue reference cannot bind to an rvalue
5047 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5054 if (!FromClassification.isRValue()) {
5055 // rvalue reference cannot bind to an lvalue
5056 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5063 // Success. Mark this as a reference binding.
5065 ICS.Standard.setAsIdentityConversion();
5066 ICS.Standard.Second = SecondKind;
5067 ICS.Standard.setFromType(FromType);
5068 ICS.Standard.setAllToTypes(ImplicitParamType);
5069 ICS.Standard.ReferenceBinding = true;
5070 ICS.Standard.DirectBinding = true;
5071 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5072 ICS.Standard.BindsToFunctionLvalue = false;
5073 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5074 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5075 = (Method->getRefQualifier() == RQ_None);
5079 /// PerformObjectArgumentInitialization - Perform initialization of
5080 /// the implicit object parameter for the given Method with the given
5083 Sema::PerformObjectArgumentInitialization(Expr *From,
5084 NestedNameSpecifier *Qualifier,
5085 NamedDecl *FoundDecl,
5086 CXXMethodDecl *Method) {
5087 QualType FromRecordType, DestType;
5088 QualType ImplicitParamRecordType =
5089 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
5091 Expr::Classification FromClassification;
5092 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5093 FromRecordType = PT->getPointeeType();
5094 DestType = Method->getThisType(Context);
5095 FromClassification = Expr::Classification::makeSimpleLValue();
5097 FromRecordType = From->getType();
5098 DestType = ImplicitParamRecordType;
5099 FromClassification = From->Classify(Context);
5102 // Note that we always use the true parent context when performing
5103 // the actual argument initialization.
5104 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5105 *this, From->getLocStart(), From->getType(), FromClassification, Method,
5106 Method->getParent());
5108 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
5109 Qualifiers FromQs = FromRecordType.getQualifiers();
5110 Qualifiers ToQs = DestType.getQualifiers();
5111 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5113 Diag(From->getLocStart(),
5114 diag::err_member_function_call_bad_cvr)
5115 << Method->getDeclName() << FromRecordType << (CVR - 1)
5116 << From->getSourceRange();
5117 Diag(Method->getLocation(), diag::note_previous_decl)
5118 << Method->getDeclName();
5123 return Diag(From->getLocStart(),
5124 diag::err_implicit_object_parameter_init)
5125 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
5128 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5129 ExprResult FromRes =
5130 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5131 if (FromRes.isInvalid())
5133 From = FromRes.get();
5136 if (!Context.hasSameType(From->getType(), DestType))
5137 From = ImpCastExprToType(From, DestType, CK_NoOp,
5138 From->getValueKind()).get();
5142 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5143 /// expression From to bool (C++0x [conv]p3).
5144 static ImplicitConversionSequence
5145 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5146 return TryImplicitConversion(S, From, S.Context.BoolTy,
5147 /*SuppressUserConversions=*/false,
5148 /*AllowExplicit=*/true,
5149 /*InOverloadResolution=*/false,
5151 /*AllowObjCWritebackConversion=*/false,
5152 /*AllowObjCConversionOnExplicit=*/false);
5155 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5156 /// of the expression From to bool (C++0x [conv]p3).
5157 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5158 if (checkPlaceholderForOverload(*this, From))
5161 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5163 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5165 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5166 return Diag(From->getLocStart(),
5167 diag::err_typecheck_bool_condition)
5168 << From->getType() << From->getSourceRange();
5172 /// Check that the specified conversion is permitted in a converted constant
5173 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5175 static bool CheckConvertedConstantConversions(Sema &S,
5176 StandardConversionSequence &SCS) {
5177 // Since we know that the target type is an integral or unscoped enumeration
5178 // type, most conversion kinds are impossible. All possible First and Third
5179 // conversions are fine.
5180 switch (SCS.Second) {
5182 case ICK_Function_Conversion:
5183 case ICK_Integral_Promotion:
5184 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5185 case ICK_Zero_Queue_Conversion:
5188 case ICK_Boolean_Conversion:
5189 // Conversion from an integral or unscoped enumeration type to bool is
5190 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5191 // conversion, so we allow it in a converted constant expression.
5193 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5194 // a lot of popular code. We should at least add a warning for this
5195 // (non-conforming) extension.
5196 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5197 SCS.getToType(2)->isBooleanType();
5199 case ICK_Pointer_Conversion:
5200 case ICK_Pointer_Member:
5201 // C++1z: null pointer conversions and null member pointer conversions are
5202 // only permitted if the source type is std::nullptr_t.
5203 return SCS.getFromType()->isNullPtrType();
5205 case ICK_Floating_Promotion:
5206 case ICK_Complex_Promotion:
5207 case ICK_Floating_Conversion:
5208 case ICK_Complex_Conversion:
5209 case ICK_Floating_Integral:
5210 case ICK_Compatible_Conversion:
5211 case ICK_Derived_To_Base:
5212 case ICK_Vector_Conversion:
5213 case ICK_Vector_Splat:
5214 case ICK_Complex_Real:
5215 case ICK_Block_Pointer_Conversion:
5216 case ICK_TransparentUnionConversion:
5217 case ICK_Writeback_Conversion:
5218 case ICK_Zero_Event_Conversion:
5219 case ICK_C_Only_Conversion:
5220 case ICK_Incompatible_Pointer_Conversion:
5223 case ICK_Lvalue_To_Rvalue:
5224 case ICK_Array_To_Pointer:
5225 case ICK_Function_To_Pointer:
5226 llvm_unreachable("found a first conversion kind in Second");
5228 case ICK_Qualification:
5229 llvm_unreachable("found a third conversion kind in Second");
5231 case ICK_Num_Conversion_Kinds:
5235 llvm_unreachable("unknown conversion kind");
5238 /// CheckConvertedConstantExpression - Check that the expression From is a
5239 /// converted constant expression of type T, perform the conversion and produce
5240 /// the converted expression, per C++11 [expr.const]p3.
5241 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5242 QualType T, APValue &Value,
5245 assert(S.getLangOpts().CPlusPlus11 &&
5246 "converted constant expression outside C++11");
5248 if (checkPlaceholderForOverload(S, From))
5251 // C++1z [expr.const]p3:
5252 // A converted constant expression of type T is an expression,
5253 // implicitly converted to type T, where the converted
5254 // expression is a constant expression and the implicit conversion
5255 // sequence contains only [... list of conversions ...].
5256 // C++1z [stmt.if]p2:
5257 // If the if statement is of the form if constexpr, the value of the
5258 // condition shall be a contextually converted constant expression of type
5260 ImplicitConversionSequence ICS =
5261 CCE == Sema::CCEK_ConstexprIf
5262 ? TryContextuallyConvertToBool(S, From)
5263 : TryCopyInitialization(S, From, T,
5264 /*SuppressUserConversions=*/false,
5265 /*InOverloadResolution=*/false,
5266 /*AllowObjcWritebackConversion=*/false,
5267 /*AllowExplicit=*/false);
5268 StandardConversionSequence *SCS = nullptr;
5269 switch (ICS.getKind()) {
5270 case ImplicitConversionSequence::StandardConversion:
5271 SCS = &ICS.Standard;
5273 case ImplicitConversionSequence::UserDefinedConversion:
5274 // We are converting to a non-class type, so the Before sequence
5276 SCS = &ICS.UserDefined.After;
5278 case ImplicitConversionSequence::AmbiguousConversion:
5279 case ImplicitConversionSequence::BadConversion:
5280 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5281 return S.Diag(From->getLocStart(),
5282 diag::err_typecheck_converted_constant_expression)
5283 << From->getType() << From->getSourceRange() << T;
5286 case ImplicitConversionSequence::EllipsisConversion:
5287 llvm_unreachable("ellipsis conversion in converted constant expression");
5290 // Check that we would only use permitted conversions.
5291 if (!CheckConvertedConstantConversions(S, *SCS)) {
5292 return S.Diag(From->getLocStart(),
5293 diag::err_typecheck_converted_constant_expression_disallowed)
5294 << From->getType() << From->getSourceRange() << T;
5296 // [...] and where the reference binding (if any) binds directly.
5297 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5298 return S.Diag(From->getLocStart(),
5299 diag::err_typecheck_converted_constant_expression_indirect)
5300 << From->getType() << From->getSourceRange() << T;
5304 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5305 if (Result.isInvalid())
5308 // Check for a narrowing implicit conversion.
5309 APValue PreNarrowingValue;
5310 QualType PreNarrowingType;
5311 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5312 PreNarrowingType)) {
5313 case NK_Dependent_Narrowing:
5314 // Implicit conversion to a narrower type, but the expression is
5315 // value-dependent so we can't tell whether it's actually narrowing.
5316 case NK_Variable_Narrowing:
5317 // Implicit conversion to a narrower type, and the value is not a constant
5318 // expression. We'll diagnose this in a moment.
5319 case NK_Not_Narrowing:
5322 case NK_Constant_Narrowing:
5323 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5324 << CCE << /*Constant*/1
5325 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5328 case NK_Type_Narrowing:
5329 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
5330 << CCE << /*Constant*/0 << From->getType() << T;
5334 if (Result.get()->isValueDependent()) {
5339 // Check the expression is a constant expression.
5340 SmallVector<PartialDiagnosticAt, 8> Notes;
5341 Expr::EvalResult Eval;
5344 if ((T->isReferenceType()
5345 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5346 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5347 (RequireInt && !Eval.Val.isInt())) {
5348 // The expression can't be folded, so we can't keep it at this position in
5350 Result = ExprError();
5354 if (Notes.empty()) {
5355 // It's a constant expression.
5360 // It's not a constant expression. Produce an appropriate diagnostic.
5361 if (Notes.size() == 1 &&
5362 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5363 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5365 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
5366 << CCE << From->getSourceRange();
5367 for (unsigned I = 0; I < Notes.size(); ++I)
5368 S.Diag(Notes[I].first, Notes[I].second);
5373 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5374 APValue &Value, CCEKind CCE) {
5375 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5378 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5379 llvm::APSInt &Value,
5381 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5384 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5385 if (!R.isInvalid() && !R.get()->isValueDependent())
5391 /// dropPointerConversions - If the given standard conversion sequence
5392 /// involves any pointer conversions, remove them. This may change
5393 /// the result type of the conversion sequence.
5394 static void dropPointerConversion(StandardConversionSequence &SCS) {
5395 if (SCS.Second == ICK_Pointer_Conversion) {
5396 SCS.Second = ICK_Identity;
5397 SCS.Third = ICK_Identity;
5398 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5402 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5403 /// convert the expression From to an Objective-C pointer type.
5404 static ImplicitConversionSequence
5405 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5406 // Do an implicit conversion to 'id'.
5407 QualType Ty = S.Context.getObjCIdType();
5408 ImplicitConversionSequence ICS
5409 = TryImplicitConversion(S, From, Ty,
5410 // FIXME: Are these flags correct?
5411 /*SuppressUserConversions=*/false,
5412 /*AllowExplicit=*/true,
5413 /*InOverloadResolution=*/false,
5415 /*AllowObjCWritebackConversion=*/false,
5416 /*AllowObjCConversionOnExplicit=*/true);
5418 // Strip off any final conversions to 'id'.
5419 switch (ICS.getKind()) {
5420 case ImplicitConversionSequence::BadConversion:
5421 case ImplicitConversionSequence::AmbiguousConversion:
5422 case ImplicitConversionSequence::EllipsisConversion:
5425 case ImplicitConversionSequence::UserDefinedConversion:
5426 dropPointerConversion(ICS.UserDefined.After);
5429 case ImplicitConversionSequence::StandardConversion:
5430 dropPointerConversion(ICS.Standard);
5437 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5438 /// conversion of the expression From to an Objective-C pointer type.
5439 /// Returns a valid but null ExprResult if no conversion sequence exists.
5440 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5441 if (checkPlaceholderForOverload(*this, From))
5444 QualType Ty = Context.getObjCIdType();
5445 ImplicitConversionSequence ICS =
5446 TryContextuallyConvertToObjCPointer(*this, From);
5448 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5449 return ExprResult();
5452 /// Determine whether the provided type is an integral type, or an enumeration
5453 /// type of a permitted flavor.
5454 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5455 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5456 : T->isIntegralOrUnscopedEnumerationType();
5460 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5461 Sema::ContextualImplicitConverter &Converter,
5462 QualType T, UnresolvedSetImpl &ViableConversions) {
5464 if (Converter.Suppress)
5467 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5468 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5469 CXXConversionDecl *Conv =
5470 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5471 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5472 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5478 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5479 Sema::ContextualImplicitConverter &Converter,
5480 QualType T, bool HadMultipleCandidates,
5481 UnresolvedSetImpl &ExplicitConversions) {
5482 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5483 DeclAccessPair Found = ExplicitConversions[0];
5484 CXXConversionDecl *Conversion =
5485 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5487 // The user probably meant to invoke the given explicit
5488 // conversion; use it.
5489 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5490 std::string TypeStr;
5491 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5493 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5494 << FixItHint::CreateInsertion(From->getLocStart(),
5495 "static_cast<" + TypeStr + ">(")
5496 << FixItHint::CreateInsertion(
5497 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5498 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5500 // If we aren't in a SFINAE context, build a call to the
5501 // explicit conversion function.
5502 if (SemaRef.isSFINAEContext())
5505 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5506 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5507 HadMultipleCandidates);
5508 if (Result.isInvalid())
5510 // Record usage of conversion in an implicit cast.
5511 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5512 CK_UserDefinedConversion, Result.get(),
5513 nullptr, Result.get()->getValueKind());
5518 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5519 Sema::ContextualImplicitConverter &Converter,
5520 QualType T, bool HadMultipleCandidates,
5521 DeclAccessPair &Found) {
5522 CXXConversionDecl *Conversion =
5523 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5524 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5526 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5527 if (!Converter.SuppressConversion) {
5528 if (SemaRef.isSFINAEContext())
5531 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5532 << From->getSourceRange();
5535 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5536 HadMultipleCandidates);
5537 if (Result.isInvalid())
5539 // Record usage of conversion in an implicit cast.
5540 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5541 CK_UserDefinedConversion, Result.get(),
5542 nullptr, Result.get()->getValueKind());
5546 static ExprResult finishContextualImplicitConversion(
5547 Sema &SemaRef, SourceLocation Loc, Expr *From,
5548 Sema::ContextualImplicitConverter &Converter) {
5549 if (!Converter.match(From->getType()) && !Converter.Suppress)
5550 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5551 << From->getSourceRange();
5553 return SemaRef.DefaultLvalueConversion(From);
5557 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5558 UnresolvedSetImpl &ViableConversions,
5559 OverloadCandidateSet &CandidateSet) {
5560 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5561 DeclAccessPair FoundDecl = ViableConversions[I];
5562 NamedDecl *D = FoundDecl.getDecl();
5563 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5564 if (isa<UsingShadowDecl>(D))
5565 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5567 CXXConversionDecl *Conv;
5568 FunctionTemplateDecl *ConvTemplate;
5569 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5570 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5572 Conv = cast<CXXConversionDecl>(D);
5575 SemaRef.AddTemplateConversionCandidate(
5576 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5577 /*AllowObjCConversionOnExplicit=*/false);
5579 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5580 ToType, CandidateSet,
5581 /*AllowObjCConversionOnExplicit=*/false);
5585 /// \brief Attempt to convert the given expression to a type which is accepted
5586 /// by the given converter.
5588 /// This routine will attempt to convert an expression of class type to a
5589 /// type accepted by the specified converter. In C++11 and before, the class
5590 /// must have a single non-explicit conversion function converting to a matching
5591 /// type. In C++1y, there can be multiple such conversion functions, but only
5592 /// one target type.
5594 /// \param Loc The source location of the construct that requires the
5597 /// \param From The expression we're converting from.
5599 /// \param Converter Used to control and diagnose the conversion process.
5601 /// \returns The expression, converted to an integral or enumeration type if
5603 ExprResult Sema::PerformContextualImplicitConversion(
5604 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5605 // We can't perform any more checking for type-dependent expressions.
5606 if (From->isTypeDependent())
5609 // Process placeholders immediately.
5610 if (From->hasPlaceholderType()) {
5611 ExprResult result = CheckPlaceholderExpr(From);
5612 if (result.isInvalid())
5614 From = result.get();
5617 // If the expression already has a matching type, we're golden.
5618 QualType T = From->getType();
5619 if (Converter.match(T))
5620 return DefaultLvalueConversion(From);
5622 // FIXME: Check for missing '()' if T is a function type?
5624 // We can only perform contextual implicit conversions on objects of class
5626 const RecordType *RecordTy = T->getAs<RecordType>();
5627 if (!RecordTy || !getLangOpts().CPlusPlus) {
5628 if (!Converter.Suppress)
5629 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5633 // We must have a complete class type.
5634 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5635 ContextualImplicitConverter &Converter;
5638 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5639 : Converter(Converter), From(From) {}
5641 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5642 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5644 } IncompleteDiagnoser(Converter, From);
5646 if (Converter.Suppress ? !isCompleteType(Loc, T)
5647 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5650 // Look for a conversion to an integral or enumeration type.
5652 ViableConversions; // These are *potentially* viable in C++1y.
5653 UnresolvedSet<4> ExplicitConversions;
5654 const auto &Conversions =
5655 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5657 bool HadMultipleCandidates =
5658 (std::distance(Conversions.begin(), Conversions.end()) > 1);
5660 // To check that there is only one target type, in C++1y:
5662 bool HasUniqueTargetType = true;
5664 // Collect explicit or viable (potentially in C++1y) conversions.
5665 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5666 NamedDecl *D = (*I)->getUnderlyingDecl();
5667 CXXConversionDecl *Conversion;
5668 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5670 if (getLangOpts().CPlusPlus14)
5671 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5673 continue; // C++11 does not consider conversion operator templates(?).
5675 Conversion = cast<CXXConversionDecl>(D);
5677 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5678 "Conversion operator templates are considered potentially "
5681 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5682 if (Converter.match(CurToType) || ConvTemplate) {
5684 if (Conversion->isExplicit()) {
5685 // FIXME: For C++1y, do we need this restriction?
5686 // cf. diagnoseNoViableConversion()
5688 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5690 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5691 if (ToType.isNull())
5692 ToType = CurToType.getUnqualifiedType();
5693 else if (HasUniqueTargetType &&
5694 (CurToType.getUnqualifiedType() != ToType))
5695 HasUniqueTargetType = false;
5697 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5702 if (getLangOpts().CPlusPlus14) {
5704 // ... An expression e of class type E appearing in such a context
5705 // is said to be contextually implicitly converted to a specified
5706 // type T and is well-formed if and only if e can be implicitly
5707 // converted to a type T that is determined as follows: E is searched
5708 // for conversion functions whose return type is cv T or reference to
5709 // cv T such that T is allowed by the context. There shall be
5710 // exactly one such T.
5712 // If no unique T is found:
5713 if (ToType.isNull()) {
5714 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5715 HadMultipleCandidates,
5716 ExplicitConversions))
5718 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5721 // If more than one unique Ts are found:
5722 if (!HasUniqueTargetType)
5723 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5726 // If one unique T is found:
5727 // First, build a candidate set from the previously recorded
5728 // potentially viable conversions.
5729 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5730 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5733 // Then, perform overload resolution over the candidate set.
5734 OverloadCandidateSet::iterator Best;
5735 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5737 // Apply this conversion.
5738 DeclAccessPair Found =
5739 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5740 if (recordConversion(*this, Loc, From, Converter, T,
5741 HadMultipleCandidates, Found))
5746 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5748 case OR_No_Viable_Function:
5749 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5750 HadMultipleCandidates,
5751 ExplicitConversions))
5753 // fall through 'OR_Deleted' case.
5755 // We'll complain below about a non-integral condition type.
5759 switch (ViableConversions.size()) {
5761 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5762 HadMultipleCandidates,
5763 ExplicitConversions))
5766 // We'll complain below about a non-integral condition type.
5770 // Apply this conversion.
5771 DeclAccessPair Found = ViableConversions[0];
5772 if (recordConversion(*this, Loc, From, Converter, T,
5773 HadMultipleCandidates, Found))
5778 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5783 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5786 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5787 /// an acceptable non-member overloaded operator for a call whose
5788 /// arguments have types T1 (and, if non-empty, T2). This routine
5789 /// implements the check in C++ [over.match.oper]p3b2 concerning
5790 /// enumeration types.
5791 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5793 ArrayRef<Expr *> Args) {
5794 QualType T1 = Args[0]->getType();
5795 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5797 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5800 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5803 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5804 if (Proto->getNumParams() < 1)
5807 if (T1->isEnumeralType()) {
5808 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5809 if (Context.hasSameUnqualifiedType(T1, ArgType))
5813 if (Proto->getNumParams() < 2)
5816 if (!T2.isNull() && T2->isEnumeralType()) {
5817 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5818 if (Context.hasSameUnqualifiedType(T2, ArgType))
5825 /// AddOverloadCandidate - Adds the given function to the set of
5826 /// candidate functions, using the given function call arguments. If
5827 /// @p SuppressUserConversions, then don't allow user-defined
5828 /// conversions via constructors or conversion operators.
5830 /// \param PartialOverloading true if we are performing "partial" overloading
5831 /// based on an incomplete set of function arguments. This feature is used by
5832 /// code completion.
5834 Sema::AddOverloadCandidate(FunctionDecl *Function,
5835 DeclAccessPair FoundDecl,
5836 ArrayRef<Expr *> Args,
5837 OverloadCandidateSet &CandidateSet,
5838 bool SuppressUserConversions,
5839 bool PartialOverloading,
5840 bool AllowExplicit) {
5841 const FunctionProtoType *Proto
5842 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5843 assert(Proto && "Functions without a prototype cannot be overloaded");
5844 assert(!Function->getDescribedFunctionTemplate() &&
5845 "Use AddTemplateOverloadCandidate for function templates");
5847 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5848 if (!isa<CXXConstructorDecl>(Method)) {
5849 // If we get here, it's because we're calling a member function
5850 // that is named without a member access expression (e.g.,
5851 // "this->f") that was either written explicitly or created
5852 // implicitly. This can happen with a qualified call to a member
5853 // function, e.g., X::f(). We use an empty type for the implied
5854 // object argument (C++ [over.call.func]p3), and the acting context
5856 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5857 QualType(), Expr::Classification::makeSimpleLValue(),
5858 Args, CandidateSet, SuppressUserConversions,
5859 PartialOverloading);
5862 // We treat a constructor like a non-member function, since its object
5863 // argument doesn't participate in overload resolution.
5866 if (!CandidateSet.isNewCandidate(Function))
5869 // C++ [over.match.oper]p3:
5870 // if no operand has a class type, only those non-member functions in the
5871 // lookup set that have a first parameter of type T1 or "reference to
5872 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5873 // is a right operand) a second parameter of type T2 or "reference to
5874 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5875 // candidate functions.
5876 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5877 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5880 // C++11 [class.copy]p11: [DR1402]
5881 // A defaulted move constructor that is defined as deleted is ignored by
5882 // overload resolution.
5883 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5884 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5885 Constructor->isMoveConstructor())
5888 // Overload resolution is always an unevaluated context.
5889 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5891 // Add this candidate
5892 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5893 Candidate.FoundDecl = FoundDecl;
5894 Candidate.Function = Function;
5895 Candidate.Viable = true;
5896 Candidate.IsSurrogate = false;
5897 Candidate.IgnoreObjectArgument = false;
5898 Candidate.ExplicitCallArguments = Args.size();
5901 // C++ [class.copy]p3:
5902 // A member function template is never instantiated to perform the copy
5903 // of a class object to an object of its class type.
5904 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5905 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
5906 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5907 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(),
5909 Candidate.Viable = false;
5910 Candidate.FailureKind = ovl_fail_illegal_constructor;
5915 unsigned NumParams = Proto->getNumParams();
5917 // (C++ 13.3.2p2): A candidate function having fewer than m
5918 // parameters is viable only if it has an ellipsis in its parameter
5920 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5921 !Proto->isVariadic()) {
5922 Candidate.Viable = false;
5923 Candidate.FailureKind = ovl_fail_too_many_arguments;
5927 // (C++ 13.3.2p2): A candidate function having more than m parameters
5928 // is viable only if the (m+1)st parameter has a default argument
5929 // (8.3.6). For the purposes of overload resolution, the
5930 // parameter list is truncated on the right, so that there are
5931 // exactly m parameters.
5932 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5933 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5934 // Not enough arguments.
5935 Candidate.Viable = false;
5936 Candidate.FailureKind = ovl_fail_too_few_arguments;
5940 // (CUDA B.1): Check for invalid calls between targets.
5941 if (getLangOpts().CUDA)
5942 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5943 // Skip the check for callers that are implicit members, because in this
5944 // case we may not yet know what the member's target is; the target is
5945 // inferred for the member automatically, based on the bases and fields of
5947 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
5948 Candidate.Viable = false;
5949 Candidate.FailureKind = ovl_fail_bad_target;
5953 // Determine the implicit conversion sequences for each of the
5955 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5956 if (ArgIdx < NumParams) {
5957 // (C++ 13.3.2p3): for F to be a viable function, there shall
5958 // exist for each argument an implicit conversion sequence
5959 // (13.3.3.1) that converts that argument to the corresponding
5961 QualType ParamType = Proto->getParamType(ArgIdx);
5962 Candidate.Conversions[ArgIdx]
5963 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5964 SuppressUserConversions,
5965 /*InOverloadResolution=*/true,
5966 /*AllowObjCWritebackConversion=*/
5967 getLangOpts().ObjCAutoRefCount,
5969 if (Candidate.Conversions[ArgIdx].isBad()) {
5970 Candidate.Viable = false;
5971 Candidate.FailureKind = ovl_fail_bad_conversion;
5975 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5976 // argument for which there is no corresponding parameter is
5977 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5978 Candidate.Conversions[ArgIdx].setEllipsis();
5982 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5983 Candidate.Viable = false;
5984 Candidate.FailureKind = ovl_fail_enable_if;
5985 Candidate.DeductionFailure.Data = FailedAttr;
5989 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
5990 Candidate.Viable = false;
5991 Candidate.FailureKind = ovl_fail_ext_disabled;
5997 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
5998 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
5999 if (Methods.size() <= 1)
6002 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6004 ObjCMethodDecl *Method = Methods[b];
6005 unsigned NumNamedArgs = Sel.getNumArgs();
6006 // Method might have more arguments than selector indicates. This is due
6007 // to addition of c-style arguments in method.
6008 if (Method->param_size() > NumNamedArgs)
6009 NumNamedArgs = Method->param_size();
6010 if (Args.size() < NumNamedArgs)
6013 for (unsigned i = 0; i < NumNamedArgs; i++) {
6014 // We can't do any type-checking on a type-dependent argument.
6015 if (Args[i]->isTypeDependent()) {
6020 ParmVarDecl *param = Method->parameters()[i];
6021 Expr *argExpr = Args[i];
6022 assert(argExpr && "SelectBestMethod(): missing expression");
6024 // Strip the unbridged-cast placeholder expression off unless it's
6025 // a consumed argument.
6026 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6027 !param->hasAttr<CFConsumedAttr>())
6028 argExpr = stripARCUnbridgedCast(argExpr);
6030 // If the parameter is __unknown_anytype, move on to the next method.
6031 if (param->getType() == Context.UnknownAnyTy) {
6036 ImplicitConversionSequence ConversionState
6037 = TryCopyInitialization(*this, argExpr, param->getType(),
6038 /*SuppressUserConversions*/false,
6039 /*InOverloadResolution=*/true,
6040 /*AllowObjCWritebackConversion=*/
6041 getLangOpts().ObjCAutoRefCount,
6042 /*AllowExplicit*/false);
6043 // This function looks for a reasonably-exact match, so we consider
6044 // incompatible pointer conversions to be a failure here.
6045 if (ConversionState.isBad() ||
6046 (ConversionState.isStandard() &&
6047 ConversionState.Standard.Second ==
6048 ICK_Incompatible_Pointer_Conversion)) {
6053 // Promote additional arguments to variadic methods.
6054 if (Match && Method->isVariadic()) {
6055 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6056 if (Args[i]->isTypeDependent()) {
6060 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6062 if (Arg.isInvalid()) {
6068 // Check for extra arguments to non-variadic methods.
6069 if (Args.size() != NumNamedArgs)
6071 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6072 // Special case when selectors have no argument. In this case, select
6073 // one with the most general result type of 'id'.
6074 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6075 QualType ReturnT = Methods[b]->getReturnType();
6076 if (ReturnT->isObjCIdType())
6088 // specific_attr_iterator iterates over enable_if attributes in reverse, and
6089 // enable_if is order-sensitive. As a result, we need to reverse things
6090 // sometimes. Size of 4 elements is arbitrary.
6091 static SmallVector<EnableIfAttr *, 4>
6092 getOrderedEnableIfAttrs(const FunctionDecl *Function) {
6093 SmallVector<EnableIfAttr *, 4> Result;
6094 if (!Function->hasAttrs())
6097 const auto &FuncAttrs = Function->getAttrs();
6098 for (Attr *Attr : FuncAttrs)
6099 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr))
6100 Result.push_back(EnableIf);
6102 std::reverse(Result.begin(), Result.end());
6106 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6107 bool MissingImplicitThis) {
6108 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function);
6109 if (EnableIfAttrs.empty())
6112 SFINAETrap Trap(*this);
6113 SmallVector<Expr *, 16> ConvertedArgs;
6114 bool InitializationFailed = false;
6116 // Ignore any variadic arguments. Converting them is pointless, since the
6117 // user can't refer to them in the enable_if condition.
6118 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6120 // Convert the arguments.
6121 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6123 if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
6124 !cast<CXXMethodDecl>(Function)->isStatic() &&
6125 !isa<CXXConstructorDecl>(Function)) {
6126 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6127 R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
6130 R = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6131 Context, Function->getParamDecl(I)),
6132 SourceLocation(), Args[I]);
6135 if (R.isInvalid()) {
6136 InitializationFailed = true;
6140 ConvertedArgs.push_back(R.get());
6143 if (InitializationFailed || Trap.hasErrorOccurred())
6144 return EnableIfAttrs[0];
6146 // Push default arguments if needed.
6147 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6148 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6149 ParmVarDecl *P = Function->getParamDecl(i);
6150 ExprResult R = PerformCopyInitialization(
6151 InitializedEntity::InitializeParameter(Context,
6152 Function->getParamDecl(i)),
6154 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
6155 : P->getDefaultArg());
6156 if (R.isInvalid()) {
6157 InitializationFailed = true;
6160 ConvertedArgs.push_back(R.get());
6163 if (InitializationFailed || Trap.hasErrorOccurred())
6164 return EnableIfAttrs[0];
6167 for (auto *EIA : EnableIfAttrs) {
6169 // FIXME: This doesn't consider value-dependent cases, because doing so is
6170 // very difficult. Ideally, we should handle them more gracefully.
6171 if (!EIA->getCond()->EvaluateWithSubstitution(
6172 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6175 if (!Result.isInt() || !Result.getInt().getBoolValue())
6181 /// \brief Add all of the function declarations in the given function set to
6182 /// the overload candidate set.
6183 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6184 ArrayRef<Expr *> Args,
6185 OverloadCandidateSet& CandidateSet,
6186 TemplateArgumentListInfo *ExplicitTemplateArgs,
6187 bool SuppressUserConversions,
6188 bool PartialOverloading) {
6189 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6190 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6191 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6192 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
6193 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6194 cast<CXXMethodDecl>(FD)->getParent(),
6195 Args[0]->getType(), Args[0]->Classify(Context),
6196 Args.slice(1), CandidateSet,
6197 SuppressUserConversions, PartialOverloading);
6199 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
6200 SuppressUserConversions, PartialOverloading);
6202 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
6203 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
6204 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
6205 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
6206 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6207 ExplicitTemplateArgs,
6209 Args[0]->Classify(Context), Args.slice(1),
6210 CandidateSet, SuppressUserConversions,
6211 PartialOverloading);
6213 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6214 ExplicitTemplateArgs, Args,
6215 CandidateSet, SuppressUserConversions,
6216 PartialOverloading);
6221 /// AddMethodCandidate - Adds a named decl (which is some kind of
6222 /// method) as a method candidate to the given overload set.
6223 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6224 QualType ObjectType,
6225 Expr::Classification ObjectClassification,
6226 ArrayRef<Expr *> Args,
6227 OverloadCandidateSet& CandidateSet,
6228 bool SuppressUserConversions) {
6229 NamedDecl *Decl = FoundDecl.getDecl();
6230 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6232 if (isa<UsingShadowDecl>(Decl))
6233 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6235 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6236 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6237 "Expected a member function template");
6238 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6239 /*ExplicitArgs*/ nullptr,
6240 ObjectType, ObjectClassification,
6242 SuppressUserConversions);
6244 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6245 ObjectType, ObjectClassification,
6247 CandidateSet, SuppressUserConversions);
6251 /// AddMethodCandidate - Adds the given C++ member function to the set
6252 /// of candidate functions, using the given function call arguments
6253 /// and the object argument (@c Object). For example, in a call
6254 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6255 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6256 /// allow user-defined conversions via constructors or conversion
6259 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6260 CXXRecordDecl *ActingContext, QualType ObjectType,
6261 Expr::Classification ObjectClassification,
6262 ArrayRef<Expr *> Args,
6263 OverloadCandidateSet &CandidateSet,
6264 bool SuppressUserConversions,
6265 bool PartialOverloading) {
6266 const FunctionProtoType *Proto
6267 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6268 assert(Proto && "Methods without a prototype cannot be overloaded");
6269 assert(!isa<CXXConstructorDecl>(Method) &&
6270 "Use AddOverloadCandidate for constructors");
6272 if (!CandidateSet.isNewCandidate(Method))
6275 // C++11 [class.copy]p23: [DR1402]
6276 // A defaulted move assignment operator that is defined as deleted is
6277 // ignored by overload resolution.
6278 if (Method->isDefaulted() && Method->isDeleted() &&
6279 Method->isMoveAssignmentOperator())
6282 // Overload resolution is always an unevaluated context.
6283 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6285 // Add this candidate
6286 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6287 Candidate.FoundDecl = FoundDecl;
6288 Candidate.Function = Method;
6289 Candidate.IsSurrogate = false;
6290 Candidate.IgnoreObjectArgument = false;
6291 Candidate.ExplicitCallArguments = Args.size();
6293 unsigned NumParams = Proto->getNumParams();
6295 // (C++ 13.3.2p2): A candidate function having fewer than m
6296 // parameters is viable only if it has an ellipsis in its parameter
6298 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6299 !Proto->isVariadic()) {
6300 Candidate.Viable = false;
6301 Candidate.FailureKind = ovl_fail_too_many_arguments;
6305 // (C++ 13.3.2p2): A candidate function having more than m parameters
6306 // is viable only if the (m+1)st parameter has a default argument
6307 // (8.3.6). For the purposes of overload resolution, the
6308 // parameter list is truncated on the right, so that there are
6309 // exactly m parameters.
6310 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6311 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6312 // Not enough arguments.
6313 Candidate.Viable = false;
6314 Candidate.FailureKind = ovl_fail_too_few_arguments;
6318 Candidate.Viable = true;
6320 if (Method->isStatic() || ObjectType.isNull())
6321 // The implicit object argument is ignored.
6322 Candidate.IgnoreObjectArgument = true;
6324 // Determine the implicit conversion sequence for the object
6326 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6327 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6328 Method, ActingContext);
6329 if (Candidate.Conversions[0].isBad()) {
6330 Candidate.Viable = false;
6331 Candidate.FailureKind = ovl_fail_bad_conversion;
6336 // (CUDA B.1): Check for invalid calls between targets.
6337 if (getLangOpts().CUDA)
6338 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6339 if (!IsAllowedCUDACall(Caller, Method)) {
6340 Candidate.Viable = false;
6341 Candidate.FailureKind = ovl_fail_bad_target;
6345 // Determine the implicit conversion sequences for each of the
6347 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6348 if (ArgIdx < NumParams) {
6349 // (C++ 13.3.2p3): for F to be a viable function, there shall
6350 // exist for each argument an implicit conversion sequence
6351 // (13.3.3.1) that converts that argument to the corresponding
6353 QualType ParamType = Proto->getParamType(ArgIdx);
6354 Candidate.Conversions[ArgIdx + 1]
6355 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6356 SuppressUserConversions,
6357 /*InOverloadResolution=*/true,
6358 /*AllowObjCWritebackConversion=*/
6359 getLangOpts().ObjCAutoRefCount);
6360 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6361 Candidate.Viable = false;
6362 Candidate.FailureKind = ovl_fail_bad_conversion;
6366 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6367 // argument for which there is no corresponding parameter is
6368 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6369 Candidate.Conversions[ArgIdx + 1].setEllipsis();
6373 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6374 Candidate.Viable = false;
6375 Candidate.FailureKind = ovl_fail_enable_if;
6376 Candidate.DeductionFailure.Data = FailedAttr;
6381 /// \brief Add a C++ member function template as a candidate to the candidate
6382 /// set, using template argument deduction to produce an appropriate member
6383 /// function template specialization.
6385 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6386 DeclAccessPair FoundDecl,
6387 CXXRecordDecl *ActingContext,
6388 TemplateArgumentListInfo *ExplicitTemplateArgs,
6389 QualType ObjectType,
6390 Expr::Classification ObjectClassification,
6391 ArrayRef<Expr *> Args,
6392 OverloadCandidateSet& CandidateSet,
6393 bool SuppressUserConversions,
6394 bool PartialOverloading) {
6395 if (!CandidateSet.isNewCandidate(MethodTmpl))
6398 // C++ [over.match.funcs]p7:
6399 // In each case where a candidate is a function template, candidate
6400 // function template specializations are generated using template argument
6401 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6402 // candidate functions in the usual way.113) A given name can refer to one
6403 // or more function templates and also to a set of overloaded non-template
6404 // functions. In such a case, the candidate functions generated from each
6405 // function template are combined with the set of non-template candidate
6407 TemplateDeductionInfo Info(CandidateSet.getLocation());
6408 FunctionDecl *Specialization = nullptr;
6409 if (TemplateDeductionResult Result
6410 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
6411 Specialization, Info, PartialOverloading)) {
6412 OverloadCandidate &Candidate = CandidateSet.addCandidate();
6413 Candidate.FoundDecl = FoundDecl;
6414 Candidate.Function = MethodTmpl->getTemplatedDecl();
6415 Candidate.Viable = false;
6416 Candidate.FailureKind = ovl_fail_bad_deduction;
6417 Candidate.IsSurrogate = false;
6418 Candidate.IgnoreObjectArgument = false;
6419 Candidate.ExplicitCallArguments = Args.size();
6420 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6425 // Add the function template specialization produced by template argument
6426 // deduction as a candidate.
6427 assert(Specialization && "Missing member function template specialization?");
6428 assert(isa<CXXMethodDecl>(Specialization) &&
6429 "Specialization is not a member function?");
6430 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6431 ActingContext, ObjectType, ObjectClassification, Args,
6432 CandidateSet, SuppressUserConversions, PartialOverloading);
6435 /// \brief Add a C++ function template specialization as a candidate
6436 /// in the candidate set, using template argument deduction to produce
6437 /// an appropriate function template specialization.
6439 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
6440 DeclAccessPair FoundDecl,
6441 TemplateArgumentListInfo *ExplicitTemplateArgs,
6442 ArrayRef<Expr *> Args,
6443 OverloadCandidateSet& CandidateSet,
6444 bool SuppressUserConversions,
6445 bool PartialOverloading) {
6446 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6449 // C++ [over.match.funcs]p7:
6450 // In each case where a candidate is a function template, candidate
6451 // function template specializations are generated using template argument
6452 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6453 // candidate functions in the usual way.113) A given name can refer to one
6454 // or more function templates and also to a set of overloaded non-template
6455 // functions. In such a case, the candidate functions generated from each
6456 // function template are combined with the set of non-template candidate
6458 TemplateDeductionInfo Info(CandidateSet.getLocation());
6459 FunctionDecl *Specialization = nullptr;
6460 if (TemplateDeductionResult Result
6461 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6462 Specialization, Info, PartialOverloading)) {
6463 OverloadCandidate &Candidate = CandidateSet.addCandidate();
6464 Candidate.FoundDecl = FoundDecl;
6465 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6466 Candidate.Viable = false;
6467 Candidate.FailureKind = ovl_fail_bad_deduction;
6468 Candidate.IsSurrogate = false;
6469 Candidate.IgnoreObjectArgument = false;
6470 Candidate.ExplicitCallArguments = Args.size();
6471 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6476 // Add the function template specialization produced by template argument
6477 // deduction as a candidate.
6478 assert(Specialization && "Missing function template specialization?");
6479 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6480 SuppressUserConversions, PartialOverloading);
6483 /// Determine whether this is an allowable conversion from the result
6484 /// of an explicit conversion operator to the expected type, per C++
6485 /// [over.match.conv]p1 and [over.match.ref]p1.
6487 /// \param ConvType The return type of the conversion function.
6489 /// \param ToType The type we are converting to.
6491 /// \param AllowObjCPointerConversion Allow a conversion from one
6492 /// Objective-C pointer to another.
6494 /// \returns true if the conversion is allowable, false otherwise.
6495 static bool isAllowableExplicitConversion(Sema &S,
6496 QualType ConvType, QualType ToType,
6497 bool AllowObjCPointerConversion) {
6498 QualType ToNonRefType = ToType.getNonReferenceType();
6500 // Easy case: the types are the same.
6501 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6504 // Allow qualification conversions.
6505 bool ObjCLifetimeConversion;
6506 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6507 ObjCLifetimeConversion))
6510 // If we're not allowed to consider Objective-C pointer conversions,
6512 if (!AllowObjCPointerConversion)
6515 // Is this an Objective-C pointer conversion?
6516 bool IncompatibleObjC = false;
6517 QualType ConvertedType;
6518 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6522 /// AddConversionCandidate - Add a C++ conversion function as a
6523 /// candidate in the candidate set (C++ [over.match.conv],
6524 /// C++ [over.match.copy]). From is the expression we're converting from,
6525 /// and ToType is the type that we're eventually trying to convert to
6526 /// (which may or may not be the same type as the type that the
6527 /// conversion function produces).
6529 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6530 DeclAccessPair FoundDecl,
6531 CXXRecordDecl *ActingContext,
6532 Expr *From, QualType ToType,
6533 OverloadCandidateSet& CandidateSet,
6534 bool AllowObjCConversionOnExplicit) {
6535 assert(!Conversion->getDescribedFunctionTemplate() &&
6536 "Conversion function templates use AddTemplateConversionCandidate");
6537 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6538 if (!CandidateSet.isNewCandidate(Conversion))
6541 // If the conversion function has an undeduced return type, trigger its
6543 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6544 if (DeduceReturnType(Conversion, From->getExprLoc()))
6546 ConvType = Conversion->getConversionType().getNonReferenceType();
6549 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6550 // operator is only a candidate if its return type is the target type or
6551 // can be converted to the target type with a qualification conversion.
6552 if (Conversion->isExplicit() &&
6553 !isAllowableExplicitConversion(*this, ConvType, ToType,
6554 AllowObjCConversionOnExplicit))
6557 // Overload resolution is always an unevaluated context.
6558 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6560 // Add this candidate
6561 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6562 Candidate.FoundDecl = FoundDecl;
6563 Candidate.Function = Conversion;
6564 Candidate.IsSurrogate = false;
6565 Candidate.IgnoreObjectArgument = false;
6566 Candidate.FinalConversion.setAsIdentityConversion();
6567 Candidate.FinalConversion.setFromType(ConvType);
6568 Candidate.FinalConversion.setAllToTypes(ToType);
6569 Candidate.Viable = true;
6570 Candidate.ExplicitCallArguments = 1;
6572 // C++ [over.match.funcs]p4:
6573 // For conversion functions, the function is considered to be a member of
6574 // the class of the implicit implied object argument for the purpose of
6575 // defining the type of the implicit object parameter.
6577 // Determine the implicit conversion sequence for the implicit
6578 // object parameter.
6579 QualType ImplicitParamType = From->getType();
6580 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6581 ImplicitParamType = FromPtrType->getPointeeType();
6582 CXXRecordDecl *ConversionContext
6583 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6585 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6586 *this, CandidateSet.getLocation(), From->getType(),
6587 From->Classify(Context), Conversion, ConversionContext);
6589 if (Candidate.Conversions[0].isBad()) {
6590 Candidate.Viable = false;
6591 Candidate.FailureKind = ovl_fail_bad_conversion;
6595 // We won't go through a user-defined type conversion function to convert a
6596 // derived to base as such conversions are given Conversion Rank. They only
6597 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6599 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6600 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6601 if (FromCanon == ToCanon ||
6602 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
6603 Candidate.Viable = false;
6604 Candidate.FailureKind = ovl_fail_trivial_conversion;
6608 // To determine what the conversion from the result of calling the
6609 // conversion function to the type we're eventually trying to
6610 // convert to (ToType), we need to synthesize a call to the
6611 // conversion function and attempt copy initialization from it. This
6612 // makes sure that we get the right semantics with respect to
6613 // lvalues/rvalues and the type. Fortunately, we can allocate this
6614 // call on the stack and we don't need its arguments to be
6616 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6617 VK_LValue, From->getLocStart());
6618 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6619 Context.getPointerType(Conversion->getType()),
6620 CK_FunctionToPointerDecay,
6621 &ConversionRef, VK_RValue);
6623 QualType ConversionType = Conversion->getConversionType();
6624 if (!isCompleteType(From->getLocStart(), ConversionType)) {
6625 Candidate.Viable = false;
6626 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6630 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6632 // Note that it is safe to allocate CallExpr on the stack here because
6633 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6635 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6636 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6637 From->getLocStart());
6638 ImplicitConversionSequence ICS =
6639 TryCopyInitialization(*this, &Call, ToType,
6640 /*SuppressUserConversions=*/true,
6641 /*InOverloadResolution=*/false,
6642 /*AllowObjCWritebackConversion=*/false);
6644 switch (ICS.getKind()) {
6645 case ImplicitConversionSequence::StandardConversion:
6646 Candidate.FinalConversion = ICS.Standard;
6648 // C++ [over.ics.user]p3:
6649 // If the user-defined conversion is specified by a specialization of a
6650 // conversion function template, the second standard conversion sequence
6651 // shall have exact match rank.
6652 if (Conversion->getPrimaryTemplate() &&
6653 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6654 Candidate.Viable = false;
6655 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6659 // C++0x [dcl.init.ref]p5:
6660 // In the second case, if the reference is an rvalue reference and
6661 // the second standard conversion sequence of the user-defined
6662 // conversion sequence includes an lvalue-to-rvalue conversion, the
6663 // program is ill-formed.
6664 if (ToType->isRValueReferenceType() &&
6665 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6666 Candidate.Viable = false;
6667 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6672 case ImplicitConversionSequence::BadConversion:
6673 Candidate.Viable = false;
6674 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6679 "Can only end up with a standard conversion sequence or failure");
6682 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6683 Candidate.Viable = false;
6684 Candidate.FailureKind = ovl_fail_enable_if;
6685 Candidate.DeductionFailure.Data = FailedAttr;
6690 /// \brief Adds a conversion function template specialization
6691 /// candidate to the overload set, using template argument deduction
6692 /// to deduce the template arguments of the conversion function
6693 /// template from the type that we are converting to (C++
6694 /// [temp.deduct.conv]).
6696 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6697 DeclAccessPair FoundDecl,
6698 CXXRecordDecl *ActingDC,
6699 Expr *From, QualType ToType,
6700 OverloadCandidateSet &CandidateSet,
6701 bool AllowObjCConversionOnExplicit) {
6702 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6703 "Only conversion function templates permitted here");
6705 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6708 TemplateDeductionInfo Info(CandidateSet.getLocation());
6709 CXXConversionDecl *Specialization = nullptr;
6710 if (TemplateDeductionResult Result
6711 = DeduceTemplateArguments(FunctionTemplate, ToType,
6712 Specialization, Info)) {
6713 OverloadCandidate &Candidate = CandidateSet.addCandidate();
6714 Candidate.FoundDecl = FoundDecl;
6715 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6716 Candidate.Viable = false;
6717 Candidate.FailureKind = ovl_fail_bad_deduction;
6718 Candidate.IsSurrogate = false;
6719 Candidate.IgnoreObjectArgument = false;
6720 Candidate.ExplicitCallArguments = 1;
6721 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6726 // Add the conversion function template specialization produced by
6727 // template argument deduction as a candidate.
6728 assert(Specialization && "Missing function template specialization?");
6729 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6730 CandidateSet, AllowObjCConversionOnExplicit);
6733 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6734 /// converts the given @c Object to a function pointer via the
6735 /// conversion function @c Conversion, and then attempts to call it
6736 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6737 /// the type of function that we'll eventually be calling.
6738 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6739 DeclAccessPair FoundDecl,
6740 CXXRecordDecl *ActingContext,
6741 const FunctionProtoType *Proto,
6743 ArrayRef<Expr *> Args,
6744 OverloadCandidateSet& CandidateSet) {
6745 if (!CandidateSet.isNewCandidate(Conversion))
6748 // Overload resolution is always an unevaluated context.
6749 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6751 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6752 Candidate.FoundDecl = FoundDecl;
6753 Candidate.Function = nullptr;
6754 Candidate.Surrogate = Conversion;
6755 Candidate.Viable = true;
6756 Candidate.IsSurrogate = true;
6757 Candidate.IgnoreObjectArgument = false;
6758 Candidate.ExplicitCallArguments = Args.size();
6760 // Determine the implicit conversion sequence for the implicit
6761 // object parameter.
6762 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
6763 *this, CandidateSet.getLocation(), Object->getType(),
6764 Object->Classify(Context), Conversion, ActingContext);
6765 if (ObjectInit.isBad()) {
6766 Candidate.Viable = false;
6767 Candidate.FailureKind = ovl_fail_bad_conversion;
6768 Candidate.Conversions[0] = ObjectInit;
6772 // The first conversion is actually a user-defined conversion whose
6773 // first conversion is ObjectInit's standard conversion (which is
6774 // effectively a reference binding). Record it as such.
6775 Candidate.Conversions[0].setUserDefined();
6776 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6777 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6778 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6779 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6780 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6781 Candidate.Conversions[0].UserDefined.After
6782 = Candidate.Conversions[0].UserDefined.Before;
6783 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6786 unsigned NumParams = Proto->getNumParams();
6788 // (C++ 13.3.2p2): A candidate function having fewer than m
6789 // parameters is viable only if it has an ellipsis in its parameter
6791 if (Args.size() > NumParams && !Proto->isVariadic()) {
6792 Candidate.Viable = false;
6793 Candidate.FailureKind = ovl_fail_too_many_arguments;
6797 // Function types don't have any default arguments, so just check if
6798 // we have enough arguments.
6799 if (Args.size() < NumParams) {
6800 // Not enough arguments.
6801 Candidate.Viable = false;
6802 Candidate.FailureKind = ovl_fail_too_few_arguments;
6806 // Determine the implicit conversion sequences for each of the
6808 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6809 if (ArgIdx < NumParams) {
6810 // (C++ 13.3.2p3): for F to be a viable function, there shall
6811 // exist for each argument an implicit conversion sequence
6812 // (13.3.3.1) that converts that argument to the corresponding
6814 QualType ParamType = Proto->getParamType(ArgIdx);
6815 Candidate.Conversions[ArgIdx + 1]
6816 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6817 /*SuppressUserConversions=*/false,
6818 /*InOverloadResolution=*/false,
6819 /*AllowObjCWritebackConversion=*/
6820 getLangOpts().ObjCAutoRefCount);
6821 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6822 Candidate.Viable = false;
6823 Candidate.FailureKind = ovl_fail_bad_conversion;
6827 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6828 // argument for which there is no corresponding parameter is
6829 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6830 Candidate.Conversions[ArgIdx + 1].setEllipsis();
6834 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
6835 Candidate.Viable = false;
6836 Candidate.FailureKind = ovl_fail_enable_if;
6837 Candidate.DeductionFailure.Data = FailedAttr;
6842 /// \brief Add overload candidates for overloaded operators that are
6843 /// member functions.
6845 /// Add the overloaded operator candidates that are member functions
6846 /// for the operator Op that was used in an operator expression such
6847 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
6848 /// CandidateSet will store the added overload candidates. (C++
6849 /// [over.match.oper]).
6850 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6851 SourceLocation OpLoc,
6852 ArrayRef<Expr *> Args,
6853 OverloadCandidateSet& CandidateSet,
6854 SourceRange OpRange) {
6855 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6857 // C++ [over.match.oper]p3:
6858 // For a unary operator @ with an operand of a type whose
6859 // cv-unqualified version is T1, and for a binary operator @ with
6860 // a left operand of a type whose cv-unqualified version is T1 and
6861 // a right operand of a type whose cv-unqualified version is T2,
6862 // three sets of candidate functions, designated member
6863 // candidates, non-member candidates and built-in candidates, are
6864 // constructed as follows:
6865 QualType T1 = Args[0]->getType();
6867 // -- If T1 is a complete class type or a class currently being
6868 // defined, the set of member candidates is the result of the
6869 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6870 // the set of member candidates is empty.
6871 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6872 // Complete the type if it can be completed.
6873 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
6875 // If the type is neither complete nor being defined, bail out now.
6876 if (!T1Rec->getDecl()->getDefinition())
6879 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6880 LookupQualifiedName(Operators, T1Rec->getDecl());
6881 Operators.suppressDiagnostics();
6883 for (LookupResult::iterator Oper = Operators.begin(),
6884 OperEnd = Operators.end();
6887 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6888 Args[0]->Classify(Context),
6891 /* SuppressUserConversions = */ false);
6895 /// AddBuiltinCandidate - Add a candidate for a built-in
6896 /// operator. ResultTy and ParamTys are the result and parameter types
6897 /// of the built-in candidate, respectively. Args and NumArgs are the
6898 /// arguments being passed to the candidate. IsAssignmentOperator
6899 /// should be true when this built-in candidate is an assignment
6900 /// operator. NumContextualBoolArguments is the number of arguments
6901 /// (at the beginning of the argument list) that will be contextually
6902 /// converted to bool.
6903 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6904 ArrayRef<Expr *> Args,
6905 OverloadCandidateSet& CandidateSet,
6906 bool IsAssignmentOperator,
6907 unsigned NumContextualBoolArguments) {
6908 // Overload resolution is always an unevaluated context.
6909 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6911 // Add this candidate
6912 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6913 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6914 Candidate.Function = nullptr;
6915 Candidate.IsSurrogate = false;
6916 Candidate.IgnoreObjectArgument = false;
6917 Candidate.BuiltinTypes.ResultTy = ResultTy;
6918 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6919 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6921 // Determine the implicit conversion sequences for each of the
6923 Candidate.Viable = true;
6924 Candidate.ExplicitCallArguments = Args.size();
6925 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6926 // C++ [over.match.oper]p4:
6927 // For the built-in assignment operators, conversions of the
6928 // left operand are restricted as follows:
6929 // -- no temporaries are introduced to hold the left operand, and
6930 // -- no user-defined conversions are applied to the left
6931 // operand to achieve a type match with the left-most
6932 // parameter of a built-in candidate.
6934 // We block these conversions by turning off user-defined
6935 // conversions, since that is the only way that initialization of
6936 // a reference to a non-class type can occur from something that
6937 // is not of the same type.
6938 if (ArgIdx < NumContextualBoolArguments) {
6939 assert(ParamTys[ArgIdx] == Context.BoolTy &&
6940 "Contextual conversion to bool requires bool type");
6941 Candidate.Conversions[ArgIdx]
6942 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6944 Candidate.Conversions[ArgIdx]
6945 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6946 ArgIdx == 0 && IsAssignmentOperator,
6947 /*InOverloadResolution=*/false,
6948 /*AllowObjCWritebackConversion=*/
6949 getLangOpts().ObjCAutoRefCount);
6951 if (Candidate.Conversions[ArgIdx].isBad()) {
6952 Candidate.Viable = false;
6953 Candidate.FailureKind = ovl_fail_bad_conversion;
6961 /// BuiltinCandidateTypeSet - A set of types that will be used for the
6962 /// candidate operator functions for built-in operators (C++
6963 /// [over.built]). The types are separated into pointer types and
6964 /// enumeration types.
6965 class BuiltinCandidateTypeSet {
6966 /// TypeSet - A set of types.
6967 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
6968 llvm::SmallPtrSet<QualType, 8>> TypeSet;
6970 /// PointerTypes - The set of pointer types that will be used in the
6971 /// built-in candidates.
6972 TypeSet PointerTypes;
6974 /// MemberPointerTypes - The set of member pointer types that will be
6975 /// used in the built-in candidates.
6976 TypeSet MemberPointerTypes;
6978 /// EnumerationTypes - The set of enumeration types that will be
6979 /// used in the built-in candidates.
6980 TypeSet EnumerationTypes;
6982 /// \brief The set of vector types that will be used in the built-in
6984 TypeSet VectorTypes;
6986 /// \brief A flag indicating non-record types are viable candidates
6987 bool HasNonRecordTypes;
6989 /// \brief A flag indicating whether either arithmetic or enumeration types
6990 /// were present in the candidate set.
6991 bool HasArithmeticOrEnumeralTypes;
6993 /// \brief A flag indicating whether the nullptr type was present in the
6995 bool HasNullPtrType;
6997 /// Sema - The semantic analysis instance where we are building the
6998 /// candidate type set.
7001 /// Context - The AST context in which we will build the type sets.
7002 ASTContext &Context;
7004 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7005 const Qualifiers &VisibleQuals);
7006 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7009 /// iterator - Iterates through the types that are part of the set.
7010 typedef TypeSet::iterator iterator;
7012 BuiltinCandidateTypeSet(Sema &SemaRef)
7013 : HasNonRecordTypes(false),
7014 HasArithmeticOrEnumeralTypes(false),
7015 HasNullPtrType(false),
7017 Context(SemaRef.Context) { }
7019 void AddTypesConvertedFrom(QualType Ty,
7021 bool AllowUserConversions,
7022 bool AllowExplicitConversions,
7023 const Qualifiers &VisibleTypeConversionsQuals);
7025 /// pointer_begin - First pointer type found;
7026 iterator pointer_begin() { return PointerTypes.begin(); }
7028 /// pointer_end - Past the last pointer type found;
7029 iterator pointer_end() { return PointerTypes.end(); }
7031 /// member_pointer_begin - First member pointer type found;
7032 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7034 /// member_pointer_end - Past the last member pointer type found;
7035 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7037 /// enumeration_begin - First enumeration type found;
7038 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7040 /// enumeration_end - Past the last enumeration type found;
7041 iterator enumeration_end() { return EnumerationTypes.end(); }
7043 iterator vector_begin() { return VectorTypes.begin(); }
7044 iterator vector_end() { return VectorTypes.end(); }
7046 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7047 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7048 bool hasNullPtrType() const { return HasNullPtrType; }
7051 } // end anonymous namespace
7053 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7054 /// the set of pointer types along with any more-qualified variants of
7055 /// that type. For example, if @p Ty is "int const *", this routine
7056 /// will add "int const *", "int const volatile *", "int const
7057 /// restrict *", and "int const volatile restrict *" to the set of
7058 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7059 /// false otherwise.
7061 /// FIXME: what to do about extended qualifiers?
7063 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7064 const Qualifiers &VisibleQuals) {
7066 // Insert this type.
7067 if (!PointerTypes.insert(Ty))
7071 const PointerType *PointerTy = Ty->getAs<PointerType>();
7072 bool buildObjCPtr = false;
7074 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7075 PointeeTy = PTy->getPointeeType();
7076 buildObjCPtr = true;
7078 PointeeTy = PointerTy->getPointeeType();
7081 // Don't add qualified variants of arrays. For one, they're not allowed
7082 // (the qualifier would sink to the element type), and for another, the
7083 // only overload situation where it matters is subscript or pointer +- int,
7084 // and those shouldn't have qualifier variants anyway.
7085 if (PointeeTy->isArrayType())
7088 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7089 bool hasVolatile = VisibleQuals.hasVolatile();
7090 bool hasRestrict = VisibleQuals.hasRestrict();
7092 // Iterate through all strict supersets of BaseCVR.
7093 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7094 if ((CVR | BaseCVR) != CVR) continue;
7095 // Skip over volatile if no volatile found anywhere in the types.
7096 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7098 // Skip over restrict if no restrict found anywhere in the types, or if
7099 // the type cannot be restrict-qualified.
7100 if ((CVR & Qualifiers::Restrict) &&
7102 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7105 // Build qualified pointee type.
7106 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7108 // Build qualified pointer type.
7109 QualType QPointerTy;
7111 QPointerTy = Context.getPointerType(QPointeeTy);
7113 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7115 // Insert qualified pointer type.
7116 PointerTypes.insert(QPointerTy);
7122 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7123 /// to the set of pointer types along with any more-qualified variants of
7124 /// that type. For example, if @p Ty is "int const *", this routine
7125 /// will add "int const *", "int const volatile *", "int const
7126 /// restrict *", and "int const volatile restrict *" to the set of
7127 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7128 /// false otherwise.
7130 /// FIXME: what to do about extended qualifiers?
7132 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7134 // Insert this type.
7135 if (!MemberPointerTypes.insert(Ty))
7138 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7139 assert(PointerTy && "type was not a member pointer type!");
7141 QualType PointeeTy = PointerTy->getPointeeType();
7142 // Don't add qualified variants of arrays. For one, they're not allowed
7143 // (the qualifier would sink to the element type), and for another, the
7144 // only overload situation where it matters is subscript or pointer +- int,
7145 // and those shouldn't have qualifier variants anyway.
7146 if (PointeeTy->isArrayType())
7148 const Type *ClassTy = PointerTy->getClass();
7150 // Iterate through all strict supersets of the pointee type's CVR
7152 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7153 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7154 if ((CVR | BaseCVR) != CVR) continue;
7156 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7157 MemberPointerTypes.insert(
7158 Context.getMemberPointerType(QPointeeTy, ClassTy));
7164 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7165 /// Ty can be implicit converted to the given set of @p Types. We're
7166 /// primarily interested in pointer types and enumeration types. We also
7167 /// take member pointer types, for the conditional operator.
7168 /// AllowUserConversions is true if we should look at the conversion
7169 /// functions of a class type, and AllowExplicitConversions if we
7170 /// should also include the explicit conversion functions of a class
7173 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7175 bool AllowUserConversions,
7176 bool AllowExplicitConversions,
7177 const Qualifiers &VisibleQuals) {
7178 // Only deal with canonical types.
7179 Ty = Context.getCanonicalType(Ty);
7181 // Look through reference types; they aren't part of the type of an
7182 // expression for the purposes of conversions.
7183 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7184 Ty = RefTy->getPointeeType();
7186 // If we're dealing with an array type, decay to the pointer.
7187 if (Ty->isArrayType())
7188 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7190 // Otherwise, we don't care about qualifiers on the type.
7191 Ty = Ty.getLocalUnqualifiedType();
7193 // Flag if we ever add a non-record type.
7194 const RecordType *TyRec = Ty->getAs<RecordType>();
7195 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7197 // Flag if we encounter an arithmetic type.
7198 HasArithmeticOrEnumeralTypes =
7199 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7201 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7202 PointerTypes.insert(Ty);
7203 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7204 // Insert our type, and its more-qualified variants, into the set
7206 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7208 } else if (Ty->isMemberPointerType()) {
7209 // Member pointers are far easier, since the pointee can't be converted.
7210 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7212 } else if (Ty->isEnumeralType()) {
7213 HasArithmeticOrEnumeralTypes = true;
7214 EnumerationTypes.insert(Ty);
7215 } else if (Ty->isVectorType()) {
7216 // We treat vector types as arithmetic types in many contexts as an
7218 HasArithmeticOrEnumeralTypes = true;
7219 VectorTypes.insert(Ty);
7220 } else if (Ty->isNullPtrType()) {
7221 HasNullPtrType = true;
7222 } else if (AllowUserConversions && TyRec) {
7223 // No conversion functions in incomplete types.
7224 if (!SemaRef.isCompleteType(Loc, Ty))
7227 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7228 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7229 if (isa<UsingShadowDecl>(D))
7230 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7232 // Skip conversion function templates; they don't tell us anything
7233 // about which builtin types we can convert to.
7234 if (isa<FunctionTemplateDecl>(D))
7237 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7238 if (AllowExplicitConversions || !Conv->isExplicit()) {
7239 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7246 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
7247 /// the volatile- and non-volatile-qualified assignment operators for the
7248 /// given type to the candidate set.
7249 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7251 ArrayRef<Expr *> Args,
7252 OverloadCandidateSet &CandidateSet) {
7253 QualType ParamTypes[2];
7255 // T& operator=(T&, T)
7256 ParamTypes[0] = S.Context.getLValueReferenceType(T);
7258 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7259 /*IsAssignmentOperator=*/true);
7261 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7262 // volatile T& operator=(volatile T&, T)
7264 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
7266 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7267 /*IsAssignmentOperator=*/true);
7271 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7272 /// if any, found in visible type conversion functions found in ArgExpr's type.
7273 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7275 const RecordType *TyRec;
7276 if (const MemberPointerType *RHSMPType =
7277 ArgExpr->getType()->getAs<MemberPointerType>())
7278 TyRec = RHSMPType->getClass()->getAs<RecordType>();
7280 TyRec = ArgExpr->getType()->getAs<RecordType>();
7282 // Just to be safe, assume the worst case.
7283 VRQuals.addVolatile();
7284 VRQuals.addRestrict();
7288 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7289 if (!ClassDecl->hasDefinition())
7292 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7293 if (isa<UsingShadowDecl>(D))
7294 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7295 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7296 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7297 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7298 CanTy = ResTypeRef->getPointeeType();
7299 // Need to go down the pointer/mempointer chain and add qualifiers
7303 if (CanTy.isRestrictQualified())
7304 VRQuals.addRestrict();
7305 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7306 CanTy = ResTypePtr->getPointeeType();
7307 else if (const MemberPointerType *ResTypeMPtr =
7308 CanTy->getAs<MemberPointerType>())
7309 CanTy = ResTypeMPtr->getPointeeType();
7312 if (CanTy.isVolatileQualified())
7313 VRQuals.addVolatile();
7314 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7324 /// \brief Helper class to manage the addition of builtin operator overload
7325 /// candidates. It provides shared state and utility methods used throughout
7326 /// the process, as well as a helper method to add each group of builtin
7327 /// operator overloads from the standard to a candidate set.
7328 class BuiltinOperatorOverloadBuilder {
7329 // Common instance state available to all overload candidate addition methods.
7331 ArrayRef<Expr *> Args;
7332 Qualifiers VisibleTypeConversionsQuals;
7333 bool HasArithmeticOrEnumeralCandidateType;
7334 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7335 OverloadCandidateSet &CandidateSet;
7337 // Define some constants used to index and iterate over the arithemetic types
7338 // provided via the getArithmeticType() method below.
7339 // The "promoted arithmetic types" are the arithmetic
7340 // types are that preserved by promotion (C++ [over.built]p2).
7341 static const unsigned FirstIntegralType = 4;
7342 static const unsigned LastIntegralType = 21;
7343 static const unsigned FirstPromotedIntegralType = 4,
7344 LastPromotedIntegralType = 12;
7345 static const unsigned FirstPromotedArithmeticType = 0,
7346 LastPromotedArithmeticType = 12;
7347 static const unsigned NumArithmeticTypes = 21;
7349 /// \brief Get the canonical type for a given arithmetic type index.
7350 CanQualType getArithmeticType(unsigned index) {
7351 assert(index < NumArithmeticTypes);
7352 static CanQualType ASTContext::* const
7353 ArithmeticTypes[NumArithmeticTypes] = {
7354 // Start of promoted types.
7355 &ASTContext::FloatTy,
7356 &ASTContext::DoubleTy,
7357 &ASTContext::LongDoubleTy,
7358 &ASTContext::Float128Ty,
7360 // Start of integral types.
7362 &ASTContext::LongTy,
7363 &ASTContext::LongLongTy,
7364 &ASTContext::Int128Ty,
7365 &ASTContext::UnsignedIntTy,
7366 &ASTContext::UnsignedLongTy,
7367 &ASTContext::UnsignedLongLongTy,
7368 &ASTContext::UnsignedInt128Ty,
7369 // End of promoted types.
7371 &ASTContext::BoolTy,
7372 &ASTContext::CharTy,
7373 &ASTContext::WCharTy,
7374 &ASTContext::Char16Ty,
7375 &ASTContext::Char32Ty,
7376 &ASTContext::SignedCharTy,
7377 &ASTContext::ShortTy,
7378 &ASTContext::UnsignedCharTy,
7379 &ASTContext::UnsignedShortTy,
7380 // End of integral types.
7381 // FIXME: What about complex? What about half?
7383 return S.Context.*ArithmeticTypes[index];
7386 /// \brief Gets the canonical type resulting from the usual arithemetic
7387 /// converions for the given arithmetic types.
7388 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7389 // Accelerator table for performing the usual arithmetic conversions.
7390 // The rules are basically:
7391 // - if either is floating-point, use the wider floating-point
7392 // - if same signedness, use the higher rank
7393 // - if same size, use unsigned of the higher rank
7394 // - use the larger type
7395 // These rules, together with the axiom that higher ranks are
7396 // never smaller, are sufficient to precompute all of these results
7397 // *except* when dealing with signed types of higher rank.
7398 // (we could precompute SLL x UI for all known platforms, but it's
7399 // better not to make any assumptions).
7400 // We assume that int128 has a higher rank than long long on all platforms.
7401 enum PromotedType : int8_t {
7403 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
7405 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
7406 [LastPromotedArithmeticType] = {
7407 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7408 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7409 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7410 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7411 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7412 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7413 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7414 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7415 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7416 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7417 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
7420 assert(L < LastPromotedArithmeticType);
7421 assert(R < LastPromotedArithmeticType);
7422 int Idx = ConversionsTable[L][R];
7424 // Fast path: the table gives us a concrete answer.
7425 if (Idx != Dep) return getArithmeticType(Idx);
7427 // Slow path: we need to compare widths.
7428 // An invariant is that the signed type has higher rank.
7429 CanQualType LT = getArithmeticType(L),
7430 RT = getArithmeticType(R);
7431 unsigned LW = S.Context.getIntWidth(LT),
7432 RW = S.Context.getIntWidth(RT);
7434 // If they're different widths, use the signed type.
7435 if (LW > RW) return LT;
7436 else if (LW < RW) return RT;
7438 // Otherwise, use the unsigned type of the signed type's rank.
7439 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7440 assert(L == SLL || R == SLL);
7441 return S.Context.UnsignedLongLongTy;
7444 /// \brief Helper method to factor out the common pattern of adding overloads
7445 /// for '++' and '--' builtin operators.
7446 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7449 QualType ParamTypes[2] = {
7450 S.Context.getLValueReferenceType(CandidateTy),
7454 // Non-volatile version.
7455 if (Args.size() == 1)
7456 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7458 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7460 // Use a heuristic to reduce number of builtin candidates in the set:
7461 // add volatile version only if there are conversions to a volatile type.
7464 S.Context.getLValueReferenceType(
7465 S.Context.getVolatileType(CandidateTy));
7466 if (Args.size() == 1)
7467 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7469 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7472 // Add restrict version only if there are conversions to a restrict type
7473 // and our candidate type is a non-restrict-qualified pointer.
7474 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7475 !CandidateTy.isRestrictQualified()) {
7477 = S.Context.getLValueReferenceType(
7478 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7479 if (Args.size() == 1)
7480 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7482 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7486 = S.Context.getLValueReferenceType(
7487 S.Context.getCVRQualifiedType(CandidateTy,
7488 (Qualifiers::Volatile |
7489 Qualifiers::Restrict)));
7490 if (Args.size() == 1)
7491 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7493 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7500 BuiltinOperatorOverloadBuilder(
7501 Sema &S, ArrayRef<Expr *> Args,
7502 Qualifiers VisibleTypeConversionsQuals,
7503 bool HasArithmeticOrEnumeralCandidateType,
7504 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7505 OverloadCandidateSet &CandidateSet)
7507 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7508 HasArithmeticOrEnumeralCandidateType(
7509 HasArithmeticOrEnumeralCandidateType),
7510 CandidateTypes(CandidateTypes),
7511 CandidateSet(CandidateSet) {
7512 // Validate some of our static helper constants in debug builds.
7513 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
7514 "Invalid first promoted integral type");
7515 assert(getArithmeticType(LastPromotedIntegralType - 1)
7516 == S.Context.UnsignedInt128Ty &&
7517 "Invalid last promoted integral type");
7518 assert(getArithmeticType(FirstPromotedArithmeticType)
7519 == S.Context.FloatTy &&
7520 "Invalid first promoted arithmetic type");
7521 assert(getArithmeticType(LastPromotedArithmeticType - 1)
7522 == S.Context.UnsignedInt128Ty &&
7523 "Invalid last promoted arithmetic type");
7526 // C++ [over.built]p3:
7528 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7529 // is either volatile or empty, there exist candidate operator
7530 // functions of the form
7532 // VQ T& operator++(VQ T&);
7533 // T operator++(VQ T&, int);
7535 // C++ [over.built]p4:
7537 // For every pair (T, VQ), where T is an arithmetic type other
7538 // than bool, and VQ is either volatile or empty, there exist
7539 // candidate operator functions of the form
7541 // VQ T& operator--(VQ T&);
7542 // T operator--(VQ T&, int);
7543 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7544 if (!HasArithmeticOrEnumeralCandidateType)
7547 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7548 Arith < NumArithmeticTypes; ++Arith) {
7549 addPlusPlusMinusMinusStyleOverloads(
7550 getArithmeticType(Arith),
7551 VisibleTypeConversionsQuals.hasVolatile(),
7552 VisibleTypeConversionsQuals.hasRestrict());
7556 // C++ [over.built]p5:
7558 // For every pair (T, VQ), where T is a cv-qualified or
7559 // cv-unqualified object type, and VQ is either volatile or
7560 // empty, there exist candidate operator functions of the form
7562 // T*VQ& operator++(T*VQ&);
7563 // T*VQ& operator--(T*VQ&);
7564 // T* operator++(T*VQ&, int);
7565 // T* operator--(T*VQ&, int);
7566 void addPlusPlusMinusMinusPointerOverloads() {
7567 for (BuiltinCandidateTypeSet::iterator
7568 Ptr = CandidateTypes[0].pointer_begin(),
7569 PtrEnd = CandidateTypes[0].pointer_end();
7570 Ptr != PtrEnd; ++Ptr) {
7571 // Skip pointer types that aren't pointers to object types.
7572 if (!(*Ptr)->getPointeeType()->isObjectType())
7575 addPlusPlusMinusMinusStyleOverloads(*Ptr,
7576 (!(*Ptr).isVolatileQualified() &&
7577 VisibleTypeConversionsQuals.hasVolatile()),
7578 (!(*Ptr).isRestrictQualified() &&
7579 VisibleTypeConversionsQuals.hasRestrict()));
7583 // C++ [over.built]p6:
7584 // For every cv-qualified or cv-unqualified object type T, there
7585 // exist candidate operator functions of the form
7587 // T& operator*(T*);
7589 // C++ [over.built]p7:
7590 // For every function type T that does not have cv-qualifiers or a
7591 // ref-qualifier, there exist candidate operator functions of the form
7592 // T& operator*(T*);
7593 void addUnaryStarPointerOverloads() {
7594 for (BuiltinCandidateTypeSet::iterator
7595 Ptr = CandidateTypes[0].pointer_begin(),
7596 PtrEnd = CandidateTypes[0].pointer_end();
7597 Ptr != PtrEnd; ++Ptr) {
7598 QualType ParamTy = *Ptr;
7599 QualType PointeeTy = ParamTy->getPointeeType();
7600 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7603 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7604 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7607 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7608 &ParamTy, Args, CandidateSet);
7612 // C++ [over.built]p9:
7613 // For every promoted arithmetic type T, there exist candidate
7614 // operator functions of the form
7618 void addUnaryPlusOrMinusArithmeticOverloads() {
7619 if (!HasArithmeticOrEnumeralCandidateType)
7622 for (unsigned Arith = FirstPromotedArithmeticType;
7623 Arith < LastPromotedArithmeticType; ++Arith) {
7624 QualType ArithTy = getArithmeticType(Arith);
7625 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7628 // Extension: We also add these operators for vector types.
7629 for (BuiltinCandidateTypeSet::iterator
7630 Vec = CandidateTypes[0].vector_begin(),
7631 VecEnd = CandidateTypes[0].vector_end();
7632 Vec != VecEnd; ++Vec) {
7633 QualType VecTy = *Vec;
7634 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7638 // C++ [over.built]p8:
7639 // For every type T, there exist candidate operator functions of
7642 // T* operator+(T*);
7643 void addUnaryPlusPointerOverloads() {
7644 for (BuiltinCandidateTypeSet::iterator
7645 Ptr = CandidateTypes[0].pointer_begin(),
7646 PtrEnd = CandidateTypes[0].pointer_end();
7647 Ptr != PtrEnd; ++Ptr) {
7648 QualType ParamTy = *Ptr;
7649 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7653 // C++ [over.built]p10:
7654 // For every promoted integral type T, there exist candidate
7655 // operator functions of the form
7658 void addUnaryTildePromotedIntegralOverloads() {
7659 if (!HasArithmeticOrEnumeralCandidateType)
7662 for (unsigned Int = FirstPromotedIntegralType;
7663 Int < LastPromotedIntegralType; ++Int) {
7664 QualType IntTy = getArithmeticType(Int);
7665 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7668 // Extension: We also add this operator for vector types.
7669 for (BuiltinCandidateTypeSet::iterator
7670 Vec = CandidateTypes[0].vector_begin(),
7671 VecEnd = CandidateTypes[0].vector_end();
7672 Vec != VecEnd; ++Vec) {
7673 QualType VecTy = *Vec;
7674 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7678 // C++ [over.match.oper]p16:
7679 // For every pointer to member type T or type std::nullptr_t, there
7680 // exist candidate operator functions of the form
7682 // bool operator==(T,T);
7683 // bool operator!=(T,T);
7684 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
7685 /// Set of (canonical) types that we've already handled.
7686 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7688 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7689 for (BuiltinCandidateTypeSet::iterator
7690 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7691 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7692 MemPtr != MemPtrEnd;
7694 // Don't add the same builtin candidate twice.
7695 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7698 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7699 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7702 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7703 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7704 if (AddedTypes.insert(NullPtrTy).second) {
7705 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7706 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7713 // C++ [over.built]p15:
7715 // For every T, where T is an enumeration type or a pointer type,
7716 // there exist candidate operator functions of the form
7718 // bool operator<(T, T);
7719 // bool operator>(T, T);
7720 // bool operator<=(T, T);
7721 // bool operator>=(T, T);
7722 // bool operator==(T, T);
7723 // bool operator!=(T, T);
7724 void addRelationalPointerOrEnumeralOverloads() {
7725 // C++ [over.match.oper]p3:
7726 // [...]the built-in candidates include all of the candidate operator
7727 // functions defined in 13.6 that, compared to the given operator, [...]
7728 // do not have the same parameter-type-list as any non-template non-member
7731 // Note that in practice, this only affects enumeration types because there
7732 // aren't any built-in candidates of record type, and a user-defined operator
7733 // must have an operand of record or enumeration type. Also, the only other
7734 // overloaded operator with enumeration arguments, operator=,
7735 // cannot be overloaded for enumeration types, so this is the only place
7736 // where we must suppress candidates like this.
7737 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7738 UserDefinedBinaryOperators;
7740 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7741 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7742 CandidateTypes[ArgIdx].enumeration_end()) {
7743 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7744 CEnd = CandidateSet.end();
7746 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7749 if (C->Function->isFunctionTemplateSpecialization())
7752 QualType FirstParamType =
7753 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7754 QualType SecondParamType =
7755 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7757 // Skip if either parameter isn't of enumeral type.
7758 if (!FirstParamType->isEnumeralType() ||
7759 !SecondParamType->isEnumeralType())
7762 // Add this operator to the set of known user-defined operators.
7763 UserDefinedBinaryOperators.insert(
7764 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7765 S.Context.getCanonicalType(SecondParamType)));
7770 /// Set of (canonical) types that we've already handled.
7771 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7773 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7774 for (BuiltinCandidateTypeSet::iterator
7775 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7776 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7777 Ptr != PtrEnd; ++Ptr) {
7778 // Don't add the same builtin candidate twice.
7779 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7782 QualType ParamTypes[2] = { *Ptr, *Ptr };
7783 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7785 for (BuiltinCandidateTypeSet::iterator
7786 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7787 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7788 Enum != EnumEnd; ++Enum) {
7789 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7791 // Don't add the same builtin candidate twice, or if a user defined
7792 // candidate exists.
7793 if (!AddedTypes.insert(CanonType).second ||
7794 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7798 QualType ParamTypes[2] = { *Enum, *Enum };
7799 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7804 // C++ [over.built]p13:
7806 // For every cv-qualified or cv-unqualified object type T
7807 // there exist candidate operator functions of the form
7809 // T* operator+(T*, ptrdiff_t);
7810 // T& operator[](T*, ptrdiff_t); [BELOW]
7811 // T* operator-(T*, ptrdiff_t);
7812 // T* operator+(ptrdiff_t, T*);
7813 // T& operator[](ptrdiff_t, T*); [BELOW]
7815 // C++ [over.built]p14:
7817 // For every T, where T is a pointer to object type, there
7818 // exist candidate operator functions of the form
7820 // ptrdiff_t operator-(T, T);
7821 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7822 /// Set of (canonical) types that we've already handled.
7823 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7825 for (int Arg = 0; Arg < 2; ++Arg) {
7826 QualType AsymmetricParamTypes[2] = {
7827 S.Context.getPointerDiffType(),
7828 S.Context.getPointerDiffType(),
7830 for (BuiltinCandidateTypeSet::iterator
7831 Ptr = CandidateTypes[Arg].pointer_begin(),
7832 PtrEnd = CandidateTypes[Arg].pointer_end();
7833 Ptr != PtrEnd; ++Ptr) {
7834 QualType PointeeTy = (*Ptr)->getPointeeType();
7835 if (!PointeeTy->isObjectType())
7838 AsymmetricParamTypes[Arg] = *Ptr;
7839 if (Arg == 0 || Op == OO_Plus) {
7840 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7841 // T* operator+(ptrdiff_t, T*);
7842 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
7844 if (Op == OO_Minus) {
7845 // ptrdiff_t operator-(T, T);
7846 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
7849 QualType ParamTypes[2] = { *Ptr, *Ptr };
7850 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7851 Args, CandidateSet);
7857 // C++ [over.built]p12:
7859 // For every pair of promoted arithmetic types L and R, there
7860 // exist candidate operator functions of the form
7862 // LR operator*(L, R);
7863 // LR operator/(L, R);
7864 // LR operator+(L, R);
7865 // LR operator-(L, R);
7866 // bool operator<(L, R);
7867 // bool operator>(L, R);
7868 // bool operator<=(L, R);
7869 // bool operator>=(L, R);
7870 // bool operator==(L, R);
7871 // bool operator!=(L, R);
7873 // where LR is the result of the usual arithmetic conversions
7874 // between types L and R.
7876 // C++ [over.built]p24:
7878 // For every pair of promoted arithmetic types L and R, there exist
7879 // candidate operator functions of the form
7881 // LR operator?(bool, L, R);
7883 // where LR is the result of the usual arithmetic conversions
7884 // between types L and R.
7885 // Our candidates ignore the first parameter.
7886 void addGenericBinaryArithmeticOverloads(bool isComparison) {
7887 if (!HasArithmeticOrEnumeralCandidateType)
7890 for (unsigned Left = FirstPromotedArithmeticType;
7891 Left < LastPromotedArithmeticType; ++Left) {
7892 for (unsigned Right = FirstPromotedArithmeticType;
7893 Right < LastPromotedArithmeticType; ++Right) {
7894 QualType LandR[2] = { getArithmeticType(Left),
7895 getArithmeticType(Right) };
7897 isComparison ? S.Context.BoolTy
7898 : getUsualArithmeticConversions(Left, Right);
7899 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7903 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7904 // conditional operator for vector types.
7905 for (BuiltinCandidateTypeSet::iterator
7906 Vec1 = CandidateTypes[0].vector_begin(),
7907 Vec1End = CandidateTypes[0].vector_end();
7908 Vec1 != Vec1End; ++Vec1) {
7909 for (BuiltinCandidateTypeSet::iterator
7910 Vec2 = CandidateTypes[1].vector_begin(),
7911 Vec2End = CandidateTypes[1].vector_end();
7912 Vec2 != Vec2End; ++Vec2) {
7913 QualType LandR[2] = { *Vec1, *Vec2 };
7914 QualType Result = S.Context.BoolTy;
7915 if (!isComparison) {
7916 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7922 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7927 // C++ [over.built]p17:
7929 // For every pair of promoted integral types L and R, there
7930 // exist candidate operator functions of the form
7932 // LR operator%(L, R);
7933 // LR operator&(L, R);
7934 // LR operator^(L, R);
7935 // LR operator|(L, R);
7936 // L operator<<(L, R);
7937 // L operator>>(L, R);
7939 // where LR is the result of the usual arithmetic conversions
7940 // between types L and R.
7941 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7942 if (!HasArithmeticOrEnumeralCandidateType)
7945 for (unsigned Left = FirstPromotedIntegralType;
7946 Left < LastPromotedIntegralType; ++Left) {
7947 for (unsigned Right = FirstPromotedIntegralType;
7948 Right < LastPromotedIntegralType; ++Right) {
7949 QualType LandR[2] = { getArithmeticType(Left),
7950 getArithmeticType(Right) };
7951 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7953 : getUsualArithmeticConversions(Left, Right);
7954 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7959 // C++ [over.built]p20:
7961 // For every pair (T, VQ), where T is an enumeration or
7962 // pointer to member type and VQ is either volatile or
7963 // empty, there exist candidate operator functions of the form
7965 // VQ T& operator=(VQ T&, T);
7966 void addAssignmentMemberPointerOrEnumeralOverloads() {
7967 /// Set of (canonical) types that we've already handled.
7968 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7970 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7971 for (BuiltinCandidateTypeSet::iterator
7972 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7973 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7974 Enum != EnumEnd; ++Enum) {
7975 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
7978 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7981 for (BuiltinCandidateTypeSet::iterator
7982 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7983 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7984 MemPtr != MemPtrEnd; ++MemPtr) {
7985 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
7988 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7993 // C++ [over.built]p19:
7995 // For every pair (T, VQ), where T is any type and VQ is either
7996 // volatile or empty, there exist candidate operator functions
7999 // T*VQ& operator=(T*VQ&, T*);
8001 // C++ [over.built]p21:
8003 // For every pair (T, VQ), where T is a cv-qualified or
8004 // cv-unqualified object type and VQ is either volatile or
8005 // empty, there exist candidate operator functions of the form
8007 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8008 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8009 void addAssignmentPointerOverloads(bool isEqualOp) {
8010 /// Set of (canonical) types that we've already handled.
8011 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8013 for (BuiltinCandidateTypeSet::iterator
8014 Ptr = CandidateTypes[0].pointer_begin(),
8015 PtrEnd = CandidateTypes[0].pointer_end();
8016 Ptr != PtrEnd; ++Ptr) {
8017 // If this is operator=, keep track of the builtin candidates we added.
8019 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8020 else if (!(*Ptr)->getPointeeType()->isObjectType())
8023 // non-volatile version
8024 QualType ParamTypes[2] = {
8025 S.Context.getLValueReferenceType(*Ptr),
8026 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8028 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8029 /*IsAssigmentOperator=*/ isEqualOp);
8031 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8032 VisibleTypeConversionsQuals.hasVolatile();
8036 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8037 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8038 /*IsAssigmentOperator=*/isEqualOp);
8041 if (!(*Ptr).isRestrictQualified() &&
8042 VisibleTypeConversionsQuals.hasRestrict()) {
8045 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8046 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8047 /*IsAssigmentOperator=*/isEqualOp);
8050 // volatile restrict version
8052 = S.Context.getLValueReferenceType(
8053 S.Context.getCVRQualifiedType(*Ptr,
8054 (Qualifiers::Volatile |
8055 Qualifiers::Restrict)));
8056 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8057 /*IsAssigmentOperator=*/isEqualOp);
8063 for (BuiltinCandidateTypeSet::iterator
8064 Ptr = CandidateTypes[1].pointer_begin(),
8065 PtrEnd = CandidateTypes[1].pointer_end();
8066 Ptr != PtrEnd; ++Ptr) {
8067 // Make sure we don't add the same candidate twice.
8068 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8071 QualType ParamTypes[2] = {
8072 S.Context.getLValueReferenceType(*Ptr),
8076 // non-volatile version
8077 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8078 /*IsAssigmentOperator=*/true);
8080 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8081 VisibleTypeConversionsQuals.hasVolatile();
8085 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8086 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8087 /*IsAssigmentOperator=*/true);
8090 if (!(*Ptr).isRestrictQualified() &&
8091 VisibleTypeConversionsQuals.hasRestrict()) {
8094 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8095 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8096 /*IsAssigmentOperator=*/true);
8099 // volatile restrict version
8101 = S.Context.getLValueReferenceType(
8102 S.Context.getCVRQualifiedType(*Ptr,
8103 (Qualifiers::Volatile |
8104 Qualifiers::Restrict)));
8105 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8106 /*IsAssigmentOperator=*/true);
8113 // C++ [over.built]p18:
8115 // For every triple (L, VQ, R), where L is an arithmetic type,
8116 // VQ is either volatile or empty, and R is a promoted
8117 // arithmetic type, there exist candidate operator functions of
8120 // VQ L& operator=(VQ L&, R);
8121 // VQ L& operator*=(VQ L&, R);
8122 // VQ L& operator/=(VQ L&, R);
8123 // VQ L& operator+=(VQ L&, R);
8124 // VQ L& operator-=(VQ L&, R);
8125 void addAssignmentArithmeticOverloads(bool isEqualOp) {
8126 if (!HasArithmeticOrEnumeralCandidateType)
8129 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8130 for (unsigned Right = FirstPromotedArithmeticType;
8131 Right < LastPromotedArithmeticType; ++Right) {
8132 QualType ParamTypes[2];
8133 ParamTypes[1] = getArithmeticType(Right);
8135 // Add this built-in operator as a candidate (VQ is empty).
8137 S.Context.getLValueReferenceType(getArithmeticType(Left));
8138 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8139 /*IsAssigmentOperator=*/isEqualOp);
8141 // Add this built-in operator as a candidate (VQ is 'volatile').
8142 if (VisibleTypeConversionsQuals.hasVolatile()) {
8144 S.Context.getVolatileType(getArithmeticType(Left));
8145 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8146 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8147 /*IsAssigmentOperator=*/isEqualOp);
8152 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8153 for (BuiltinCandidateTypeSet::iterator
8154 Vec1 = CandidateTypes[0].vector_begin(),
8155 Vec1End = CandidateTypes[0].vector_end();
8156 Vec1 != Vec1End; ++Vec1) {
8157 for (BuiltinCandidateTypeSet::iterator
8158 Vec2 = CandidateTypes[1].vector_begin(),
8159 Vec2End = CandidateTypes[1].vector_end();
8160 Vec2 != Vec2End; ++Vec2) {
8161 QualType ParamTypes[2];
8162 ParamTypes[1] = *Vec2;
8163 // Add this built-in operator as a candidate (VQ is empty).
8164 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8165 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8166 /*IsAssigmentOperator=*/isEqualOp);
8168 // Add this built-in operator as a candidate (VQ is 'volatile').
8169 if (VisibleTypeConversionsQuals.hasVolatile()) {
8170 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8171 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8172 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
8173 /*IsAssigmentOperator=*/isEqualOp);
8179 // C++ [over.built]p22:
8181 // For every triple (L, VQ, R), where L is an integral type, VQ
8182 // is either volatile or empty, and R is a promoted integral
8183 // type, there exist candidate operator functions of the form
8185 // VQ L& operator%=(VQ L&, R);
8186 // VQ L& operator<<=(VQ L&, R);
8187 // VQ L& operator>>=(VQ L&, R);
8188 // VQ L& operator&=(VQ L&, R);
8189 // VQ L& operator^=(VQ L&, R);
8190 // VQ L& operator|=(VQ L&, R);
8191 void addAssignmentIntegralOverloads() {
8192 if (!HasArithmeticOrEnumeralCandidateType)
8195 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8196 for (unsigned Right = FirstPromotedIntegralType;
8197 Right < LastPromotedIntegralType; ++Right) {
8198 QualType ParamTypes[2];
8199 ParamTypes[1] = getArithmeticType(Right);
8201 // Add this built-in operator as a candidate (VQ is empty).
8203 S.Context.getLValueReferenceType(getArithmeticType(Left));
8204 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8205 if (VisibleTypeConversionsQuals.hasVolatile()) {
8206 // Add this built-in operator as a candidate (VQ is 'volatile').
8207 ParamTypes[0] = getArithmeticType(Left);
8208 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8209 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8210 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
8216 // C++ [over.operator]p23:
8218 // There also exist candidate operator functions of the form
8220 // bool operator!(bool);
8221 // bool operator&&(bool, bool);
8222 // bool operator||(bool, bool);
8223 void addExclaimOverload() {
8224 QualType ParamTy = S.Context.BoolTy;
8225 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
8226 /*IsAssignmentOperator=*/false,
8227 /*NumContextualBoolArguments=*/1);
8229 void addAmpAmpOrPipePipeOverload() {
8230 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8231 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
8232 /*IsAssignmentOperator=*/false,
8233 /*NumContextualBoolArguments=*/2);
8236 // C++ [over.built]p13:
8238 // For every cv-qualified or cv-unqualified object type T there
8239 // exist candidate operator functions of the form
8241 // T* operator+(T*, ptrdiff_t); [ABOVE]
8242 // T& operator[](T*, ptrdiff_t);
8243 // T* operator-(T*, ptrdiff_t); [ABOVE]
8244 // T* operator+(ptrdiff_t, T*); [ABOVE]
8245 // T& operator[](ptrdiff_t, T*);
8246 void addSubscriptOverloads() {
8247 for (BuiltinCandidateTypeSet::iterator
8248 Ptr = CandidateTypes[0].pointer_begin(),
8249 PtrEnd = CandidateTypes[0].pointer_end();
8250 Ptr != PtrEnd; ++Ptr) {
8251 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8252 QualType PointeeType = (*Ptr)->getPointeeType();
8253 if (!PointeeType->isObjectType())
8256 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8258 // T& operator[](T*, ptrdiff_t)
8259 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8262 for (BuiltinCandidateTypeSet::iterator
8263 Ptr = CandidateTypes[1].pointer_begin(),
8264 PtrEnd = CandidateTypes[1].pointer_end();
8265 Ptr != PtrEnd; ++Ptr) {
8266 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8267 QualType PointeeType = (*Ptr)->getPointeeType();
8268 if (!PointeeType->isObjectType())
8271 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8273 // T& operator[](ptrdiff_t, T*)
8274 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8278 // C++ [over.built]p11:
8279 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8280 // C1 is the same type as C2 or is a derived class of C2, T is an object
8281 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8282 // there exist candidate operator functions of the form
8284 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8286 // where CV12 is the union of CV1 and CV2.
8287 void addArrowStarOverloads() {
8288 for (BuiltinCandidateTypeSet::iterator
8289 Ptr = CandidateTypes[0].pointer_begin(),
8290 PtrEnd = CandidateTypes[0].pointer_end();
8291 Ptr != PtrEnd; ++Ptr) {
8292 QualType C1Ty = (*Ptr);
8294 QualifierCollector Q1;
8295 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8296 if (!isa<RecordType>(C1))
8298 // heuristic to reduce number of builtin candidates in the set.
8299 // Add volatile/restrict version only if there are conversions to a
8300 // volatile/restrict type.
8301 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8303 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8305 for (BuiltinCandidateTypeSet::iterator
8306 MemPtr = CandidateTypes[1].member_pointer_begin(),
8307 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8308 MemPtr != MemPtrEnd; ++MemPtr) {
8309 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8310 QualType C2 = QualType(mptr->getClass(), 0);
8311 C2 = C2.getUnqualifiedType();
8312 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8314 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8316 QualType T = mptr->getPointeeType();
8317 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8318 T.isVolatileQualified())
8320 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8321 T.isRestrictQualified())
8323 T = Q1.apply(S.Context, T);
8324 QualType ResultTy = S.Context.getLValueReferenceType(T);
8325 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
8330 // Note that we don't consider the first argument, since it has been
8331 // contextually converted to bool long ago. The candidates below are
8332 // therefore added as binary.
8334 // C++ [over.built]p25:
8335 // For every type T, where T is a pointer, pointer-to-member, or scoped
8336 // enumeration type, there exist candidate operator functions of the form
8338 // T operator?(bool, T, T);
8340 void addConditionalOperatorOverloads() {
8341 /// Set of (canonical) types that we've already handled.
8342 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8344 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8345 for (BuiltinCandidateTypeSet::iterator
8346 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8347 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8348 Ptr != PtrEnd; ++Ptr) {
8349 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8352 QualType ParamTypes[2] = { *Ptr, *Ptr };
8353 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
8356 for (BuiltinCandidateTypeSet::iterator
8357 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8358 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8359 MemPtr != MemPtrEnd; ++MemPtr) {
8360 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8363 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8364 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
8367 if (S.getLangOpts().CPlusPlus11) {
8368 for (BuiltinCandidateTypeSet::iterator
8369 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8370 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8371 Enum != EnumEnd; ++Enum) {
8372 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8375 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8378 QualType ParamTypes[2] = { *Enum, *Enum };
8379 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
8386 } // end anonymous namespace
8388 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
8389 /// operator overloads to the candidate set (C++ [over.built]), based
8390 /// on the operator @p Op and the arguments given. For example, if the
8391 /// operator is a binary '+', this routine might add "int
8392 /// operator+(int, int)" to cover integer addition.
8393 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8394 SourceLocation OpLoc,
8395 ArrayRef<Expr *> Args,
8396 OverloadCandidateSet &CandidateSet) {
8397 // Find all of the types that the arguments can convert to, but only
8398 // if the operator we're looking at has built-in operator candidates
8399 // that make use of these types. Also record whether we encounter non-record
8400 // candidate types or either arithmetic or enumeral candidate types.
8401 Qualifiers VisibleTypeConversionsQuals;
8402 VisibleTypeConversionsQuals.addConst();
8403 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8404 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8406 bool HasNonRecordCandidateType = false;
8407 bool HasArithmeticOrEnumeralCandidateType = false;
8408 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8409 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8410 CandidateTypes.emplace_back(*this);
8411 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8414 (Op == OO_Exclaim ||
8417 VisibleTypeConversionsQuals);
8418 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8419 CandidateTypes[ArgIdx].hasNonRecordTypes();
8420 HasArithmeticOrEnumeralCandidateType =
8421 HasArithmeticOrEnumeralCandidateType ||
8422 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8425 // Exit early when no non-record types have been added to the candidate set
8426 // for any of the arguments to the operator.
8428 // We can't exit early for !, ||, or &&, since there we have always have
8429 // 'bool' overloads.
8430 if (!HasNonRecordCandidateType &&
8431 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8434 // Setup an object to manage the common state for building overloads.
8435 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8436 VisibleTypeConversionsQuals,
8437 HasArithmeticOrEnumeralCandidateType,
8438 CandidateTypes, CandidateSet);
8440 // Dispatch over the operation to add in only those overloads which apply.
8443 case NUM_OVERLOADED_OPERATORS:
8444 llvm_unreachable("Expected an overloaded operator");
8449 case OO_Array_Delete:
8452 "Special operators don't use AddBuiltinOperatorCandidates");
8457 // C++ [over.match.oper]p3:
8458 // -- For the operator ',', the unary operator '&', the
8459 // operator '->', or the operator 'co_await', the
8460 // built-in candidates set is empty.
8463 case OO_Plus: // '+' is either unary or binary
8464 if (Args.size() == 1)
8465 OpBuilder.addUnaryPlusPointerOverloads();
8468 case OO_Minus: // '-' is either unary or binary
8469 if (Args.size() == 1) {
8470 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8472 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8473 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8477 case OO_Star: // '*' is either unary or binary
8478 if (Args.size() == 1)
8479 OpBuilder.addUnaryStarPointerOverloads();
8481 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8485 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8490 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8491 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8495 case OO_ExclaimEqual:
8496 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8502 case OO_GreaterEqual:
8503 OpBuilder.addRelationalPointerOrEnumeralOverloads();
8504 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8511 case OO_GreaterGreater:
8512 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8515 case OO_Amp: // '&' is either unary or binary
8516 if (Args.size() == 1)
8517 // C++ [over.match.oper]p3:
8518 // -- For the operator ',', the unary operator '&', or the
8519 // operator '->', the built-in candidates set is empty.
8522 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8526 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8530 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8535 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8540 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8543 case OO_PercentEqual:
8544 case OO_LessLessEqual:
8545 case OO_GreaterGreaterEqual:
8549 OpBuilder.addAssignmentIntegralOverloads();
8553 OpBuilder.addExclaimOverload();
8558 OpBuilder.addAmpAmpOrPipePipeOverload();
8562 OpBuilder.addSubscriptOverloads();
8566 OpBuilder.addArrowStarOverloads();
8569 case OO_Conditional:
8570 OpBuilder.addConditionalOperatorOverloads();
8571 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8576 /// \brief Add function candidates found via argument-dependent lookup
8577 /// to the set of overloading candidates.
8579 /// This routine performs argument-dependent name lookup based on the
8580 /// given function name (which may also be an operator name) and adds
8581 /// all of the overload candidates found by ADL to the overload
8582 /// candidate set (C++ [basic.lookup.argdep]).
8584 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8586 ArrayRef<Expr *> Args,
8587 TemplateArgumentListInfo *ExplicitTemplateArgs,
8588 OverloadCandidateSet& CandidateSet,
8589 bool PartialOverloading) {
8592 // FIXME: This approach for uniquing ADL results (and removing
8593 // redundant candidates from the set) relies on pointer-equality,
8594 // which means we need to key off the canonical decl. However,
8595 // always going back to the canonical decl might not get us the
8596 // right set of default arguments. What default arguments are
8597 // we supposed to consider on ADL candidates, anyway?
8599 // FIXME: Pass in the explicit template arguments?
8600 ArgumentDependentLookup(Name, Loc, Args, Fns);
8602 // Erase all of the candidates we already knew about.
8603 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8604 CandEnd = CandidateSet.end();
8605 Cand != CandEnd; ++Cand)
8606 if (Cand->Function) {
8607 Fns.erase(Cand->Function);
8608 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8612 // For each of the ADL candidates we found, add it to the overload
8614 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8615 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8616 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8617 if (ExplicitTemplateArgs)
8620 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8621 PartialOverloading);
8623 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8624 FoundDecl, ExplicitTemplateArgs,
8625 Args, CandidateSet, PartialOverloading);
8630 enum class Comparison { Equal, Better, Worse };
8633 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
8634 /// overload resolution.
8636 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
8637 /// Cand1's first N enable_if attributes have precisely the same conditions as
8638 /// Cand2's first N enable_if attributes (where N = the number of enable_if
8639 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
8641 /// Note that you can have a pair of candidates such that Cand1's enable_if
8642 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
8643 /// worse than Cand1's.
8644 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
8645 const FunctionDecl *Cand2) {
8646 // Common case: One (or both) decls don't have enable_if attrs.
8647 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
8648 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
8649 if (!Cand1Attr || !Cand2Attr) {
8650 if (Cand1Attr == Cand2Attr)
8651 return Comparison::Equal;
8652 return Cand1Attr ? Comparison::Better : Comparison::Worse;
8655 // FIXME: The next several lines are just
8656 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8657 // instead of reverse order which is how they're stored in the AST.
8658 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1);
8659 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2);
8661 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
8662 // has fewer enable_if attributes than Cand2.
8663 if (Cand1Attrs.size() < Cand2Attrs.size())
8664 return Comparison::Worse;
8666 auto Cand1I = Cand1Attrs.begin();
8667 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8668 for (auto &Cand2A : Cand2Attrs) {
8672 auto &Cand1A = *Cand1I++;
8673 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true);
8674 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true);
8675 if (Cand1ID != Cand2ID)
8676 return Comparison::Worse;
8679 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better;
8682 /// isBetterOverloadCandidate - Determines whether the first overload
8683 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8684 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8685 const OverloadCandidate &Cand2,
8687 bool UserDefinedConversion) {
8688 // Define viable functions to be better candidates than non-viable
8691 return Cand1.Viable;
8692 else if (!Cand1.Viable)
8695 // C++ [over.match.best]p1:
8697 // -- if F is a static member function, ICS1(F) is defined such
8698 // that ICS1(F) is neither better nor worse than ICS1(G) for
8699 // any function G, and, symmetrically, ICS1(G) is neither
8700 // better nor worse than ICS1(F).
8701 unsigned StartArg = 0;
8702 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8705 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
8706 // We don't allow incompatible pointer conversions in C++.
8707 if (!S.getLangOpts().CPlusPlus)
8708 return ICS.isStandard() &&
8709 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
8711 // The only ill-formed conversion we allow in C++ is the string literal to
8712 // char* conversion, which is only considered ill-formed after C++11.
8713 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
8714 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
8717 // Define functions that don't require ill-formed conversions for a given
8718 // argument to be better candidates than functions that do.
8719 unsigned NumArgs = Cand1.NumConversions;
8720 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8721 bool HasBetterConversion = false;
8722 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8723 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
8724 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
8725 if (Cand1Bad != Cand2Bad) {
8728 HasBetterConversion = true;
8732 if (HasBetterConversion)
8735 // C++ [over.match.best]p1:
8736 // A viable function F1 is defined to be a better function than another
8737 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
8738 // conversion sequence than ICSi(F2), and then...
8739 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8740 switch (CompareImplicitConversionSequences(S, Loc,
8741 Cand1.Conversions[ArgIdx],
8742 Cand2.Conversions[ArgIdx])) {
8743 case ImplicitConversionSequence::Better:
8744 // Cand1 has a better conversion sequence.
8745 HasBetterConversion = true;
8748 case ImplicitConversionSequence::Worse:
8749 // Cand1 can't be better than Cand2.
8752 case ImplicitConversionSequence::Indistinguishable:
8758 // -- for some argument j, ICSj(F1) is a better conversion sequence than
8759 // ICSj(F2), or, if not that,
8760 if (HasBetterConversion)
8763 // -- the context is an initialization by user-defined conversion
8764 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8765 // from the return type of F1 to the destination type (i.e.,
8766 // the type of the entity being initialized) is a better
8767 // conversion sequence than the standard conversion sequence
8768 // from the return type of F2 to the destination type.
8769 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8770 isa<CXXConversionDecl>(Cand1.Function) &&
8771 isa<CXXConversionDecl>(Cand2.Function)) {
8772 // First check whether we prefer one of the conversion functions over the
8773 // other. This only distinguishes the results in non-standard, extension
8774 // cases such as the conversion from a lambda closure type to a function
8775 // pointer or block.
8776 ImplicitConversionSequence::CompareKind Result =
8777 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8778 if (Result == ImplicitConversionSequence::Indistinguishable)
8779 Result = CompareStandardConversionSequences(S, Loc,
8780 Cand1.FinalConversion,
8781 Cand2.FinalConversion);
8783 if (Result != ImplicitConversionSequence::Indistinguishable)
8784 return Result == ImplicitConversionSequence::Better;
8786 // FIXME: Compare kind of reference binding if conversion functions
8787 // convert to a reference type used in direct reference binding, per
8788 // C++14 [over.match.best]p1 section 2 bullet 3.
8791 // -- F1 is a non-template function and F2 is a function template
8792 // specialization, or, if not that,
8793 bool Cand1IsSpecialization = Cand1.Function &&
8794 Cand1.Function->getPrimaryTemplate();
8795 bool Cand2IsSpecialization = Cand2.Function &&
8796 Cand2.Function->getPrimaryTemplate();
8797 if (Cand1IsSpecialization != Cand2IsSpecialization)
8798 return Cand2IsSpecialization;
8800 // -- F1 and F2 are function template specializations, and the function
8801 // template for F1 is more specialized than the template for F2
8802 // according to the partial ordering rules described in 14.5.5.2, or,
8804 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8805 if (FunctionTemplateDecl *BetterTemplate
8806 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8807 Cand2.Function->getPrimaryTemplate(),
8809 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8811 Cand1.ExplicitCallArguments,
8812 Cand2.ExplicitCallArguments))
8813 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
8816 // FIXME: Work around a defect in the C++17 inheriting constructor wording.
8817 // A derived-class constructor beats an (inherited) base class constructor.
8818 bool Cand1IsInherited =
8819 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
8820 bool Cand2IsInherited =
8821 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
8822 if (Cand1IsInherited != Cand2IsInherited)
8823 return Cand2IsInherited;
8824 else if (Cand1IsInherited) {
8825 assert(Cand2IsInherited);
8826 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
8827 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
8828 if (Cand1Class->isDerivedFrom(Cand2Class))
8830 if (Cand2Class->isDerivedFrom(Cand1Class))
8832 // Inherited from sibling base classes: still ambiguous.
8835 // Check for enable_if value-based overload resolution.
8836 if (Cand1.Function && Cand2.Function) {
8837 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
8838 if (Cmp != Comparison::Equal)
8839 return Cmp == Comparison::Better;
8842 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
8843 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8844 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
8845 S.IdentifyCUDAPreference(Caller, Cand2.Function);
8848 bool HasPS1 = Cand1.Function != nullptr &&
8849 functionHasPassObjectSizeParams(Cand1.Function);
8850 bool HasPS2 = Cand2.Function != nullptr &&
8851 functionHasPassObjectSizeParams(Cand2.Function);
8852 return HasPS1 != HasPS2 && HasPS1;
8855 /// Determine whether two declarations are "equivalent" for the purposes of
8856 /// name lookup and overload resolution. This applies when the same internal/no
8857 /// linkage entity is defined by two modules (probably by textually including
8858 /// the same header). In such a case, we don't consider the declarations to
8859 /// declare the same entity, but we also don't want lookups with both
8860 /// declarations visible to be ambiguous in some cases (this happens when using
8861 /// a modularized libstdc++).
8862 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
8863 const NamedDecl *B) {
8864 auto *VA = dyn_cast_or_null<ValueDecl>(A);
8865 auto *VB = dyn_cast_or_null<ValueDecl>(B);
8869 // The declarations must be declaring the same name as an internal linkage
8870 // entity in different modules.
8871 if (!VA->getDeclContext()->getRedeclContext()->Equals(
8872 VB->getDeclContext()->getRedeclContext()) ||
8873 getOwningModule(const_cast<ValueDecl *>(VA)) ==
8874 getOwningModule(const_cast<ValueDecl *>(VB)) ||
8875 VA->isExternallyVisible() || VB->isExternallyVisible())
8878 // Check that the declarations appear to be equivalent.
8880 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
8881 // For constants and functions, we should check the initializer or body is
8882 // the same. For non-constant variables, we shouldn't allow it at all.
8883 if (Context.hasSameType(VA->getType(), VB->getType()))
8886 // Enum constants within unnamed enumerations will have different types, but
8887 // may still be similar enough to be interchangeable for our purposes.
8888 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
8889 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
8890 // Only handle anonymous enums. If the enumerations were named and
8891 // equivalent, they would have been merged to the same type.
8892 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
8893 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
8894 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
8895 !Context.hasSameType(EnumA->getIntegerType(),
8896 EnumB->getIntegerType()))
8898 // Allow this only if the value is the same for both enumerators.
8899 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
8903 // Nothing else is sufficiently similar.
8907 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
8908 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
8909 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
8911 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
8912 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
8913 << !M << (M ? M->getFullModuleName() : "");
8915 for (auto *E : Equiv) {
8916 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
8917 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
8918 << !M << (M ? M->getFullModuleName() : "");
8922 /// \brief Computes the best viable function (C++ 13.3.3)
8923 /// within an overload candidate set.
8925 /// \param Loc The location of the function name (or operator symbol) for
8926 /// which overload resolution occurs.
8928 /// \param Best If overload resolution was successful or found a deleted
8929 /// function, \p Best points to the candidate function found.
8931 /// \returns The result of overload resolution.
8933 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8935 bool UserDefinedConversion) {
8936 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
8937 std::transform(begin(), end(), std::back_inserter(Candidates),
8938 [](OverloadCandidate &Cand) { return &Cand; });
8940 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
8941 // are accepted by both clang and NVCC. However, during a particular
8942 // compilation mode only one call variant is viable. We need to
8943 // exclude non-viable overload candidates from consideration based
8944 // only on their host/device attributes. Specifically, if one
8945 // candidate call is WrongSide and the other is SameSide, we ignore
8946 // the WrongSide candidate.
8947 if (S.getLangOpts().CUDA) {
8948 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
8949 bool ContainsSameSideCandidate =
8950 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
8951 return Cand->Function &&
8952 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8955 if (ContainsSameSideCandidate) {
8956 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
8957 return Cand->Function &&
8958 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
8959 Sema::CFP_WrongSide;
8961 Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(),
8962 IsWrongSideCandidate),
8967 // Find the best viable function.
8969 for (auto *Cand : Candidates)
8971 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8972 UserDefinedConversion))
8975 // If we didn't find any viable functions, abort.
8977 return OR_No_Viable_Function;
8979 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
8981 // Make sure that this function is better than every other viable
8982 // function. If not, we have an ambiguity.
8983 for (auto *Cand : Candidates) {
8986 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8987 UserDefinedConversion)) {
8988 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
8990 EquivalentCands.push_back(Cand->Function);
8995 return OR_Ambiguous;
8999 // Best is the best viable function.
9000 if (Best->Function &&
9001 (Best->Function->isDeleted() ||
9002 S.isFunctionConsideredUnavailable(Best->Function)))
9005 if (!EquivalentCands.empty())
9006 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9014 enum OverloadCandidateKind {
9018 oc_function_template,
9020 oc_constructor_template,
9021 oc_implicit_default_constructor,
9022 oc_implicit_copy_constructor,
9023 oc_implicit_move_constructor,
9024 oc_implicit_copy_assignment,
9025 oc_implicit_move_assignment,
9026 oc_inherited_constructor,
9027 oc_inherited_constructor_template
9030 static OverloadCandidateKind
9031 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9032 std::string &Description) {
9033 bool isTemplate = false;
9035 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9037 Description = S.getTemplateArgumentBindingsText(
9038 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9041 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9042 if (!Ctor->isImplicit()) {
9043 if (isa<ConstructorUsingShadowDecl>(Found))
9044 return isTemplate ? oc_inherited_constructor_template
9045 : oc_inherited_constructor;
9047 return isTemplate ? oc_constructor_template : oc_constructor;
9050 if (Ctor->isDefaultConstructor())
9051 return oc_implicit_default_constructor;
9053 if (Ctor->isMoveConstructor())
9054 return oc_implicit_move_constructor;
9056 assert(Ctor->isCopyConstructor() &&
9057 "unexpected sort of implicit constructor");
9058 return oc_implicit_copy_constructor;
9061 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9062 // This actually gets spelled 'candidate function' for now, but
9063 // it doesn't hurt to split it out.
9064 if (!Meth->isImplicit())
9065 return isTemplate ? oc_method_template : oc_method;
9067 if (Meth->isMoveAssignmentOperator())
9068 return oc_implicit_move_assignment;
9070 if (Meth->isCopyAssignmentOperator())
9071 return oc_implicit_copy_assignment;
9073 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9077 return isTemplate ? oc_function_template : oc_function;
9080 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9081 // FIXME: It'd be nice to only emit a note once per using-decl per overload
9083 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9084 S.Diag(FoundDecl->getLocation(),
9085 diag::note_ovl_candidate_inherited_constructor)
9086 << Shadow->getNominatedBaseClass();
9089 } // end anonymous namespace
9091 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9092 const FunctionDecl *FD) {
9093 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9095 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9103 /// \brief Returns true if we can take the address of the function.
9105 /// \param Complain - If true, we'll emit a diagnostic
9106 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9107 /// we in overload resolution?
9108 /// \param Loc - The location of the statement we're complaining about. Ignored
9109 /// if we're not complaining, or if we're in overload resolution.
9110 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9112 bool InOverloadResolution,
9113 SourceLocation Loc) {
9114 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9116 if (InOverloadResolution)
9117 S.Diag(FD->getLocStart(),
9118 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9120 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9125 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9126 return P->hasAttr<PassObjectSizeAttr>();
9128 if (I == FD->param_end())
9132 // Add one to ParamNo because it's user-facing
9133 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9134 if (InOverloadResolution)
9135 S.Diag(FD->getLocation(),
9136 diag::note_ovl_candidate_has_pass_object_size_params)
9139 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9145 static bool checkAddressOfCandidateIsAvailable(Sema &S,
9146 const FunctionDecl *FD) {
9147 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9148 /*InOverloadResolution=*/true,
9149 /*Loc=*/SourceLocation());
9152 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9154 SourceLocation Loc) {
9155 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9156 /*InOverloadResolution=*/false,
9160 // Notes the location of an overload candidate.
9161 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9162 QualType DestType, bool TakingAddress) {
9163 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9167 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9168 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9169 << (unsigned) K << Fn << FnDesc;
9171 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9172 Diag(Fn->getLocation(), PD);
9173 MaybeEmitInheritedConstructorNote(*this, Found);
9176 // Notes the location of all overload candidates designated through
9178 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9179 bool TakingAddress) {
9180 assert(OverloadedExpr->getType() == Context.OverloadTy);
9182 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9183 OverloadExpr *OvlExpr = Ovl.Expression;
9185 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9186 IEnd = OvlExpr->decls_end();
9188 if (FunctionTemplateDecl *FunTmpl =
9189 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9190 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9192 } else if (FunctionDecl *Fun
9193 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9194 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9199 /// Diagnoses an ambiguous conversion. The partial diagnostic is the
9200 /// "lead" diagnostic; it will be given two arguments, the source and
9201 /// target types of the conversion.
9202 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9204 SourceLocation CaretLoc,
9205 const PartialDiagnostic &PDiag) const {
9206 S.Diag(CaretLoc, PDiag)
9207 << Ambiguous.getFromType() << Ambiguous.getToType();
9208 // FIXME: The note limiting machinery is borrowed from
9209 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9210 // refactoring here.
9211 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9212 unsigned CandsShown = 0;
9213 AmbiguousConversionSequence::const_iterator I, E;
9214 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9215 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9218 S.NoteOverloadCandidate(I->first, I->second);
9221 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9224 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9225 unsigned I, bool TakingCandidateAddress) {
9226 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9227 assert(Conv.isBad());
9228 assert(Cand->Function && "for now, candidate must be a function");
9229 FunctionDecl *Fn = Cand->Function;
9231 // There's a conversion slot for the object argument if this is a
9232 // non-constructor method. Note that 'I' corresponds the
9233 // conversion-slot index.
9234 bool isObjectArgument = false;
9235 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9237 isObjectArgument = true;
9243 OverloadCandidateKind FnKind =
9244 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9246 Expr *FromExpr = Conv.Bad.FromExpr;
9247 QualType FromTy = Conv.Bad.getFromType();
9248 QualType ToTy = Conv.Bad.getToType();
9250 if (FromTy == S.Context.OverloadTy) {
9251 assert(FromExpr && "overload set argument came from implicit argument?");
9252 Expr *E = FromExpr->IgnoreParens();
9253 if (isa<UnaryOperator>(E))
9254 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9255 DeclarationName Name = cast<OverloadExpr>(E)->getName();
9257 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9258 << (unsigned) FnKind << FnDesc
9259 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9260 << ToTy << Name << I+1;
9261 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9265 // Do some hand-waving analysis to see if the non-viability is due
9266 // to a qualifier mismatch.
9267 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9268 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9269 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9270 CToTy = RT->getPointeeType();
9272 // TODO: detect and diagnose the full richness of const mismatches.
9273 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9274 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9275 CFromTy = FromPT->getPointeeType();
9276 CToTy = ToPT->getPointeeType();
9280 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9281 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9282 Qualifiers FromQs = CFromTy.getQualifiers();
9283 Qualifiers ToQs = CToTy.getQualifiers();
9285 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9286 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9287 << (unsigned) FnKind << FnDesc
9288 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9290 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
9291 << (unsigned) isObjectArgument << I+1;
9292 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9296 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9297 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9298 << (unsigned) FnKind << FnDesc
9299 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9301 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9302 << (unsigned) isObjectArgument << I+1;
9303 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9307 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9308 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9309 << (unsigned) FnKind << FnDesc
9310 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9312 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9313 << (unsigned) isObjectArgument << I+1;
9314 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9318 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9319 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9320 << (unsigned) FnKind << FnDesc
9321 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9322 << FromTy << FromQs.hasUnaligned() << I+1;
9323 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9327 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9328 assert(CVR && "unexpected qualifiers mismatch");
9330 if (isObjectArgument) {
9331 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9332 << (unsigned) FnKind << FnDesc
9333 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9334 << FromTy << (CVR - 1);
9336 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9337 << (unsigned) FnKind << FnDesc
9338 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9339 << FromTy << (CVR - 1) << I+1;
9341 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9345 // Special diagnostic for failure to convert an initializer list, since
9346 // telling the user that it has type void is not useful.
9347 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9348 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9349 << (unsigned) FnKind << FnDesc
9350 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9351 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9352 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9356 // Diagnose references or pointers to incomplete types differently,
9357 // since it's far from impossible that the incompleteness triggered
9359 QualType TempFromTy = FromTy.getNonReferenceType();
9360 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9361 TempFromTy = PTy->getPointeeType();
9362 if (TempFromTy->isIncompleteType()) {
9363 // Emit the generic diagnostic and, optionally, add the hints to it.
9364 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9365 << (unsigned) FnKind << FnDesc
9366 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9367 << FromTy << ToTy << (unsigned) isObjectArgument << I+1
9368 << (unsigned) (Cand->Fix.Kind);
9370 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9374 // Diagnose base -> derived pointer conversions.
9375 unsigned BaseToDerivedConversion = 0;
9376 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9377 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9378 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9379 FromPtrTy->getPointeeType()) &&
9380 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9381 !ToPtrTy->getPointeeType()->isIncompleteType() &&
9382 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9383 FromPtrTy->getPointeeType()))
9384 BaseToDerivedConversion = 1;
9386 } else if (const ObjCObjectPointerType *FromPtrTy
9387 = FromTy->getAs<ObjCObjectPointerType>()) {
9388 if (const ObjCObjectPointerType *ToPtrTy
9389 = ToTy->getAs<ObjCObjectPointerType>())
9390 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9391 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9392 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9393 FromPtrTy->getPointeeType()) &&
9394 FromIface->isSuperClassOf(ToIface))
9395 BaseToDerivedConversion = 2;
9396 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9397 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9398 !FromTy->isIncompleteType() &&
9399 !ToRefTy->getPointeeType()->isIncompleteType() &&
9400 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9401 BaseToDerivedConversion = 3;
9402 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9403 ToTy.getNonReferenceType().getCanonicalType() ==
9404 FromTy.getNonReferenceType().getCanonicalType()) {
9405 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9406 << (unsigned) FnKind << FnDesc
9407 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9408 << (unsigned) isObjectArgument << I + 1;
9409 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9414 if (BaseToDerivedConversion) {
9415 S.Diag(Fn->getLocation(),
9416 diag::note_ovl_candidate_bad_base_to_derived_conv)
9417 << (unsigned) FnKind << FnDesc
9418 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9419 << (BaseToDerivedConversion - 1)
9420 << FromTy << ToTy << I+1;
9421 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9425 if (isa<ObjCObjectPointerType>(CFromTy) &&
9426 isa<PointerType>(CToTy)) {
9427 Qualifiers FromQs = CFromTy.getQualifiers();
9428 Qualifiers ToQs = CToTy.getQualifiers();
9429 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9430 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9431 << (unsigned) FnKind << FnDesc
9432 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9433 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
9434 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9439 if (TakingCandidateAddress &&
9440 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9443 // Emit the generic diagnostic and, optionally, add the hints to it.
9444 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9445 FDiag << (unsigned) FnKind << FnDesc
9446 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9447 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
9448 << (unsigned) (Cand->Fix.Kind);
9450 // If we can fix the conversion, suggest the FixIts.
9451 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9452 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9454 S.Diag(Fn->getLocation(), FDiag);
9456 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9459 /// Additional arity mismatch diagnosis specific to a function overload
9460 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
9461 /// over a candidate in any candidate set.
9462 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9464 FunctionDecl *Fn = Cand->Function;
9465 unsigned MinParams = Fn->getMinRequiredArguments();
9467 // With invalid overloaded operators, it's possible that we think we
9468 // have an arity mismatch when in fact it looks like we have the
9469 // right number of arguments, because only overloaded operators have
9470 // the weird behavior of overloading member and non-member functions.
9471 // Just don't report anything.
9472 if (Fn->isInvalidDecl() &&
9473 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9476 if (NumArgs < MinParams) {
9477 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9478 (Cand->FailureKind == ovl_fail_bad_deduction &&
9479 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9481 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9482 (Cand->FailureKind == ovl_fail_bad_deduction &&
9483 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9489 /// General arity mismatch diagnosis over a candidate in a candidate set.
9490 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9491 unsigned NumFormalArgs) {
9492 assert(isa<FunctionDecl>(D) &&
9493 "The templated declaration should at least be a function"
9494 " when diagnosing bad template argument deduction due to too many"
9495 " or too few arguments");
9497 FunctionDecl *Fn = cast<FunctionDecl>(D);
9499 // TODO: treat calls to a missing default constructor as a special case
9500 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
9501 unsigned MinParams = Fn->getMinRequiredArguments();
9503 // at least / at most / exactly
9504 unsigned mode, modeCount;
9505 if (NumFormalArgs < MinParams) {
9506 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
9507 FnTy->isTemplateVariadic())
9508 mode = 0; // "at least"
9510 mode = 2; // "exactly"
9511 modeCount = MinParams;
9513 if (MinParams != FnTy->getNumParams())
9514 mode = 1; // "at most"
9516 mode = 2; // "exactly"
9517 modeCount = FnTy->getNumParams();
9520 std::string Description;
9521 OverloadCandidateKind FnKind =
9522 ClassifyOverloadCandidate(S, Found, Fn, Description);
9524 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
9525 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
9526 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9527 << mode << Fn->getParamDecl(0) << NumFormalArgs;
9529 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
9530 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
9531 << mode << modeCount << NumFormalArgs;
9532 MaybeEmitInheritedConstructorNote(S, Found);
9535 /// Arity mismatch diagnosis specific to a function overload candidate.
9536 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
9537 unsigned NumFormalArgs) {
9538 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
9539 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
9542 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
9543 if (TemplateDecl *TD = Templated->getDescribedTemplate())
9545 llvm_unreachable("Unsupported: Getting the described template declaration"
9546 " for bad deduction diagnosis");
9549 /// Diagnose a failed template-argument deduction.
9550 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
9551 DeductionFailureInfo &DeductionFailure,
9553 bool TakingCandidateAddress) {
9554 TemplateParameter Param = DeductionFailure.getTemplateParameter();
9556 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9557 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9558 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
9559 switch (DeductionFailure.Result) {
9560 case Sema::TDK_Success:
9561 llvm_unreachable("TDK_success while diagnosing bad deduction");
9563 case Sema::TDK_Incomplete: {
9564 assert(ParamD && "no parameter found for incomplete deduction result");
9565 S.Diag(Templated->getLocation(),
9566 diag::note_ovl_candidate_incomplete_deduction)
9567 << ParamD->getDeclName();
9568 MaybeEmitInheritedConstructorNote(S, Found);
9572 case Sema::TDK_Underqualified: {
9573 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9574 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9576 QualType Param = DeductionFailure.getFirstArg()->getAsType();
9578 // Param will have been canonicalized, but it should just be a
9579 // qualified version of ParamD, so move the qualifiers to that.
9580 QualifierCollector Qs;
9582 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
9583 assert(S.Context.hasSameType(Param, NonCanonParam));
9585 // Arg has also been canonicalized, but there's nothing we can do
9586 // about that. It also doesn't matter as much, because it won't
9587 // have any template parameters in it (because deduction isn't
9588 // done on dependent types).
9589 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
9591 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9592 << ParamD->getDeclName() << Arg << NonCanonParam;
9593 MaybeEmitInheritedConstructorNote(S, Found);
9597 case Sema::TDK_Inconsistent: {
9598 assert(ParamD && "no parameter found for inconsistent deduction result");
9600 if (isa<TemplateTypeParmDecl>(ParamD))
9602 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
9603 // Deduction might have failed because we deduced arguments of two
9604 // different types for a non-type template parameter.
9605 // FIXME: Use a different TDK value for this.
9607 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
9609 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
9610 if (!S.Context.hasSameType(T1, T2)) {
9611 S.Diag(Templated->getLocation(),
9612 diag::note_ovl_candidate_inconsistent_deduction_types)
9613 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
9614 << *DeductionFailure.getSecondArg() << T2;
9615 MaybeEmitInheritedConstructorNote(S, Found);
9624 S.Diag(Templated->getLocation(),
9625 diag::note_ovl_candidate_inconsistent_deduction)
9626 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9627 << *DeductionFailure.getSecondArg();
9628 MaybeEmitInheritedConstructorNote(S, Found);
9632 case Sema::TDK_InvalidExplicitArguments:
9633 assert(ParamD && "no parameter found for invalid explicit arguments");
9634 if (ParamD->getDeclName())
9635 S.Diag(Templated->getLocation(),
9636 diag::note_ovl_candidate_explicit_arg_mismatch_named)
9637 << ParamD->getDeclName();
9640 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9641 index = TTP->getIndex();
9642 else if (NonTypeTemplateParmDecl *NTTP
9643 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9644 index = NTTP->getIndex();
9646 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
9647 S.Diag(Templated->getLocation(),
9648 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
9651 MaybeEmitInheritedConstructorNote(S, Found);
9654 case Sema::TDK_TooManyArguments:
9655 case Sema::TDK_TooFewArguments:
9656 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
9659 case Sema::TDK_InstantiationDepth:
9660 S.Diag(Templated->getLocation(),
9661 diag::note_ovl_candidate_instantiation_depth);
9662 MaybeEmitInheritedConstructorNote(S, Found);
9665 case Sema::TDK_SubstitutionFailure: {
9666 // Format the template argument list into the argument string.
9667 SmallString<128> TemplateArgString;
9668 if (TemplateArgumentList *Args =
9669 DeductionFailure.getTemplateArgumentList()) {
9670 TemplateArgString = " ";
9671 TemplateArgString += S.getTemplateArgumentBindingsText(
9672 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9675 // If this candidate was disabled by enable_if, say so.
9676 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
9677 if (PDiag && PDiag->second.getDiagID() ==
9678 diag::err_typename_nested_not_found_enable_if) {
9679 // FIXME: Use the source range of the condition, and the fully-qualified
9680 // name of the enable_if template. These are both present in PDiag.
9681 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9682 << "'enable_if'" << TemplateArgString;
9686 // Format the SFINAE diagnostic into the argument string.
9687 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9688 // formatted message in another diagnostic.
9689 SmallString<128> SFINAEArgString;
9692 SFINAEArgString = ": ";
9693 R = SourceRange(PDiag->first, PDiag->first);
9694 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9697 S.Diag(Templated->getLocation(),
9698 diag::note_ovl_candidate_substitution_failure)
9699 << TemplateArgString << SFINAEArgString << R;
9700 MaybeEmitInheritedConstructorNote(S, Found);
9704 case Sema::TDK_FailedOverloadResolution: {
9705 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9706 S.Diag(Templated->getLocation(),
9707 diag::note_ovl_candidate_failed_overload_resolution)
9708 << R.Expression->getName();
9712 case Sema::TDK_DeducedMismatch: {
9713 // Format the template argument list into the argument string.
9714 SmallString<128> TemplateArgString;
9715 if (TemplateArgumentList *Args =
9716 DeductionFailure.getTemplateArgumentList()) {
9717 TemplateArgString = " ";
9718 TemplateArgString += S.getTemplateArgumentBindingsText(
9719 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
9722 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
9723 << (*DeductionFailure.getCallArgIndex() + 1)
9724 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
9725 << TemplateArgString;
9729 case Sema::TDK_NonDeducedMismatch: {
9730 // FIXME: Provide a source location to indicate what we couldn't match.
9731 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9732 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
9733 if (FirstTA.getKind() == TemplateArgument::Template &&
9734 SecondTA.getKind() == TemplateArgument::Template) {
9735 TemplateName FirstTN = FirstTA.getAsTemplate();
9736 TemplateName SecondTN = SecondTA.getAsTemplate();
9737 if (FirstTN.getKind() == TemplateName::Template &&
9738 SecondTN.getKind() == TemplateName::Template) {
9739 if (FirstTN.getAsTemplateDecl()->getName() ==
9740 SecondTN.getAsTemplateDecl()->getName()) {
9741 // FIXME: This fixes a bad diagnostic where both templates are named
9742 // the same. This particular case is a bit difficult since:
9743 // 1) It is passed as a string to the diagnostic printer.
9744 // 2) The diagnostic printer only attempts to find a better
9745 // name for types, not decls.
9746 // Ideally, this should folded into the diagnostic printer.
9747 S.Diag(Templated->getLocation(),
9748 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9749 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9755 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
9756 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
9759 // FIXME: For generic lambda parameters, check if the function is a lambda
9760 // call operator, and if so, emit a prettier and more informative
9761 // diagnostic that mentions 'auto' and lambda in addition to
9762 // (or instead of?) the canonical template type parameters.
9763 S.Diag(Templated->getLocation(),
9764 diag::note_ovl_candidate_non_deduced_mismatch)
9765 << FirstTA << SecondTA;
9768 // TODO: diagnose these individually, then kill off
9769 // note_ovl_candidate_bad_deduction, which is uselessly vague.
9770 case Sema::TDK_MiscellaneousDeductionFailure:
9771 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9772 MaybeEmitInheritedConstructorNote(S, Found);
9774 case Sema::TDK_CUDATargetMismatch:
9775 S.Diag(Templated->getLocation(),
9776 diag::note_cuda_ovl_candidate_target_mismatch);
9781 /// Diagnose a failed template-argument deduction, for function calls.
9782 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9784 bool TakingCandidateAddress) {
9785 unsigned TDK = Cand->DeductionFailure.Result;
9786 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9787 if (CheckArityMismatch(S, Cand, NumArgs))
9790 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
9791 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
9794 /// CUDA: diagnose an invalid call across targets.
9795 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
9796 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9797 FunctionDecl *Callee = Cand->Function;
9799 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9800 CalleeTarget = S.IdentifyCUDATarget(Callee);
9803 OverloadCandidateKind FnKind =
9804 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
9806 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
9807 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9809 // This could be an implicit constructor for which we could not infer the
9810 // target due to a collsion. Diagnose that case.
9811 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9812 if (Meth != nullptr && Meth->isImplicit()) {
9813 CXXRecordDecl *ParentClass = Meth->getParent();
9814 Sema::CXXSpecialMember CSM;
9819 case oc_implicit_default_constructor:
9820 CSM = Sema::CXXDefaultConstructor;
9822 case oc_implicit_copy_constructor:
9823 CSM = Sema::CXXCopyConstructor;
9825 case oc_implicit_move_constructor:
9826 CSM = Sema::CXXMoveConstructor;
9828 case oc_implicit_copy_assignment:
9829 CSM = Sema::CXXCopyAssignment;
9831 case oc_implicit_move_assignment:
9832 CSM = Sema::CXXMoveAssignment;
9836 bool ConstRHS = false;
9837 if (Meth->getNumParams()) {
9838 if (const ReferenceType *RT =
9839 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9840 ConstRHS = RT->getPointeeType().isConstQualified();
9844 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9845 /* ConstRHS */ ConstRHS,
9846 /* Diagnose */ true);
9850 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
9851 FunctionDecl *Callee = Cand->Function;
9852 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9854 S.Diag(Callee->getLocation(),
9855 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9856 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9859 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
9860 FunctionDecl *Callee = Cand->Function;
9862 S.Diag(Callee->getLocation(),
9863 diag::note_ovl_candidate_disabled_by_extension);
9866 /// Generates a 'note' diagnostic for an overload candidate. We've
9867 /// already generated a primary error at the call site.
9869 /// It really does need to be a single diagnostic with its caret
9870 /// pointed at the candidate declaration. Yes, this creates some
9871 /// major challenges of technical writing. Yes, this makes pointing
9872 /// out problems with specific arguments quite awkward. It's still
9873 /// better than generating twenty screens of text for every failed
9876 /// It would be great to be able to express per-candidate problems
9877 /// more richly for those diagnostic clients that cared, but we'd
9878 /// still have to be just as careful with the default diagnostics.
9879 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9881 bool TakingCandidateAddress) {
9882 FunctionDecl *Fn = Cand->Function;
9884 // Note deleted candidates, but only if they're viable.
9885 if (Cand->Viable && (Fn->isDeleted() ||
9886 S.isFunctionConsideredUnavailable(Fn))) {
9888 OverloadCandidateKind FnKind =
9889 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9891 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
9893 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
9894 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9898 // We don't really have anything else to say about viable candidates.
9900 S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
9904 switch (Cand->FailureKind) {
9905 case ovl_fail_too_many_arguments:
9906 case ovl_fail_too_few_arguments:
9907 return DiagnoseArityMismatch(S, Cand, NumArgs);
9909 case ovl_fail_bad_deduction:
9910 return DiagnoseBadDeduction(S, Cand, NumArgs,
9911 TakingCandidateAddress);
9913 case ovl_fail_illegal_constructor: {
9914 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9915 << (Fn->getPrimaryTemplate() ? 1 : 0);
9916 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9920 case ovl_fail_trivial_conversion:
9921 case ovl_fail_bad_final_conversion:
9922 case ovl_fail_final_conversion_not_exact:
9923 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
9925 case ovl_fail_bad_conversion: {
9926 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
9927 for (unsigned N = Cand->NumConversions; I != N; ++I)
9928 if (Cand->Conversions[I].isBad())
9929 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
9931 // FIXME: this currently happens when we're called from SemaInit
9932 // when user-conversion overload fails. Figure out how to handle
9933 // those conditions and diagnose them well.
9934 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
9937 case ovl_fail_bad_target:
9938 return DiagnoseBadTarget(S, Cand);
9940 case ovl_fail_enable_if:
9941 return DiagnoseFailedEnableIfAttr(S, Cand);
9943 case ovl_fail_ext_disabled:
9944 return DiagnoseOpenCLExtensionDisabled(S, Cand);
9946 case ovl_fail_addr_not_available: {
9947 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
9955 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9956 // Desugar the type of the surrogate down to a function type,
9957 // retaining as many typedefs as possible while still showing
9958 // the function type (and, therefore, its parameter types).
9959 QualType FnType = Cand->Surrogate->getConversionType();
9960 bool isLValueReference = false;
9961 bool isRValueReference = false;
9962 bool isPointer = false;
9963 if (const LValueReferenceType *FnTypeRef =
9964 FnType->getAs<LValueReferenceType>()) {
9965 FnType = FnTypeRef->getPointeeType();
9966 isLValueReference = true;
9967 } else if (const RValueReferenceType *FnTypeRef =
9968 FnType->getAs<RValueReferenceType>()) {
9969 FnType = FnTypeRef->getPointeeType();
9970 isRValueReference = true;
9972 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9973 FnType = FnTypePtr->getPointeeType();
9976 // Desugar down to a function type.
9977 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9978 // Reconstruct the pointer/reference as appropriate.
9979 if (isPointer) FnType = S.Context.getPointerType(FnType);
9980 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9981 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9983 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9987 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9988 SourceLocation OpLoc,
9989 OverloadCandidate *Cand) {
9990 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
9991 std::string TypeStr("operator");
9994 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
9995 if (Cand->NumConversions == 1) {
9997 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10000 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
10002 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10006 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10007 OverloadCandidate *Cand) {
10008 unsigned NoOperands = Cand->NumConversions;
10009 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
10010 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
10011 if (ICS.isBad()) break; // all meaningless after first invalid
10012 if (!ICS.isAmbiguous()) continue;
10014 ICS.DiagnoseAmbiguousConversion(
10015 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10019 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10020 if (Cand->Function)
10021 return Cand->Function->getLocation();
10022 if (Cand->IsSurrogate)
10023 return Cand->Surrogate->getLocation();
10024 return SourceLocation();
10027 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10028 switch ((Sema::TemplateDeductionResult)DFI.Result) {
10029 case Sema::TDK_Success:
10030 llvm_unreachable("TDK_success while diagnosing bad deduction");
10032 case Sema::TDK_Invalid:
10033 case Sema::TDK_Incomplete:
10036 case Sema::TDK_Underqualified:
10037 case Sema::TDK_Inconsistent:
10040 case Sema::TDK_SubstitutionFailure:
10041 case Sema::TDK_DeducedMismatch:
10042 case Sema::TDK_NonDeducedMismatch:
10043 case Sema::TDK_MiscellaneousDeductionFailure:
10044 case Sema::TDK_CUDATargetMismatch:
10047 case Sema::TDK_InstantiationDepth:
10048 case Sema::TDK_FailedOverloadResolution:
10051 case Sema::TDK_InvalidExplicitArguments:
10054 case Sema::TDK_TooManyArguments:
10055 case Sema::TDK_TooFewArguments:
10058 llvm_unreachable("Unhandled deduction result");
10062 struct CompareOverloadCandidatesForDisplay {
10064 SourceLocation Loc;
10067 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs)
10068 : S(S), NumArgs(nArgs) {}
10070 bool operator()(const OverloadCandidate *L,
10071 const OverloadCandidate *R) {
10072 // Fast-path this check.
10073 if (L == R) return false;
10075 // Order first by viability.
10077 if (!R->Viable) return true;
10079 // TODO: introduce a tri-valued comparison for overload
10080 // candidates. Would be more worthwhile if we had a sort
10081 // that could exploit it.
10082 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
10083 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
10084 } else if (R->Viable)
10087 assert(L->Viable == R->Viable);
10089 // Criteria by which we can sort non-viable candidates:
10091 // 1. Arity mismatches come after other candidates.
10092 if (L->FailureKind == ovl_fail_too_many_arguments ||
10093 L->FailureKind == ovl_fail_too_few_arguments) {
10094 if (R->FailureKind == ovl_fail_too_many_arguments ||
10095 R->FailureKind == ovl_fail_too_few_arguments) {
10096 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10097 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10098 if (LDist == RDist) {
10099 if (L->FailureKind == R->FailureKind)
10100 // Sort non-surrogates before surrogates.
10101 return !L->IsSurrogate && R->IsSurrogate;
10102 // Sort candidates requiring fewer parameters than there were
10103 // arguments given after candidates requiring more parameters
10104 // than there were arguments given.
10105 return L->FailureKind == ovl_fail_too_many_arguments;
10107 return LDist < RDist;
10111 if (R->FailureKind == ovl_fail_too_many_arguments ||
10112 R->FailureKind == ovl_fail_too_few_arguments)
10115 // 2. Bad conversions come first and are ordered by the number
10116 // of bad conversions and quality of good conversions.
10117 if (L->FailureKind == ovl_fail_bad_conversion) {
10118 if (R->FailureKind != ovl_fail_bad_conversion)
10121 // The conversion that can be fixed with a smaller number of changes,
10123 unsigned numLFixes = L->Fix.NumConversionsFixed;
10124 unsigned numRFixes = R->Fix.NumConversionsFixed;
10125 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10126 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10127 if (numLFixes != numRFixes) {
10128 return numLFixes < numRFixes;
10131 // If there's any ordering between the defined conversions...
10132 // FIXME: this might not be transitive.
10133 assert(L->NumConversions == R->NumConversions);
10135 int leftBetter = 0;
10136 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10137 for (unsigned E = L->NumConversions; I != E; ++I) {
10138 switch (CompareImplicitConversionSequences(S, Loc,
10140 R->Conversions[I])) {
10141 case ImplicitConversionSequence::Better:
10145 case ImplicitConversionSequence::Worse:
10149 case ImplicitConversionSequence::Indistinguishable:
10153 if (leftBetter > 0) return true;
10154 if (leftBetter < 0) return false;
10156 } else if (R->FailureKind == ovl_fail_bad_conversion)
10159 if (L->FailureKind == ovl_fail_bad_deduction) {
10160 if (R->FailureKind != ovl_fail_bad_deduction)
10163 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10164 return RankDeductionFailure(L->DeductionFailure)
10165 < RankDeductionFailure(R->DeductionFailure);
10166 } else if (R->FailureKind == ovl_fail_bad_deduction)
10172 // Sort everything else by location.
10173 SourceLocation LLoc = GetLocationForCandidate(L);
10174 SourceLocation RLoc = GetLocationForCandidate(R);
10176 // Put candidates without locations (e.g. builtins) at the end.
10177 if (LLoc.isInvalid()) return false;
10178 if (RLoc.isInvalid()) return true;
10180 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10185 /// CompleteNonViableCandidate - Normally, overload resolution only
10186 /// computes up to the first. Produces the FixIt set if possible.
10187 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10188 ArrayRef<Expr *> Args) {
10189 assert(!Cand->Viable);
10191 // Don't do anything on failures other than bad conversion.
10192 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10194 // We only want the FixIts if all the arguments can be corrected.
10195 bool Unfixable = false;
10196 // Use a implicit copy initialization to check conversion fixes.
10197 Cand->Fix.setConversionChecker(TryCopyInitialization);
10199 // Skip forward to the first bad conversion.
10200 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
10201 unsigned ConvCount = Cand->NumConversions;
10203 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10205 if (Cand->Conversions[ConvIdx - 1].isBad()) {
10206 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
10211 if (ConvIdx == ConvCount)
10214 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
10215 "remaining conversion is initialized?");
10217 // FIXME: this should probably be preserved from the overload
10218 // operation somehow.
10219 bool SuppressUserConversions = false;
10221 const FunctionProtoType* Proto;
10222 unsigned ArgIdx = ConvIdx;
10224 if (Cand->IsSurrogate) {
10226 = Cand->Surrogate->getConversionType().getNonReferenceType();
10227 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10228 ConvType = ConvPtrType->getPointeeType();
10229 Proto = ConvType->getAs<FunctionProtoType>();
10231 } else if (Cand->Function) {
10232 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
10233 if (isa<CXXMethodDecl>(Cand->Function) &&
10234 !isa<CXXConstructorDecl>(Cand->Function))
10237 // Builtin binary operator with a bad first conversion.
10238 assert(ConvCount <= 3);
10239 for (; ConvIdx != ConvCount; ++ConvIdx)
10240 Cand->Conversions[ConvIdx]
10241 = TryCopyInitialization(S, Args[ConvIdx],
10242 Cand->BuiltinTypes.ParamTypes[ConvIdx],
10243 SuppressUserConversions,
10244 /*InOverloadResolution*/ true,
10245 /*AllowObjCWritebackConversion=*/
10246 S.getLangOpts().ObjCAutoRefCount);
10250 // Fill in the rest of the conversions.
10251 unsigned NumParams = Proto->getNumParams();
10252 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10253 if (ArgIdx < NumParams) {
10254 Cand->Conversions[ConvIdx] = TryCopyInitialization(
10255 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
10256 /*InOverloadResolution=*/true,
10257 /*AllowObjCWritebackConversion=*/
10258 S.getLangOpts().ObjCAutoRefCount);
10259 // Store the FixIt in the candidate if it exists.
10260 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10261 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10264 Cand->Conversions[ConvIdx].setEllipsis();
10268 /// PrintOverloadCandidates - When overload resolution fails, prints
10269 /// diagnostic messages containing the candidates in the candidate
10271 void OverloadCandidateSet::NoteCandidates(
10272 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10273 StringRef Opc, SourceLocation OpLoc,
10274 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10275 // Sort the candidates by viability and position. Sorting directly would
10276 // be prohibitive, so we make a set of pointers and sort those.
10277 SmallVector<OverloadCandidate*, 32> Cands;
10278 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10279 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10280 if (!Filter(*Cand))
10283 Cands.push_back(Cand);
10284 else if (OCD == OCD_AllCandidates) {
10285 CompleteNonViableCandidate(S, Cand, Args);
10286 if (Cand->Function || Cand->IsSurrogate)
10287 Cands.push_back(Cand);
10288 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10289 // want to list every possible builtin candidate.
10293 std::sort(Cands.begin(), Cands.end(),
10294 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size()));
10296 bool ReportedAmbiguousConversions = false;
10298 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
10299 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10300 unsigned CandsShown = 0;
10301 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10302 OverloadCandidate *Cand = *I;
10304 // Set an arbitrary limit on the number of candidate functions we'll spam
10305 // the user with. FIXME: This limit should depend on details of the
10307 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10312 if (Cand->Function)
10313 NoteFunctionCandidate(S, Cand, Args.size(),
10314 /*TakingCandidateAddress=*/false);
10315 else if (Cand->IsSurrogate)
10316 NoteSurrogateCandidate(S, Cand);
10318 assert(Cand->Viable &&
10319 "Non-viable built-in candidates are not added to Cands.");
10320 // Generally we only see ambiguities including viable builtin
10321 // operators if overload resolution got screwed up by an
10322 // ambiguous user-defined conversion.
10324 // FIXME: It's quite possible for different conversions to see
10325 // different ambiguities, though.
10326 if (!ReportedAmbiguousConversions) {
10327 NoteAmbiguousUserConversions(S, OpLoc, Cand);
10328 ReportedAmbiguousConversions = true;
10331 // If this is a viable builtin, print it.
10332 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10337 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10340 static SourceLocation
10341 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10342 return Cand->Specialization ? Cand->Specialization->getLocation()
10343 : SourceLocation();
10347 struct CompareTemplateSpecCandidatesForDisplay {
10349 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10351 bool operator()(const TemplateSpecCandidate *L,
10352 const TemplateSpecCandidate *R) {
10353 // Fast-path this check.
10357 // Assuming that both candidates are not matches...
10359 // Sort by the ranking of deduction failures.
10360 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10361 return RankDeductionFailure(L->DeductionFailure) <
10362 RankDeductionFailure(R->DeductionFailure);
10364 // Sort everything else by location.
10365 SourceLocation LLoc = GetLocationForCandidate(L);
10366 SourceLocation RLoc = GetLocationForCandidate(R);
10368 // Put candidates without locations (e.g. builtins) at the end.
10369 if (LLoc.isInvalid())
10371 if (RLoc.isInvalid())
10374 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10379 /// Diagnose a template argument deduction failure.
10380 /// We are treating these failures as overload failures due to bad
10382 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10383 bool ForTakingAddress) {
10384 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10385 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10388 void TemplateSpecCandidateSet::destroyCandidates() {
10389 for (iterator i = begin(), e = end(); i != e; ++i) {
10390 i->DeductionFailure.Destroy();
10394 void TemplateSpecCandidateSet::clear() {
10395 destroyCandidates();
10396 Candidates.clear();
10399 /// NoteCandidates - When no template specialization match is found, prints
10400 /// diagnostic messages containing the non-matching specializations that form
10401 /// the candidate set.
10402 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10403 /// OCD == OCD_AllCandidates and Cand->Viable == false.
10404 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10405 // Sort the candidates by position (assuming no candidate is a match).
10406 // Sorting directly would be prohibitive, so we make a set of pointers
10408 SmallVector<TemplateSpecCandidate *, 32> Cands;
10409 Cands.reserve(size());
10410 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10411 if (Cand->Specialization)
10412 Cands.push_back(Cand);
10413 // Otherwise, this is a non-matching builtin candidate. We do not,
10414 // in general, want to list every possible builtin candidate.
10417 std::sort(Cands.begin(), Cands.end(),
10418 CompareTemplateSpecCandidatesForDisplay(S));
10420 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
10421 // for generalization purposes (?).
10422 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10424 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
10425 unsigned CandsShown = 0;
10426 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10427 TemplateSpecCandidate *Cand = *I;
10429 // Set an arbitrary limit on the number of candidates we'll spam
10430 // the user with. FIXME: This limit should depend on details of the
10432 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10436 assert(Cand->Specialization &&
10437 "Non-matching built-in candidates are not added to Cands.");
10438 Cand->NoteDeductionFailure(S, ForTakingAddress);
10442 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
10445 // [PossiblyAFunctionType] --> [Return]
10446 // NonFunctionType --> NonFunctionType
10448 // R (*)(A) --> R (A)
10449 // R (&)(A) --> R (A)
10450 // R (S::*)(A) --> R (A)
10451 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
10452 QualType Ret = PossiblyAFunctionType;
10453 if (const PointerType *ToTypePtr =
10454 PossiblyAFunctionType->getAs<PointerType>())
10455 Ret = ToTypePtr->getPointeeType();
10456 else if (const ReferenceType *ToTypeRef =
10457 PossiblyAFunctionType->getAs<ReferenceType>())
10458 Ret = ToTypeRef->getPointeeType();
10459 else if (const MemberPointerType *MemTypePtr =
10460 PossiblyAFunctionType->getAs<MemberPointerType>())
10461 Ret = MemTypePtr->getPointeeType();
10463 Context.getCanonicalType(Ret).getUnqualifiedType();
10467 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
10468 bool Complain = true) {
10469 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
10470 S.DeduceReturnType(FD, Loc, Complain))
10473 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
10474 if (S.getLangOpts().CPlusPlus1z &&
10475 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
10476 !S.ResolveExceptionSpec(Loc, FPT))
10483 // A helper class to help with address of function resolution
10484 // - allows us to avoid passing around all those ugly parameters
10485 class AddressOfFunctionResolver {
10488 const QualType& TargetType;
10489 QualType TargetFunctionType; // Extracted function type from target type
10492 //DeclAccessPair& ResultFunctionAccessPair;
10493 ASTContext& Context;
10495 bool TargetTypeIsNonStaticMemberFunction;
10496 bool FoundNonTemplateFunction;
10497 bool StaticMemberFunctionFromBoundPointer;
10498 bool HasComplained;
10500 OverloadExpr::FindResult OvlExprInfo;
10501 OverloadExpr *OvlExpr;
10502 TemplateArgumentListInfo OvlExplicitTemplateArgs;
10503 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
10504 TemplateSpecCandidateSet FailedCandidates;
10507 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
10508 const QualType &TargetType, bool Complain)
10509 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
10510 Complain(Complain), Context(S.getASTContext()),
10511 TargetTypeIsNonStaticMemberFunction(
10512 !!TargetType->getAs<MemberPointerType>()),
10513 FoundNonTemplateFunction(false),
10514 StaticMemberFunctionFromBoundPointer(false),
10515 HasComplained(false),
10516 OvlExprInfo(OverloadExpr::find(SourceExpr)),
10517 OvlExpr(OvlExprInfo.Expression),
10518 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
10519 ExtractUnqualifiedFunctionTypeFromTargetType();
10521 if (TargetFunctionType->isFunctionType()) {
10522 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
10523 if (!UME->isImplicitAccess() &&
10524 !S.ResolveSingleFunctionTemplateSpecialization(UME))
10525 StaticMemberFunctionFromBoundPointer = true;
10526 } else if (OvlExpr->hasExplicitTemplateArgs()) {
10527 DeclAccessPair dap;
10528 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
10529 OvlExpr, false, &dap)) {
10530 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
10531 if (!Method->isStatic()) {
10532 // If the target type is a non-function type and the function found
10533 // is a non-static member function, pretend as if that was the
10534 // target, it's the only possible type to end up with.
10535 TargetTypeIsNonStaticMemberFunction = true;
10537 // And skip adding the function if its not in the proper form.
10538 // We'll diagnose this due to an empty set of functions.
10539 if (!OvlExprInfo.HasFormOfMemberPointer)
10543 Matches.push_back(std::make_pair(dap, Fn));
10548 if (OvlExpr->hasExplicitTemplateArgs())
10549 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
10551 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
10552 // C++ [over.over]p4:
10553 // If more than one function is selected, [...]
10554 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
10555 if (FoundNonTemplateFunction)
10556 EliminateAllTemplateMatches();
10558 EliminateAllExceptMostSpecializedTemplate();
10562 if (S.getLangOpts().CUDA && Matches.size() > 1)
10563 EliminateSuboptimalCudaMatches();
10566 bool hasComplained() const { return HasComplained; }
10569 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
10571 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
10572 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
10575 /// \return true if A is considered a better overload candidate for the
10576 /// desired type than B.
10577 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
10578 // If A doesn't have exactly the correct type, we don't want to classify it
10579 // as "better" than anything else. This way, the user is required to
10580 // disambiguate for us if there are multiple candidates and no exact match.
10581 return candidateHasExactlyCorrectType(A) &&
10582 (!candidateHasExactlyCorrectType(B) ||
10583 compareEnableIfAttrs(S, A, B) == Comparison::Better);
10586 /// \return true if we were able to eliminate all but one overload candidate,
10587 /// false otherwise.
10588 bool eliminiateSuboptimalOverloadCandidates() {
10589 // Same algorithm as overload resolution -- one pass to pick the "best",
10590 // another pass to be sure that nothing is better than the best.
10591 auto Best = Matches.begin();
10592 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
10593 if (isBetterCandidate(I->second, Best->second))
10596 const FunctionDecl *BestFn = Best->second;
10597 auto IsBestOrInferiorToBest = [this, BestFn](
10598 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
10599 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
10602 // Note: We explicitly leave Matches unmodified if there isn't a clear best
10603 // option, so we can potentially give the user a better error
10604 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest))
10606 Matches[0] = *Best;
10611 bool isTargetTypeAFunction() const {
10612 return TargetFunctionType->isFunctionType();
10615 // [ToType] [Return]
10617 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
10618 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
10619 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
10620 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
10621 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
10624 // return true if any matching specializations were found
10625 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
10626 const DeclAccessPair& CurAccessFunPair) {
10627 if (CXXMethodDecl *Method
10628 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
10629 // Skip non-static function templates when converting to pointer, and
10630 // static when converting to member pointer.
10631 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10634 else if (TargetTypeIsNonStaticMemberFunction)
10637 // C++ [over.over]p2:
10638 // If the name is a function template, template argument deduction is
10639 // done (14.8.2.2), and if the argument deduction succeeds, the
10640 // resulting template argument list is used to generate a single
10641 // function template specialization, which is added to the set of
10642 // overloaded functions considered.
10643 FunctionDecl *Specialization = nullptr;
10644 TemplateDeductionInfo Info(FailedCandidates.getLocation());
10645 if (Sema::TemplateDeductionResult Result
10646 = S.DeduceTemplateArguments(FunctionTemplate,
10647 &OvlExplicitTemplateArgs,
10648 TargetFunctionType, Specialization,
10649 Info, /*IsAddressOfFunction*/true)) {
10650 // Make a note of the failed deduction for diagnostics.
10651 FailedCandidates.addCandidate()
10652 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
10653 MakeDeductionFailureInfo(Context, Result, Info));
10657 // Template argument deduction ensures that we have an exact match or
10658 // compatible pointer-to-function arguments that would be adjusted by ICS.
10659 // This function template specicalization works.
10660 assert(S.isSameOrCompatibleFunctionType(
10661 Context.getCanonicalType(Specialization->getType()),
10662 Context.getCanonicalType(TargetFunctionType)));
10664 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
10667 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
10671 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
10672 const DeclAccessPair& CurAccessFunPair) {
10673 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10674 // Skip non-static functions when converting to pointer, and static
10675 // when converting to member pointer.
10676 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
10679 else if (TargetTypeIsNonStaticMemberFunction)
10682 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
10683 if (S.getLangOpts().CUDA)
10684 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
10685 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
10688 // If any candidate has a placeholder return type, trigger its deduction
10690 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(),
10692 HasComplained |= Complain;
10696 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
10699 // If we're in C, we need to support types that aren't exactly identical.
10700 if (!S.getLangOpts().CPlusPlus ||
10701 candidateHasExactlyCorrectType(FunDecl)) {
10702 Matches.push_back(std::make_pair(
10703 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
10704 FoundNonTemplateFunction = true;
10712 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10715 // If the overload expression doesn't have the form of a pointer to
10716 // member, don't try to convert it to a pointer-to-member type.
10717 if (IsInvalidFormOfPointerToMemberFunction())
10720 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10721 E = OvlExpr->decls_end();
10723 // Look through any using declarations to find the underlying function.
10724 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10726 // C++ [over.over]p3:
10727 // Non-member functions and static member functions match
10728 // targets of type "pointer-to-function" or "reference-to-function."
10729 // Nonstatic member functions match targets of
10730 // type "pointer-to-member-function."
10731 // Note that according to DR 247, the containing class does not matter.
10732 if (FunctionTemplateDecl *FunctionTemplate
10733 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10734 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10737 // If we have explicit template arguments supplied, skip non-templates.
10738 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10739 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10742 assert(Ret || Matches.empty());
10746 void EliminateAllExceptMostSpecializedTemplate() {
10747 // [...] and any given function template specialization F1 is
10748 // eliminated if the set contains a second function template
10749 // specialization whose function template is more specialized
10750 // than the function template of F1 according to the partial
10751 // ordering rules of 14.5.5.2.
10753 // The algorithm specified above is quadratic. We instead use a
10754 // two-pass algorithm (similar to the one used to identify the
10755 // best viable function in an overload set) that identifies the
10756 // best function template (if it exists).
10758 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10759 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10760 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
10762 // TODO: It looks like FailedCandidates does not serve much purpose
10763 // here, since the no_viable diagnostic has index 0.
10764 UnresolvedSetIterator Result = S.getMostSpecialized(
10765 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
10766 SourceExpr->getLocStart(), S.PDiag(),
10767 S.PDiag(diag::err_addr_ovl_ambiguous)
10768 << Matches[0].second->getDeclName(),
10769 S.PDiag(diag::note_ovl_candidate)
10770 << (unsigned)oc_function_template,
10771 Complain, TargetFunctionType);
10773 if (Result != MatchesCopy.end()) {
10774 // Make it the first and only element
10775 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10776 Matches[0].second = cast<FunctionDecl>(*Result);
10779 HasComplained |= Complain;
10782 void EliminateAllTemplateMatches() {
10783 // [...] any function template specializations in the set are
10784 // eliminated if the set also contains a non-template function, [...]
10785 for (unsigned I = 0, N = Matches.size(); I != N; ) {
10786 if (Matches[I].second->getPrimaryTemplate() == nullptr)
10789 Matches[I] = Matches[--N];
10795 void EliminateSuboptimalCudaMatches() {
10796 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
10800 void ComplainNoMatchesFound() const {
10801 assert(Matches.empty());
10802 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10803 << OvlExpr->getName() << TargetFunctionType
10804 << OvlExpr->getSourceRange();
10805 if (FailedCandidates.empty())
10806 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10807 /*TakingAddress=*/true);
10809 // We have some deduction failure messages. Use them to diagnose
10810 // the function templates, and diagnose the non-template candidates
10812 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10813 IEnd = OvlExpr->decls_end();
10815 if (FunctionDecl *Fun =
10816 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10817 if (!functionHasPassObjectSizeParams(Fun))
10818 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
10819 /*TakingAddress=*/true);
10820 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10824 bool IsInvalidFormOfPointerToMemberFunction() const {
10825 return TargetTypeIsNonStaticMemberFunction &&
10826 !OvlExprInfo.HasFormOfMemberPointer;
10829 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10830 // TODO: Should we condition this on whether any functions might
10831 // have matched, or is it more appropriate to do that in callers?
10832 // TODO: a fixit wouldn't hurt.
10833 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10834 << TargetType << OvlExpr->getSourceRange();
10837 bool IsStaticMemberFunctionFromBoundPointer() const {
10838 return StaticMemberFunctionFromBoundPointer;
10841 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10842 S.Diag(OvlExpr->getLocStart(),
10843 diag::err_invalid_form_pointer_member_function)
10844 << OvlExpr->getSourceRange();
10847 void ComplainOfInvalidConversion() const {
10848 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10849 << OvlExpr->getName() << TargetType;
10852 void ComplainMultipleMatchesFound() const {
10853 assert(Matches.size() > 1);
10854 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10855 << OvlExpr->getName()
10856 << OvlExpr->getSourceRange();
10857 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
10858 /*TakingAddress=*/true);
10861 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10863 int getNumMatches() const { return Matches.size(); }
10865 FunctionDecl* getMatchingFunctionDecl() const {
10866 if (Matches.size() != 1) return nullptr;
10867 return Matches[0].second;
10870 const DeclAccessPair* getMatchingFunctionAccessPair() const {
10871 if (Matches.size() != 1) return nullptr;
10872 return &Matches[0].first;
10877 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10878 /// an overloaded function (C++ [over.over]), where @p From is an
10879 /// expression with overloaded function type and @p ToType is the type
10880 /// we're trying to resolve to. For example:
10886 /// int (*pfd)(double) = f; // selects f(double)
10889 /// This routine returns the resulting FunctionDecl if it could be
10890 /// resolved, and NULL otherwise. When @p Complain is true, this
10891 /// routine will emit diagnostics if there is an error.
10893 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10894 QualType TargetType,
10896 DeclAccessPair &FoundResult,
10897 bool *pHadMultipleCandidates) {
10898 assert(AddressOfExpr->getType() == Context.OverloadTy);
10900 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10902 int NumMatches = Resolver.getNumMatches();
10903 FunctionDecl *Fn = nullptr;
10904 bool ShouldComplain = Complain && !Resolver.hasComplained();
10905 if (NumMatches == 0 && ShouldComplain) {
10906 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10907 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10909 Resolver.ComplainNoMatchesFound();
10911 else if (NumMatches > 1 && ShouldComplain)
10912 Resolver.ComplainMultipleMatchesFound();
10913 else if (NumMatches == 1) {
10914 Fn = Resolver.getMatchingFunctionDecl();
10916 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
10917 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
10918 FoundResult = *Resolver.getMatchingFunctionAccessPair();
10920 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10921 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10923 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10927 if (pHadMultipleCandidates)
10928 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
10932 /// \brief Given an expression that refers to an overloaded function, try to
10933 /// resolve that function to a single function that can have its address taken.
10934 /// This will modify `Pair` iff it returns non-null.
10936 /// This routine can only realistically succeed if all but one candidates in the
10937 /// overload set for SrcExpr cannot have their addresses taken.
10939 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
10940 DeclAccessPair &Pair) {
10941 OverloadExpr::FindResult R = OverloadExpr::find(E);
10942 OverloadExpr *Ovl = R.Expression;
10943 FunctionDecl *Result = nullptr;
10944 DeclAccessPair DAP;
10945 // Don't use the AddressOfResolver because we're specifically looking for
10946 // cases where we have one overload candidate that lacks
10947 // enable_if/pass_object_size/...
10948 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
10949 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
10953 if (!checkAddressOfFunctionIsAvailable(FD))
10956 // We have more than one result; quit.
10968 /// \brief Given an overloaded function, tries to turn it into a non-overloaded
10969 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
10970 /// will perform access checks, diagnose the use of the resultant decl, and, if
10971 /// necessary, perform a function-to-pointer decay.
10973 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
10974 /// Otherwise, returns true. This may emit diagnostics and return true.
10975 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
10976 ExprResult &SrcExpr) {
10977 Expr *E = SrcExpr.get();
10978 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
10980 DeclAccessPair DAP;
10981 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
10985 // Emitting multiple diagnostics for a function that is both inaccessible and
10986 // unavailable is consistent with our behavior elsewhere. So, always check
10988 DiagnoseUseOfDecl(Found, E->getExprLoc());
10989 CheckAddressOfMemberAccess(E, DAP);
10990 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
10991 if (Fixed->getType()->isFunctionType())
10992 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
10998 /// \brief Given an expression that refers to an overloaded function, try to
10999 /// resolve that overloaded function expression down to a single function.
11001 /// This routine can only resolve template-ids that refer to a single function
11002 /// template, where that template-id refers to a single template whose template
11003 /// arguments are either provided by the template-id or have defaults,
11004 /// as described in C++0x [temp.arg.explicit]p3.
11006 /// If no template-ids are found, no diagnostics are emitted and NULL is
11009 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11011 DeclAccessPair *FoundResult) {
11012 // C++ [over.over]p1:
11013 // [...] [Note: any redundant set of parentheses surrounding the
11014 // overloaded function name is ignored (5.1). ]
11015 // C++ [over.over]p1:
11016 // [...] The overloaded function name can be preceded by the &
11019 // If we didn't actually find any template-ids, we're done.
11020 if (!ovl->hasExplicitTemplateArgs())
11023 TemplateArgumentListInfo ExplicitTemplateArgs;
11024 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11025 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11027 // Look through all of the overloaded functions, searching for one
11028 // whose type matches exactly.
11029 FunctionDecl *Matched = nullptr;
11030 for (UnresolvedSetIterator I = ovl->decls_begin(),
11031 E = ovl->decls_end(); I != E; ++I) {
11032 // C++0x [temp.arg.explicit]p3:
11033 // [...] In contexts where deduction is done and fails, or in contexts
11034 // where deduction is not done, if a template argument list is
11035 // specified and it, along with any default template arguments,
11036 // identifies a single function template specialization, then the
11037 // template-id is an lvalue for the function template specialization.
11038 FunctionTemplateDecl *FunctionTemplate
11039 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11041 // C++ [over.over]p2:
11042 // If the name is a function template, template argument deduction is
11043 // done (14.8.2.2), and if the argument deduction succeeds, the
11044 // resulting template argument list is used to generate a single
11045 // function template specialization, which is added to the set of
11046 // overloaded functions considered.
11047 FunctionDecl *Specialization = nullptr;
11048 TemplateDeductionInfo Info(FailedCandidates.getLocation());
11049 if (TemplateDeductionResult Result
11050 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11051 Specialization, Info,
11052 /*IsAddressOfFunction*/true)) {
11053 // Make a note of the failed deduction for diagnostics.
11054 // TODO: Actually use the failed-deduction info?
11055 FailedCandidates.addCandidate()
11056 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11057 MakeDeductionFailureInfo(Context, Result, Info));
11061 assert(Specialization && "no specialization and no error?");
11063 // Multiple matches; we can't resolve to a single declaration.
11066 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11068 NoteAllOverloadCandidates(ovl);
11073 Matched = Specialization;
11074 if (FoundResult) *FoundResult = I.getPair();
11078 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11087 // Resolve and fix an overloaded expression that can be resolved
11088 // because it identifies a single function template specialization.
11090 // Last three arguments should only be supplied if Complain = true
11092 // Return true if it was logically possible to so resolve the
11093 // expression, regardless of whether or not it succeeded. Always
11094 // returns true if 'complain' is set.
11095 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11096 ExprResult &SrcExpr, bool doFunctionPointerConverion,
11097 bool complain, SourceRange OpRangeForComplaining,
11098 QualType DestTypeForComplaining,
11099 unsigned DiagIDForComplaining) {
11100 assert(SrcExpr.get()->getType() == Context.OverloadTy);
11102 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11104 DeclAccessPair found;
11105 ExprResult SingleFunctionExpression;
11106 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11107 ovl.Expression, /*complain*/ false, &found)) {
11108 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
11109 SrcExpr = ExprError();
11113 // It is only correct to resolve to an instance method if we're
11114 // resolving a form that's permitted to be a pointer to member.
11115 // Otherwise we'll end up making a bound member expression, which
11116 // is illegal in all the contexts we resolve like this.
11117 if (!ovl.HasFormOfMemberPointer &&
11118 isa<CXXMethodDecl>(fn) &&
11119 cast<CXXMethodDecl>(fn)->isInstance()) {
11120 if (!complain) return false;
11122 Diag(ovl.Expression->getExprLoc(),
11123 diag::err_bound_member_function)
11124 << 0 << ovl.Expression->getSourceRange();
11126 // TODO: I believe we only end up here if there's a mix of
11127 // static and non-static candidates (otherwise the expression
11128 // would have 'bound member' type, not 'overload' type).
11129 // Ideally we would note which candidate was chosen and why
11130 // the static candidates were rejected.
11131 SrcExpr = ExprError();
11135 // Fix the expression to refer to 'fn'.
11136 SingleFunctionExpression =
11137 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11139 // If desired, do function-to-pointer decay.
11140 if (doFunctionPointerConverion) {
11141 SingleFunctionExpression =
11142 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11143 if (SingleFunctionExpression.isInvalid()) {
11144 SrcExpr = ExprError();
11150 if (!SingleFunctionExpression.isUsable()) {
11152 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11153 << ovl.Expression->getName()
11154 << DestTypeForComplaining
11155 << OpRangeForComplaining
11156 << ovl.Expression->getQualifierLoc().getSourceRange();
11157 NoteAllOverloadCandidates(SrcExpr.get());
11159 SrcExpr = ExprError();
11166 SrcExpr = SingleFunctionExpression;
11170 /// \brief Add a single candidate to the overload set.
11171 static void AddOverloadedCallCandidate(Sema &S,
11172 DeclAccessPair FoundDecl,
11173 TemplateArgumentListInfo *ExplicitTemplateArgs,
11174 ArrayRef<Expr *> Args,
11175 OverloadCandidateSet &CandidateSet,
11176 bool PartialOverloading,
11178 NamedDecl *Callee = FoundDecl.getDecl();
11179 if (isa<UsingShadowDecl>(Callee))
11180 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11182 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11183 if (ExplicitTemplateArgs) {
11184 assert(!KnownValid && "Explicit template arguments?");
11187 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11188 /*SuppressUsedConversions=*/false,
11189 PartialOverloading);
11193 if (FunctionTemplateDecl *FuncTemplate
11194 = dyn_cast<FunctionTemplateDecl>(Callee)) {
11195 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11196 ExplicitTemplateArgs, Args, CandidateSet,
11197 /*SuppressUsedConversions=*/false,
11198 PartialOverloading);
11202 assert(!KnownValid && "unhandled case in overloaded call candidate");
11205 /// \brief Add the overload candidates named by callee and/or found by argument
11206 /// dependent lookup to the given overload set.
11207 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11208 ArrayRef<Expr *> Args,
11209 OverloadCandidateSet &CandidateSet,
11210 bool PartialOverloading) {
11213 // Verify that ArgumentDependentLookup is consistent with the rules
11214 // in C++0x [basic.lookup.argdep]p3:
11216 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11217 // and let Y be the lookup set produced by argument dependent
11218 // lookup (defined as follows). If X contains
11220 // -- a declaration of a class member, or
11222 // -- a block-scope function declaration that is not a
11223 // using-declaration, or
11225 // -- a declaration that is neither a function or a function
11228 // then Y is empty.
11230 if (ULE->requiresADL()) {
11231 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11232 E = ULE->decls_end(); I != E; ++I) {
11233 assert(!(*I)->getDeclContext()->isRecord());
11234 assert(isa<UsingShadowDecl>(*I) ||
11235 !(*I)->getDeclContext()->isFunctionOrMethod());
11236 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11241 // It would be nice to avoid this copy.
11242 TemplateArgumentListInfo TABuffer;
11243 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11244 if (ULE->hasExplicitTemplateArgs()) {
11245 ULE->copyTemplateArgumentsInto(TABuffer);
11246 ExplicitTemplateArgs = &TABuffer;
11249 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11250 E = ULE->decls_end(); I != E; ++I)
11251 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11252 CandidateSet, PartialOverloading,
11253 /*KnownValid*/ true);
11255 if (ULE->requiresADL())
11256 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11257 Args, ExplicitTemplateArgs,
11258 CandidateSet, PartialOverloading);
11261 /// Determine whether a declaration with the specified name could be moved into
11262 /// a different namespace.
11263 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11264 switch (Name.getCXXOverloadedOperator()) {
11265 case OO_New: case OO_Array_New:
11266 case OO_Delete: case OO_Array_Delete:
11274 /// Attempt to recover from an ill-formed use of a non-dependent name in a
11275 /// template, where the non-dependent name was declared after the template
11276 /// was defined. This is common in code written for a compilers which do not
11277 /// correctly implement two-stage name lookup.
11279 /// Returns true if a viable candidate was found and a diagnostic was issued.
11281 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11282 const CXXScopeSpec &SS, LookupResult &R,
11283 OverloadCandidateSet::CandidateSetKind CSK,
11284 TemplateArgumentListInfo *ExplicitTemplateArgs,
11285 ArrayRef<Expr *> Args,
11286 bool *DoDiagnoseEmptyLookup = nullptr) {
11287 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
11290 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11291 if (DC->isTransparentContext())
11294 SemaRef.LookupQualifiedName(R, DC);
11297 R.suppressDiagnostics();
11299 if (isa<CXXRecordDecl>(DC)) {
11300 // Don't diagnose names we find in classes; we get much better
11301 // diagnostics for these from DiagnoseEmptyLookup.
11303 if (DoDiagnoseEmptyLookup)
11304 *DoDiagnoseEmptyLookup = true;
11308 OverloadCandidateSet Candidates(FnLoc, CSK);
11309 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11310 AddOverloadedCallCandidate(SemaRef, I.getPair(),
11311 ExplicitTemplateArgs, Args,
11312 Candidates, false, /*KnownValid*/ false);
11314 OverloadCandidateSet::iterator Best;
11315 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11316 // No viable functions. Don't bother the user with notes for functions
11317 // which don't work and shouldn't be found anyway.
11322 // Find the namespaces where ADL would have looked, and suggest
11323 // declaring the function there instead.
11324 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11325 Sema::AssociatedClassSet AssociatedClasses;
11326 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11327 AssociatedNamespaces,
11328 AssociatedClasses);
11329 Sema::AssociatedNamespaceSet SuggestedNamespaces;
11330 if (canBeDeclaredInNamespace(R.getLookupName())) {
11331 DeclContext *Std = SemaRef.getStdNamespace();
11332 for (Sema::AssociatedNamespaceSet::iterator
11333 it = AssociatedNamespaces.begin(),
11334 end = AssociatedNamespaces.end(); it != end; ++it) {
11335 // Never suggest declaring a function within namespace 'std'.
11336 if (Std && Std->Encloses(*it))
11339 // Never suggest declaring a function within a namespace with a
11340 // reserved name, like __gnu_cxx.
11341 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11343 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11346 SuggestedNamespaces.insert(*it);
11350 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11351 << R.getLookupName();
11352 if (SuggestedNamespaces.empty()) {
11353 SemaRef.Diag(Best->Function->getLocation(),
11354 diag::note_not_found_by_two_phase_lookup)
11355 << R.getLookupName() << 0;
11356 } else if (SuggestedNamespaces.size() == 1) {
11357 SemaRef.Diag(Best->Function->getLocation(),
11358 diag::note_not_found_by_two_phase_lookup)
11359 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11361 // FIXME: It would be useful to list the associated namespaces here,
11362 // but the diagnostics infrastructure doesn't provide a way to produce
11363 // a localized representation of a list of items.
11364 SemaRef.Diag(Best->Function->getLocation(),
11365 diag::note_not_found_by_two_phase_lookup)
11366 << R.getLookupName() << 2;
11369 // Try to recover by calling this function.
11379 /// Attempt to recover from ill-formed use of a non-dependent operator in a
11380 /// template, where the non-dependent operator was declared after the template
11383 /// Returns true if a viable candidate was found and a diagnostic was issued.
11385 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11386 SourceLocation OpLoc,
11387 ArrayRef<Expr *> Args) {
11388 DeclarationName OpName =
11389 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11390 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11391 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11392 OverloadCandidateSet::CSK_Operator,
11393 /*ExplicitTemplateArgs=*/nullptr, Args);
11397 class BuildRecoveryCallExprRAII {
11400 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11401 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11402 SemaRef.IsBuildingRecoveryCallExpr = true;
11405 ~BuildRecoveryCallExprRAII() {
11406 SemaRef.IsBuildingRecoveryCallExpr = false;
11412 static std::unique_ptr<CorrectionCandidateCallback>
11413 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
11414 bool HasTemplateArgs, bool AllowTypoCorrection) {
11415 if (!AllowTypoCorrection)
11416 return llvm::make_unique<NoTypoCorrectionCCC>();
11417 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
11418 HasTemplateArgs, ME);
11421 /// Attempts to recover from a call where no functions were found.
11423 /// Returns true if new candidates were found.
11425 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11426 UnresolvedLookupExpr *ULE,
11427 SourceLocation LParenLoc,
11428 MutableArrayRef<Expr *> Args,
11429 SourceLocation RParenLoc,
11430 bool EmptyLookup, bool AllowTypoCorrection) {
11431 // Do not try to recover if it is already building a recovery call.
11432 // This stops infinite loops for template instantiations like
11434 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
11435 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
11437 if (SemaRef.IsBuildingRecoveryCallExpr)
11438 return ExprError();
11439 BuildRecoveryCallExprRAII RCE(SemaRef);
11442 SS.Adopt(ULE->getQualifierLoc());
11443 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
11445 TemplateArgumentListInfo TABuffer;
11446 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11447 if (ULE->hasExplicitTemplateArgs()) {
11448 ULE->copyTemplateArgumentsInto(TABuffer);
11449 ExplicitTemplateArgs = &TABuffer;
11452 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
11453 Sema::LookupOrdinaryName);
11454 bool DoDiagnoseEmptyLookup = EmptyLookup;
11455 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
11456 OverloadCandidateSet::CSK_Normal,
11457 ExplicitTemplateArgs, Args,
11458 &DoDiagnoseEmptyLookup) &&
11459 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
11461 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
11462 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
11463 ExplicitTemplateArgs, Args)))
11464 return ExprError();
11466 assert(!R.empty() && "lookup results empty despite recovery");
11468 // If recovery created an ambiguity, just bail out.
11469 if (R.isAmbiguous()) {
11470 R.suppressDiagnostics();
11471 return ExprError();
11474 // Build an implicit member call if appropriate. Just drop the
11475 // casts and such from the call, we don't really care.
11476 ExprResult NewFn = ExprError();
11477 if ((*R.begin())->isCXXClassMember())
11478 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11479 ExplicitTemplateArgs, S);
11480 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
11481 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
11482 ExplicitTemplateArgs);
11484 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
11486 if (NewFn.isInvalid())
11487 return ExprError();
11489 // This shouldn't cause an infinite loop because we're giving it
11490 // an expression with viable lookup results, which should never
11492 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
11493 MultiExprArg(Args.data(), Args.size()),
11497 /// \brief Constructs and populates an OverloadedCandidateSet from
11498 /// the given function.
11499 /// \returns true when an the ExprResult output parameter has been set.
11500 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
11501 UnresolvedLookupExpr *ULE,
11503 SourceLocation RParenLoc,
11504 OverloadCandidateSet *CandidateSet,
11505 ExprResult *Result) {
11507 if (ULE->requiresADL()) {
11508 // To do ADL, we must have found an unqualified name.
11509 assert(!ULE->getQualifier() && "qualified name with ADL");
11511 // We don't perform ADL for implicit declarations of builtins.
11512 // Verify that this was correctly set up.
11514 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
11515 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
11516 F->getBuiltinID() && F->isImplicit())
11517 llvm_unreachable("performing ADL for builtin");
11519 // We don't perform ADL in C.
11520 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
11524 UnbridgedCastsSet UnbridgedCasts;
11525 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
11526 *Result = ExprError();
11530 // Add the functions denoted by the callee to the set of candidate
11531 // functions, including those from argument-dependent lookup.
11532 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
11534 if (getLangOpts().MSVCCompat &&
11535 CurContext->isDependentContext() && !isSFINAEContext() &&
11536 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
11538 OverloadCandidateSet::iterator Best;
11539 if (CandidateSet->empty() ||
11540 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
11541 OR_No_Viable_Function) {
11542 // In Microsoft mode, if we are inside a template class member function then
11543 // create a type dependent CallExpr. The goal is to postpone name lookup
11544 // to instantiation time to be able to search into type dependent base
11546 CallExpr *CE = new (Context) CallExpr(
11547 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
11548 CE->setTypeDependent(true);
11549 CE->setValueDependent(true);
11550 CE->setInstantiationDependent(true);
11556 if (CandidateSet->empty())
11559 UnbridgedCasts.restore();
11563 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
11564 /// the completed call expression. If overload resolution fails, emits
11565 /// diagnostics and returns ExprError()
11566 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
11567 UnresolvedLookupExpr *ULE,
11568 SourceLocation LParenLoc,
11570 SourceLocation RParenLoc,
11572 OverloadCandidateSet *CandidateSet,
11573 OverloadCandidateSet::iterator *Best,
11574 OverloadingResult OverloadResult,
11575 bool AllowTypoCorrection) {
11576 if (CandidateSet->empty())
11577 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
11578 RParenLoc, /*EmptyLookup=*/true,
11579 AllowTypoCorrection);
11581 switch (OverloadResult) {
11583 FunctionDecl *FDecl = (*Best)->Function;
11584 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
11585 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
11586 return ExprError();
11587 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11588 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11592 case OR_No_Viable_Function: {
11593 // Try to recover by looking for viable functions which the user might
11594 // have meant to call.
11595 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
11597 /*EmptyLookup=*/false,
11598 AllowTypoCorrection);
11599 if (!Recovery.isInvalid())
11602 // If the user passes in a function that we can't take the address of, we
11603 // generally end up emitting really bad error messages. Here, we attempt to
11604 // emit better ones.
11605 for (const Expr *Arg : Args) {
11606 if (!Arg->getType()->isFunctionType())
11608 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
11609 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11611 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11612 Arg->getExprLoc()))
11613 return ExprError();
11617 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call)
11618 << ULE->getName() << Fn->getSourceRange();
11619 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11624 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
11625 << ULE->getName() << Fn->getSourceRange();
11626 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
11630 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
11631 << (*Best)->Function->isDeleted()
11633 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
11634 << Fn->getSourceRange();
11635 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
11637 // We emitted an error for the unvailable/deleted function call but keep
11638 // the call in the AST.
11639 FunctionDecl *FDecl = (*Best)->Function;
11640 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
11641 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
11646 // Overload resolution failed.
11647 return ExprError();
11650 static void markUnaddressableCandidatesUnviable(Sema &S,
11651 OverloadCandidateSet &CS) {
11652 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
11654 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
11656 I->FailureKind = ovl_fail_addr_not_available;
11661 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
11662 /// (which eventually refers to the declaration Func) and the call
11663 /// arguments Args/NumArgs, attempt to resolve the function call down
11664 /// to a specific function. If overload resolution succeeds, returns
11665 /// the call expression produced by overload resolution.
11666 /// Otherwise, emits diagnostics and returns ExprError.
11667 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
11668 UnresolvedLookupExpr *ULE,
11669 SourceLocation LParenLoc,
11671 SourceLocation RParenLoc,
11673 bool AllowTypoCorrection,
11674 bool CalleesAddressIsTaken) {
11675 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
11676 OverloadCandidateSet::CSK_Normal);
11679 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
11683 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
11684 // functions that aren't addressible are considered unviable.
11685 if (CalleesAddressIsTaken)
11686 markUnaddressableCandidatesUnviable(*this, CandidateSet);
11688 OverloadCandidateSet::iterator Best;
11689 OverloadingResult OverloadResult =
11690 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
11692 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
11693 RParenLoc, ExecConfig, &CandidateSet,
11694 &Best, OverloadResult,
11695 AllowTypoCorrection);
11698 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
11699 return Functions.size() > 1 ||
11700 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
11703 /// \brief Create a unary operation that may resolve to an overloaded
11706 /// \param OpLoc The location of the operator itself (e.g., '*').
11708 /// \param Opc The UnaryOperatorKind that describes this operator.
11710 /// \param Fns The set of non-member functions that will be
11711 /// considered by overload resolution. The caller needs to build this
11712 /// set based on the context using, e.g.,
11713 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11714 /// set should not contain any member functions; those will be added
11715 /// by CreateOverloadedUnaryOp().
11717 /// \param Input The input argument.
11719 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
11720 const UnresolvedSetImpl &Fns,
11722 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
11723 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
11724 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11725 // TODO: provide better source location info.
11726 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11728 if (checkPlaceholderForOverload(*this, Input))
11729 return ExprError();
11731 Expr *Args[2] = { Input, nullptr };
11732 unsigned NumArgs = 1;
11734 // For post-increment and post-decrement, add the implicit '0' as
11735 // the second argument, so that we know this is a post-increment or
11737 if (Opc == UO_PostInc || Opc == UO_PostDec) {
11738 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
11739 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
11744 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
11746 if (Input->isTypeDependent()) {
11748 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
11749 VK_RValue, OK_Ordinary, OpLoc);
11751 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11752 UnresolvedLookupExpr *Fn
11753 = UnresolvedLookupExpr::Create(Context, NamingClass,
11754 NestedNameSpecifierLoc(), OpNameInfo,
11755 /*ADL*/ true, IsOverloaded(Fns),
11756 Fns.begin(), Fns.end());
11757 return new (Context)
11758 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
11759 VK_RValue, OpLoc, false);
11762 // Build an empty overload set.
11763 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11765 // Add the candidates from the given function set.
11766 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
11768 // Add operator candidates that are member functions.
11769 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11771 // Add candidates from ADL.
11772 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
11773 /*ExplicitTemplateArgs*/nullptr,
11776 // Add builtin operator candidates.
11777 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
11779 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11781 // Perform overload resolution.
11782 OverloadCandidateSet::iterator Best;
11783 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11785 // We found a built-in operator or an overloaded operator.
11786 FunctionDecl *FnDecl = Best->Function;
11789 // We matched an overloaded operator. Build a call to that
11792 // Convert the arguments.
11793 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
11794 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
11796 ExprResult InputRes =
11797 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
11798 Best->FoundDecl, Method);
11799 if (InputRes.isInvalid())
11800 return ExprError();
11801 Input = InputRes.get();
11803 // Convert the arguments.
11804 ExprResult InputInit
11805 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11807 FnDecl->getParamDecl(0)),
11810 if (InputInit.isInvalid())
11811 return ExprError();
11812 Input = InputInit.get();
11815 // Build the actual expression node.
11816 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
11817 HadMultipleCandidates, OpLoc);
11818 if (FnExpr.isInvalid())
11819 return ExprError();
11821 // Determine the result type.
11822 QualType ResultTy = FnDecl->getReturnType();
11823 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11824 ResultTy = ResultTy.getNonLValueExprType(Context);
11827 CallExpr *TheCall =
11828 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
11829 ResultTy, VK, OpLoc, false);
11831 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
11832 return ExprError();
11834 return MaybeBindToTemporary(TheCall);
11836 // We matched a built-in operator. Convert the arguments, then
11837 // break out so that we will build the appropriate built-in
11839 ExprResult InputRes =
11840 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11841 Best->Conversions[0], AA_Passing);
11842 if (InputRes.isInvalid())
11843 return ExprError();
11844 Input = InputRes.get();
11849 case OR_No_Viable_Function:
11850 // This is an erroneous use of an operator which can be overloaded by
11851 // a non-member function. Check for non-member operators which were
11852 // defined too late to be candidates.
11853 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
11854 // FIXME: Recover by calling the found function.
11855 return ExprError();
11857 // No viable function; fall through to handling this as a
11858 // built-in operator, which will produce an error message for us.
11862 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11863 << UnaryOperator::getOpcodeStr(Opc)
11864 << Input->getType()
11865 << Input->getSourceRange();
11866 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
11867 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11868 return ExprError();
11871 Diag(OpLoc, diag::err_ovl_deleted_oper)
11872 << Best->Function->isDeleted()
11873 << UnaryOperator::getOpcodeStr(Opc)
11874 << getDeletedOrUnavailableSuffix(Best->Function)
11875 << Input->getSourceRange();
11876 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
11877 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11878 return ExprError();
11881 // Either we found no viable overloaded operator or we matched a
11882 // built-in operator. In either case, fall through to trying to
11883 // build a built-in operation.
11884 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11887 /// \brief Create a binary operation that may resolve to an overloaded
11890 /// \param OpLoc The location of the operator itself (e.g., '+').
11892 /// \param Opc The BinaryOperatorKind that describes this operator.
11894 /// \param Fns The set of non-member functions that will be
11895 /// considered by overload resolution. The caller needs to build this
11896 /// set based on the context using, e.g.,
11897 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11898 /// set should not contain any member functions; those will be added
11899 /// by CreateOverloadedBinOp().
11901 /// \param LHS Left-hand argument.
11902 /// \param RHS Right-hand argument.
11904 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
11905 BinaryOperatorKind Opc,
11906 const UnresolvedSetImpl &Fns,
11907 Expr *LHS, Expr *RHS) {
11908 Expr *Args[2] = { LHS, RHS };
11909 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
11911 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11912 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11914 // If either side is type-dependent, create an appropriate dependent
11916 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11918 // If there are no functions to store, just build a dependent
11919 // BinaryOperator or CompoundAssignment.
11920 if (Opc <= BO_Assign || Opc > BO_OrAssign)
11921 return new (Context) BinaryOperator(
11922 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11923 OpLoc, FPFeatures.fp_contract);
11925 return new (Context) CompoundAssignOperator(
11926 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11927 Context.DependentTy, Context.DependentTy, OpLoc,
11928 FPFeatures.fp_contract);
11931 // FIXME: save results of ADL from here?
11932 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11933 // TODO: provide better source location info in DNLoc component.
11934 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
11935 UnresolvedLookupExpr *Fn
11936 = UnresolvedLookupExpr::Create(Context, NamingClass,
11937 NestedNameSpecifierLoc(), OpNameInfo,
11938 /*ADL*/ true, IsOverloaded(Fns),
11939 Fns.begin(), Fns.end());
11940 return new (Context)
11941 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11942 VK_RValue, OpLoc, FPFeatures.fp_contract);
11945 // Always do placeholder-like conversions on the RHS.
11946 if (checkPlaceholderForOverload(*this, Args[1]))
11947 return ExprError();
11949 // Do placeholder-like conversion on the LHS; note that we should
11950 // not get here with a PseudoObject LHS.
11951 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
11952 if (checkPlaceholderForOverload(*this, Args[0]))
11953 return ExprError();
11955 // If this is the assignment operator, we only perform overload resolution
11956 // if the left-hand side is a class or enumeration type. This is actually
11957 // a hack. The standard requires that we do overload resolution between the
11958 // various built-in candidates, but as DR507 points out, this can lead to
11959 // problems. So we do it this way, which pretty much follows what GCC does.
11960 // Note that we go the traditional code path for compound assignment forms.
11961 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
11962 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11964 // If this is the .* operator, which is not overloadable, just
11965 // create a built-in binary operator.
11966 if (Opc == BO_PtrMemD)
11967 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11969 // Build an empty overload set.
11970 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
11972 // Add the candidates from the given function set.
11973 AddFunctionCandidates(Fns, Args, CandidateSet);
11975 // Add operator candidates that are member functions.
11976 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11978 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11979 // performed for an assignment operator (nor for operator[] nor operator->,
11980 // which don't get here).
11981 if (Opc != BO_Assign)
11982 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11983 /*ExplicitTemplateArgs*/ nullptr,
11986 // Add builtin operator candidates.
11987 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
11989 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11991 // Perform overload resolution.
11992 OverloadCandidateSet::iterator Best;
11993 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11995 // We found a built-in operator or an overloaded operator.
11996 FunctionDecl *FnDecl = Best->Function;
11999 // We matched an overloaded operator. Build a call to that
12002 // Convert the arguments.
12003 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12004 // Best->Access is only meaningful for class members.
12005 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12008 PerformCopyInitialization(
12009 InitializedEntity::InitializeParameter(Context,
12010 FnDecl->getParamDecl(0)),
12011 SourceLocation(), Args[1]);
12012 if (Arg1.isInvalid())
12013 return ExprError();
12016 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12017 Best->FoundDecl, Method);
12018 if (Arg0.isInvalid())
12019 return ExprError();
12020 Args[0] = Arg0.getAs<Expr>();
12021 Args[1] = RHS = Arg1.getAs<Expr>();
12023 // Convert the arguments.
12024 ExprResult Arg0 = PerformCopyInitialization(
12025 InitializedEntity::InitializeParameter(Context,
12026 FnDecl->getParamDecl(0)),
12027 SourceLocation(), Args[0]);
12028 if (Arg0.isInvalid())
12029 return ExprError();
12032 PerformCopyInitialization(
12033 InitializedEntity::InitializeParameter(Context,
12034 FnDecl->getParamDecl(1)),
12035 SourceLocation(), Args[1]);
12036 if (Arg1.isInvalid())
12037 return ExprError();
12038 Args[0] = LHS = Arg0.getAs<Expr>();
12039 Args[1] = RHS = Arg1.getAs<Expr>();
12042 // Build the actual expression node.
12043 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12045 HadMultipleCandidates, OpLoc);
12046 if (FnExpr.isInvalid())
12047 return ExprError();
12049 // Determine the result type.
12050 QualType ResultTy = FnDecl->getReturnType();
12051 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12052 ResultTy = ResultTy.getNonLValueExprType(Context);
12054 CXXOperatorCallExpr *TheCall =
12055 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
12056 Args, ResultTy, VK, OpLoc,
12057 FPFeatures.fp_contract);
12059 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12061 return ExprError();
12063 ArrayRef<const Expr *> ArgsArray(Args, 2);
12064 // Cut off the implicit 'this'.
12065 if (isa<CXXMethodDecl>(FnDecl))
12066 ArgsArray = ArgsArray.slice(1);
12068 // Check for a self move.
12069 if (Op == OO_Equal)
12070 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12072 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
12073 TheCall->getSourceRange(), VariadicDoesNotApply);
12075 return MaybeBindToTemporary(TheCall);
12077 // We matched a built-in operator. Convert the arguments, then
12078 // break out so that we will build the appropriate built-in
12080 ExprResult ArgsRes0 =
12081 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12082 Best->Conversions[0], AA_Passing);
12083 if (ArgsRes0.isInvalid())
12084 return ExprError();
12085 Args[0] = ArgsRes0.get();
12087 ExprResult ArgsRes1 =
12088 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12089 Best->Conversions[1], AA_Passing);
12090 if (ArgsRes1.isInvalid())
12091 return ExprError();
12092 Args[1] = ArgsRes1.get();
12097 case OR_No_Viable_Function: {
12098 // C++ [over.match.oper]p9:
12099 // If the operator is the operator , [...] and there are no
12100 // viable functions, then the operator is assumed to be the
12101 // built-in operator and interpreted according to clause 5.
12102 if (Opc == BO_Comma)
12105 // For class as left operand for assignment or compound assigment
12106 // operator do not fall through to handling in built-in, but report that
12107 // no overloaded assignment operator found
12108 ExprResult Result = ExprError();
12109 if (Args[0]->getType()->isRecordType() &&
12110 Opc >= BO_Assign && Opc <= BO_OrAssign) {
12111 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12112 << BinaryOperator::getOpcodeStr(Opc)
12113 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12114 if (Args[0]->getType()->isIncompleteType()) {
12115 Diag(OpLoc, diag::note_assign_lhs_incomplete)
12116 << Args[0]->getType()
12117 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12120 // This is an erroneous use of an operator which can be overloaded by
12121 // a non-member function. Check for non-member operators which were
12122 // defined too late to be candidates.
12123 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12124 // FIXME: Recover by calling the found function.
12125 return ExprError();
12127 // No viable function; try to create a built-in operation, which will
12128 // produce an error. Then, show the non-viable candidates.
12129 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12131 assert(Result.isInvalid() &&
12132 "C++ binary operator overloading is missing candidates!");
12133 if (Result.isInvalid())
12134 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12135 BinaryOperator::getOpcodeStr(Opc), OpLoc);
12140 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
12141 << BinaryOperator::getOpcodeStr(Opc)
12142 << Args[0]->getType() << Args[1]->getType()
12143 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12144 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12145 BinaryOperator::getOpcodeStr(Opc), OpLoc);
12146 return ExprError();
12149 if (isImplicitlyDeleted(Best->Function)) {
12150 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12151 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12152 << Context.getRecordType(Method->getParent())
12153 << getSpecialMember(Method);
12155 // The user probably meant to call this special member. Just
12156 // explain why it's deleted.
12157 NoteDeletedFunction(Method);
12158 return ExprError();
12160 Diag(OpLoc, diag::err_ovl_deleted_oper)
12161 << Best->Function->isDeleted()
12162 << BinaryOperator::getOpcodeStr(Opc)
12163 << getDeletedOrUnavailableSuffix(Best->Function)
12164 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12166 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12167 BinaryOperator::getOpcodeStr(Opc), OpLoc);
12168 return ExprError();
12171 // We matched a built-in operator; build it.
12172 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12176 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12177 SourceLocation RLoc,
12178 Expr *Base, Expr *Idx) {
12179 Expr *Args[2] = { Base, Idx };
12180 DeclarationName OpName =
12181 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12183 // If either side is type-dependent, create an appropriate dependent
12185 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12187 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12188 // CHECKME: no 'operator' keyword?
12189 DeclarationNameInfo OpNameInfo(OpName, LLoc);
12190 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12191 UnresolvedLookupExpr *Fn
12192 = UnresolvedLookupExpr::Create(Context, NamingClass,
12193 NestedNameSpecifierLoc(), OpNameInfo,
12194 /*ADL*/ true, /*Overloaded*/ false,
12195 UnresolvedSetIterator(),
12196 UnresolvedSetIterator());
12197 // Can't add any actual overloads yet
12199 return new (Context)
12200 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
12201 Context.DependentTy, VK_RValue, RLoc, false);
12204 // Handle placeholders on both operands.
12205 if (checkPlaceholderForOverload(*this, Args[0]))
12206 return ExprError();
12207 if (checkPlaceholderForOverload(*this, Args[1]))
12208 return ExprError();
12210 // Build an empty overload set.
12211 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12213 // Subscript can only be overloaded as a member function.
12215 // Add operator candidates that are member functions.
12216 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12218 // Add builtin operator candidates.
12219 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12221 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12223 // Perform overload resolution.
12224 OverloadCandidateSet::iterator Best;
12225 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12227 // We found a built-in operator or an overloaded operator.
12228 FunctionDecl *FnDecl = Best->Function;
12231 // We matched an overloaded operator. Build a call to that
12234 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12236 // Convert the arguments.
12237 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12239 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12240 Best->FoundDecl, Method);
12241 if (Arg0.isInvalid())
12242 return ExprError();
12243 Args[0] = Arg0.get();
12245 // Convert the arguments.
12246 ExprResult InputInit
12247 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12249 FnDecl->getParamDecl(0)),
12252 if (InputInit.isInvalid())
12253 return ExprError();
12255 Args[1] = InputInit.getAs<Expr>();
12257 // Build the actual expression node.
12258 DeclarationNameInfo OpLocInfo(OpName, LLoc);
12259 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12260 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12262 HadMultipleCandidates,
12263 OpLocInfo.getLoc(),
12264 OpLocInfo.getInfo());
12265 if (FnExpr.isInvalid())
12266 return ExprError();
12268 // Determine the result type
12269 QualType ResultTy = FnDecl->getReturnType();
12270 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12271 ResultTy = ResultTy.getNonLValueExprType(Context);
12273 CXXOperatorCallExpr *TheCall =
12274 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
12275 FnExpr.get(), Args,
12276 ResultTy, VK, RLoc,
12279 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12280 return ExprError();
12282 return MaybeBindToTemporary(TheCall);
12284 // We matched a built-in operator. Convert the arguments, then
12285 // break out so that we will build the appropriate built-in
12287 ExprResult ArgsRes0 =
12288 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
12289 Best->Conversions[0], AA_Passing);
12290 if (ArgsRes0.isInvalid())
12291 return ExprError();
12292 Args[0] = ArgsRes0.get();
12294 ExprResult ArgsRes1 =
12295 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
12296 Best->Conversions[1], AA_Passing);
12297 if (ArgsRes1.isInvalid())
12298 return ExprError();
12299 Args[1] = ArgsRes1.get();
12305 case OR_No_Viable_Function: {
12306 if (CandidateSet.empty())
12307 Diag(LLoc, diag::err_ovl_no_oper)
12308 << Args[0]->getType() << /*subscript*/ 0
12309 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12311 Diag(LLoc, diag::err_ovl_no_viable_subscript)
12312 << Args[0]->getType()
12313 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12314 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12316 return ExprError();
12320 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
12322 << Args[0]->getType() << Args[1]->getType()
12323 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12324 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
12326 return ExprError();
12329 Diag(LLoc, diag::err_ovl_deleted_oper)
12330 << Best->Function->isDeleted() << "[]"
12331 << getDeletedOrUnavailableSuffix(Best->Function)
12332 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12333 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
12335 return ExprError();
12338 // We matched a built-in operator; build it.
12339 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12342 /// BuildCallToMemberFunction - Build a call to a member
12343 /// function. MemExpr is the expression that refers to the member
12344 /// function (and includes the object parameter), Args/NumArgs are the
12345 /// arguments to the function call (not including the object
12346 /// parameter). The caller needs to validate that the member
12347 /// expression refers to a non-static member function or an overloaded
12348 /// member function.
12350 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12351 SourceLocation LParenLoc,
12353 SourceLocation RParenLoc) {
12354 assert(MemExprE->getType() == Context.BoundMemberTy ||
12355 MemExprE->getType() == Context.OverloadTy);
12357 // Dig out the member expression. This holds both the object
12358 // argument and the member function we're referring to.
12359 Expr *NakedMemExpr = MemExprE->IgnoreParens();
12361 // Determine whether this is a call to a pointer-to-member function.
12362 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12363 assert(op->getType() == Context.BoundMemberTy);
12364 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12367 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12369 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12370 QualType resultType = proto->getCallResultType(Context);
12371 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12373 // Check that the object type isn't more qualified than the
12374 // member function we're calling.
12375 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
12377 QualType objectType = op->getLHS()->getType();
12378 if (op->getOpcode() == BO_PtrMemI)
12379 objectType = objectType->castAs<PointerType>()->getPointeeType();
12380 Qualifiers objectQuals = objectType.getQualifiers();
12382 Qualifiers difference = objectQuals - funcQuals;
12383 difference.removeObjCGCAttr();
12384 difference.removeAddressSpace();
12386 std::string qualsString = difference.getAsString();
12387 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12388 << fnType.getUnqualifiedType()
12390 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12393 CXXMemberCallExpr *call
12394 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12395 resultType, valueKind, RParenLoc);
12397 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
12399 return ExprError();
12401 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
12402 return ExprError();
12404 if (CheckOtherCall(call, proto))
12405 return ExprError();
12407 return MaybeBindToTemporary(call);
12410 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
12411 return new (Context)
12412 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
12414 UnbridgedCastsSet UnbridgedCasts;
12415 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12416 return ExprError();
12418 MemberExpr *MemExpr;
12419 CXXMethodDecl *Method = nullptr;
12420 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
12421 NestedNameSpecifier *Qualifier = nullptr;
12422 if (isa<MemberExpr>(NakedMemExpr)) {
12423 MemExpr = cast<MemberExpr>(NakedMemExpr);
12424 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
12425 FoundDecl = MemExpr->getFoundDecl();
12426 Qualifier = MemExpr->getQualifier();
12427 UnbridgedCasts.restore();
12429 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
12430 Qualifier = UnresExpr->getQualifier();
12432 QualType ObjectType = UnresExpr->getBaseType();
12433 Expr::Classification ObjectClassification
12434 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
12435 : UnresExpr->getBase()->Classify(Context);
12437 // Add overload candidates
12438 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
12439 OverloadCandidateSet::CSK_Normal);
12441 // FIXME: avoid copy.
12442 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12443 if (UnresExpr->hasExplicitTemplateArgs()) {
12444 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12445 TemplateArgs = &TemplateArgsBuffer;
12448 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
12449 E = UnresExpr->decls_end(); I != E; ++I) {
12451 NamedDecl *Func = *I;
12452 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
12453 if (isa<UsingShadowDecl>(Func))
12454 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
12457 // Microsoft supports direct constructor calls.
12458 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
12459 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
12460 Args, CandidateSet);
12461 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
12462 // If explicit template arguments were provided, we can't call a
12463 // non-template member function.
12467 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
12468 ObjectClassification, Args, CandidateSet,
12469 /*SuppressUserConversions=*/false);
12471 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
12472 I.getPair(), ActingDC, TemplateArgs,
12473 ObjectType, ObjectClassification,
12474 Args, CandidateSet,
12475 /*SuppressUsedConversions=*/false);
12479 DeclarationName DeclName = UnresExpr->getMemberName();
12481 UnbridgedCasts.restore();
12483 OverloadCandidateSet::iterator Best;
12484 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
12487 Method = cast<CXXMethodDecl>(Best->Function);
12488 FoundDecl = Best->FoundDecl;
12489 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
12490 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
12491 return ExprError();
12492 // If FoundDecl is different from Method (such as if one is a template
12493 // and the other a specialization), make sure DiagnoseUseOfDecl is
12495 // FIXME: This would be more comprehensively addressed by modifying
12496 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
12498 if (Method != FoundDecl.getDecl() &&
12499 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
12500 return ExprError();
12503 case OR_No_Viable_Function:
12504 Diag(UnresExpr->getMemberLoc(),
12505 diag::err_ovl_no_viable_member_function_in_call)
12506 << DeclName << MemExprE->getSourceRange();
12507 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12508 // FIXME: Leaking incoming expressions!
12509 return ExprError();
12512 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
12513 << DeclName << MemExprE->getSourceRange();
12514 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12515 // FIXME: Leaking incoming expressions!
12516 return ExprError();
12519 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
12520 << Best->Function->isDeleted()
12522 << getDeletedOrUnavailableSuffix(Best->Function)
12523 << MemExprE->getSourceRange();
12524 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12525 // FIXME: Leaking incoming expressions!
12526 return ExprError();
12529 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
12531 // If overload resolution picked a static member, build a
12532 // non-member call based on that function.
12533 if (Method->isStatic()) {
12534 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
12538 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
12541 QualType ResultType = Method->getReturnType();
12542 ExprValueKind VK = Expr::getValueKindForType(ResultType);
12543 ResultType = ResultType.getNonLValueExprType(Context);
12545 assert(Method && "Member call to something that isn't a method?");
12546 CXXMemberCallExpr *TheCall =
12547 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
12548 ResultType, VK, RParenLoc);
12550 // Check for a valid return type.
12551 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
12553 return ExprError();
12555 // Convert the object argument (for a non-static member function call).
12556 // We only need to do this if there was actually an overload; otherwise
12557 // it was done at lookup.
12558 if (!Method->isStatic()) {
12559 ExprResult ObjectArg =
12560 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
12561 FoundDecl, Method);
12562 if (ObjectArg.isInvalid())
12563 return ExprError();
12564 MemExpr->setBase(ObjectArg.get());
12567 // Convert the rest of the arguments
12568 const FunctionProtoType *Proto =
12569 Method->getType()->getAs<FunctionProtoType>();
12570 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
12572 return ExprError();
12574 DiagnoseSentinelCalls(Method, LParenLoc, Args);
12576 if (CheckFunctionCall(Method, TheCall, Proto))
12577 return ExprError();
12579 // In the case the method to call was not selected by the overloading
12580 // resolution process, we still need to handle the enable_if attribute. Do
12581 // that here, so it will not hide previous -- and more relevant -- errors.
12582 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
12583 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
12584 Diag(MemE->getMemberLoc(),
12585 diag::err_ovl_no_viable_member_function_in_call)
12586 << Method << Method->getSourceRange();
12587 Diag(Method->getLocation(),
12588 diag::note_ovl_candidate_disabled_by_enable_if_attr)
12589 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12590 return ExprError();
12594 if ((isa<CXXConstructorDecl>(CurContext) ||
12595 isa<CXXDestructorDecl>(CurContext)) &&
12596 TheCall->getMethodDecl()->isPure()) {
12597 const CXXMethodDecl *MD = TheCall->getMethodDecl();
12599 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
12600 MemExpr->performsVirtualDispatch(getLangOpts())) {
12601 Diag(MemExpr->getLocStart(),
12602 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
12603 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
12604 << MD->getParent()->getDeclName();
12606 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
12607 if (getLangOpts().AppleKext)
12608 Diag(MemExpr->getLocStart(),
12609 diag::note_pure_qualified_call_kext)
12610 << MD->getParent()->getDeclName()
12611 << MD->getDeclName();
12615 if (CXXDestructorDecl *DD =
12616 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
12617 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
12618 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
12619 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false,
12620 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
12621 MemExpr->getMemberLoc());
12624 return MaybeBindToTemporary(TheCall);
12627 /// BuildCallToObjectOfClassType - Build a call to an object of class
12628 /// type (C++ [over.call.object]), which can end up invoking an
12629 /// overloaded function call operator (@c operator()) or performing a
12630 /// user-defined conversion on the object argument.
12632 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
12633 SourceLocation LParenLoc,
12635 SourceLocation RParenLoc) {
12636 if (checkPlaceholderForOverload(*this, Obj))
12637 return ExprError();
12638 ExprResult Object = Obj;
12640 UnbridgedCastsSet UnbridgedCasts;
12641 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
12642 return ExprError();
12644 assert(Object.get()->getType()->isRecordType() &&
12645 "Requires object type argument");
12646 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
12648 // C++ [over.call.object]p1:
12649 // If the primary-expression E in the function call syntax
12650 // evaluates to a class object of type "cv T", then the set of
12651 // candidate functions includes at least the function call
12652 // operators of T. The function call operators of T are obtained by
12653 // ordinary lookup of the name operator() in the context of
12655 OverloadCandidateSet CandidateSet(LParenLoc,
12656 OverloadCandidateSet::CSK_Operator);
12657 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
12659 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
12660 diag::err_incomplete_object_call, Object.get()))
12663 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
12664 LookupQualifiedName(R, Record->getDecl());
12665 R.suppressDiagnostics();
12667 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12668 Oper != OperEnd; ++Oper) {
12669 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
12670 Object.get()->Classify(Context),
12671 Args, CandidateSet,
12672 /*SuppressUserConversions=*/ false);
12675 // C++ [over.call.object]p2:
12676 // In addition, for each (non-explicit in C++0x) conversion function
12677 // declared in T of the form
12679 // operator conversion-type-id () cv-qualifier;
12681 // where cv-qualifier is the same cv-qualification as, or a
12682 // greater cv-qualification than, cv, and where conversion-type-id
12683 // denotes the type "pointer to function of (P1,...,Pn) returning
12684 // R", or the type "reference to pointer to function of
12685 // (P1,...,Pn) returning R", or the type "reference to function
12686 // of (P1,...,Pn) returning R", a surrogate call function [...]
12687 // is also considered as a candidate function. Similarly,
12688 // surrogate call functions are added to the set of candidate
12689 // functions for each conversion function declared in an
12690 // accessible base class provided the function is not hidden
12691 // within T by another intervening declaration.
12692 const auto &Conversions =
12693 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
12694 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
12696 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
12697 if (isa<UsingShadowDecl>(D))
12698 D = cast<UsingShadowDecl>(D)->getTargetDecl();
12700 // Skip over templated conversion functions; they aren't
12702 if (isa<FunctionTemplateDecl>(D))
12705 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
12706 if (!Conv->isExplicit()) {
12707 // Strip the reference type (if any) and then the pointer type (if
12708 // any) to get down to what might be a function type.
12709 QualType ConvType = Conv->getConversionType().getNonReferenceType();
12710 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12711 ConvType = ConvPtrType->getPointeeType();
12713 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
12715 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
12716 Object.get(), Args, CandidateSet);
12721 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12723 // Perform overload resolution.
12724 OverloadCandidateSet::iterator Best;
12725 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
12728 // Overload resolution succeeded; we'll build the appropriate call
12732 case OR_No_Viable_Function:
12733 if (CandidateSet.empty())
12734 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
12735 << Object.get()->getType() << /*call*/ 1
12736 << Object.get()->getSourceRange();
12738 Diag(Object.get()->getLocStart(),
12739 diag::err_ovl_no_viable_object_call)
12740 << Object.get()->getType() << Object.get()->getSourceRange();
12741 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12745 Diag(Object.get()->getLocStart(),
12746 diag::err_ovl_ambiguous_object_call)
12747 << Object.get()->getType() << Object.get()->getSourceRange();
12748 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12752 Diag(Object.get()->getLocStart(),
12753 diag::err_ovl_deleted_object_call)
12754 << Best->Function->isDeleted()
12755 << Object.get()->getType()
12756 << getDeletedOrUnavailableSuffix(Best->Function)
12757 << Object.get()->getSourceRange();
12758 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12762 if (Best == CandidateSet.end())
12765 UnbridgedCasts.restore();
12767 if (Best->Function == nullptr) {
12768 // Since there is no function declaration, this is one of the
12769 // surrogate candidates. Dig out the conversion function.
12770 CXXConversionDecl *Conv
12771 = cast<CXXConversionDecl>(
12772 Best->Conversions[0].UserDefined.ConversionFunction);
12774 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
12776 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
12777 return ExprError();
12778 assert(Conv == Best->FoundDecl.getDecl() &&
12779 "Found Decl & conversion-to-functionptr should be same, right?!");
12780 // We selected one of the surrogate functions that converts the
12781 // object parameter to a function pointer. Perform the conversion
12782 // on the object argument, then let ActOnCallExpr finish the job.
12784 // Create an implicit member expr to refer to the conversion operator.
12785 // and then call it.
12786 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
12787 Conv, HadMultipleCandidates);
12788 if (Call.isInvalid())
12789 return ExprError();
12790 // Record usage of conversion in an implicit cast.
12791 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
12792 CK_UserDefinedConversion, Call.get(),
12793 nullptr, VK_RValue);
12795 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
12798 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
12800 // We found an overloaded operator(). Build a CXXOperatorCallExpr
12801 // that calls this method, using Object for the implicit object
12802 // parameter and passing along the remaining arguments.
12803 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12805 // An error diagnostic has already been printed when parsing the declaration.
12806 if (Method->isInvalidDecl())
12807 return ExprError();
12809 const FunctionProtoType *Proto =
12810 Method->getType()->getAs<FunctionProtoType>();
12812 unsigned NumParams = Proto->getNumParams();
12814 DeclarationNameInfo OpLocInfo(
12815 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12816 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
12817 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
12818 HadMultipleCandidates,
12819 OpLocInfo.getLoc(),
12820 OpLocInfo.getInfo());
12821 if (NewFn.isInvalid())
12824 // Build the full argument list for the method call (the implicit object
12825 // parameter is placed at the beginning of the list).
12826 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1);
12827 MethodArgs[0] = Object.get();
12828 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1);
12830 // Once we've built TheCall, all of the expressions are properly
12832 QualType ResultTy = Method->getReturnType();
12833 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12834 ResultTy = ResultTy.getNonLValueExprType(Context);
12836 CXXOperatorCallExpr *TheCall = new (Context)
12837 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy,
12838 VK, RParenLoc, false);
12840 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
12843 // We may have default arguments. If so, we need to allocate more
12844 // slots in the call for them.
12845 if (Args.size() < NumParams)
12846 TheCall->setNumArgs(Context, NumParams + 1);
12848 bool IsError = false;
12850 // Initialize the implicit object parameter.
12851 ExprResult ObjRes =
12852 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
12853 Best->FoundDecl, Method);
12854 if (ObjRes.isInvalid())
12858 TheCall->setArg(0, Object.get());
12860 // Check the argument types.
12861 for (unsigned i = 0; i != NumParams; i++) {
12863 if (i < Args.size()) {
12866 // Pass the argument.
12868 ExprResult InputInit
12869 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12871 Method->getParamDecl(i)),
12872 SourceLocation(), Arg);
12874 IsError |= InputInit.isInvalid();
12875 Arg = InputInit.getAs<Expr>();
12878 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12879 if (DefArg.isInvalid()) {
12884 Arg = DefArg.getAs<Expr>();
12887 TheCall->setArg(i + 1, Arg);
12890 // If this is a variadic call, handle args passed through "...".
12891 if (Proto->isVariadic()) {
12892 // Promote the arguments (C99 6.5.2.2p7).
12893 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
12894 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12896 IsError |= Arg.isInvalid();
12897 TheCall->setArg(i + 1, Arg.get());
12901 if (IsError) return true;
12903 DiagnoseSentinelCalls(Method, LParenLoc, Args);
12905 if (CheckFunctionCall(Method, TheCall, Proto))
12908 return MaybeBindToTemporary(TheCall);
12911 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
12912 /// (if one exists), where @c Base is an expression of class type and
12913 /// @c Member is the name of the member we're trying to find.
12915 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12916 bool *NoArrowOperatorFound) {
12917 assert(Base->getType()->isRecordType() &&
12918 "left-hand side must have class type");
12920 if (checkPlaceholderForOverload(*this, Base))
12921 return ExprError();
12923 SourceLocation Loc = Base->getExprLoc();
12925 // C++ [over.ref]p1:
12927 // [...] An expression x->m is interpreted as (x.operator->())->m
12928 // for a class object x of type T if T::operator->() exists and if
12929 // the operator is selected as the best match function by the
12930 // overload resolution mechanism (13.3).
12931 DeclarationName OpName =
12932 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
12933 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
12934 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
12936 if (RequireCompleteType(Loc, Base->getType(),
12937 diag::err_typecheck_incomplete_tag, Base))
12938 return ExprError();
12940 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12941 LookupQualifiedName(R, BaseRecord->getDecl());
12942 R.suppressDiagnostics();
12944 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
12945 Oper != OperEnd; ++Oper) {
12946 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
12947 None, CandidateSet, /*SuppressUserConversions=*/false);
12950 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12952 // Perform overload resolution.
12953 OverloadCandidateSet::iterator Best;
12954 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12956 // Overload resolution succeeded; we'll build the call below.
12959 case OR_No_Viable_Function:
12960 if (CandidateSet.empty()) {
12961 QualType BaseType = Base->getType();
12962 if (NoArrowOperatorFound) {
12963 // Report this specific error to the caller instead of emitting a
12964 // diagnostic, as requested.
12965 *NoArrowOperatorFound = true;
12966 return ExprError();
12968 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12969 << BaseType << Base->getSourceRange();
12970 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
12971 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
12972 << FixItHint::CreateReplacement(OpLoc, ".");
12975 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12976 << "operator->" << Base->getSourceRange();
12977 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12978 return ExprError();
12981 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12982 << "->" << Base->getType() << Base->getSourceRange();
12983 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
12984 return ExprError();
12987 Diag(OpLoc, diag::err_ovl_deleted_oper)
12988 << Best->Function->isDeleted()
12990 << getDeletedOrUnavailableSuffix(Best->Function)
12991 << Base->getSourceRange();
12992 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
12993 return ExprError();
12996 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
12998 // Convert the object parameter.
12999 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13000 ExprResult BaseResult =
13001 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13002 Best->FoundDecl, Method);
13003 if (BaseResult.isInvalid())
13004 return ExprError();
13005 Base = BaseResult.get();
13007 // Build the operator call.
13008 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13009 HadMultipleCandidates, OpLoc);
13010 if (FnExpr.isInvalid())
13011 return ExprError();
13013 QualType ResultTy = Method->getReturnType();
13014 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13015 ResultTy = ResultTy.getNonLValueExprType(Context);
13016 CXXOperatorCallExpr *TheCall =
13017 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
13018 Base, ResultTy, VK, OpLoc, false);
13020 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13021 return ExprError();
13023 return MaybeBindToTemporary(TheCall);
13026 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13027 /// a literal operator described by the provided lookup results.
13028 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13029 DeclarationNameInfo &SuffixInfo,
13030 ArrayRef<Expr*> Args,
13031 SourceLocation LitEndLoc,
13032 TemplateArgumentListInfo *TemplateArgs) {
13033 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13035 OverloadCandidateSet CandidateSet(UDSuffixLoc,
13036 OverloadCandidateSet::CSK_Normal);
13037 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13038 /*SuppressUserConversions=*/true);
13040 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13042 // Perform overload resolution. This will usually be trivial, but might need
13043 // to perform substitutions for a literal operator template.
13044 OverloadCandidateSet::iterator Best;
13045 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13050 case OR_No_Viable_Function:
13051 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
13052 << R.getLookupName();
13053 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
13054 return ExprError();
13057 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
13058 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
13059 return ExprError();
13062 FunctionDecl *FD = Best->Function;
13063 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13064 HadMultipleCandidates,
13065 SuffixInfo.getLoc(),
13066 SuffixInfo.getInfo());
13067 if (Fn.isInvalid())
13070 // Check the argument types. This should almost always be a no-op, except
13071 // that array-to-pointer decay is applied to string literals.
13073 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13074 ExprResult InputInit = PerformCopyInitialization(
13075 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13076 SourceLocation(), Args[ArgIdx]);
13077 if (InputInit.isInvalid())
13079 ConvArgs[ArgIdx] = InputInit.get();
13082 QualType ResultTy = FD->getReturnType();
13083 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13084 ResultTy = ResultTy.getNonLValueExprType(Context);
13086 UserDefinedLiteral *UDL =
13087 new (Context) UserDefinedLiteral(Context, Fn.get(),
13088 llvm::makeArrayRef(ConvArgs, Args.size()),
13089 ResultTy, VK, LitEndLoc, UDSuffixLoc);
13091 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13092 return ExprError();
13094 if (CheckFunctionCall(FD, UDL, nullptr))
13095 return ExprError();
13097 return MaybeBindToTemporary(UDL);
13100 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13101 /// given LookupResult is non-empty, it is assumed to describe a member which
13102 /// will be invoked. Otherwise, the function will be found via argument
13103 /// dependent lookup.
13104 /// CallExpr is set to a valid expression and FRS_Success returned on success,
13105 /// otherwise CallExpr is set to ExprError() and some non-success value
13107 Sema::ForRangeStatus
13108 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13109 SourceLocation RangeLoc,
13110 const DeclarationNameInfo &NameInfo,
13111 LookupResult &MemberLookup,
13112 OverloadCandidateSet *CandidateSet,
13113 Expr *Range, ExprResult *CallExpr) {
13114 Scope *S = nullptr;
13116 CandidateSet->clear();
13117 if (!MemberLookup.empty()) {
13118 ExprResult MemberRef =
13119 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13120 /*IsPtr=*/false, CXXScopeSpec(),
13121 /*TemplateKWLoc=*/SourceLocation(),
13122 /*FirstQualifierInScope=*/nullptr,
13124 /*TemplateArgs=*/nullptr, S);
13125 if (MemberRef.isInvalid()) {
13126 *CallExpr = ExprError();
13127 return FRS_DiagnosticIssued;
13129 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13130 if (CallExpr->isInvalid()) {
13131 *CallExpr = ExprError();
13132 return FRS_DiagnosticIssued;
13135 UnresolvedSet<0> FoundNames;
13136 UnresolvedLookupExpr *Fn =
13137 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13138 NestedNameSpecifierLoc(), NameInfo,
13139 /*NeedsADL=*/true, /*Overloaded=*/false,
13140 FoundNames.begin(), FoundNames.end());
13142 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13143 CandidateSet, CallExpr);
13144 if (CandidateSet->empty() || CandidateSetError) {
13145 *CallExpr = ExprError();
13146 return FRS_NoViableFunction;
13148 OverloadCandidateSet::iterator Best;
13149 OverloadingResult OverloadResult =
13150 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
13152 if (OverloadResult == OR_No_Viable_Function) {
13153 *CallExpr = ExprError();
13154 return FRS_NoViableFunction;
13156 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13157 Loc, nullptr, CandidateSet, &Best,
13159 /*AllowTypoCorrection=*/false);
13160 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13161 *CallExpr = ExprError();
13162 return FRS_DiagnosticIssued;
13165 return FRS_Success;
13169 /// FixOverloadedFunctionReference - E is an expression that refers to
13170 /// a C++ overloaded function (possibly with some parentheses and
13171 /// perhaps a '&' around it). We have resolved the overloaded function
13172 /// to the function declaration Fn, so patch up the expression E to
13173 /// refer (possibly indirectly) to Fn. Returns the new expr.
13174 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13175 FunctionDecl *Fn) {
13176 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13177 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13179 if (SubExpr == PE->getSubExpr())
13182 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13185 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13186 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13188 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13189 SubExpr->getType()) &&
13190 "Implicit cast type cannot be determined from overload");
13191 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13192 if (SubExpr == ICE->getSubExpr())
13195 return ImplicitCastExpr::Create(Context, ICE->getType(),
13196 ICE->getCastKind(),
13198 ICE->getValueKind());
13201 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13202 if (!GSE->isResultDependent()) {
13204 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13205 if (SubExpr == GSE->getResultExpr())
13208 // Replace the resulting type information before rebuilding the generic
13209 // selection expression.
13210 ArrayRef<Expr *> A = GSE->getAssocExprs();
13211 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13212 unsigned ResultIdx = GSE->getResultIndex();
13213 AssocExprs[ResultIdx] = SubExpr;
13215 return new (Context) GenericSelectionExpr(
13216 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13217 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13218 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13221 // Rather than fall through to the unreachable, return the original generic
13222 // selection expression.
13226 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13227 assert(UnOp->getOpcode() == UO_AddrOf &&
13228 "Can only take the address of an overloaded function");
13229 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13230 if (Method->isStatic()) {
13231 // Do nothing: static member functions aren't any different
13232 // from non-member functions.
13234 // Fix the subexpression, which really has to be an
13235 // UnresolvedLookupExpr holding an overloaded member function
13237 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13239 if (SubExpr == UnOp->getSubExpr())
13242 assert(isa<DeclRefExpr>(SubExpr)
13243 && "fixed to something other than a decl ref");
13244 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13245 && "fixed to a member ref with no nested name qualifier");
13247 // We have taken the address of a pointer to member
13248 // function. Perform the computation here so that we get the
13249 // appropriate pointer to member type.
13251 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13252 QualType MemPtrType
13253 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13254 // Under the MS ABI, lock down the inheritance model now.
13255 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13256 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13258 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13259 VK_RValue, OK_Ordinary,
13260 UnOp->getOperatorLoc());
13263 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13265 if (SubExpr == UnOp->getSubExpr())
13268 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13269 Context.getPointerType(SubExpr->getType()),
13270 VK_RValue, OK_Ordinary,
13271 UnOp->getOperatorLoc());
13274 // C++ [except.spec]p17:
13275 // An exception-specification is considered to be needed when:
13276 // - in an expression the function is the unique lookup result or the
13277 // selected member of a set of overloaded functions
13278 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13279 ResolveExceptionSpec(E->getExprLoc(), FPT);
13281 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13282 // FIXME: avoid copy.
13283 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13284 if (ULE->hasExplicitTemplateArgs()) {
13285 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13286 TemplateArgs = &TemplateArgsBuffer;
13289 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13290 ULE->getQualifierLoc(),
13291 ULE->getTemplateKeywordLoc(),
13293 /*enclosing*/ false, // FIXME?
13299 MarkDeclRefReferenced(DRE);
13300 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13304 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13305 // FIXME: avoid copy.
13306 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13307 if (MemExpr->hasExplicitTemplateArgs()) {
13308 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13309 TemplateArgs = &TemplateArgsBuffer;
13314 // If we're filling in a static method where we used to have an
13315 // implicit member access, rewrite to a simple decl ref.
13316 if (MemExpr->isImplicitAccess()) {
13317 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13318 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
13319 MemExpr->getQualifierLoc(),
13320 MemExpr->getTemplateKeywordLoc(),
13322 /*enclosing*/ false,
13323 MemExpr->getMemberLoc(),
13328 MarkDeclRefReferenced(DRE);
13329 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13332 SourceLocation Loc = MemExpr->getMemberLoc();
13333 if (MemExpr->getQualifier())
13334 Loc = MemExpr->getQualifierLoc().getBeginLoc();
13335 CheckCXXThisCapture(Loc);
13336 Base = new (Context) CXXThisExpr(Loc,
13337 MemExpr->getBaseType(),
13338 /*isImplicit=*/true);
13341 Base = MemExpr->getBase();
13343 ExprValueKind valueKind;
13345 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13346 valueKind = VK_LValue;
13347 type = Fn->getType();
13349 valueKind = VK_RValue;
13350 type = Context.BoundMemberTy;
13353 MemberExpr *ME = MemberExpr::Create(
13354 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13355 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13356 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
13358 ME->setHadMultipleCandidates(true);
13359 MarkMemberReferenced(ME);
13363 llvm_unreachable("Invalid reference to overloaded function");
13366 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13367 DeclAccessPair Found,
13368 FunctionDecl *Fn) {
13369 return FixOverloadedFunctionReference(E.get(), Found, Fn);