1 //===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
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 //===----------------------------------------------------------------------===//
15 #include "clang/Basic/Diagnostic.h"
16 #include "clang/Lex/Preprocessor.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/TypeOrdering.h"
22 #include "clang/Basic/PartialDiagnostic.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/Support/Compiler.h"
31 /// GetConversionCategory - Retrieve the implicit conversion
32 /// category corresponding to the given implicit conversion kind.
33 ImplicitConversionCategory
34 GetConversionCategory(ImplicitConversionKind Kind) {
35 static const ImplicitConversionCategory
36 Category[(int)ICK_Num_Conversion_Kinds] = {
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
41 ICC_Qualification_Adjustment,
56 return Category[(int)Kind];
59 /// GetConversionRank - Retrieve the implicit conversion rank
60 /// corresponding to the given implicit conversion kind.
61 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
62 static const ImplicitConversionRank
63 Rank[(int)ICK_Num_Conversion_Kinds] = {
83 return Rank[(int)Kind];
86 /// GetImplicitConversionName - Return the name of this kind of
87 /// implicit conversion.
88 const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
89 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
93 "Function-to-pointer",
96 "Floating point promotion",
98 "Integral conversion",
99 "Floating conversion",
100 "Complex conversion",
101 "Floating-integral conversion",
102 "Complex-real conversion",
103 "Pointer conversion",
104 "Pointer-to-member conversion",
105 "Boolean conversion",
106 "Compatible-types conversion",
107 "Derived-to-base conversion"
112 /// StandardConversionSequence - Set the standard conversion
113 /// sequence to the identity conversion.
114 void StandardConversionSequence::setAsIdentityConversion() {
115 First = ICK_Identity;
116 Second = ICK_Identity;
117 Third = ICK_Identity;
119 ReferenceBinding = false;
120 DirectBinding = false;
125 /// getRank - Retrieve the rank of this standard conversion sequence
126 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
127 /// implicit conversions.
128 ImplicitConversionRank StandardConversionSequence::getRank() const {
129 ImplicitConversionRank Rank = ICR_Exact_Match;
130 if (GetConversionRank(First) > Rank)
131 Rank = GetConversionRank(First);
132 if (GetConversionRank(Second) > Rank)
133 Rank = GetConversionRank(Second);
134 if (GetConversionRank(Third) > Rank)
135 Rank = GetConversionRank(Third);
139 /// isPointerConversionToBool - Determines whether this conversion is
140 /// a conversion of a pointer or pointer-to-member to bool. This is
141 /// used as part of the ranking of standard conversion sequences
142 /// (C++ 13.3.3.2p4).
143 bool StandardConversionSequence::isPointerConversionToBool() const {
144 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
145 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
147 // Note that FromType has not necessarily been transformed by the
148 // array-to-pointer or function-to-pointer implicit conversions, so
149 // check for their presence as well as checking whether FromType is
151 if (ToType->isBooleanType() &&
152 (FromType->isPointerType() || FromType->isBlockPointerType() ||
153 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
159 /// isPointerConversionToVoidPointer - Determines whether this
160 /// conversion is a conversion of a pointer to a void pointer. This is
161 /// used as part of the ranking of standard conversion sequences (C++
164 StandardConversionSequence::
165 isPointerConversionToVoidPointer(ASTContext& Context) const {
166 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
167 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
169 // Note that FromType has not necessarily been transformed by the
170 // array-to-pointer implicit conversion, so check for its presence
171 // and redo the conversion to get a pointer.
172 if (First == ICK_Array_To_Pointer)
173 FromType = Context.getArrayDecayedType(FromType);
175 if (Second == ICK_Pointer_Conversion)
176 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
177 return ToPtrType->getPointeeType()->isVoidType();
182 /// DebugPrint - Print this standard conversion sequence to standard
183 /// error. Useful for debugging overloading issues.
184 void StandardConversionSequence::DebugPrint() const {
185 bool PrintedSomething = false;
186 if (First != ICK_Identity) {
187 fprintf(stderr, "%s", GetImplicitConversionName(First));
188 PrintedSomething = true;
191 if (Second != ICK_Identity) {
192 if (PrintedSomething) {
193 fprintf(stderr, " -> ");
195 fprintf(stderr, "%s", GetImplicitConversionName(Second));
197 if (CopyConstructor) {
198 fprintf(stderr, " (by copy constructor)");
199 } else if (DirectBinding) {
200 fprintf(stderr, " (direct reference binding)");
201 } else if (ReferenceBinding) {
202 fprintf(stderr, " (reference binding)");
204 PrintedSomething = true;
207 if (Third != ICK_Identity) {
208 if (PrintedSomething) {
209 fprintf(stderr, " -> ");
211 fprintf(stderr, "%s", GetImplicitConversionName(Third));
212 PrintedSomething = true;
215 if (!PrintedSomething) {
216 fprintf(stderr, "No conversions required");
220 /// DebugPrint - Print this user-defined conversion sequence to standard
221 /// error. Useful for debugging overloading issues.
222 void UserDefinedConversionSequence::DebugPrint() const {
223 if (Before.First || Before.Second || Before.Third) {
225 fprintf(stderr, " -> ");
227 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
228 if (After.First || After.Second || After.Third) {
229 fprintf(stderr, " -> ");
234 /// DebugPrint - Print this implicit conversion sequence to standard
235 /// error. Useful for debugging overloading issues.
236 void ImplicitConversionSequence::DebugPrint() const {
237 switch (ConversionKind) {
238 case StandardConversion:
239 fprintf(stderr, "Standard conversion: ");
240 Standard.DebugPrint();
242 case UserDefinedConversion:
243 fprintf(stderr, "User-defined conversion: ");
244 UserDefined.DebugPrint();
246 case EllipsisConversion:
247 fprintf(stderr, "Ellipsis conversion");
250 fprintf(stderr, "Bad conversion");
254 fprintf(stderr, "\n");
257 // IsOverload - Determine whether the given New declaration is an
258 // overload of the Old declaration. This routine returns false if New
259 // and Old cannot be overloaded, e.g., if they are functions with the
260 // same signature (C++ 1.3.10) or if the Old declaration isn't a
261 // function (or overload set). When it does return false and Old is an
262 // OverloadedFunctionDecl, MatchedDecl will be set to point to the
263 // FunctionDecl that New cannot be overloaded with.
265 // Example: Given the following input:
267 // void f(int, float); // #1
268 // void f(int, int); // #2
269 // int f(int, int); // #3
271 // When we process #1, there is no previous declaration of "f",
272 // so IsOverload will not be used.
274 // When we process #2, Old is a FunctionDecl for #1. By comparing the
275 // parameter types, we see that #1 and #2 are overloaded (since they
276 // have different signatures), so this routine returns false;
277 // MatchedDecl is unchanged.
279 // When we process #3, Old is an OverloadedFunctionDecl containing #1
280 // and #2. We compare the signatures of #3 to #1 (they're overloaded,
281 // so we do nothing) and then #3 to #2. Since the signatures of #3 and
282 // #2 are identical (return types of functions are not part of the
283 // signature), IsOverload returns false and MatchedDecl will be set to
284 // point to the FunctionDecl for #2.
286 Sema::IsOverload(FunctionDecl *New, Decl* OldD,
287 OverloadedFunctionDecl::function_iterator& MatchedDecl) {
288 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
289 // Is this new function an overload of every function in the
291 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
292 FuncEnd = Ovl->function_end();
293 for (; Func != FuncEnd; ++Func) {
294 if (!IsOverload(New, *Func, MatchedDecl)) {
300 // This function overloads every function in the overload set.
302 } else if (FunctionTemplateDecl *Old = dyn_cast<FunctionTemplateDecl>(OldD))
303 return IsOverload(New, Old->getTemplatedDecl(), MatchedDecl);
304 else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
305 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
306 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
309 // A function template can be overloaded with other function templates
310 // and with normal (non-template) functions.
311 if ((OldTemplate == 0) != (NewTemplate == 0))
314 // Is the function New an overload of the function Old?
315 QualType OldQType = Context.getCanonicalType(Old->getType());
316 QualType NewQType = Context.getCanonicalType(New->getType());
318 // Compare the signatures (C++ 1.3.10) of the two functions to
319 // determine whether they are overloads. If we find any mismatch
320 // in the signature, they are overloads.
322 // If either of these functions is a K&R-style function (no
323 // prototype), then we consider them to have matching signatures.
324 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
325 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
328 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
329 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
331 // The signature of a function includes the types of its
332 // parameters (C++ 1.3.10), which includes the presence or absence
333 // of the ellipsis; see C++ DR 357).
334 if (OldQType != NewQType &&
335 (OldType->getNumArgs() != NewType->getNumArgs() ||
336 OldType->isVariadic() != NewType->isVariadic() ||
337 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
338 NewType->arg_type_begin())))
341 // C++ [temp.over.link]p4:
342 // The signature of a function template consists of its function
343 // signature, its return type and its template parameter list. The names
344 // of the template parameters are significant only for establishing the
345 // relationship between the template parameters and the rest of the
348 // We check the return type and template parameter lists for function
349 // templates first; the remaining checks follow.
351 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
352 OldTemplate->getTemplateParameters(),
353 false, false, SourceLocation()) ||
354 OldType->getResultType() != NewType->getResultType()))
357 // If the function is a class member, its signature includes the
358 // cv-qualifiers (if any) on the function itself.
360 // As part of this, also check whether one of the member functions
361 // is static, in which case they are not overloads (C++
362 // 13.1p2). While not part of the definition of the signature,
363 // this check is important to determine whether these functions
364 // can be overloaded.
365 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
366 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
367 if (OldMethod && NewMethod &&
368 !OldMethod->isStatic() && !NewMethod->isStatic() &&
369 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
372 // The signatures match; this is not an overload.
376 // Only function declarations can be overloaded; object and type
377 // declarations cannot be overloaded.
382 /// TryImplicitConversion - Attempt to perform an implicit conversion
383 /// from the given expression (Expr) to the given type (ToType). This
384 /// function returns an implicit conversion sequence that can be used
385 /// to perform the initialization. Given
388 /// void g(int i) { f(i); }
390 /// this routine would produce an implicit conversion sequence to
391 /// describe the initialization of f from i, which will be a standard
392 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
393 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
395 /// Note that this routine only determines how the conversion can be
396 /// performed; it does not actually perform the conversion. As such,
397 /// it will not produce any diagnostics if no conversion is available,
398 /// but will instead return an implicit conversion sequence of kind
401 /// If @p SuppressUserConversions, then user-defined conversions are
403 /// If @p AllowExplicit, then explicit user-defined conversions are
405 /// If @p ForceRValue, then overloading is performed as if From was an rvalue,
406 /// no matter its actual lvalueness.
407 /// If @p UserCast, the implicit conversion is being done for a user-specified
409 ImplicitConversionSequence
410 Sema::TryImplicitConversion(Expr* From, QualType ToType,
411 bool SuppressUserConversions,
412 bool AllowExplicit, bool ForceRValue,
413 bool InOverloadResolution,
415 ImplicitConversionSequence ICS;
416 OverloadCandidateSet Conversions;
417 OverloadingResult UserDefResult = OR_Success;
418 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
419 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
420 else if (getLangOptions().CPlusPlus &&
421 (UserDefResult = IsUserDefinedConversion(From, ToType,
424 !SuppressUserConversions, AllowExplicit,
425 ForceRValue, UserCast)) == OR_Success) {
426 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
427 // C++ [over.ics.user]p4:
428 // A conversion of an expression of class type to the same class
429 // type is given Exact Match rank, and a conversion of an
430 // expression of class type to a base class of that type is
431 // given Conversion rank, in spite of the fact that a copy
432 // constructor (i.e., a user-defined conversion function) is
433 // called for those cases.
434 if (CXXConstructorDecl *Constructor
435 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
437 = Context.getCanonicalType(From->getType().getUnqualifiedType());
438 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
439 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
440 // Turn this into a "standard" conversion sequence, so that it
441 // gets ranked with standard conversion sequences.
442 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
443 ICS.Standard.setAsIdentityConversion();
444 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
445 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
446 ICS.Standard.CopyConstructor = Constructor;
447 if (ToCanon != FromCanon)
448 ICS.Standard.Second = ICK_Derived_To_Base;
452 // C++ [over.best.ics]p4:
453 // However, when considering the argument of a user-defined
454 // conversion function that is a candidate by 13.3.1.3 when
455 // invoked for the copying of the temporary in the second step
456 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
457 // 13.3.1.6 in all cases, only standard conversion sequences and
458 // ellipsis conversion sequences are allowed.
459 if (SuppressUserConversions &&
460 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
461 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
463 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
464 if (UserDefResult == OR_Ambiguous) {
465 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
466 Cand != Conversions.end(); ++Cand)
468 ICS.ConversionFunctionSet.push_back(Cand->Function);
475 /// IsStandardConversion - Determines whether there is a standard
476 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
477 /// expression From to the type ToType. Standard conversion sequences
478 /// only consider non-class types; for conversions that involve class
479 /// types, use TryImplicitConversion. If a conversion exists, SCS will
480 /// contain the standard conversion sequence required to perform this
481 /// conversion and this routine will return true. Otherwise, this
482 /// routine will return false and the value of SCS is unspecified.
484 Sema::IsStandardConversion(Expr* From, QualType ToType,
485 bool InOverloadResolution,
486 StandardConversionSequence &SCS) {
487 QualType FromType = From->getType();
489 // Standard conversions (C++ [conv])
490 SCS.setAsIdentityConversion();
491 SCS.Deprecated = false;
492 SCS.IncompatibleObjC = false;
493 SCS.FromTypePtr = FromType.getAsOpaquePtr();
494 SCS.CopyConstructor = 0;
496 // There are no standard conversions for class types in C++, so
497 // abort early. When overloading in C, however, we do permit
498 if (FromType->isRecordType() || ToType->isRecordType()) {
499 if (getLangOptions().CPlusPlus)
502 // When we're overloading in C, we allow, as standard conversions,
505 // The first conversion can be an lvalue-to-rvalue conversion,
506 // array-to-pointer conversion, or function-to-pointer conversion
509 // Lvalue-to-rvalue conversion (C++ 4.1):
510 // An lvalue (3.10) of a non-function, non-array type T can be
511 // converted to an rvalue.
512 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
513 if (argIsLvalue == Expr::LV_Valid &&
514 !FromType->isFunctionType() && !FromType->isArrayType() &&
515 Context.getCanonicalType(FromType) != Context.OverloadTy) {
516 SCS.First = ICK_Lvalue_To_Rvalue;
518 // If T is a non-class type, the type of the rvalue is the
519 // cv-unqualified version of T. Otherwise, the type of the rvalue
520 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
521 // just strip the qualifiers because they don't matter.
523 // FIXME: Doesn't see through to qualifiers behind a typedef!
524 FromType = FromType.getUnqualifiedType();
525 } else if (FromType->isArrayType()) {
526 // Array-to-pointer conversion (C++ 4.2)
527 SCS.First = ICK_Array_To_Pointer;
529 // An lvalue or rvalue of type "array of N T" or "array of unknown
530 // bound of T" can be converted to an rvalue of type "pointer to
532 FromType = Context.getArrayDecayedType(FromType);
534 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
535 // This conversion is deprecated. (C++ D.4).
536 SCS.Deprecated = true;
538 // For the purpose of ranking in overload resolution
539 // (13.3.3.1.1), this conversion is considered an
540 // array-to-pointer conversion followed by a qualification
541 // conversion (4.4). (C++ 4.2p2)
542 SCS.Second = ICK_Identity;
543 SCS.Third = ICK_Qualification;
544 SCS.ToTypePtr = ToType.getAsOpaquePtr();
547 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
548 // Function-to-pointer conversion (C++ 4.3).
549 SCS.First = ICK_Function_To_Pointer;
551 // An lvalue of function type T can be converted to an rvalue of
552 // type "pointer to T." The result is a pointer to the
553 // function. (C++ 4.3p1).
554 FromType = Context.getPointerType(FromType);
555 } else if (FunctionDecl *Fn
556 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
557 // Address of overloaded function (C++ [over.over]).
558 SCS.First = ICK_Function_To_Pointer;
560 // We were able to resolve the address of the overloaded function,
561 // so we can convert to the type of that function.
562 FromType = Fn->getType();
563 if (ToType->isLValueReferenceType())
564 FromType = Context.getLValueReferenceType(FromType);
565 else if (ToType->isRValueReferenceType())
566 FromType = Context.getRValueReferenceType(FromType);
567 else if (ToType->isMemberPointerType()) {
568 // Resolve address only succeeds if both sides are member pointers,
569 // but it doesn't have to be the same class. See DR 247.
570 // Note that this means that the type of &Derived::fn can be
571 // Ret (Base::*)(Args) if the fn overload actually found is from the
572 // base class, even if it was brought into the derived class via a
573 // using declaration. The standard isn't clear on this issue at all.
574 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
575 FromType = Context.getMemberPointerType(FromType,
576 Context.getTypeDeclType(M->getParent()).getTypePtr());
578 FromType = Context.getPointerType(FromType);
580 // We don't require any conversions for the first step.
581 SCS.First = ICK_Identity;
584 // The second conversion can be an integral promotion, floating
585 // point promotion, integral conversion, floating point conversion,
586 // floating-integral conversion, pointer conversion,
587 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
588 // For overloading in C, this can also be a "compatible-type"
590 bool IncompatibleObjC = false;
591 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
592 // The unqualified versions of the types are the same: there's no
594 SCS.Second = ICK_Identity;
595 } else if (IsIntegralPromotion(From, FromType, ToType)) {
596 // Integral promotion (C++ 4.5).
597 SCS.Second = ICK_Integral_Promotion;
598 FromType = ToType.getUnqualifiedType();
599 } else if (IsFloatingPointPromotion(FromType, ToType)) {
600 // Floating point promotion (C++ 4.6).
601 SCS.Second = ICK_Floating_Promotion;
602 FromType = ToType.getUnqualifiedType();
603 } else if (IsComplexPromotion(FromType, ToType)) {
604 // Complex promotion (Clang extension)
605 SCS.Second = ICK_Complex_Promotion;
606 FromType = ToType.getUnqualifiedType();
607 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
608 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
609 // Integral conversions (C++ 4.7).
610 // FIXME: isIntegralType shouldn't be true for enums in C++.
611 SCS.Second = ICK_Integral_Conversion;
612 FromType = ToType.getUnqualifiedType();
613 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
614 // Floating point conversions (C++ 4.8).
615 SCS.Second = ICK_Floating_Conversion;
616 FromType = ToType.getUnqualifiedType();
617 } else if (FromType->isComplexType() && ToType->isComplexType()) {
618 // Complex conversions (C99 6.3.1.6)
619 SCS.Second = ICK_Complex_Conversion;
620 FromType = ToType.getUnqualifiedType();
621 } else if ((FromType->isFloatingType() &&
622 ToType->isIntegralType() && (!ToType->isBooleanType() &&
623 !ToType->isEnumeralType())) ||
624 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
625 ToType->isFloatingType())) {
626 // Floating-integral conversions (C++ 4.9).
627 // FIXME: isIntegralType shouldn't be true for enums in C++.
628 SCS.Second = ICK_Floating_Integral;
629 FromType = ToType.getUnqualifiedType();
630 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
631 (ToType->isComplexType() && FromType->isArithmeticType())) {
632 // Complex-real conversions (C99 6.3.1.7)
633 SCS.Second = ICK_Complex_Real;
634 FromType = ToType.getUnqualifiedType();
635 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
636 FromType, IncompatibleObjC)) {
637 // Pointer conversions (C++ 4.10).
638 SCS.Second = ICK_Pointer_Conversion;
639 SCS.IncompatibleObjC = IncompatibleObjC;
640 } else if (IsMemberPointerConversion(From, FromType, ToType,
641 InOverloadResolution, FromType)) {
642 // Pointer to member conversions (4.11).
643 SCS.Second = ICK_Pointer_Member;
644 } else if (ToType->isBooleanType() &&
645 (FromType->isArithmeticType() ||
646 FromType->isEnumeralType() ||
647 FromType->isPointerType() ||
648 FromType->isBlockPointerType() ||
649 FromType->isMemberPointerType() ||
650 FromType->isNullPtrType())) {
651 // Boolean conversions (C++ 4.12).
652 SCS.Second = ICK_Boolean_Conversion;
653 FromType = Context.BoolTy;
654 } else if (!getLangOptions().CPlusPlus &&
655 Context.typesAreCompatible(ToType, FromType)) {
656 // Compatible conversions (Clang extension for C function overloading)
657 SCS.Second = ICK_Compatible_Conversion;
659 // No second conversion required.
660 SCS.Second = ICK_Identity;
665 // The third conversion can be a qualification conversion (C++ 4p1).
666 if (IsQualificationConversion(FromType, ToType)) {
667 SCS.Third = ICK_Qualification;
669 CanonFrom = Context.getCanonicalType(FromType);
670 CanonTo = Context.getCanonicalType(ToType);
672 // No conversion required
673 SCS.Third = ICK_Identity;
675 // C++ [over.best.ics]p6:
676 // [...] Any difference in top-level cv-qualification is
677 // subsumed by the initialization itself and does not constitute
678 // a conversion. [...]
679 CanonFrom = Context.getCanonicalType(FromType);
680 CanonTo = Context.getCanonicalType(ToType);
681 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
682 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
688 // If we have not converted the argument type to the parameter type,
689 // this is a bad conversion sequence.
690 if (CanonFrom != CanonTo)
693 SCS.ToTypePtr = FromType.getAsOpaquePtr();
697 /// IsIntegralPromotion - Determines whether the conversion from the
698 /// expression From (whose potentially-adjusted type is FromType) to
699 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
700 /// sets PromotedType to the promoted type.
701 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
702 const BuiltinType *To = ToType->getAs<BuiltinType>();
703 // All integers are built-in.
708 // An rvalue of type char, signed char, unsigned char, short int, or
709 // unsigned short int can be converted to an rvalue of type int if
710 // int can represent all the values of the source type; otherwise,
711 // the source rvalue can be converted to an rvalue of type unsigned
713 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
714 if (// We can promote any signed, promotable integer type to an int
715 (FromType->isSignedIntegerType() ||
716 // We can promote any unsigned integer type whose size is
717 // less than int to an int.
718 (!FromType->isSignedIntegerType() &&
719 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
720 return To->getKind() == BuiltinType::Int;
723 return To->getKind() == BuiltinType::UInt;
726 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
727 // can be converted to an rvalue of the first of the following types
728 // that can represent all the values of its underlying type: int,
729 // unsigned int, long, or unsigned long (C++ 4.5p2).
730 if ((FromType->isEnumeralType() || FromType->isWideCharType())
731 && ToType->isIntegerType()) {
732 // Determine whether the type we're converting from is signed or
735 uint64_t FromSize = Context.getTypeSize(FromType);
736 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
737 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
738 FromIsSigned = UnderlyingType->isSignedIntegerType();
740 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
744 // The types we'll try to promote to, in the appropriate
745 // order. Try each of these types.
746 QualType PromoteTypes[6] = {
747 Context.IntTy, Context.UnsignedIntTy,
748 Context.LongTy, Context.UnsignedLongTy ,
749 Context.LongLongTy, Context.UnsignedLongLongTy
751 for (int Idx = 0; Idx < 6; ++Idx) {
752 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
753 if (FromSize < ToSize ||
754 (FromSize == ToSize &&
755 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
756 // We found the type that we can promote to. If this is the
757 // type we wanted, we have a promotion. Otherwise, no
759 return Context.getCanonicalType(ToType).getUnqualifiedType()
760 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
765 // An rvalue for an integral bit-field (9.6) can be converted to an
766 // rvalue of type int if int can represent all the values of the
767 // bit-field; otherwise, it can be converted to unsigned int if
768 // unsigned int can represent all the values of the bit-field. If
769 // the bit-field is larger yet, no integral promotion applies to
770 // it. If the bit-field has an enumerated type, it is treated as any
771 // other value of that type for promotion purposes (C++ 4.5p3).
772 // FIXME: We should delay checking of bit-fields until we actually perform the
776 if (FieldDecl *MemberDecl = From->getBitField()) {
778 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
779 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
780 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
781 ToSize = Context.getTypeSize(ToType);
783 // Are we promoting to an int from a bitfield that fits in an int?
784 if (BitWidth < ToSize ||
785 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
786 return To->getKind() == BuiltinType::Int;
789 // Are we promoting to an unsigned int from an unsigned bitfield
790 // that fits into an unsigned int?
791 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
792 return To->getKind() == BuiltinType::UInt;
799 // An rvalue of type bool can be converted to an rvalue of type int,
800 // with false becoming zero and true becoming one (C++ 4.5p4).
801 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
808 /// IsFloatingPointPromotion - Determines whether the conversion from
809 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
810 /// returns true and sets PromotedType to the promoted type.
811 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
812 /// An rvalue of type float can be converted to an rvalue of type
813 /// double. (C++ 4.6p1).
814 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
815 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
816 if (FromBuiltin->getKind() == BuiltinType::Float &&
817 ToBuiltin->getKind() == BuiltinType::Double)
821 // When a float is promoted to double or long double, or a
822 // double is promoted to long double [...].
823 if (!getLangOptions().CPlusPlus &&
824 (FromBuiltin->getKind() == BuiltinType::Float ||
825 FromBuiltin->getKind() == BuiltinType::Double) &&
826 (ToBuiltin->getKind() == BuiltinType::LongDouble))
833 /// \brief Determine if a conversion is a complex promotion.
835 /// A complex promotion is defined as a complex -> complex conversion
836 /// where the conversion between the underlying real types is a
837 /// floating-point or integral promotion.
838 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
839 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
843 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
847 return IsFloatingPointPromotion(FromComplex->getElementType(),
848 ToComplex->getElementType()) ||
849 IsIntegralPromotion(0, FromComplex->getElementType(),
850 ToComplex->getElementType());
853 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
854 /// the pointer type FromPtr to a pointer to type ToPointee, with the
855 /// same type qualifiers as FromPtr has on its pointee type. ToType,
856 /// if non-empty, will be a pointer to ToType that may or may not have
857 /// the right set of qualifiers on its pointee.
859 BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
860 QualType ToPointee, QualType ToType,
861 ASTContext &Context) {
862 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
863 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
864 Qualifiers Quals = CanonFromPointee.getQualifiers();
866 // Exact qualifier match -> return the pointer type we're converting to.
867 if (CanonToPointee.getQualifiers() == Quals) {
868 // ToType is exactly what we need. Return it.
869 if (!ToType.isNull())
872 // Build a pointer to ToPointee. It has the right qualifiers
874 return Context.getPointerType(ToPointee);
877 // Just build a canonical type that has the right qualifiers.
878 return Context.getPointerType(
879 Context.getQualifiedType(CanonToPointee.getUnqualifiedType(), Quals));
882 static bool isNullPointerConstantForConversion(Expr *Expr,
883 bool InOverloadResolution,
884 ASTContext &Context) {
885 // Handle value-dependent integral null pointer constants correctly.
886 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
887 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
888 Expr->getType()->isIntegralType())
889 return !InOverloadResolution;
891 return Expr->isNullPointerConstant(Context,
892 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
893 : Expr::NPC_ValueDependentIsNull);
896 /// IsPointerConversion - Determines whether the conversion of the
897 /// expression From, which has the (possibly adjusted) type FromType,
898 /// can be converted to the type ToType via a pointer conversion (C++
899 /// 4.10). If so, returns true and places the converted type (that
900 /// might differ from ToType in its cv-qualifiers at some level) into
903 /// This routine also supports conversions to and from block pointers
904 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
905 /// pointers to interfaces. FIXME: Once we've determined the
906 /// appropriate overloading rules for Objective-C, we may want to
907 /// split the Objective-C checks into a different routine; however,
908 /// GCC seems to consider all of these conversions to be pointer
909 /// conversions, so for now they live here. IncompatibleObjC will be
910 /// set if the conversion is an allowed Objective-C conversion that
911 /// should result in a warning.
912 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
913 bool InOverloadResolution,
914 QualType& ConvertedType,
915 bool &IncompatibleObjC) {
916 IncompatibleObjC = false;
917 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
920 // Conversion from a null pointer constant to any Objective-C pointer type.
921 if (ToType->isObjCObjectPointerType() &&
922 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
923 ConvertedType = ToType;
927 // Blocks: Block pointers can be converted to void*.
928 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
929 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
930 ConvertedType = ToType;
933 // Blocks: A null pointer constant can be converted to a block
935 if (ToType->isBlockPointerType() &&
936 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
937 ConvertedType = ToType;
941 // If the left-hand-side is nullptr_t, the right side can be a null
943 if (ToType->isNullPtrType() &&
944 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
945 ConvertedType = ToType;
949 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
953 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
954 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
955 ConvertedType = ToType;
959 // Beyond this point, both types need to be pointers.
960 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
964 QualType FromPointeeType = FromTypePtr->getPointeeType();
965 QualType ToPointeeType = ToTypePtr->getPointeeType();
967 // An rvalue of type "pointer to cv T," where T is an object type,
968 // can be converted to an rvalue of type "pointer to cv void" (C++
970 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
971 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
977 // When we're overloading in C, we allow a special kind of pointer
978 // conversion for compatible-but-not-identical pointee types.
979 if (!getLangOptions().CPlusPlus &&
980 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
981 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
989 // An rvalue of type "pointer to cv D," where D is a class type,
990 // can be converted to an rvalue of type "pointer to cv B," where
991 // B is a base class (clause 10) of D. If B is an inaccessible
992 // (clause 11) or ambiguous (10.2) base class of D, a program that
993 // necessitates this conversion is ill-formed. The result of the
994 // conversion is a pointer to the base class sub-object of the
995 // derived class object. The null pointer value is converted to
996 // the null pointer value of the destination type.
998 // Note that we do not check for ambiguity or inaccessibility
999 // here. That is handled by CheckPointerConversion.
1000 if (getLangOptions().CPlusPlus &&
1001 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1002 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
1003 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
1004 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1013 /// isObjCPointerConversion - Determines whether this is an
1014 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1015 /// with the same arguments and return values.
1016 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
1017 QualType& ConvertedType,
1018 bool &IncompatibleObjC) {
1019 if (!getLangOptions().ObjC1)
1022 // First, we handle all conversions on ObjC object pointer types.
1023 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
1024 const ObjCObjectPointerType *FromObjCPtr =
1025 FromType->getAs<ObjCObjectPointerType>();
1027 if (ToObjCPtr && FromObjCPtr) {
1028 // Objective C++: We're able to convert between "id" or "Class" and a
1029 // pointer to any interface (in both directions).
1030 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
1031 ConvertedType = ToType;
1034 // Conversions with Objective-C's id<...>.
1035 if ((FromObjCPtr->isObjCQualifiedIdType() ||
1036 ToObjCPtr->isObjCQualifiedIdType()) &&
1037 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
1038 /*compare=*/false)) {
1039 ConvertedType = ToType;
1042 // Objective C++: We're able to convert from a pointer to an
1043 // interface to a pointer to a different interface.
1044 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1045 ConvertedType = ToType;
1049 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1050 // Okay: this is some kind of implicit downcast of Objective-C
1051 // interfaces, which is permitted. However, we're going to
1052 // complain about it.
1053 IncompatibleObjC = true;
1054 ConvertedType = FromType;
1058 // Beyond this point, both types need to be C pointers or block pointers.
1059 QualType ToPointeeType;
1060 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
1061 ToPointeeType = ToCPtr->getPointeeType();
1062 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
1063 ToPointeeType = ToBlockPtr->getPointeeType();
1067 QualType FromPointeeType;
1068 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
1069 FromPointeeType = FromCPtr->getPointeeType();
1070 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
1071 FromPointeeType = FromBlockPtr->getPointeeType();
1075 // If we have pointers to pointers, recursively check whether this
1076 // is an Objective-C conversion.
1077 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1078 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1079 IncompatibleObjC)) {
1080 // We always complain about this conversion.
1081 IncompatibleObjC = true;
1082 ConvertedType = ToType;
1085 // If we have pointers to functions or blocks, check whether the only
1086 // differences in the argument and result types are in Objective-C
1087 // pointer conversions. If so, we permit the conversion (but
1088 // complain about it).
1089 const FunctionProtoType *FromFunctionType
1090 = FromPointeeType->getAs<FunctionProtoType>();
1091 const FunctionProtoType *ToFunctionType
1092 = ToPointeeType->getAs<FunctionProtoType>();
1093 if (FromFunctionType && ToFunctionType) {
1094 // If the function types are exactly the same, this isn't an
1095 // Objective-C pointer conversion.
1096 if (Context.getCanonicalType(FromPointeeType)
1097 == Context.getCanonicalType(ToPointeeType))
1100 // Perform the quick checks that will tell us whether these
1101 // function types are obviously different.
1102 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1103 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1104 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1107 bool HasObjCConversion = false;
1108 if (Context.getCanonicalType(FromFunctionType->getResultType())
1109 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1110 // Okay, the types match exactly. Nothing to do.
1111 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1112 ToFunctionType->getResultType(),
1113 ConvertedType, IncompatibleObjC)) {
1114 // Okay, we have an Objective-C pointer conversion.
1115 HasObjCConversion = true;
1117 // Function types are too different. Abort.
1121 // Check argument types.
1122 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1123 ArgIdx != NumArgs; ++ArgIdx) {
1124 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1125 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1126 if (Context.getCanonicalType(FromArgType)
1127 == Context.getCanonicalType(ToArgType)) {
1128 // Okay, the types match exactly. Nothing to do.
1129 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1130 ConvertedType, IncompatibleObjC)) {
1131 // Okay, we have an Objective-C pointer conversion.
1132 HasObjCConversion = true;
1134 // Argument types are too different. Abort.
1139 if (HasObjCConversion) {
1140 // We had an Objective-C conversion. Allow this pointer
1141 // conversion, but complain about it.
1142 ConvertedType = ToType;
1143 IncompatibleObjC = true;
1151 /// CheckPointerConversion - Check the pointer conversion from the
1152 /// expression From to the type ToType. This routine checks for
1153 /// ambiguous or inaccessible derived-to-base pointer
1154 /// conversions for which IsPointerConversion has already returned
1155 /// true. It returns true and produces a diagnostic if there was an
1156 /// error, or returns false otherwise.
1157 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
1158 CastExpr::CastKind &Kind) {
1159 QualType FromType = From->getType();
1161 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1162 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
1163 QualType FromPointeeType = FromPtrType->getPointeeType(),
1164 ToPointeeType = ToPtrType->getPointeeType();
1166 if (FromPointeeType->isRecordType() &&
1167 ToPointeeType->isRecordType()) {
1168 // We must have a derived-to-base conversion. Check an
1169 // ambiguous or inaccessible conversion.
1170 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1172 From->getSourceRange()))
1175 // The conversion was successful.
1176 Kind = CastExpr::CK_DerivedToBase;
1179 if (const ObjCObjectPointerType *FromPtrType =
1180 FromType->getAs<ObjCObjectPointerType>())
1181 if (const ObjCObjectPointerType *ToPtrType =
1182 ToType->getAs<ObjCObjectPointerType>()) {
1183 // Objective-C++ conversions are always okay.
1184 // FIXME: We should have a different class of conversions for the
1185 // Objective-C++ implicit conversions.
1186 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
1193 /// IsMemberPointerConversion - Determines whether the conversion of the
1194 /// expression From, which has the (possibly adjusted) type FromType, can be
1195 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
1196 /// If so, returns true and places the converted type (that might differ from
1197 /// ToType in its cv-qualifiers at some level) into ConvertedType.
1198 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1200 bool InOverloadResolution,
1201 QualType &ConvertedType) {
1202 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
1206 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1207 if (From->isNullPointerConstant(Context,
1208 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1209 : Expr::NPC_ValueDependentIsNull)) {
1210 ConvertedType = ToType;
1214 // Otherwise, both types have to be member pointers.
1215 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
1219 // A pointer to member of B can be converted to a pointer to member of D,
1220 // where D is derived from B (C++ 4.11p2).
1221 QualType FromClass(FromTypePtr->getClass(), 0);
1222 QualType ToClass(ToTypePtr->getClass(), 0);
1223 // FIXME: What happens when these are dependent? Is this function even called?
1225 if (IsDerivedFrom(ToClass, FromClass)) {
1226 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1227 ToClass.getTypePtr());
1234 /// CheckMemberPointerConversion - Check the member pointer conversion from the
1235 /// expression From to the type ToType. This routine checks for ambiguous or
1236 /// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1237 /// for which IsMemberPointerConversion has already returned true. It returns
1238 /// true and produces a diagnostic if there was an error, or returns false
1240 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
1241 CastExpr::CastKind &Kind) {
1242 QualType FromType = From->getType();
1243 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
1245 // This must be a null pointer to member pointer conversion
1246 assert(From->isNullPointerConstant(Context,
1247 Expr::NPC_ValueDependentIsNull) &&
1248 "Expr must be null pointer constant!");
1249 Kind = CastExpr::CK_NullToMemberPointer;
1253 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
1254 assert(ToPtrType && "No member pointer cast has a target type "
1255 "that is not a member pointer.");
1257 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1258 QualType ToClass = QualType(ToPtrType->getClass(), 0);
1260 // FIXME: What about dependent types?
1261 assert(FromClass->isRecordType() && "Pointer into non-class.");
1262 assert(ToClass->isRecordType() && "Pointer into non-class.");
1264 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1265 /*DetectVirtual=*/true);
1266 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1267 assert(DerivationOkay &&
1268 "Should not have been called if derivation isn't OK.");
1269 (void)DerivationOkay;
1271 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1272 getUnqualifiedType())) {
1273 // Derivation is ambiguous. Redo the check to find the exact paths.
1275 Paths.setRecordingPaths(true);
1276 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1277 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1280 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1281 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1282 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1286 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1287 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1288 << FromClass << ToClass << QualType(VBase, 0)
1289 << From->getSourceRange();
1293 // Must be a base to derived member conversion.
1294 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
1298 /// IsQualificationConversion - Determines whether the conversion from
1299 /// an rvalue of type FromType to ToType is a qualification conversion
1302 Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
1303 FromType = Context.getCanonicalType(FromType);
1304 ToType = Context.getCanonicalType(ToType);
1306 // If FromType and ToType are the same type, this is not a
1307 // qualification conversion.
1308 if (FromType == ToType)
1312 // A conversion can add cv-qualifiers at levels other than the first
1313 // in multi-level pointers, subject to the following rules: [...]
1314 bool PreviousToQualsIncludeConst = true;
1315 bool UnwrappedAnyPointer = false;
1316 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
1317 // Within each iteration of the loop, we check the qualifiers to
1318 // determine if this still looks like a qualification
1319 // conversion. Then, if all is well, we unwrap one more level of
1320 // pointers or pointers-to-members and do it all again
1321 // until there are no more pointers or pointers-to-members left to
1323 UnwrappedAnyPointer = true;
1325 // -- for every j > 0, if const is in cv 1,j then const is in cv
1326 // 2,j, and similarly for volatile.
1327 if (!ToType.isAtLeastAsQualifiedAs(FromType))
1330 // -- if the cv 1,j and cv 2,j are different, then const is in
1331 // every cv for 0 < k < j.
1332 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
1333 && !PreviousToQualsIncludeConst)
1336 // Keep track of whether all prior cv-qualifiers in the "to" type
1338 PreviousToQualsIncludeConst
1339 = PreviousToQualsIncludeConst && ToType.isConstQualified();
1342 // We are left with FromType and ToType being the pointee types
1343 // after unwrapping the original FromType and ToType the same number
1344 // of types. If we unwrapped any pointers, and if FromType and
1345 // ToType have the same unqualified type (since we checked
1346 // qualifiers above), then this is a qualification conversion.
1347 return UnwrappedAnyPointer &&
1348 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1351 /// \brief Given a function template or function, extract the function template
1352 /// declaration (if any) and the underlying function declaration.
1353 template<typename T>
1354 static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1355 FunctionTemplateDecl *&FunctionTemplate) {
1356 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1357 if (FunctionTemplate)
1358 Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1360 Function = cast<T>(Orig);
1363 /// Determines whether there is a user-defined conversion sequence
1364 /// (C++ [over.ics.user]) that converts expression From to the type
1365 /// ToType. If such a conversion exists, User will contain the
1366 /// user-defined conversion sequence that performs such a conversion
1367 /// and this routine will return true. Otherwise, this routine returns
1368 /// false and User is unspecified.
1370 /// \param AllowConversionFunctions true if the conversion should
1371 /// consider conversion functions at all. If false, only constructors
1372 /// will be considered.
1374 /// \param AllowExplicit true if the conversion should consider C++0x
1375 /// "explicit" conversion functions as well as non-explicit conversion
1376 /// functions (C++0x [class.conv.fct]p2).
1378 /// \param ForceRValue true if the expression should be treated as an rvalue
1379 /// for overload resolution.
1380 /// \param UserCast true if looking for user defined conversion for a static
1382 Sema::OverloadingResult Sema::IsUserDefinedConversion(
1383 Expr *From, QualType ToType,
1384 UserDefinedConversionSequence& User,
1385 OverloadCandidateSet& CandidateSet,
1386 bool AllowConversionFunctions,
1387 bool AllowExplicit, bool ForceRValue,
1389 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
1390 if (CXXRecordDecl *ToRecordDecl
1391 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1392 // C++ [over.match.ctor]p1:
1393 // When objects of class type are direct-initialized (8.5), or
1394 // copy-initialized from an expression of the same or a
1395 // derived class type (8.5), overload resolution selects the
1396 // constructor. [...] For copy-initialization, the candidate
1397 // functions are all the converting constructors (12.3.1) of
1398 // that class. The argument list is the expression-list within
1399 // the parentheses of the initializer.
1400 DeclarationName ConstructorName
1401 = Context.DeclarationNames.getCXXConstructorName(
1402 Context.getCanonicalType(ToType).getUnqualifiedType());
1403 DeclContext::lookup_iterator Con, ConEnd;
1404 for (llvm::tie(Con, ConEnd)
1405 = ToRecordDecl->lookup(ConstructorName);
1406 Con != ConEnd; ++Con) {
1407 // Find the constructor (which may be a template).
1408 CXXConstructorDecl *Constructor = 0;
1409 FunctionTemplateDecl *ConstructorTmpl
1410 = dyn_cast<FunctionTemplateDecl>(*Con);
1411 if (ConstructorTmpl)
1413 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1415 Constructor = cast<CXXConstructorDecl>(*Con);
1417 if (!Constructor->isInvalidDecl() &&
1418 Constructor->isConvertingConstructor(AllowExplicit)) {
1419 if (ConstructorTmpl)
1420 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
1422 /*SuppressUserConversions=*/!UserCast,
1425 // Allow one user-defined conversion when user specifies a
1426 // From->ToType conversion via an static cast (c-style, etc).
1427 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1428 /*SuppressUserConversions=*/!UserCast,
1435 if (!AllowConversionFunctions) {
1436 // Don't allow any conversion functions to enter the overload set.
1437 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1439 << From->getSourceRange())) {
1440 // No conversion functions from incomplete types.
1441 } else if (const RecordType *FromRecordType
1442 = From->getType()->getAs<RecordType>()) {
1443 if (CXXRecordDecl *FromRecordDecl
1444 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1445 // Add all of the conversion functions as candidates.
1446 OverloadedFunctionDecl *Conversions
1447 = FromRecordDecl->getVisibleConversionFunctions();
1448 for (OverloadedFunctionDecl::function_iterator Func
1449 = Conversions->function_begin();
1450 Func != Conversions->function_end(); ++Func) {
1451 CXXConversionDecl *Conv;
1452 FunctionTemplateDecl *ConvTemplate;
1453 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1455 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1457 Conv = dyn_cast<CXXConversionDecl>(*Func);
1459 if (AllowExplicit || !Conv->isExplicit()) {
1461 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1464 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1470 OverloadCandidateSet::iterator Best;
1471 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
1473 // Record the standard conversion we used and the conversion function.
1474 if (CXXConstructorDecl *Constructor
1475 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1476 // C++ [over.ics.user]p1:
1477 // If the user-defined conversion is specified by a
1478 // constructor (12.3.1), the initial standard conversion
1479 // sequence converts the source type to the type required by
1480 // the argument of the constructor.
1482 // FIXME: What about ellipsis conversions?
1483 QualType ThisType = Constructor->getThisType(Context);
1484 User.Before = Best->Conversions[0].Standard;
1485 User.ConversionFunction = Constructor;
1486 User.After.setAsIdentityConversion();
1487 User.After.FromTypePtr
1488 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
1489 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1491 } else if (CXXConversionDecl *Conversion
1492 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1493 // C++ [over.ics.user]p1:
1495 // [...] If the user-defined conversion is specified by a
1496 // conversion function (12.3.2), the initial standard
1497 // conversion sequence converts the source type to the
1498 // implicit object parameter of the conversion function.
1499 User.Before = Best->Conversions[0].Standard;
1500 User.ConversionFunction = Conversion;
1502 // C++ [over.ics.user]p2:
1503 // The second standard conversion sequence converts the
1504 // result of the user-defined conversion to the target type
1505 // for the sequence. Since an implicit conversion sequence
1506 // is an initialization, the special rules for
1507 // initialization by user-defined conversion apply when
1508 // selecting the best user-defined conversion for a
1509 // user-defined conversion sequence (see 13.3.3 and
1511 User.After = Best->FinalConversion;
1514 assert(false && "Not a constructor or conversion function?");
1515 return OR_No_Viable_Function;
1518 case OR_No_Viable_Function:
1519 return OR_No_Viable_Function;
1521 // No conversion here! We're done.
1525 return OR_Ambiguous;
1528 return OR_No_Viable_Function;
1532 Sema::DiagnoseAmbiguousUserDefinedConversion(Expr *From, QualType ToType) {
1533 ImplicitConversionSequence ICS;
1534 OverloadCandidateSet CandidateSet;
1535 OverloadingResult OvResult =
1536 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1537 CandidateSet, true, false, false);
1538 if (OvResult != OR_Ambiguous)
1540 Diag(From->getSourceRange().getBegin(),
1541 diag::err_typecheck_ambiguous_condition)
1542 << From->getType() << ToType << From->getSourceRange();
1543 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1547 /// CompareImplicitConversionSequences - Compare two implicit
1548 /// conversion sequences to determine whether one is better than the
1549 /// other or if they are indistinguishable (C++ 13.3.3.2).
1550 ImplicitConversionSequence::CompareKind
1551 Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1552 const ImplicitConversionSequence& ICS2)
1554 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1555 // conversion sequences (as defined in 13.3.3.1)
1556 // -- a standard conversion sequence (13.3.3.1.1) is a better
1557 // conversion sequence than a user-defined conversion sequence or
1558 // an ellipsis conversion sequence, and
1559 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1560 // conversion sequence than an ellipsis conversion sequence
1563 if (ICS1.ConversionKind < ICS2.ConversionKind)
1564 return ImplicitConversionSequence::Better;
1565 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1566 return ImplicitConversionSequence::Worse;
1568 // Two implicit conversion sequences of the same form are
1569 // indistinguishable conversion sequences unless one of the
1570 // following rules apply: (C++ 13.3.3.2p3):
1571 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1572 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1573 else if (ICS1.ConversionKind ==
1574 ImplicitConversionSequence::UserDefinedConversion) {
1575 // User-defined conversion sequence U1 is a better conversion
1576 // sequence than another user-defined conversion sequence U2 if
1577 // they contain the same user-defined conversion function or
1578 // constructor and if the second standard conversion sequence of
1579 // U1 is better than the second standard conversion sequence of
1580 // U2 (C++ 13.3.3.2p3).
1581 if (ICS1.UserDefined.ConversionFunction ==
1582 ICS2.UserDefined.ConversionFunction)
1583 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1584 ICS2.UserDefined.After);
1587 return ImplicitConversionSequence::Indistinguishable;
1590 /// CompareStandardConversionSequences - Compare two standard
1591 /// conversion sequences to determine whether one is better than the
1592 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
1593 ImplicitConversionSequence::CompareKind
1594 Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1595 const StandardConversionSequence& SCS2)
1597 // Standard conversion sequence S1 is a better conversion sequence
1598 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1600 // -- S1 is a proper subsequence of S2 (comparing the conversion
1601 // sequences in the canonical form defined by 13.3.3.1.1,
1602 // excluding any Lvalue Transformation; the identity conversion
1603 // sequence is considered to be a subsequence of any
1604 // non-identity conversion sequence) or, if not that,
1605 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1606 // Neither is a proper subsequence of the other. Do nothing.
1608 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1609 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1610 (SCS1.Second == ICK_Identity &&
1611 SCS1.Third == ICK_Identity))
1612 // SCS1 is a proper subsequence of SCS2.
1613 return ImplicitConversionSequence::Better;
1614 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1615 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1616 (SCS2.Second == ICK_Identity &&
1617 SCS2.Third == ICK_Identity))
1618 // SCS2 is a proper subsequence of SCS1.
1619 return ImplicitConversionSequence::Worse;
1621 // -- the rank of S1 is better than the rank of S2 (by the rules
1622 // defined below), or, if not that,
1623 ImplicitConversionRank Rank1 = SCS1.getRank();
1624 ImplicitConversionRank Rank2 = SCS2.getRank();
1626 return ImplicitConversionSequence::Better;
1627 else if (Rank2 < Rank1)
1628 return ImplicitConversionSequence::Worse;
1630 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1631 // are indistinguishable unless one of the following rules
1634 // A conversion that is not a conversion of a pointer, or
1635 // pointer to member, to bool is better than another conversion
1636 // that is such a conversion.
1637 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1638 return SCS2.isPointerConversionToBool()
1639 ? ImplicitConversionSequence::Better
1640 : ImplicitConversionSequence::Worse;
1642 // C++ [over.ics.rank]p4b2:
1644 // If class B is derived directly or indirectly from class A,
1645 // conversion of B* to A* is better than conversion of B* to
1646 // void*, and conversion of A* to void* is better than conversion
1648 bool SCS1ConvertsToVoid
1649 = SCS1.isPointerConversionToVoidPointer(Context);
1650 bool SCS2ConvertsToVoid
1651 = SCS2.isPointerConversionToVoidPointer(Context);
1652 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1653 // Exactly one of the conversion sequences is a conversion to
1654 // a void pointer; it's the worse conversion.
1655 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1656 : ImplicitConversionSequence::Worse;
1657 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1658 // Neither conversion sequence converts to a void pointer; compare
1659 // their derived-to-base conversions.
1660 if (ImplicitConversionSequence::CompareKind DerivedCK
1661 = CompareDerivedToBaseConversions(SCS1, SCS2))
1663 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1664 // Both conversion sequences are conversions to void
1665 // pointers. Compare the source types to determine if there's an
1666 // inheritance relationship in their sources.
1667 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1668 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1670 // Adjust the types we're converting from via the array-to-pointer
1671 // conversion, if we need to.
1672 if (SCS1.First == ICK_Array_To_Pointer)
1673 FromType1 = Context.getArrayDecayedType(FromType1);
1674 if (SCS2.First == ICK_Array_To_Pointer)
1675 FromType2 = Context.getArrayDecayedType(FromType2);
1677 QualType FromPointee1
1678 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1679 QualType FromPointee2
1680 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1682 if (IsDerivedFrom(FromPointee2, FromPointee1))
1683 return ImplicitConversionSequence::Better;
1684 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1685 return ImplicitConversionSequence::Worse;
1687 // Objective-C++: If one interface is more specific than the
1688 // other, it is the better one.
1689 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1690 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1691 if (FromIface1 && FromIface1) {
1692 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1693 return ImplicitConversionSequence::Better;
1694 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1695 return ImplicitConversionSequence::Worse;
1699 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1701 if (ImplicitConversionSequence::CompareKind QualCK
1702 = CompareQualificationConversions(SCS1, SCS2))
1705 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1706 // C++0x [over.ics.rank]p3b4:
1707 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1708 // implicit object parameter of a non-static member function declared
1709 // without a ref-qualifier, and S1 binds an rvalue reference to an
1710 // rvalue and S2 binds an lvalue reference.
1711 // FIXME: We don't know if we're dealing with the implicit object parameter,
1712 // or if the member function in this case has a ref qualifier.
1713 // (Of course, we don't have ref qualifiers yet.)
1714 if (SCS1.RRefBinding != SCS2.RRefBinding)
1715 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1716 : ImplicitConversionSequence::Worse;
1718 // C++ [over.ics.rank]p3b4:
1719 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1720 // which the references refer are the same type except for
1721 // top-level cv-qualifiers, and the type to which the reference
1722 // initialized by S2 refers is more cv-qualified than the type
1723 // to which the reference initialized by S1 refers.
1724 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1725 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1726 T1 = Context.getCanonicalType(T1);
1727 T2 = Context.getCanonicalType(T2);
1728 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1729 if (T2.isMoreQualifiedThan(T1))
1730 return ImplicitConversionSequence::Better;
1731 else if (T1.isMoreQualifiedThan(T2))
1732 return ImplicitConversionSequence::Worse;
1736 return ImplicitConversionSequence::Indistinguishable;
1739 /// CompareQualificationConversions - Compares two standard conversion
1740 /// sequences to determine whether they can be ranked based on their
1741 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1742 ImplicitConversionSequence::CompareKind
1743 Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1744 const StandardConversionSequence& SCS2) {
1746 // -- S1 and S2 differ only in their qualification conversion and
1747 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1748 // cv-qualification signature of type T1 is a proper subset of
1749 // the cv-qualification signature of type T2, and S1 is not the
1750 // deprecated string literal array-to-pointer conversion (4.2).
1751 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1752 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1753 return ImplicitConversionSequence::Indistinguishable;
1755 // FIXME: the example in the standard doesn't use a qualification
1757 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1758 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1759 T1 = Context.getCanonicalType(T1);
1760 T2 = Context.getCanonicalType(T2);
1762 // If the types are the same, we won't learn anything by unwrapped
1764 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1765 return ImplicitConversionSequence::Indistinguishable;
1767 ImplicitConversionSequence::CompareKind Result
1768 = ImplicitConversionSequence::Indistinguishable;
1769 while (UnwrapSimilarPointerTypes(T1, T2)) {
1770 // Within each iteration of the loop, we check the qualifiers to
1771 // determine if this still looks like a qualification
1772 // conversion. Then, if all is well, we unwrap one more level of
1773 // pointers or pointers-to-members and do it all again
1774 // until there are no more pointers or pointers-to-members left
1775 // to unwrap. This essentially mimics what
1776 // IsQualificationConversion does, but here we're checking for a
1777 // strict subset of qualifiers.
1778 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1779 // The qualifiers are the same, so this doesn't tell us anything
1780 // about how the sequences rank.
1782 else if (T2.isMoreQualifiedThan(T1)) {
1783 // T1 has fewer qualifiers, so it could be the better sequence.
1784 if (Result == ImplicitConversionSequence::Worse)
1785 // Neither has qualifiers that are a subset of the other's
1787 return ImplicitConversionSequence::Indistinguishable;
1789 Result = ImplicitConversionSequence::Better;
1790 } else if (T1.isMoreQualifiedThan(T2)) {
1791 // T2 has fewer qualifiers, so it could be the better sequence.
1792 if (Result == ImplicitConversionSequence::Better)
1793 // Neither has qualifiers that are a subset of the other's
1795 return ImplicitConversionSequence::Indistinguishable;
1797 Result = ImplicitConversionSequence::Worse;
1799 // Qualifiers are disjoint.
1800 return ImplicitConversionSequence::Indistinguishable;
1803 // If the types after this point are equivalent, we're done.
1804 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1808 // Check that the winning standard conversion sequence isn't using
1809 // the deprecated string literal array to pointer conversion.
1811 case ImplicitConversionSequence::Better:
1812 if (SCS1.Deprecated)
1813 Result = ImplicitConversionSequence::Indistinguishable;
1816 case ImplicitConversionSequence::Indistinguishable:
1819 case ImplicitConversionSequence::Worse:
1820 if (SCS2.Deprecated)
1821 Result = ImplicitConversionSequence::Indistinguishable;
1828 /// CompareDerivedToBaseConversions - Compares two standard conversion
1829 /// sequences to determine whether they can be ranked based on their
1830 /// various kinds of derived-to-base conversions (C++
1831 /// [over.ics.rank]p4b3). As part of these checks, we also look at
1832 /// conversions between Objective-C interface types.
1833 ImplicitConversionSequence::CompareKind
1834 Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1835 const StandardConversionSequence& SCS2) {
1836 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1837 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1838 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1839 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1841 // Adjust the types we're converting from via the array-to-pointer
1842 // conversion, if we need to.
1843 if (SCS1.First == ICK_Array_To_Pointer)
1844 FromType1 = Context.getArrayDecayedType(FromType1);
1845 if (SCS2.First == ICK_Array_To_Pointer)
1846 FromType2 = Context.getArrayDecayedType(FromType2);
1848 // Canonicalize all of the types.
1849 FromType1 = Context.getCanonicalType(FromType1);
1850 ToType1 = Context.getCanonicalType(ToType1);
1851 FromType2 = Context.getCanonicalType(FromType2);
1852 ToType2 = Context.getCanonicalType(ToType2);
1854 // C++ [over.ics.rank]p4b3:
1856 // If class B is derived directly or indirectly from class A and
1857 // class C is derived directly or indirectly from B,
1859 // For Objective-C, we let A, B, and C also be Objective-C
1862 // Compare based on pointer conversions.
1863 if (SCS1.Second == ICK_Pointer_Conversion &&
1864 SCS2.Second == ICK_Pointer_Conversion &&
1865 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1866 FromType1->isPointerType() && FromType2->isPointerType() &&
1867 ToType1->isPointerType() && ToType2->isPointerType()) {
1868 QualType FromPointee1
1869 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1871 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1872 QualType FromPointee2
1873 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1875 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1877 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1878 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1879 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1880 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
1882 // -- conversion of C* to B* is better than conversion of C* to A*,
1883 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1884 if (IsDerivedFrom(ToPointee1, ToPointee2))
1885 return ImplicitConversionSequence::Better;
1886 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1887 return ImplicitConversionSequence::Worse;
1889 if (ToIface1 && ToIface2) {
1890 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1891 return ImplicitConversionSequence::Better;
1892 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1893 return ImplicitConversionSequence::Worse;
1897 // -- conversion of B* to A* is better than conversion of C* to A*,
1898 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1899 if (IsDerivedFrom(FromPointee2, FromPointee1))
1900 return ImplicitConversionSequence::Better;
1901 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1902 return ImplicitConversionSequence::Worse;
1904 if (FromIface1 && FromIface2) {
1905 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1906 return ImplicitConversionSequence::Better;
1907 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1908 return ImplicitConversionSequence::Worse;
1913 // Compare based on reference bindings.
1914 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1915 SCS1.Second == ICK_Derived_To_Base) {
1916 // -- binding of an expression of type C to a reference of type
1917 // B& is better than binding an expression of type C to a
1918 // reference of type A&,
1919 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1920 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1921 if (IsDerivedFrom(ToType1, ToType2))
1922 return ImplicitConversionSequence::Better;
1923 else if (IsDerivedFrom(ToType2, ToType1))
1924 return ImplicitConversionSequence::Worse;
1927 // -- binding of an expression of type B to a reference of type
1928 // A& is better than binding an expression of type C to a
1929 // reference of type A&,
1930 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1931 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1932 if (IsDerivedFrom(FromType2, FromType1))
1933 return ImplicitConversionSequence::Better;
1934 else if (IsDerivedFrom(FromType1, FromType2))
1935 return ImplicitConversionSequence::Worse;
1939 // Ranking of member-pointer types.
1940 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
1941 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
1942 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
1943 const MemberPointerType * FromMemPointer1 =
1944 FromType1->getAs<MemberPointerType>();
1945 const MemberPointerType * ToMemPointer1 =
1946 ToType1->getAs<MemberPointerType>();
1947 const MemberPointerType * FromMemPointer2 =
1948 FromType2->getAs<MemberPointerType>();
1949 const MemberPointerType * ToMemPointer2 =
1950 ToType2->getAs<MemberPointerType>();
1951 const Type *FromPointeeType1 = FromMemPointer1->getClass();
1952 const Type *ToPointeeType1 = ToMemPointer1->getClass();
1953 const Type *FromPointeeType2 = FromMemPointer2->getClass();
1954 const Type *ToPointeeType2 = ToMemPointer2->getClass();
1955 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
1956 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
1957 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
1958 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
1959 // conversion of A::* to B::* is better than conversion of A::* to C::*,
1960 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1961 if (IsDerivedFrom(ToPointee1, ToPointee2))
1962 return ImplicitConversionSequence::Worse;
1963 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1964 return ImplicitConversionSequence::Better;
1966 // conversion of B::* to C::* is better than conversion of A::* to C::*
1967 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
1968 if (IsDerivedFrom(FromPointee1, FromPointee2))
1969 return ImplicitConversionSequence::Better;
1970 else if (IsDerivedFrom(FromPointee2, FromPointee1))
1971 return ImplicitConversionSequence::Worse;
1975 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1976 SCS1.Second == ICK_Derived_To_Base) {
1977 // -- conversion of C to B is better than conversion of C to A,
1978 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1979 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1980 if (IsDerivedFrom(ToType1, ToType2))
1981 return ImplicitConversionSequence::Better;
1982 else if (IsDerivedFrom(ToType2, ToType1))
1983 return ImplicitConversionSequence::Worse;
1986 // -- conversion of B to A is better than conversion of C to A.
1987 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1988 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1989 if (IsDerivedFrom(FromType2, FromType1))
1990 return ImplicitConversionSequence::Better;
1991 else if (IsDerivedFrom(FromType1, FromType2))
1992 return ImplicitConversionSequence::Worse;
1996 return ImplicitConversionSequence::Indistinguishable;
1999 /// TryCopyInitialization - Try to copy-initialize a value of type
2000 /// ToType from the expression From. Return the implicit conversion
2001 /// sequence required to pass this argument, which may be a bad
2002 /// conversion sequence (meaning that the argument cannot be passed to
2003 /// a parameter of this type). If @p SuppressUserConversions, then we
2004 /// do not permit any user-defined conversion sequences. If @p ForceRValue,
2005 /// then we treat @p From as an rvalue, even if it is an lvalue.
2006 ImplicitConversionSequence
2007 Sema::TryCopyInitialization(Expr *From, QualType ToType,
2008 bool SuppressUserConversions, bool ForceRValue,
2009 bool InOverloadResolution) {
2010 if (ToType->isReferenceType()) {
2011 ImplicitConversionSequence ICS;
2012 CheckReferenceInit(From, ToType,
2013 /*FIXME:*/From->getLocStart(),
2014 SuppressUserConversions,
2015 /*AllowExplicit=*/false,
2020 return TryImplicitConversion(From, ToType,
2021 SuppressUserConversions,
2022 /*AllowExplicit=*/false,
2024 InOverloadResolution);
2028 /// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2029 /// the expression @p From. Returns true (and emits a diagnostic) if there was
2030 /// an error, returns false if the initialization succeeded. Elidable should
2031 /// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2032 /// differently in C++0x for this case.
2033 bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
2034 const char* Flavor, bool Elidable) {
2035 if (!getLangOptions().CPlusPlus) {
2036 // In C, argument passing is the same as performing an assignment.
2037 QualType FromType = From->getType();
2039 AssignConvertType ConvTy =
2040 CheckSingleAssignmentConstraints(ToType, From);
2041 if (ConvTy != Compatible &&
2042 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2043 ConvTy = Compatible;
2045 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
2046 FromType, From, Flavor);
2049 if (ToType->isReferenceType())
2050 return CheckReferenceInit(From, ToType,
2051 /*FIXME:*/From->getLocStart(),
2052 /*SuppressUserConversions=*/false,
2053 /*AllowExplicit=*/false,
2054 /*ForceRValue=*/false);
2056 if (!PerformImplicitConversion(From, ToType, Flavor,
2057 /*AllowExplicit=*/false, Elidable))
2059 if (!DiagnoseAmbiguousUserDefinedConversion(From, ToType))
2060 return Diag(From->getSourceRange().getBegin(),
2061 diag::err_typecheck_convert_incompatible)
2062 << ToType << From->getType() << Flavor << From->getSourceRange();
2066 /// TryObjectArgumentInitialization - Try to initialize the object
2067 /// parameter of the given member function (@c Method) from the
2068 /// expression @p From.
2069 ImplicitConversionSequence
2070 Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
2071 QualType ClassType = Context.getTypeDeclType(Method->getParent());
2072 QualType ImplicitParamType
2073 = Context.getCVRQualifiedType(ClassType, Method->getTypeQualifiers());
2075 // Set up the conversion sequence as a "bad" conversion, to allow us
2077 ImplicitConversionSequence ICS;
2078 ICS.Standard.setAsIdentityConversion();
2079 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2081 // We need to have an object of class type.
2082 QualType FromType = From->getType();
2083 if (const PointerType *PT = FromType->getAs<PointerType>())
2084 FromType = PT->getPointeeType();
2086 assert(FromType->isRecordType());
2088 // The implicit object parmeter is has the type "reference to cv X",
2089 // where X is the class of which the function is a member
2090 // (C++ [over.match.funcs]p4). However, when finding an implicit
2091 // conversion sequence for the argument, we are not allowed to
2092 // create temporaries or perform user-defined conversions
2093 // (C++ [over.match.funcs]p5). We perform a simplified version of
2094 // reference binding here, that allows class rvalues to bind to
2095 // non-constant references.
2097 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2098 // with the implicit object parameter (C++ [over.match.funcs]p5).
2099 QualType FromTypeCanon = Context.getCanonicalType(FromType);
2100 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
2101 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
2104 // Check that we have either the same type or a derived type. It
2105 // affects the conversion rank.
2106 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2107 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2108 ICS.Standard.Second = ICK_Identity;
2109 else if (IsDerivedFrom(FromType, ClassType))
2110 ICS.Standard.Second = ICK_Derived_To_Base;
2114 // Success. Mark this as a reference binding.
2115 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2116 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2117 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2118 ICS.Standard.ReferenceBinding = true;
2119 ICS.Standard.DirectBinding = true;
2120 ICS.Standard.RRefBinding = false;
2124 /// PerformObjectArgumentInitialization - Perform initialization of
2125 /// the implicit object parameter for the given Method with the given
2128 Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
2129 QualType FromRecordType, DestType;
2130 QualType ImplicitParamRecordType =
2131 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
2133 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
2134 FromRecordType = PT->getPointeeType();
2135 DestType = Method->getThisType(Context);
2137 FromRecordType = From->getType();
2138 DestType = ImplicitParamRecordType;
2141 ImplicitConversionSequence ICS
2142 = TryObjectArgumentInitialization(From, Method);
2143 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2144 return Diag(From->getSourceRange().getBegin(),
2145 diag::err_implicit_object_parameter_init)
2146 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
2148 if (ICS.Standard.Second == ICK_Derived_To_Base &&
2149 CheckDerivedToBaseConversion(FromRecordType,
2150 ImplicitParamRecordType,
2151 From->getSourceRange().getBegin(),
2152 From->getSourceRange()))
2155 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
2160 /// TryContextuallyConvertToBool - Attempt to contextually convert the
2161 /// expression From to bool (C++0x [conv]p3).
2162 ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
2163 return TryImplicitConversion(From, Context.BoolTy,
2164 // FIXME: Are these flags correct?
2165 /*SuppressUserConversions=*/false,
2166 /*AllowExplicit=*/true,
2167 /*ForceRValue=*/false,
2168 /*InOverloadResolution=*/false);
2171 /// PerformContextuallyConvertToBool - Perform a contextual conversion
2172 /// of the expression From to bool (C++0x [conv]p3).
2173 bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2174 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2175 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2178 if (!DiagnoseAmbiguousUserDefinedConversion(From, Context.BoolTy))
2179 return Diag(From->getSourceRange().getBegin(),
2180 diag::err_typecheck_bool_condition)
2181 << From->getType() << From->getSourceRange();
2185 /// AddOverloadCandidate - Adds the given function to the set of
2186 /// candidate functions, using the given function call arguments. If
2187 /// @p SuppressUserConversions, then don't allow user-defined
2188 /// conversions via constructors or conversion operators.
2189 /// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2190 /// hacky way to implement the overloading rules for elidable copy
2191 /// initialization in C++0x (C++0x 12.8p15).
2193 /// \para PartialOverloading true if we are performing "partial" overloading
2194 /// based on an incomplete set of function arguments. This feature is used by
2195 /// code completion.
2197 Sema::AddOverloadCandidate(FunctionDecl *Function,
2198 Expr **Args, unsigned NumArgs,
2199 OverloadCandidateSet& CandidateSet,
2200 bool SuppressUserConversions,
2202 bool PartialOverloading) {
2203 const FunctionProtoType* Proto
2204 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
2205 assert(Proto && "Functions without a prototype cannot be overloaded");
2206 assert(!isa<CXXConversionDecl>(Function) &&
2207 "Use AddConversionCandidate for conversion functions");
2208 assert(!Function->getDescribedFunctionTemplate() &&
2209 "Use AddTemplateOverloadCandidate for function templates");
2211 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2212 if (!isa<CXXConstructorDecl>(Method)) {
2213 // If we get here, it's because we're calling a member function
2214 // that is named without a member access expression (e.g.,
2215 // "this->f") that was either written explicitly or created
2216 // implicitly. This can happen with a qualified call to a member
2217 // function, e.g., X::f(). We use a NULL object as the implied
2218 // object argument (C++ [over.call.func]p3).
2219 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2220 SuppressUserConversions, ForceRValue);
2223 // We treat a constructor like a non-member function, since its object
2224 // argument doesn't participate in overload resolution.
2227 if (!CandidateSet.isNewCandidate(Function))
2230 // Add this candidate
2231 CandidateSet.push_back(OverloadCandidate());
2232 OverloadCandidate& Candidate = CandidateSet.back();
2233 Candidate.Function = Function;
2234 Candidate.Viable = true;
2235 Candidate.IsSurrogate = false;
2236 Candidate.IgnoreObjectArgument = false;
2238 unsigned NumArgsInProto = Proto->getNumArgs();
2240 // (C++ 13.3.2p2): A candidate function having fewer than m
2241 // parameters is viable only if it has an ellipsis in its parameter
2243 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2244 !Proto->isVariadic()) {
2245 Candidate.Viable = false;
2249 // (C++ 13.3.2p2): A candidate function having more than m parameters
2250 // is viable only if the (m+1)st parameter has a default argument
2251 // (8.3.6). For the purposes of overload resolution, the
2252 // parameter list is truncated on the right, so that there are
2253 // exactly m parameters.
2254 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2255 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
2256 // Not enough arguments.
2257 Candidate.Viable = false;
2261 // Determine the implicit conversion sequences for each of the
2263 Candidate.Conversions.resize(NumArgs);
2264 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2265 if (ArgIdx < NumArgsInProto) {
2266 // (C++ 13.3.2p3): for F to be a viable function, there shall
2267 // exist for each argument an implicit conversion sequence
2268 // (13.3.3.1) that converts that argument to the corresponding
2270 QualType ParamType = Proto->getArgType(ArgIdx);
2271 Candidate.Conversions[ArgIdx]
2272 = TryCopyInitialization(Args[ArgIdx], ParamType,
2273 SuppressUserConversions, ForceRValue,
2274 /*InOverloadResolution=*/true);
2275 if (Candidate.Conversions[ArgIdx].ConversionKind
2276 == ImplicitConversionSequence::BadConversion) {
2277 // 13.3.3.1-p10 If several different sequences of conversions exist that
2278 // each convert the argument to the parameter type, the implicit conversion
2279 // sequence associated with the parameter is defined to be the unique conversion
2280 // sequence designated the ambiguous conversion sequence. For the purpose of
2281 // ranking implicit conversion sequences as described in 13.3.3.2, the ambiguous
2282 // conversion sequence is treated as a user-defined sequence that is
2283 // indistinguishable from any other user-defined conversion sequence
2284 if (!Candidate.Conversions[ArgIdx].ConversionFunctionSet.empty()) {
2285 Candidate.Conversions[ArgIdx].ConversionKind =
2286 ImplicitConversionSequence::UserDefinedConversion;
2287 // Set the conversion function to one of them. As due to ambiguity,
2288 // they carry the same weight and is needed for overload resolution
2290 Candidate.Conversions[ArgIdx].UserDefined.ConversionFunction =
2291 Candidate.Conversions[ArgIdx].ConversionFunctionSet[0];
2294 Candidate.Viable = false;
2299 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2300 // argument for which there is no corresponding parameter is
2301 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2302 Candidate.Conversions[ArgIdx].ConversionKind
2303 = ImplicitConversionSequence::EllipsisConversion;
2308 /// \brief Add all of the function declarations in the given function set to
2309 /// the overload canddiate set.
2310 void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2311 Expr **Args, unsigned NumArgs,
2312 OverloadCandidateSet& CandidateSet,
2313 bool SuppressUserConversions) {
2314 for (FunctionSet::const_iterator F = Functions.begin(),
2315 FEnd = Functions.end();
2317 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2318 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2319 AddMethodCandidate(cast<CXXMethodDecl>(FD),
2320 Args[0], Args + 1, NumArgs - 1,
2321 CandidateSet, SuppressUserConversions);
2323 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2324 SuppressUserConversions);
2326 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2327 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2328 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2329 AddMethodTemplateCandidate(FunTmpl,
2330 /*FIXME: explicit args */false, 0, 0,
2331 Args[0], Args + 1, NumArgs - 1,
2333 SuppressUserConversions);
2335 AddTemplateOverloadCandidate(FunTmpl,
2336 /*FIXME: explicit args */false, 0, 0,
2337 Args, NumArgs, CandidateSet,
2338 SuppressUserConversions);
2343 /// AddMethodCandidate - Adds the given C++ member function to the set
2344 /// of candidate functions, using the given function call arguments
2345 /// and the object argument (@c Object). For example, in a call
2346 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2347 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2348 /// allow user-defined conversions via constructors or conversion
2349 /// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2350 /// a slightly hacky way to implement the overloading rules for elidable copy
2351 /// initialization in C++0x (C++0x 12.8p15).
2353 Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2354 Expr **Args, unsigned NumArgs,
2355 OverloadCandidateSet& CandidateSet,
2356 bool SuppressUserConversions, bool ForceRValue) {
2357 const FunctionProtoType* Proto
2358 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
2359 assert(Proto && "Methods without a prototype cannot be overloaded");
2360 assert(!isa<CXXConversionDecl>(Method) &&
2361 "Use AddConversionCandidate for conversion functions");
2362 assert(!isa<CXXConstructorDecl>(Method) &&
2363 "Use AddOverloadCandidate for constructors");
2365 if (!CandidateSet.isNewCandidate(Method))
2368 // Add this candidate
2369 CandidateSet.push_back(OverloadCandidate());
2370 OverloadCandidate& Candidate = CandidateSet.back();
2371 Candidate.Function = Method;
2372 Candidate.IsSurrogate = false;
2373 Candidate.IgnoreObjectArgument = false;
2375 unsigned NumArgsInProto = Proto->getNumArgs();
2377 // (C++ 13.3.2p2): A candidate function having fewer than m
2378 // parameters is viable only if it has an ellipsis in its parameter
2380 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2381 Candidate.Viable = false;
2385 // (C++ 13.3.2p2): A candidate function having more than m parameters
2386 // is viable only if the (m+1)st parameter has a default argument
2387 // (8.3.6). For the purposes of overload resolution, the
2388 // parameter list is truncated on the right, so that there are
2389 // exactly m parameters.
2390 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2391 if (NumArgs < MinRequiredArgs) {
2392 // Not enough arguments.
2393 Candidate.Viable = false;
2397 Candidate.Viable = true;
2398 Candidate.Conversions.resize(NumArgs + 1);
2400 if (Method->isStatic() || !Object)
2401 // The implicit object argument is ignored.
2402 Candidate.IgnoreObjectArgument = true;
2404 // Determine the implicit conversion sequence for the object
2406 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2407 if (Candidate.Conversions[0].ConversionKind
2408 == ImplicitConversionSequence::BadConversion) {
2409 Candidate.Viable = false;
2414 // Determine the implicit conversion sequences for each of the
2416 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2417 if (ArgIdx < NumArgsInProto) {
2418 // (C++ 13.3.2p3): for F to be a viable function, there shall
2419 // exist for each argument an implicit conversion sequence
2420 // (13.3.3.1) that converts that argument to the corresponding
2422 QualType ParamType = Proto->getArgType(ArgIdx);
2423 Candidate.Conversions[ArgIdx + 1]
2424 = TryCopyInitialization(Args[ArgIdx], ParamType,
2425 SuppressUserConversions, ForceRValue,
2426 /*InOverloadResolution=*/true);
2427 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2428 == ImplicitConversionSequence::BadConversion) {
2429 Candidate.Viable = false;
2433 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2434 // argument for which there is no corresponding parameter is
2435 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2436 Candidate.Conversions[ArgIdx + 1].ConversionKind
2437 = ImplicitConversionSequence::EllipsisConversion;
2442 /// \brief Add a C++ member function template as a candidate to the candidate
2443 /// set, using template argument deduction to produce an appropriate member
2444 /// function template specialization.
2446 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2447 bool HasExplicitTemplateArgs,
2448 const TemplateArgumentLoc *ExplicitTemplateArgs,
2449 unsigned NumExplicitTemplateArgs,
2450 Expr *Object, Expr **Args, unsigned NumArgs,
2451 OverloadCandidateSet& CandidateSet,
2452 bool SuppressUserConversions,
2454 if (!CandidateSet.isNewCandidate(MethodTmpl))
2457 // C++ [over.match.funcs]p7:
2458 // In each case where a candidate is a function template, candidate
2459 // function template specializations are generated using template argument
2460 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
2461 // candidate functions in the usual way.113) A given name can refer to one
2462 // or more function templates and also to a set of overloaded non-template
2463 // functions. In such a case, the candidate functions generated from each
2464 // function template are combined with the set of non-template candidate
2466 TemplateDeductionInfo Info(Context);
2467 FunctionDecl *Specialization = 0;
2468 if (TemplateDeductionResult Result
2469 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2470 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2471 Args, NumArgs, Specialization, Info)) {
2472 // FIXME: Record what happened with template argument deduction, so
2473 // that we can give the user a beautiful diagnostic.
2478 // Add the function template specialization produced by template argument
2479 // deduction as a candidate.
2480 assert(Specialization && "Missing member function template specialization?");
2481 assert(isa<CXXMethodDecl>(Specialization) &&
2482 "Specialization is not a member function?");
2483 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
2484 CandidateSet, SuppressUserConversions, ForceRValue);
2487 /// \brief Add a C++ function template specialization as a candidate
2488 /// in the candidate set, using template argument deduction to produce
2489 /// an appropriate function template specialization.
2491 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2492 bool HasExplicitTemplateArgs,
2493 const TemplateArgumentLoc *ExplicitTemplateArgs,
2494 unsigned NumExplicitTemplateArgs,
2495 Expr **Args, unsigned NumArgs,
2496 OverloadCandidateSet& CandidateSet,
2497 bool SuppressUserConversions,
2499 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2502 // C++ [over.match.funcs]p7:
2503 // In each case where a candidate is a function template, candidate
2504 // function template specializations are generated using template argument
2505 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
2506 // candidate functions in the usual way.113) A given name can refer to one
2507 // or more function templates and also to a set of overloaded non-template
2508 // functions. In such a case, the candidate functions generated from each
2509 // function template are combined with the set of non-template candidate
2511 TemplateDeductionInfo Info(Context);
2512 FunctionDecl *Specialization = 0;
2513 if (TemplateDeductionResult Result
2514 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2515 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2516 Args, NumArgs, Specialization, Info)) {
2517 // FIXME: Record what happened with template argument deduction, so
2518 // that we can give the user a beautiful diagnostic.
2523 // Add the function template specialization produced by template argument
2524 // deduction as a candidate.
2525 assert(Specialization && "Missing function template specialization?");
2526 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2527 SuppressUserConversions, ForceRValue);
2530 /// AddConversionCandidate - Add a C++ conversion function as a
2531 /// candidate in the candidate set (C++ [over.match.conv],
2532 /// C++ [over.match.copy]). From is the expression we're converting from,
2533 /// and ToType is the type that we're eventually trying to convert to
2534 /// (which may or may not be the same type as the type that the
2535 /// conversion function produces).
2537 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2538 Expr *From, QualType ToType,
2539 OverloadCandidateSet& CandidateSet) {
2540 assert(!Conversion->getDescribedFunctionTemplate() &&
2541 "Conversion function templates use AddTemplateConversionCandidate");
2543 if (!CandidateSet.isNewCandidate(Conversion))
2546 // Add this candidate
2547 CandidateSet.push_back(OverloadCandidate());
2548 OverloadCandidate& Candidate = CandidateSet.back();
2549 Candidate.Function = Conversion;
2550 Candidate.IsSurrogate = false;
2551 Candidate.IgnoreObjectArgument = false;
2552 Candidate.FinalConversion.setAsIdentityConversion();
2553 Candidate.FinalConversion.FromTypePtr
2554 = Conversion->getConversionType().getAsOpaquePtr();
2555 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2557 // Determine the implicit conversion sequence for the implicit
2558 // object parameter.
2559 Candidate.Viable = true;
2560 Candidate.Conversions.resize(1);
2561 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
2562 // Conversion functions to a different type in the base class is visible in
2563 // the derived class. So, a derived to base conversion should not participate
2564 // in overload resolution.
2565 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2566 Candidate.Conversions[0].Standard.Second = ICK_Identity;
2567 if (Candidate.Conversions[0].ConversionKind
2568 == ImplicitConversionSequence::BadConversion) {
2569 Candidate.Viable = false;
2573 // We won't go through a user-define type conversion function to convert a
2574 // derived to base as such conversions are given Conversion Rank. They only
2575 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2577 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2578 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2579 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2580 Candidate.Viable = false;
2585 // To determine what the conversion from the result of calling the
2586 // conversion function to the type we're eventually trying to
2587 // convert to (ToType), we need to synthesize a call to the
2588 // conversion function and attempt copy initialization from it. This
2589 // makes sure that we get the right semantics with respect to
2590 // lvalues/rvalues and the type. Fortunately, we can allocate this
2591 // call on the stack and we don't need its arguments to be
2593 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2595 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
2596 CastExpr::CK_FunctionToPointerDecay,
2597 &ConversionRef, false);
2599 // Note that it is safe to allocate CallExpr on the stack here because
2600 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2602 CallExpr Call(Context, &ConversionFn, 0, 0,
2603 Conversion->getConversionType().getNonReferenceType(),
2605 ImplicitConversionSequence ICS =
2606 TryCopyInitialization(&Call, ToType,
2607 /*SuppressUserConversions=*/true,
2608 /*ForceRValue=*/false,
2609 /*InOverloadResolution=*/false);
2611 switch (ICS.ConversionKind) {
2612 case ImplicitConversionSequence::StandardConversion:
2613 Candidate.FinalConversion = ICS.Standard;
2616 case ImplicitConversionSequence::BadConversion:
2617 Candidate.Viable = false;
2622 "Can only end up with a standard conversion sequence or failure");
2626 /// \brief Adds a conversion function template specialization
2627 /// candidate to the overload set, using template argument deduction
2628 /// to deduce the template arguments of the conversion function
2629 /// template from the type that we are converting to (C++
2630 /// [temp.deduct.conv]).
2632 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2633 Expr *From, QualType ToType,
2634 OverloadCandidateSet &CandidateSet) {
2635 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2636 "Only conversion function templates permitted here");
2638 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2641 TemplateDeductionInfo Info(Context);
2642 CXXConversionDecl *Specialization = 0;
2643 if (TemplateDeductionResult Result
2644 = DeduceTemplateArguments(FunctionTemplate, ToType,
2645 Specialization, Info)) {
2646 // FIXME: Record what happened with template argument deduction, so
2647 // that we can give the user a beautiful diagnostic.
2652 // Add the conversion function template specialization produced by
2653 // template argument deduction as a candidate.
2654 assert(Specialization && "Missing function template specialization?");
2655 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2658 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2659 /// converts the given @c Object to a function pointer via the
2660 /// conversion function @c Conversion, and then attempts to call it
2661 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
2662 /// the type of function that we'll eventually be calling.
2663 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
2664 const FunctionProtoType *Proto,
2665 Expr *Object, Expr **Args, unsigned NumArgs,
2666 OverloadCandidateSet& CandidateSet) {
2667 if (!CandidateSet.isNewCandidate(Conversion))
2670 CandidateSet.push_back(OverloadCandidate());
2671 OverloadCandidate& Candidate = CandidateSet.back();
2672 Candidate.Function = 0;
2673 Candidate.Surrogate = Conversion;
2674 Candidate.Viable = true;
2675 Candidate.IsSurrogate = true;
2676 Candidate.IgnoreObjectArgument = false;
2677 Candidate.Conversions.resize(NumArgs + 1);
2679 // Determine the implicit conversion sequence for the implicit
2680 // object parameter.
2681 ImplicitConversionSequence ObjectInit
2682 = TryObjectArgumentInitialization(Object, Conversion);
2683 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2684 Candidate.Viable = false;
2688 // The first conversion is actually a user-defined conversion whose
2689 // first conversion is ObjectInit's standard conversion (which is
2690 // effectively a reference binding). Record it as such.
2691 Candidate.Conversions[0].ConversionKind
2692 = ImplicitConversionSequence::UserDefinedConversion;
2693 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2694 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2695 Candidate.Conversions[0].UserDefined.After
2696 = Candidate.Conversions[0].UserDefined.Before;
2697 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2700 unsigned NumArgsInProto = Proto->getNumArgs();
2702 // (C++ 13.3.2p2): A candidate function having fewer than m
2703 // parameters is viable only if it has an ellipsis in its parameter
2705 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2706 Candidate.Viable = false;
2710 // Function types don't have any default arguments, so just check if
2711 // we have enough arguments.
2712 if (NumArgs < NumArgsInProto) {
2713 // Not enough arguments.
2714 Candidate.Viable = false;
2718 // Determine the implicit conversion sequences for each of the
2720 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2721 if (ArgIdx < NumArgsInProto) {
2722 // (C++ 13.3.2p3): for F to be a viable function, there shall
2723 // exist for each argument an implicit conversion sequence
2724 // (13.3.3.1) that converts that argument to the corresponding
2726 QualType ParamType = Proto->getArgType(ArgIdx);
2727 Candidate.Conversions[ArgIdx + 1]
2728 = TryCopyInitialization(Args[ArgIdx], ParamType,
2729 /*SuppressUserConversions=*/false,
2730 /*ForceRValue=*/false,
2731 /*InOverloadResolution=*/false);
2732 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2733 == ImplicitConversionSequence::BadConversion) {
2734 Candidate.Viable = false;
2738 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2739 // argument for which there is no corresponding parameter is
2740 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2741 Candidate.Conversions[ArgIdx + 1].ConversionKind
2742 = ImplicitConversionSequence::EllipsisConversion;
2747 // FIXME: This will eventually be removed, once we've migrated all of the
2748 // operator overloading logic over to the scheme used by binary operators, which
2749 // works for template instantiation.
2750 void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
2751 SourceLocation OpLoc,
2752 Expr **Args, unsigned NumArgs,
2753 OverloadCandidateSet& CandidateSet,
2754 SourceRange OpRange) {
2755 FunctionSet Functions;
2757 QualType T1 = Args[0]->getType();
2760 T2 = Args[1]->getType();
2762 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2764 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
2765 ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
2766 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2767 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2768 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
2771 /// \brief Add overload candidates for overloaded operators that are
2772 /// member functions.
2774 /// Add the overloaded operator candidates that are member functions
2775 /// for the operator Op that was used in an operator expression such
2776 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
2777 /// CandidateSet will store the added overload candidates. (C++
2778 /// [over.match.oper]).
2779 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2780 SourceLocation OpLoc,
2781 Expr **Args, unsigned NumArgs,
2782 OverloadCandidateSet& CandidateSet,
2783 SourceRange OpRange) {
2784 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2786 // C++ [over.match.oper]p3:
2787 // For a unary operator @ with an operand of a type whose
2788 // cv-unqualified version is T1, and for a binary operator @ with
2789 // a left operand of a type whose cv-unqualified version is T1 and
2790 // a right operand of a type whose cv-unqualified version is T2,
2791 // three sets of candidate functions, designated member
2792 // candidates, non-member candidates and built-in candidates, are
2793 // constructed as follows:
2794 QualType T1 = Args[0]->getType();
2797 T2 = Args[1]->getType();
2799 // -- If T1 is a class type, the set of member candidates is the
2800 // result of the qualified lookup of T1::operator@
2801 // (13.3.1.1.1); otherwise, the set of member candidates is
2803 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
2804 // Complete the type if it can be completed. Otherwise, we're done.
2805 if (RequireCompleteType(OpLoc, T1, PDiag()))
2808 LookupResult Operators;
2809 LookupQualifiedName(Operators, T1Rec->getDecl(), OpName,
2810 LookupOrdinaryName, false);
2811 for (LookupResult::iterator Oper = Operators.begin(),
2812 OperEnd = Operators.end();
2815 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Oper)) {
2816 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet,
2817 /*SuppressUserConversions=*/false);
2821 assert(isa<FunctionTemplateDecl>(*Oper) &&
2822 isa<CXXMethodDecl>(cast<FunctionTemplateDecl>(*Oper)
2823 ->getTemplatedDecl()) &&
2824 "Expected a member function template");
2825 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Oper), false, 0, 0,
2826 Args[0], Args+1, NumArgs - 1, CandidateSet,
2827 /*SuppressUserConversions=*/false);
2832 /// AddBuiltinCandidate - Add a candidate for a built-in
2833 /// operator. ResultTy and ParamTys are the result and parameter types
2834 /// of the built-in candidate, respectively. Args and NumArgs are the
2835 /// arguments being passed to the candidate. IsAssignmentOperator
2836 /// should be true when this built-in candidate is an assignment
2837 /// operator. NumContextualBoolArguments is the number of arguments
2838 /// (at the beginning of the argument list) that will be contextually
2839 /// converted to bool.
2840 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2841 Expr **Args, unsigned NumArgs,
2842 OverloadCandidateSet& CandidateSet,
2843 bool IsAssignmentOperator,
2844 unsigned NumContextualBoolArguments) {
2845 // Add this candidate
2846 CandidateSet.push_back(OverloadCandidate());
2847 OverloadCandidate& Candidate = CandidateSet.back();
2848 Candidate.Function = 0;
2849 Candidate.IsSurrogate = false;
2850 Candidate.IgnoreObjectArgument = false;
2851 Candidate.BuiltinTypes.ResultTy = ResultTy;
2852 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2853 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2855 // Determine the implicit conversion sequences for each of the
2857 Candidate.Viable = true;
2858 Candidate.Conversions.resize(NumArgs);
2859 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2860 // C++ [over.match.oper]p4:
2861 // For the built-in assignment operators, conversions of the
2862 // left operand are restricted as follows:
2863 // -- no temporaries are introduced to hold the left operand, and
2864 // -- no user-defined conversions are applied to the left
2865 // operand to achieve a type match with the left-most
2866 // parameter of a built-in candidate.
2868 // We block these conversions by turning off user-defined
2869 // conversions, since that is the only way that initialization of
2870 // a reference to a non-class type can occur from something that
2871 // is not of the same type.
2872 if (ArgIdx < NumContextualBoolArguments) {
2873 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2874 "Contextual conversion to bool requires bool type");
2875 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2877 Candidate.Conversions[ArgIdx]
2878 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2879 ArgIdx == 0 && IsAssignmentOperator,
2880 /*ForceRValue=*/false,
2881 /*InOverloadResolution=*/false);
2883 if (Candidate.Conversions[ArgIdx].ConversionKind
2884 == ImplicitConversionSequence::BadConversion) {
2885 Candidate.Viable = false;
2891 /// BuiltinCandidateTypeSet - A set of types that will be used for the
2892 /// candidate operator functions for built-in operators (C++
2893 /// [over.built]). The types are separated into pointer types and
2894 /// enumeration types.
2895 class BuiltinCandidateTypeSet {
2896 /// TypeSet - A set of types.
2897 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
2899 /// PointerTypes - The set of pointer types that will be used in the
2900 /// built-in candidates.
2901 TypeSet PointerTypes;
2903 /// MemberPointerTypes - The set of member pointer types that will be
2904 /// used in the built-in candidates.
2905 TypeSet MemberPointerTypes;
2907 /// EnumerationTypes - The set of enumeration types that will be
2908 /// used in the built-in candidates.
2909 TypeSet EnumerationTypes;
2911 /// Sema - The semantic analysis instance where we are building the
2912 /// candidate type set.
2915 /// Context - The AST context in which we will build the type sets.
2916 ASTContext &Context;
2918 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
2919 const Qualifiers &VisibleQuals);
2920 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
2923 /// iterator - Iterates through the types that are part of the set.
2924 typedef TypeSet::iterator iterator;
2926 BuiltinCandidateTypeSet(Sema &SemaRef)
2927 : SemaRef(SemaRef), Context(SemaRef.Context) { }
2929 void AddTypesConvertedFrom(QualType Ty,
2931 bool AllowUserConversions,
2932 bool AllowExplicitConversions,
2933 const Qualifiers &VisibleTypeConversionsQuals);
2935 /// pointer_begin - First pointer type found;
2936 iterator pointer_begin() { return PointerTypes.begin(); }
2938 /// pointer_end - Past the last pointer type found;
2939 iterator pointer_end() { return PointerTypes.end(); }
2941 /// member_pointer_begin - First member pointer type found;
2942 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2944 /// member_pointer_end - Past the last member pointer type found;
2945 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2947 /// enumeration_begin - First enumeration type found;
2948 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2950 /// enumeration_end - Past the last enumeration type found;
2951 iterator enumeration_end() { return EnumerationTypes.end(); }
2954 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2955 /// the set of pointer types along with any more-qualified variants of
2956 /// that type. For example, if @p Ty is "int const *", this routine
2957 /// will add "int const *", "int const volatile *", "int const
2958 /// restrict *", and "int const volatile restrict *" to the set of
2959 /// pointer types. Returns true if the add of @p Ty itself succeeded,
2960 /// false otherwise.
2962 /// FIXME: what to do about extended qualifiers?
2964 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
2965 const Qualifiers &VisibleQuals) {
2967 // Insert this type.
2968 if (!PointerTypes.insert(Ty))
2971 const PointerType *PointerTy = Ty->getAs<PointerType>();
2972 assert(PointerTy && "type was not a pointer type!");
2974 QualType PointeeTy = PointerTy->getPointeeType();
2975 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
2976 bool hasVolatile = VisibleQuals.hasVolatile();
2977 bool hasRestrict = VisibleQuals.hasRestrict();
2979 // Iterate through all strict supersets of BaseCVR.
2980 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
2981 if ((CVR | BaseCVR) != CVR) continue;
2982 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
2984 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
2985 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
2986 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
2987 PointerTypes.insert(Context.getPointerType(QPointeeTy));
2993 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2994 /// to the set of pointer types along with any more-qualified variants of
2995 /// that type. For example, if @p Ty is "int const *", this routine
2996 /// will add "int const *", "int const volatile *", "int const
2997 /// restrict *", and "int const volatile restrict *" to the set of
2998 /// pointer types. Returns true if the add of @p Ty itself succeeded,
2999 /// false otherwise.
3001 /// FIXME: what to do about extended qualifiers?
3003 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3005 // Insert this type.
3006 if (!MemberPointerTypes.insert(Ty))
3009 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3010 assert(PointerTy && "type was not a member pointer type!");
3012 QualType PointeeTy = PointerTy->getPointeeType();
3013 const Type *ClassTy = PointerTy->getClass();
3015 // Iterate through all strict supersets of the pointee type's CVR
3017 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3018 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3019 if ((CVR | BaseCVR) != CVR) continue;
3021 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3022 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
3028 /// AddTypesConvertedFrom - Add each of the types to which the type @p
3029 /// Ty can be implicit converted to the given set of @p Types. We're
3030 /// primarily interested in pointer types and enumeration types. We also
3031 /// take member pointer types, for the conditional operator.
3032 /// AllowUserConversions is true if we should look at the conversion
3033 /// functions of a class type, and AllowExplicitConversions if we
3034 /// should also include the explicit conversion functions of a class
3037 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
3039 bool AllowUserConversions,
3040 bool AllowExplicitConversions,
3041 const Qualifiers &VisibleQuals) {
3042 // Only deal with canonical types.
3043 Ty = Context.getCanonicalType(Ty);
3045 // Look through reference types; they aren't part of the type of an
3046 // expression for the purposes of conversions.
3047 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
3048 Ty = RefTy->getPointeeType();
3050 // We don't care about qualifiers on the type.
3051 Ty = Ty.getUnqualifiedType();
3053 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
3054 QualType PointeeTy = PointerTy->getPointeeType();
3056 // Insert our type, and its more-qualified variants, into the set
3058 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
3060 } else if (Ty->isMemberPointerType()) {
3061 // Member pointers are far easier, since the pointee can't be converted.
3062 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3064 } else if (Ty->isEnumeralType()) {
3065 EnumerationTypes.insert(Ty);
3066 } else if (AllowUserConversions) {
3067 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
3068 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
3069 // No conversion functions in incomplete types.
3073 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
3074 OverloadedFunctionDecl *Conversions
3075 = ClassDecl->getVisibleConversionFunctions();
3076 for (OverloadedFunctionDecl::function_iterator Func
3077 = Conversions->function_begin();
3078 Func != Conversions->function_end(); ++Func) {
3079 CXXConversionDecl *Conv;
3080 FunctionTemplateDecl *ConvTemplate;
3081 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
3083 // Skip conversion function templates; they don't tell us anything
3084 // about which builtin types we can convert to.
3088 if (AllowExplicitConversions || !Conv->isExplicit()) {
3089 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
3097 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3098 /// the volatile- and non-volatile-qualified assignment operators for the
3099 /// given type to the candidate set.
3100 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3104 OverloadCandidateSet &CandidateSet) {
3105 QualType ParamTypes[2];
3107 // T& operator=(T&, T)
3108 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3110 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3111 /*IsAssignmentOperator=*/true);
3113 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3114 // volatile T& operator=(volatile T&, T)
3116 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
3118 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3119 /*IsAssignmentOperator=*/true);
3123 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3124 /// if any, found in visible type conversion functions found in ArgExpr's type.
3125 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3127 const RecordType *TyRec;
3128 if (const MemberPointerType *RHSMPType =
3129 ArgExpr->getType()->getAs<MemberPointerType>())
3130 TyRec = cast<RecordType>(RHSMPType->getClass());
3132 TyRec = ArgExpr->getType()->getAs<RecordType>();
3134 // Just to be safe, assume the worst case.
3135 VRQuals.addVolatile();
3136 VRQuals.addRestrict();
3140 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
3141 OverloadedFunctionDecl *Conversions =
3142 ClassDecl->getVisibleConversionFunctions();
3144 for (OverloadedFunctionDecl::function_iterator Func
3145 = Conversions->function_begin();
3146 Func != Conversions->function_end(); ++Func) {
3147 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*Func)) {
3148 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3149 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3150 CanTy = ResTypeRef->getPointeeType();
3151 // Need to go down the pointer/mempointer chain and add qualifiers
3155 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3156 CanTy = ResTypePtr->getPointeeType();
3157 else if (const MemberPointerType *ResTypeMPtr =
3158 CanTy->getAs<MemberPointerType>())
3159 CanTy = ResTypeMPtr->getPointeeType();
3162 if (CanTy.isVolatileQualified())
3163 VRQuals.addVolatile();
3164 if (CanTy.isRestrictQualified())
3165 VRQuals.addRestrict();
3166 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3174 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
3175 /// operator overloads to the candidate set (C++ [over.built]), based
3176 /// on the operator @p Op and the arguments given. For example, if the
3177 /// operator is a binary '+', this routine might add "int
3178 /// operator+(int, int)" to cover integer addition.
3180 Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
3181 SourceLocation OpLoc,
3182 Expr **Args, unsigned NumArgs,
3183 OverloadCandidateSet& CandidateSet) {
3184 // The set of "promoted arithmetic types", which are the arithmetic
3185 // types are that preserved by promotion (C++ [over.built]p2). Note
3186 // that the first few of these types are the promoted integral
3187 // types; these types need to be first.
3188 // FIXME: What about complex?
3189 const unsigned FirstIntegralType = 0;
3190 const unsigned LastIntegralType = 13;
3191 const unsigned FirstPromotedIntegralType = 7,
3192 LastPromotedIntegralType = 13;
3193 const unsigned FirstPromotedArithmeticType = 7,
3194 LastPromotedArithmeticType = 16;
3195 const unsigned NumArithmeticTypes = 16;
3196 QualType ArithmeticTypes[NumArithmeticTypes] = {
3197 Context.BoolTy, Context.CharTy, Context.WCharTy,
3198 // FIXME: Context.Char16Ty, Context.Char32Ty,
3199 Context.SignedCharTy, Context.ShortTy,
3200 Context.UnsignedCharTy, Context.UnsignedShortTy,
3201 Context.IntTy, Context.LongTy, Context.LongLongTy,
3202 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3203 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3205 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3206 "Invalid first promoted integral type");
3207 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3208 == Context.UnsignedLongLongTy &&
3209 "Invalid last promoted integral type");
3210 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3211 "Invalid first promoted arithmetic type");
3212 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3213 == Context.LongDoubleTy &&
3214 "Invalid last promoted arithmetic type");
3216 // Find all of the types that the arguments can convert to, but only
3217 // if the operator we're looking at has built-in operator candidates
3218 // that make use of these types.
3219 Qualifiers VisibleTypeConversionsQuals;
3220 VisibleTypeConversionsQuals.addConst();
3221 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3222 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3224 BuiltinCandidateTypeSet CandidateTypes(*this);
3225 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3226 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
3227 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
3228 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
3229 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
3230 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
3231 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3232 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
3235 (Op == OO_Exclaim ||
3238 VisibleTypeConversionsQuals);
3241 bool isComparison = false;
3244 case NUM_OVERLOADED_OPERATORS:
3245 assert(false && "Expected an overloaded operator");
3248 case OO_Star: // '*' is either unary or binary
3255 case OO_Plus: // '+' is either unary or binary
3262 case OO_Minus: // '-' is either unary or binary
3269 case OO_Amp: // '&' is either unary or binary
3277 // C++ [over.built]p3:
3279 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3280 // is either volatile or empty, there exist candidate operator
3281 // functions of the form
3283 // VQ T& operator++(VQ T&);
3284 // T operator++(VQ T&, int);
3286 // C++ [over.built]p4:
3288 // For every pair (T, VQ), where T is an arithmetic type other
3289 // than bool, and VQ is either volatile or empty, there exist
3290 // candidate operator functions of the form
3292 // VQ T& operator--(VQ T&);
3293 // T operator--(VQ T&, int);
3294 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
3295 Arith < NumArithmeticTypes; ++Arith) {
3296 QualType ArithTy = ArithmeticTypes[Arith];
3297 QualType ParamTypes[2]
3298 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
3300 // Non-volatile version.
3302 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3304 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3305 // heuristic to reduce number of builtin candidates in the set.
3306 // Add volatile version only if there are conversions to a volatile type.
3307 if (VisibleTypeConversionsQuals.hasVolatile()) {
3310 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3312 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3314 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3318 // C++ [over.built]p5:
3320 // For every pair (T, VQ), where T is a cv-qualified or
3321 // cv-unqualified object type, and VQ is either volatile or
3322 // empty, there exist candidate operator functions of the form
3324 // T*VQ& operator++(T*VQ&);
3325 // T*VQ& operator--(T*VQ&);
3326 // T* operator++(T*VQ&, int);
3327 // T* operator--(T*VQ&, int);
3328 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3329 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3330 // Skip pointer types that aren't pointers to object types.
3331 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
3334 QualType ParamTypes[2] = {
3335 Context.getLValueReferenceType(*Ptr), Context.IntTy
3340 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3342 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3344 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3345 VisibleTypeConversionsQuals.hasVolatile()) {
3348 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
3350 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3352 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3358 // C++ [over.built]p6:
3359 // For every cv-qualified or cv-unqualified object type T, there
3360 // exist candidate operator functions of the form
3362 // T& operator*(T*);
3364 // C++ [over.built]p7:
3365 // For every function type T, there exist candidate operator
3366 // functions of the form
3367 // T& operator*(T*);
3368 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3369 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3370 QualType ParamTy = *Ptr;
3371 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
3372 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
3373 &ParamTy, Args, 1, CandidateSet);
3378 // C++ [over.built]p8:
3379 // For every type T, there exist candidate operator functions of
3382 // T* operator+(T*);
3383 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3384 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3385 QualType ParamTy = *Ptr;
3386 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3392 // C++ [over.built]p9:
3393 // For every promoted arithmetic type T, there exist candidate
3394 // operator functions of the form
3398 for (unsigned Arith = FirstPromotedArithmeticType;
3399 Arith < LastPromotedArithmeticType; ++Arith) {
3400 QualType ArithTy = ArithmeticTypes[Arith];
3401 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3406 // C++ [over.built]p10:
3407 // For every promoted integral type T, there exist candidate
3408 // operator functions of the form
3411 for (unsigned Int = FirstPromotedIntegralType;
3412 Int < LastPromotedIntegralType; ++Int) {
3413 QualType IntTy = ArithmeticTypes[Int];
3414 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3421 case OO_Array_Delete:
3423 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
3429 // C++ [over.match.oper]p3:
3430 // -- For the operator ',', the unary operator '&', or the
3431 // operator '->', the built-in candidates set is empty.
3435 case OO_ExclaimEqual:
3436 // C++ [over.match.oper]p16:
3437 // For every pointer to member type T, there exist candidate operator
3438 // functions of the form
3440 // bool operator==(T,T);
3441 // bool operator!=(T,T);
3442 for (BuiltinCandidateTypeSet::iterator
3443 MemPtr = CandidateTypes.member_pointer_begin(),
3444 MemPtrEnd = CandidateTypes.member_pointer_end();
3445 MemPtr != MemPtrEnd;
3447 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3448 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3456 case OO_GreaterEqual:
3457 // C++ [over.built]p15:
3459 // For every pointer or enumeration type T, there exist
3460 // candidate operator functions of the form
3462 // bool operator<(T, T);
3463 // bool operator>(T, T);
3464 // bool operator<=(T, T);
3465 // bool operator>=(T, T);
3466 // bool operator==(T, T);
3467 // bool operator!=(T, T);
3468 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3469 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3470 QualType ParamTypes[2] = { *Ptr, *Ptr };
3471 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3473 for (BuiltinCandidateTypeSet::iterator Enum
3474 = CandidateTypes.enumeration_begin();
3475 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3476 QualType ParamTypes[2] = { *Enum, *Enum };
3477 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3481 isComparison = true;
3485 if (!isComparison) {
3486 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3488 // C++ [over.built]p13:
3490 // For every cv-qualified or cv-unqualified object type T
3491 // there exist candidate operator functions of the form
3493 // T* operator+(T*, ptrdiff_t);
3494 // T& operator[](T*, ptrdiff_t); [BELOW]
3495 // T* operator-(T*, ptrdiff_t);
3496 // T* operator+(ptrdiff_t, T*);
3497 // T& operator[](ptrdiff_t, T*); [BELOW]
3499 // C++ [over.built]p14:
3501 // For every T, where T is a pointer to object type, there
3502 // exist candidate operator functions of the form
3504 // ptrdiff_t operator-(T, T);
3505 for (BuiltinCandidateTypeSet::iterator Ptr
3506 = CandidateTypes.pointer_begin();
3507 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3508 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3510 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3511 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3513 if (Op == OO_Plus) {
3514 // T* operator+(ptrdiff_t, T*);
3515 ParamTypes[0] = ParamTypes[1];
3516 ParamTypes[1] = *Ptr;
3517 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3519 // ptrdiff_t operator-(T, T);
3520 ParamTypes[1] = *Ptr;
3521 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3522 Args, 2, CandidateSet);
3531 // C++ [over.built]p12:
3533 // For every pair of promoted arithmetic types L and R, there
3534 // exist candidate operator functions of the form
3536 // LR operator*(L, R);
3537 // LR operator/(L, R);
3538 // LR operator+(L, R);
3539 // LR operator-(L, R);
3540 // bool operator<(L, R);
3541 // bool operator>(L, R);
3542 // bool operator<=(L, R);
3543 // bool operator>=(L, R);
3544 // bool operator==(L, R);
3545 // bool operator!=(L, R);
3547 // where LR is the result of the usual arithmetic conversions
3548 // between types L and R.
3550 // C++ [over.built]p24:
3552 // For every pair of promoted arithmetic types L and R, there exist
3553 // candidate operator functions of the form
3555 // LR operator?(bool, L, R);
3557 // where LR is the result of the usual arithmetic conversions
3558 // between types L and R.
3559 // Our candidates ignore the first parameter.
3560 for (unsigned Left = FirstPromotedArithmeticType;
3561 Left < LastPromotedArithmeticType; ++Left) {
3562 for (unsigned Right = FirstPromotedArithmeticType;
3563 Right < LastPromotedArithmeticType; ++Right) {
3564 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3568 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
3569 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3579 case OO_GreaterGreater:
3580 // C++ [over.built]p17:
3582 // For every pair of promoted integral types L and R, there
3583 // exist candidate operator functions of the form
3585 // LR operator%(L, R);
3586 // LR operator&(L, R);
3587 // LR operator^(L, R);
3588 // LR operator|(L, R);
3589 // L operator<<(L, R);
3590 // L operator>>(L, R);
3592 // where LR is the result of the usual arithmetic conversions
3593 // between types L and R.
3594 for (unsigned Left = FirstPromotedIntegralType;
3595 Left < LastPromotedIntegralType; ++Left) {
3596 for (unsigned Right = FirstPromotedIntegralType;
3597 Right < LastPromotedIntegralType; ++Right) {
3598 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3599 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3601 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
3602 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3608 // C++ [over.built]p20:
3610 // For every pair (T, VQ), where T is an enumeration or
3611 // pointer to member type and VQ is either volatile or
3612 // empty, there exist candidate operator functions of the form
3614 // VQ T& operator=(VQ T&, T);
3615 for (BuiltinCandidateTypeSet::iterator
3616 Enum = CandidateTypes.enumeration_begin(),
3617 EnumEnd = CandidateTypes.enumeration_end();
3618 Enum != EnumEnd; ++Enum)
3619 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
3621 for (BuiltinCandidateTypeSet::iterator
3622 MemPtr = CandidateTypes.member_pointer_begin(),
3623 MemPtrEnd = CandidateTypes.member_pointer_end();
3624 MemPtr != MemPtrEnd; ++MemPtr)
3625 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
3631 // C++ [over.built]p19:
3633 // For every pair (T, VQ), where T is any type and VQ is either
3634 // volatile or empty, there exist candidate operator functions
3637 // T*VQ& operator=(T*VQ&, T*);
3639 // C++ [over.built]p21:
3641 // For every pair (T, VQ), where T is a cv-qualified or
3642 // cv-unqualified object type and VQ is either volatile or
3643 // empty, there exist candidate operator functions of the form
3645 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3646 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3647 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3648 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3649 QualType ParamTypes[2];
3650 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3652 // non-volatile version
3653 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
3654 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3655 /*IsAssigmentOperator=*/Op == OO_Equal);
3657 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3658 VisibleTypeConversionsQuals.hasVolatile()) {
3661 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
3662 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3663 /*IsAssigmentOperator=*/Op == OO_Equal);
3670 // C++ [over.built]p18:
3672 // For every triple (L, VQ, R), where L is an arithmetic type,
3673 // VQ is either volatile or empty, and R is a promoted
3674 // arithmetic type, there exist candidate operator functions of
3677 // VQ L& operator=(VQ L&, R);
3678 // VQ L& operator*=(VQ L&, R);
3679 // VQ L& operator/=(VQ L&, R);
3680 // VQ L& operator+=(VQ L&, R);
3681 // VQ L& operator-=(VQ L&, R);
3682 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3683 for (unsigned Right = FirstPromotedArithmeticType;
3684 Right < LastPromotedArithmeticType; ++Right) {
3685 QualType ParamTypes[2];
3686 ParamTypes[1] = ArithmeticTypes[Right];
3688 // Add this built-in operator as a candidate (VQ is empty).
3689 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
3690 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3691 /*IsAssigmentOperator=*/Op == OO_Equal);
3693 // Add this built-in operator as a candidate (VQ is 'volatile').
3694 if (VisibleTypeConversionsQuals.hasVolatile()) {
3695 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3696 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3697 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3698 /*IsAssigmentOperator=*/Op == OO_Equal);
3704 case OO_PercentEqual:
3705 case OO_LessLessEqual:
3706 case OO_GreaterGreaterEqual:
3710 // C++ [over.built]p22:
3712 // For every triple (L, VQ, R), where L is an integral type, VQ
3713 // is either volatile or empty, and R is a promoted integral
3714 // type, there exist candidate operator functions of the form
3716 // VQ L& operator%=(VQ L&, R);
3717 // VQ L& operator<<=(VQ L&, R);
3718 // VQ L& operator>>=(VQ L&, R);
3719 // VQ L& operator&=(VQ L&, R);
3720 // VQ L& operator^=(VQ L&, R);
3721 // VQ L& operator|=(VQ L&, R);
3722 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3723 for (unsigned Right = FirstPromotedIntegralType;
3724 Right < LastPromotedIntegralType; ++Right) {
3725 QualType ParamTypes[2];
3726 ParamTypes[1] = ArithmeticTypes[Right];
3728 // Add this built-in operator as a candidate (VQ is empty).
3729 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
3730 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3731 if (VisibleTypeConversionsQuals.hasVolatile()) {
3732 // Add this built-in operator as a candidate (VQ is 'volatile').
3733 ParamTypes[0] = ArithmeticTypes[Left];
3734 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3735 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3736 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3743 // C++ [over.operator]p23:
3745 // There also exist candidate operator functions of the form
3747 // bool operator!(bool);
3748 // bool operator&&(bool, bool); [BELOW]
3749 // bool operator||(bool, bool); [BELOW]
3750 QualType ParamTy = Context.BoolTy;
3751 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3752 /*IsAssignmentOperator=*/false,
3753 /*NumContextualBoolArguments=*/1);
3759 // C++ [over.operator]p23:
3761 // There also exist candidate operator functions of the form
3763 // bool operator!(bool); [ABOVE]
3764 // bool operator&&(bool, bool);
3765 // bool operator||(bool, bool);
3766 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
3767 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3768 /*IsAssignmentOperator=*/false,
3769 /*NumContextualBoolArguments=*/2);
3774 // C++ [over.built]p13:
3776 // For every cv-qualified or cv-unqualified object type T there
3777 // exist candidate operator functions of the form
3779 // T* operator+(T*, ptrdiff_t); [ABOVE]
3780 // T& operator[](T*, ptrdiff_t);
3781 // T* operator-(T*, ptrdiff_t); [ABOVE]
3782 // T* operator+(ptrdiff_t, T*); [ABOVE]
3783 // T& operator[](ptrdiff_t, T*);
3784 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3785 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3786 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3787 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
3788 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
3790 // T& operator[](T*, ptrdiff_t)
3791 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3793 // T& operator[](ptrdiff_t, T*);
3794 ParamTypes[0] = ParamTypes[1];
3795 ParamTypes[1] = *Ptr;
3796 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3801 // C++ [over.built]p11:
3802 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
3803 // C1 is the same type as C2 or is a derived class of C2, T is an object
3804 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
3805 // there exist candidate operator functions of the form
3806 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
3807 // where CV12 is the union of CV1 and CV2.
3809 for (BuiltinCandidateTypeSet::iterator Ptr =
3810 CandidateTypes.pointer_begin();
3811 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3812 QualType C1Ty = (*Ptr);
3814 QualifierCollector Q1;
3815 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
3816 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
3817 if (!isa<RecordType>(C1))
3819 // heuristic to reduce number of builtin candidates in the set.
3820 // Add volatile/restrict version only if there are conversions to a
3821 // volatile/restrict type.
3822 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
3824 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
3827 for (BuiltinCandidateTypeSet::iterator
3828 MemPtr = CandidateTypes.member_pointer_begin(),
3829 MemPtrEnd = CandidateTypes.member_pointer_end();
3830 MemPtr != MemPtrEnd; ++MemPtr) {
3831 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
3832 QualType C2 = QualType(mptr->getClass(), 0);
3833 C2 = C2.getUnqualifiedType();
3834 if (C1 != C2 && !IsDerivedFrom(C1, C2))
3836 QualType ParamTypes[2] = { *Ptr, *MemPtr };
3838 QualType T = mptr->getPointeeType();
3839 if (!VisibleTypeConversionsQuals.hasVolatile() &&
3840 T.isVolatileQualified())
3842 if (!VisibleTypeConversionsQuals.hasRestrict() &&
3843 T.isRestrictQualified())
3846 QualType ResultTy = Context.getLValueReferenceType(T);
3847 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3853 case OO_Conditional:
3854 // Note that we don't consider the first argument, since it has been
3855 // contextually converted to bool long ago. The candidates below are
3856 // therefore added as binary.
3858 // C++ [over.built]p24:
3859 // For every type T, where T is a pointer or pointer-to-member type,
3860 // there exist candidate operator functions of the form
3862 // T operator?(bool, T, T);
3864 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3865 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3866 QualType ParamTypes[2] = { *Ptr, *Ptr };
3867 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3869 for (BuiltinCandidateTypeSet::iterator Ptr =
3870 CandidateTypes.member_pointer_begin(),
3871 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3872 QualType ParamTypes[2] = { *Ptr, *Ptr };
3873 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3879 /// \brief Add function candidates found via argument-dependent lookup
3880 /// to the set of overloading candidates.
3882 /// This routine performs argument-dependent name lookup based on the
3883 /// given function name (which may also be an operator name) and adds
3884 /// all of the overload candidates found by ADL to the overload
3885 /// candidate set (C++ [basic.lookup.argdep]).
3887 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3888 Expr **Args, unsigned NumArgs,
3889 bool HasExplicitTemplateArgs,
3890 const TemplateArgumentLoc *ExplicitTemplateArgs,
3891 unsigned NumExplicitTemplateArgs,
3892 OverloadCandidateSet& CandidateSet,
3893 bool PartialOverloading) {
3894 FunctionSet Functions;
3896 // FIXME: Should we be trafficking in canonical function decls throughout?
3898 // Record all of the function candidates that we've already
3899 // added to the overload set, so that we don't add those same
3900 // candidates a second time.
3901 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3902 CandEnd = CandidateSet.end();
3903 Cand != CandEnd; ++Cand)
3904 if (Cand->Function) {
3905 Functions.insert(Cand->Function);
3906 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3907 Functions.insert(FunTmpl);
3910 // FIXME: Pass in the explicit template arguments?
3911 ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
3913 // Erase all of the candidates we already knew about.
3914 // FIXME: This is suboptimal. Is there a better way?
3915 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3916 CandEnd = CandidateSet.end();
3917 Cand != CandEnd; ++Cand)
3918 if (Cand->Function) {
3919 Functions.erase(Cand->Function);
3920 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3921 Functions.erase(FunTmpl);
3924 // For each of the ADL candidates we found, add it to the overload
3926 for (FunctionSet::iterator Func = Functions.begin(),
3927 FuncEnd = Functions.end();
3928 Func != FuncEnd; ++Func) {
3929 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
3930 if (HasExplicitTemplateArgs)
3933 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
3934 false, false, PartialOverloading);
3936 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
3937 HasExplicitTemplateArgs,
3938 ExplicitTemplateArgs,
3939 NumExplicitTemplateArgs,
3940 Args, NumArgs, CandidateSet);
3944 /// isBetterOverloadCandidate - Determines whether the first overload
3945 /// candidate is a better candidate than the second (C++ 13.3.3p1).
3947 Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3948 const OverloadCandidate& Cand2) {
3949 // Define viable functions to be better candidates than non-viable
3952 return Cand1.Viable;
3953 else if (!Cand1.Viable)
3956 // C++ [over.match.best]p1:
3958 // -- if F is a static member function, ICS1(F) is defined such
3959 // that ICS1(F) is neither better nor worse than ICS1(G) for
3960 // any function G, and, symmetrically, ICS1(G) is neither
3961 // better nor worse than ICS1(F).
3962 unsigned StartArg = 0;
3963 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3966 // C++ [over.match.best]p1:
3967 // A viable function F1 is defined to be a better function than another
3968 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
3969 // conversion sequence than ICSi(F2), and then...
3970 unsigned NumArgs = Cand1.Conversions.size();
3971 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3972 bool HasBetterConversion = false;
3973 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
3974 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3975 Cand2.Conversions[ArgIdx])) {
3976 case ImplicitConversionSequence::Better:
3977 // Cand1 has a better conversion sequence.
3978 HasBetterConversion = true;
3981 case ImplicitConversionSequence::Worse:
3982 // Cand1 can't be better than Cand2.
3985 case ImplicitConversionSequence::Indistinguishable:
3991 // -- for some argument j, ICSj(F1) is a better conversion sequence than
3992 // ICSj(F2), or, if not that,
3993 if (HasBetterConversion)
3996 // - F1 is a non-template function and F2 is a function template
3997 // specialization, or, if not that,
3998 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3999 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4002 // -- F1 and F2 are function template specializations, and the function
4003 // template for F1 is more specialized than the template for F2
4004 // according to the partial ordering rules described in 14.5.5.2, or,
4006 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4007 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4008 if (FunctionTemplateDecl *BetterTemplate
4009 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4010 Cand2.Function->getPrimaryTemplate(),
4011 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4013 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
4015 // -- the context is an initialization by user-defined conversion
4016 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4017 // from the return type of F1 to the destination type (i.e.,
4018 // the type of the entity being initialized) is a better
4019 // conversion sequence than the standard conversion sequence
4020 // from the return type of F2 to the destination type.
4021 if (Cand1.Function && Cand2.Function &&
4022 isa<CXXConversionDecl>(Cand1.Function) &&
4023 isa<CXXConversionDecl>(Cand2.Function)) {
4024 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4025 Cand2.FinalConversion)) {
4026 case ImplicitConversionSequence::Better:
4027 // Cand1 has a better conversion sequence.
4030 case ImplicitConversionSequence::Worse:
4031 // Cand1 can't be better than Cand2.
4034 case ImplicitConversionSequence::Indistinguishable:
4043 /// \brief Computes the best viable function (C++ 13.3.3)
4044 /// within an overload candidate set.
4046 /// \param CandidateSet the set of candidate functions.
4048 /// \param Loc the location of the function name (or operator symbol) for
4049 /// which overload resolution occurs.
4051 /// \param Best f overload resolution was successful or found a deleted
4052 /// function, Best points to the candidate function found.
4054 /// \returns The result of overload resolution.
4055 Sema::OverloadingResult
4056 Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4058 OverloadCandidateSet::iterator& Best) {
4059 // Find the best viable function.
4060 Best = CandidateSet.end();
4061 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4062 Cand != CandidateSet.end(); ++Cand) {
4064 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4069 // If we didn't find any viable functions, abort.
4070 if (Best == CandidateSet.end())
4071 return OR_No_Viable_Function;
4073 // Make sure that this function is better than every other viable
4074 // function. If not, we have an ambiguity.
4075 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4076 Cand != CandidateSet.end(); ++Cand) {
4079 !isBetterOverloadCandidate(*Best, *Cand)) {
4080 Best = CandidateSet.end();
4081 return OR_Ambiguous;
4085 // Best is the best viable function.
4086 if (Best->Function &&
4087 (Best->Function->isDeleted() ||
4088 Best->Function->getAttr<UnavailableAttr>()))
4091 // C++ [basic.def.odr]p2:
4092 // An overloaded function is used if it is selected by overload resolution
4093 // when referred to from a potentially-evaluated expression. [Note: this
4094 // covers calls to named functions (5.2.2), operator overloading
4095 // (clause 13), user-defined conversions (12.3.2), allocation function for
4096 // placement new (5.3.4), as well as non-default initialization (8.5).
4098 MarkDeclarationReferenced(Loc, Best->Function);
4102 /// PrintOverloadCandidates - When overload resolution fails, prints
4103 /// diagnostic messages containing the candidates in the candidate
4104 /// set. If OnlyViable is true, only viable candidates will be printed.
4106 Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
4109 SourceLocation OpLoc) {
4110 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4111 LastCand = CandidateSet.end();
4112 bool Reported = false;
4113 for (; Cand != LastCand; ++Cand) {
4114 if (Cand->Viable || !OnlyViable) {
4115 if (Cand->Function) {
4116 if (Cand->Function->isDeleted() ||
4117 Cand->Function->getAttr<UnavailableAttr>()) {
4118 // Deleted or "unavailable" function.
4119 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
4120 << Cand->Function->isDeleted();
4121 } else if (FunctionTemplateDecl *FunTmpl
4122 = Cand->Function->getPrimaryTemplate()) {
4123 // Function template specialization
4124 // FIXME: Give a better reason!
4125 Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
4126 << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
4127 *Cand->Function->getTemplateSpecializationArgs());
4130 bool errReported = false;
4131 if (!Cand->Viable && Cand->Conversions.size() > 0) {
4132 for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
4133 const ImplicitConversionSequence &Conversion =
4134 Cand->Conversions[i];
4135 if ((Conversion.ConversionKind !=
4136 ImplicitConversionSequence::BadConversion) ||
4137 Conversion.ConversionFunctionSet.size() == 0)
4139 Diag(Cand->Function->getLocation(),
4140 diag::err_ovl_candidate_not_viable) << (i+1);
4142 for (int j = Conversion.ConversionFunctionSet.size()-1;
4144 FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
4145 Diag(Func->getLocation(), diag::err_ovl_candidate);
4150 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
4152 } else if (Cand->IsSurrogate) {
4153 // Desugar the type of the surrogate down to a function type,
4154 // retaining as many typedefs as possible while still showing
4155 // the function type (and, therefore, its parameter types).
4156 QualType FnType = Cand->Surrogate->getConversionType();
4157 bool isLValueReference = false;
4158 bool isRValueReference = false;
4159 bool isPointer = false;
4160 if (const LValueReferenceType *FnTypeRef =
4161 FnType->getAs<LValueReferenceType>()) {
4162 FnType = FnTypeRef->getPointeeType();
4163 isLValueReference = true;
4164 } else if (const RValueReferenceType *FnTypeRef =
4165 FnType->getAs<RValueReferenceType>()) {
4166 FnType = FnTypeRef->getPointeeType();
4167 isRValueReference = true;
4169 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4170 FnType = FnTypePtr->getPointeeType();
4173 // Desugar down to a function type.
4174 FnType = QualType(FnType->getAs<FunctionType>(), 0);
4175 // Reconstruct the pointer/reference as appropriate.
4176 if (isPointer) FnType = Context.getPointerType(FnType);
4177 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
4178 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
4180 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
4182 } else if (OnlyViable) {
4183 assert(Cand->Conversions.size() <= 2 &&
4184 "builtin-binary-operator-not-binary");
4185 std::string TypeStr("operator");
4188 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4189 if (Cand->Conversions.size() == 1) {
4191 Diag(OpLoc, diag::err_ovl_builtin_unary_candidate) << TypeStr;
4195 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4197 Diag(OpLoc, diag::err_ovl_builtin_binary_candidate) << TypeStr;
4200 else if (!Cand->Viable && !Reported) {
4201 // Non-viability might be due to ambiguous user-defined conversions,
4202 // needed for built-in operators. Report them as well, but only once
4203 // as we have typically many built-in candidates.
4204 unsigned NoOperands = Cand->Conversions.size();
4205 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
4206 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
4207 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion ||
4208 ICS.ConversionFunctionSet.empty())
4210 if (CXXConversionDecl *Func = dyn_cast<CXXConversionDecl>(
4211 Cand->Conversions[ArgIdx].ConversionFunctionSet[0])) {
4214 static_cast<Type*>(ICS.UserDefined.Before.FromTypePtr),0);
4215 Diag(OpLoc,diag::note_ambiguous_type_conversion)
4216 << FromTy << Func->getConversionType();
4218 for (unsigned j = 0; j < ICS.ConversionFunctionSet.size(); j++) {
4219 FunctionDecl *Func =
4220 Cand->Conversions[ArgIdx].ConversionFunctionSet[j];
4221 Diag(Func->getLocation(),diag::err_ovl_candidate);
4230 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4231 /// an overloaded function (C++ [over.over]), where @p From is an
4232 /// expression with overloaded function type and @p ToType is the type
4233 /// we're trying to resolve to. For example:
4239 /// int (*pfd)(double) = f; // selects f(double)
4242 /// This routine returns the resulting FunctionDecl if it could be
4243 /// resolved, and NULL otherwise. When @p Complain is true, this
4244 /// routine will emit diagnostics if there is an error.
4246 Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
4248 QualType FunctionType = ToType;
4249 bool IsMember = false;
4250 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
4251 FunctionType = ToTypePtr->getPointeeType();
4252 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
4253 FunctionType = ToTypeRef->getPointeeType();
4254 else if (const MemberPointerType *MemTypePtr =
4255 ToType->getAs<MemberPointerType>()) {
4256 FunctionType = MemTypePtr->getPointeeType();
4260 // We only look at pointers or references to functions.
4261 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
4262 if (!FunctionType->isFunctionType())
4265 // Find the actual overloaded function declaration.
4266 OverloadedFunctionDecl *Ovl = 0;
4268 // C++ [over.over]p1:
4269 // [...] [Note: any redundant set of parentheses surrounding the
4270 // overloaded function name is ignored (5.1). ]
4271 Expr *OvlExpr = From->IgnoreParens();
4273 // C++ [over.over]p1:
4274 // [...] The overloaded function name can be preceded by the &
4276 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4277 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4278 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4281 bool HasExplicitTemplateArgs = false;
4282 const TemplateArgumentLoc *ExplicitTemplateArgs = 0;
4283 unsigned NumExplicitTemplateArgs = 0;
4285 // Try to dig out the overloaded function.
4286 FunctionTemplateDecl *FunctionTemplate = 0;
4287 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
4288 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
4289 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
4290 HasExplicitTemplateArgs = DR->hasExplicitTemplateArgumentList();
4291 ExplicitTemplateArgs = DR->getTemplateArgs();
4292 NumExplicitTemplateArgs = DR->getNumTemplateArgs();
4293 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(OvlExpr)) {
4294 Ovl = dyn_cast<OverloadedFunctionDecl>(ME->getMemberDecl());
4295 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(ME->getMemberDecl());
4296 HasExplicitTemplateArgs = ME->hasExplicitTemplateArgumentList();
4297 ExplicitTemplateArgs = ME->getTemplateArgs();
4298 NumExplicitTemplateArgs = ME->getNumTemplateArgs();
4299 } else if (TemplateIdRefExpr *TIRE = dyn_cast<TemplateIdRefExpr>(OvlExpr)) {
4300 TemplateName Name = TIRE->getTemplateName();
4301 Ovl = Name.getAsOverloadedFunctionDecl();
4303 dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4305 HasExplicitTemplateArgs = true;
4306 ExplicitTemplateArgs = TIRE->getTemplateArgs();
4307 NumExplicitTemplateArgs = TIRE->getNumTemplateArgs();
4310 // If there's no overloaded function declaration or function template,
4312 if (!Ovl && !FunctionTemplate)
4315 OverloadIterator Fun;
4319 Fun = FunctionTemplate;
4321 // Look through all of the overloaded functions, searching for one
4322 // whose type matches exactly.
4323 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
4324 bool FoundNonTemplateFunction = false;
4325 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
4326 // C++ [over.over]p3:
4327 // Non-member functions and static member functions match
4328 // targets of type "pointer-to-function" or "reference-to-function."
4329 // Nonstatic member functions match targets of
4330 // type "pointer-to-member-function."
4331 // Note that according to DR 247, the containing class does not matter.
4333 if (FunctionTemplateDecl *FunctionTemplate
4334 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
4335 if (CXXMethodDecl *Method
4336 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
4337 // Skip non-static function templates when converting to pointer, and
4338 // static when converting to member pointer.
4339 if (Method->isStatic() == IsMember)
4341 } else if (IsMember)
4344 // C++ [over.over]p2:
4345 // If the name is a function template, template argument deduction is
4346 // done (14.8.2.2), and if the argument deduction succeeds, the
4347 // resulting template argument list is used to generate a single
4348 // function template specialization, which is added to the set of
4349 // overloaded functions considered.
4350 // FIXME: We don't really want to build the specialization here, do we?
4351 FunctionDecl *Specialization = 0;
4352 TemplateDeductionInfo Info(Context);
4353 if (TemplateDeductionResult Result
4354 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
4355 ExplicitTemplateArgs,
4356 NumExplicitTemplateArgs,
4357 FunctionType, Specialization, Info)) {
4358 // FIXME: make a note of the failed deduction for diagnostics.
4361 // FIXME: If the match isn't exact, shouldn't we just drop this as
4362 // a candidate? Find a testcase before changing the code.
4364 == Context.getCanonicalType(Specialization->getType()));
4366 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
4370 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
4371 // Skip non-static functions when converting to pointer, and static
4372 // when converting to member pointer.
4373 if (Method->isStatic() == IsMember)
4376 // If we have explicit template arguments, skip non-templates.
4377 if (HasExplicitTemplateArgs)
4379 } else if (IsMember)
4382 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
4383 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
4384 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
4385 FoundNonTemplateFunction = true;
4390 // If there were 0 or 1 matches, we're done.
4391 if (Matches.empty())
4393 else if (Matches.size() == 1) {
4394 FunctionDecl *Result = *Matches.begin();
4395 MarkDeclarationReferenced(From->getLocStart(), Result);
4399 // C++ [over.over]p4:
4400 // If more than one function is selected, [...]
4401 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
4402 if (!FoundNonTemplateFunction) {
4403 // [...] and any given function template specialization F1 is
4404 // eliminated if the set contains a second function template
4405 // specialization whose function template is more specialized
4406 // than the function template of F1 according to the partial
4407 // ordering rules of 14.5.5.2.
4409 // The algorithm specified above is quadratic. We instead use a
4410 // two-pass algorithm (similar to the one used to identify the
4411 // best viable function in an overload set) that identifies the
4412 // best function template (if it exists).
4413 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
4415 FunctionDecl *Result =
4416 getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4417 TPOC_Other, From->getLocStart(),
4419 PDiag(diag::err_addr_ovl_ambiguous)
4420 << TemplateMatches[0]->getDeclName(),
4421 PDiag(diag::err_ovl_template_candidate));
4422 MarkDeclarationReferenced(From->getLocStart(), Result);
4426 // [...] any function template specializations in the set are
4427 // eliminated if the set also contains a non-template function, [...]
4428 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4429 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4430 if ((*M)->getPrimaryTemplate() == 0)
4431 RemainingMatches.push_back(*M);
4433 // [...] After such eliminations, if any, there shall remain exactly one
4434 // selected function.
4435 if (RemainingMatches.size() == 1) {
4436 FunctionDecl *Result = RemainingMatches.front();
4437 MarkDeclarationReferenced(From->getLocStart(), Result);
4441 // FIXME: We should probably return the same thing that BestViableFunction
4442 // returns (even if we issue the diagnostics here).
4443 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4444 << RemainingMatches[0]->getDeclName();
4445 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4446 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
4450 /// \brief Add a single candidate to the overload set.
4451 static void AddOverloadedCallCandidate(Sema &S,
4452 AnyFunctionDecl Callee,
4453 bool &ArgumentDependentLookup,
4454 bool HasExplicitTemplateArgs,
4455 const TemplateArgumentLoc *ExplicitTemplateArgs,
4456 unsigned NumExplicitTemplateArgs,
4457 Expr **Args, unsigned NumArgs,
4458 OverloadCandidateSet &CandidateSet,
4459 bool PartialOverloading) {
4460 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
4461 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
4462 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4463 PartialOverloading);
4465 if (Func->getDeclContext()->isRecord() ||
4466 Func->getDeclContext()->isFunctionOrMethod())
4467 ArgumentDependentLookup = false;
4471 FunctionTemplateDecl *FuncTemplate = cast<FunctionTemplateDecl>(Callee);
4472 S.AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4473 ExplicitTemplateArgs,
4474 NumExplicitTemplateArgs,
4475 Args, NumArgs, CandidateSet);
4477 if (FuncTemplate->getDeclContext()->isRecord())
4478 ArgumentDependentLookup = false;
4481 /// \brief Add the overload candidates named by callee and/or found by argument
4482 /// dependent lookup to the given overload set.
4483 void Sema::AddOverloadedCallCandidates(NamedDecl *Callee,
4484 DeclarationName &UnqualifiedName,
4485 bool &ArgumentDependentLookup,
4486 bool HasExplicitTemplateArgs,
4487 const TemplateArgumentLoc *ExplicitTemplateArgs,
4488 unsigned NumExplicitTemplateArgs,
4489 Expr **Args, unsigned NumArgs,
4490 OverloadCandidateSet &CandidateSet,
4491 bool PartialOverloading) {
4492 // Add the functions denoted by Callee to the set of candidate
4493 // functions. While we're doing so, track whether argument-dependent
4494 // lookup still applies, per:
4496 // C++0x [basic.lookup.argdep]p3:
4497 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4498 // and let Y be the lookup set produced by argument dependent
4499 // lookup (defined as follows). If X contains
4501 // -- a declaration of a class member, or
4503 // -- a block-scope function declaration that is not a
4504 // using-declaration (FIXME: check for using declaration), or
4506 // -- a declaration that is neither a function or a function
4512 } else if (OverloadedFunctionDecl *Ovl
4513 = dyn_cast<OverloadedFunctionDecl>(Callee)) {
4514 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4515 FuncEnd = Ovl->function_end();
4516 Func != FuncEnd; ++Func)
4517 AddOverloadedCallCandidate(*this, *Func, ArgumentDependentLookup,
4518 HasExplicitTemplateArgs,
4519 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4520 Args, NumArgs, CandidateSet,
4521 PartialOverloading);
4522 } else if (isa<FunctionDecl>(Callee) || isa<FunctionTemplateDecl>(Callee))
4523 AddOverloadedCallCandidate(*this,
4524 AnyFunctionDecl::getFromNamedDecl(Callee),
4525 ArgumentDependentLookup,
4526 HasExplicitTemplateArgs,
4527 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4528 Args, NumArgs, CandidateSet,
4529 PartialOverloading);
4530 // FIXME: assert isa<FunctionDecl> || isa<FunctionTemplateDecl> rather than
4531 // checking dynamically.
4534 UnqualifiedName = Callee->getDeclName();
4536 if (ArgumentDependentLookup)
4537 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
4538 HasExplicitTemplateArgs,
4539 ExplicitTemplateArgs,
4540 NumExplicitTemplateArgs,
4542 PartialOverloading);
4545 /// ResolveOverloadedCallFn - Given the call expression that calls Fn
4546 /// (which eventually refers to the declaration Func) and the call
4547 /// arguments Args/NumArgs, attempt to resolve the function call down
4548 /// to a specific function. If overload resolution succeeds, returns
4549 /// the function declaration produced by overload
4550 /// resolution. Otherwise, emits diagnostics, deletes all of the
4551 /// arguments and Fn, and returns NULL.
4552 FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
4553 DeclarationName UnqualifiedName,
4554 bool HasExplicitTemplateArgs,
4555 const TemplateArgumentLoc *ExplicitTemplateArgs,
4556 unsigned NumExplicitTemplateArgs,
4557 SourceLocation LParenLoc,
4558 Expr **Args, unsigned NumArgs,
4559 SourceLocation *CommaLocs,
4560 SourceLocation RParenLoc,
4561 bool &ArgumentDependentLookup) {
4562 OverloadCandidateSet CandidateSet;
4564 // Add the functions denoted by Callee to the set of candidate
4566 AddOverloadedCallCandidates(Callee, UnqualifiedName, ArgumentDependentLookup,
4567 HasExplicitTemplateArgs, ExplicitTemplateArgs,
4568 NumExplicitTemplateArgs, Args, NumArgs,
4570 OverloadCandidateSet::iterator Best;
4571 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
4573 return Best->Function;
4575 case OR_No_Viable_Function:
4576 Diag(Fn->getSourceRange().getBegin(),
4577 diag::err_ovl_no_viable_function_in_call)
4578 << UnqualifiedName << Fn->getSourceRange();
4579 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4583 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
4584 << UnqualifiedName << Fn->getSourceRange();
4585 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4589 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4590 << Best->Function->isDeleted()
4592 << Fn->getSourceRange();
4593 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4597 // Overload resolution failed. Destroy all of the subexpressions and
4599 Fn->Destroy(Context);
4600 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4601 Args[Arg]->Destroy(Context);
4605 /// \brief Create a unary operation that may resolve to an overloaded
4608 /// \param OpLoc The location of the operator itself (e.g., '*').
4610 /// \param OpcIn The UnaryOperator::Opcode that describes this
4613 /// \param Functions The set of non-member functions that will be
4614 /// considered by overload resolution. The caller needs to build this
4615 /// set based on the context using, e.g.,
4616 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4617 /// set should not contain any member functions; those will be added
4618 /// by CreateOverloadedUnaryOp().
4620 /// \param input The input argument.
4621 Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4623 FunctionSet &Functions,
4625 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4626 Expr *Input = (Expr *)input.get();
4628 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4629 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4630 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4632 Expr *Args[2] = { Input, 0 };
4633 unsigned NumArgs = 1;
4635 // For post-increment and post-decrement, add the implicit '0' as
4636 // the second argument, so that we know this is a post-increment or
4638 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4639 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
4640 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
4645 if (Input->isTypeDependent()) {
4646 OverloadedFunctionDecl *Overloads
4647 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4648 for (FunctionSet::iterator Func = Functions.begin(),
4649 FuncEnd = Functions.end();
4650 Func != FuncEnd; ++Func)
4651 Overloads->addOverload(*Func);
4653 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4654 OpLoc, false, false);
4657 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4659 Context.DependentTy,
4663 // Build an empty overload set.
4664 OverloadCandidateSet CandidateSet;
4666 // Add the candidates from the given function set.
4667 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4669 // Add operator candidates that are member functions.
4670 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4672 // Add builtin operator candidates.
4673 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4675 // Perform overload resolution.
4676 OverloadCandidateSet::iterator Best;
4677 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
4679 // We found a built-in operator or an overloaded operator.
4680 FunctionDecl *FnDecl = Best->Function;
4683 // We matched an overloaded operator. Build a call to that
4686 // Convert the arguments.
4687 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4688 if (PerformObjectArgumentInitialization(Input, Method))
4691 // Convert the arguments.
4692 if (PerformCopyInitialization(Input,
4693 FnDecl->getParamDecl(0)->getType(),
4698 // Determine the result type
4699 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
4701 // Build the actual expression node.
4702 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4704 UsualUnaryConversions(FnExpr);
4708 ExprOwningPtr<CallExpr> TheCall(this,
4709 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4710 &Input, 1, ResultTy, OpLoc));
4712 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4716 return MaybeBindToTemporary(TheCall.release());
4718 // We matched a built-in operator. Convert the arguments, then
4719 // break out so that we will build the appropriate built-in
4721 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4722 Best->Conversions[0], "passing"))
4729 case OR_No_Viable_Function:
4730 // No viable function; fall through to handling this as a
4731 // built-in operator, which will produce an error message for us.
4735 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4736 << UnaryOperator::getOpcodeStr(Opc)
4737 << Input->getSourceRange();
4738 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4739 UnaryOperator::getOpcodeStr(Opc), OpLoc);
4743 Diag(OpLoc, diag::err_ovl_deleted_oper)
4744 << Best->Function->isDeleted()
4745 << UnaryOperator::getOpcodeStr(Opc)
4746 << Input->getSourceRange();
4747 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4751 // Either we found no viable overloaded operator or we matched a
4752 // built-in operator. In either case, fall through to trying to
4753 // build a built-in operation.
4755 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4758 /// \brief Create a binary operation that may resolve to an overloaded
4761 /// \param OpLoc The location of the operator itself (e.g., '+').
4763 /// \param OpcIn The BinaryOperator::Opcode that describes this
4766 /// \param Functions The set of non-member functions that will be
4767 /// considered by overload resolution. The caller needs to build this
4768 /// set based on the context using, e.g.,
4769 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4770 /// set should not contain any member functions; those will be added
4771 /// by CreateOverloadedBinOp().
4773 /// \param LHS Left-hand argument.
4774 /// \param RHS Right-hand argument.
4775 Sema::OwningExprResult
4776 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
4778 FunctionSet &Functions,
4779 Expr *LHS, Expr *RHS) {
4780 Expr *Args[2] = { LHS, RHS };
4781 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
4783 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4784 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4785 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4787 // If either side is type-dependent, create an appropriate dependent
4789 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
4790 // .* cannot be overloaded.
4791 if (Opc == BinaryOperator::PtrMemD)
4792 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
4793 Context.DependentTy, OpLoc));
4795 OverloadedFunctionDecl *Overloads
4796 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4797 for (FunctionSet::iterator Func = Functions.begin(),
4798 FuncEnd = Functions.end();
4799 Func != FuncEnd; ++Func)
4800 Overloads->addOverload(*Func);
4802 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4803 OpLoc, false, false);
4805 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4807 Context.DependentTy,
4811 // If this is the .* operator, which is not overloadable, just
4812 // create a built-in binary operator.
4813 if (Opc == BinaryOperator::PtrMemD)
4814 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
4816 // If this is one of the assignment operators, we only perform
4817 // overload resolution if the left-hand side is a class or
4818 // enumeration type (C++ [expr.ass]p3).
4819 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
4820 !Args[0]->getType()->isOverloadableType())
4821 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
4823 // Build an empty overload set.
4824 OverloadCandidateSet CandidateSet;
4826 // Add the candidates from the given function set.
4827 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4829 // Add operator candidates that are member functions.
4830 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4832 // Add builtin operator candidates.
4833 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4835 // Perform overload resolution.
4836 OverloadCandidateSet::iterator Best;
4837 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
4839 // We found a built-in operator or an overloaded operator.
4840 FunctionDecl *FnDecl = Best->Function;
4843 // We matched an overloaded operator. Build a call to that
4846 // Convert the arguments.
4847 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4848 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4849 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
4853 // Convert the arguments.
4854 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
4856 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
4861 // Determine the result type
4863 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
4864 ResultTy = ResultTy.getNonReferenceType();
4866 // Build the actual expression node.
4867 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4869 UsualUnaryConversions(FnExpr);
4871 ExprOwningPtr<CXXOperatorCallExpr>
4872 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4876 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4880 return MaybeBindToTemporary(TheCall.release());
4882 // We matched a built-in operator. Convert the arguments, then
4883 // break out so that we will build the appropriate built-in
4885 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
4886 Best->Conversions[0], "passing") ||
4887 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
4888 Best->Conversions[1], "passing"))
4895 case OR_No_Viable_Function: {
4896 // C++ [over.match.oper]p9:
4897 // If the operator is the operator , [...] and there are no
4898 // viable functions, then the operator is assumed to be the
4899 // built-in operator and interpreted according to clause 5.
4900 if (Opc == BinaryOperator::Comma)
4903 // For class as left operand for assignment or compound assigment operator
4904 // do not fall through to handling in built-in, but report that no overloaded
4905 // assignment operator found
4906 OwningExprResult Result = ExprError();
4907 if (Args[0]->getType()->isRecordType() &&
4908 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
4909 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4910 << BinaryOperator::getOpcodeStr(Opc)
4911 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
4913 // No viable function; try to create a built-in operation, which will
4914 // produce an error. Then, show the non-viable candidates.
4915 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
4917 assert(Result.isInvalid() &&
4918 "C++ binary operator overloading is missing candidates!");
4919 if (Result.isInvalid())
4920 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
4921 BinaryOperator::getOpcodeStr(Opc), OpLoc);
4922 return move(Result);
4926 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4927 << BinaryOperator::getOpcodeStr(Opc)
4928 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
4929 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4930 BinaryOperator::getOpcodeStr(Opc), OpLoc);
4934 Diag(OpLoc, diag::err_ovl_deleted_oper)
4935 << Best->Function->isDeleted()
4936 << BinaryOperator::getOpcodeStr(Opc)
4937 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
4938 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4942 // We matched a built-in operator; build it.
4943 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
4946 Action::OwningExprResult
4947 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
4948 SourceLocation RLoc,
4949 ExprArg Base, ExprArg Idx) {
4950 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
4951 static_cast<Expr*>(Idx.get()) };
4952 DeclarationName OpName =
4953 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
4955 // If either side is type-dependent, create an appropriate dependent
4957 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
4959 OverloadedFunctionDecl *Overloads
4960 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4962 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4963 LLoc, false, false);
4967 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
4969 Context.DependentTy,
4973 // Build an empty overload set.
4974 OverloadCandidateSet CandidateSet;
4976 // Subscript can only be overloaded as a member function.
4978 // Add operator candidates that are member functions.
4979 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
4981 // Add builtin operator candidates.
4982 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
4984 // Perform overload resolution.
4985 OverloadCandidateSet::iterator Best;
4986 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
4988 // We found a built-in operator or an overloaded operator.
4989 FunctionDecl *FnDecl = Best->Function;
4992 // We matched an overloaded operator. Build a call to that
4995 // Convert the arguments.
4996 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
4997 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4998 PerformCopyInitialization(Args[1],
4999 FnDecl->getParamDecl(0)->getType(),
5003 // Determine the result type
5005 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5006 ResultTy = ResultTy.getNonReferenceType();
5008 // Build the actual expression node.
5009 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5011 UsualUnaryConversions(FnExpr);
5015 ExprOwningPtr<CXXOperatorCallExpr>
5016 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5020 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5024 return MaybeBindToTemporary(TheCall.release());
5026 // We matched a built-in operator. Convert the arguments, then
5027 // break out so that we will build the appropriate built-in
5029 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
5030 Best->Conversions[0], "passing") ||
5031 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
5032 Best->Conversions[1], "passing"))
5039 case OR_No_Viable_Function: {
5040 // No viable function; try to create a built-in operation, which will
5041 // produce an error. Then, show the non-viable candidates.
5042 OwningExprResult Result =
5043 CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
5044 assert(Result.isInvalid() &&
5045 "C++ subscript operator overloading is missing candidates!");
5046 if (Result.isInvalid())
5047 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5049 return move(Result);
5053 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5054 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5055 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5060 Diag(LLoc, diag::err_ovl_deleted_oper)
5061 << Best->Function->isDeleted() << "[]"
5062 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5063 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5067 // We matched a built-in operator; build it.
5070 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5071 Owned(Args[1]), RLoc);
5074 /// BuildCallToMemberFunction - Build a call to a member
5075 /// function. MemExpr is the expression that refers to the member
5076 /// function (and includes the object parameter), Args/NumArgs are the
5077 /// arguments to the function call (not including the object
5078 /// parameter). The caller needs to validate that the member
5079 /// expression refers to a member function or an overloaded member
5082 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5083 SourceLocation LParenLoc, Expr **Args,
5084 unsigned NumArgs, SourceLocation *CommaLocs,
5085 SourceLocation RParenLoc) {
5086 // Dig out the member expression. This holds both the object
5087 // argument and the member function we're referring to.
5088 MemberExpr *MemExpr = 0;
5089 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
5090 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
5092 MemExpr = dyn_cast<MemberExpr>(MemExprE);
5093 assert(MemExpr && "Building member call without member expression");
5095 // Extract the object argument.
5096 Expr *ObjectArg = MemExpr->getBase();
5098 CXXMethodDecl *Method = 0;
5099 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
5100 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
5101 // Add overload candidates
5102 OverloadCandidateSet CandidateSet;
5103 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
5105 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
5106 Func != FuncEnd; ++Func) {
5107 if ((Method = dyn_cast<CXXMethodDecl>(*Func))) {
5108 // If explicit template arguments were provided, we can't call a
5109 // non-template member function.
5110 if (MemExpr->hasExplicitTemplateArgumentList())
5113 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
5114 /*SuppressUserConversions=*/false);
5116 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
5117 MemExpr->hasExplicitTemplateArgumentList(),
5118 MemExpr->getTemplateArgs(),
5119 MemExpr->getNumTemplateArgs(),
5120 ObjectArg, Args, NumArgs,
5122 /*SuppressUsedConversions=*/false);
5125 OverloadCandidateSet::iterator Best;
5126 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
5128 Method = cast<CXXMethodDecl>(Best->Function);
5131 case OR_No_Viable_Function:
5132 Diag(MemExpr->getSourceRange().getBegin(),
5133 diag::err_ovl_no_viable_member_function_in_call)
5134 << DeclName << MemExprE->getSourceRange();
5135 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5136 // FIXME: Leaking incoming expressions!
5140 Diag(MemExpr->getSourceRange().getBegin(),
5141 diag::err_ovl_ambiguous_member_call)
5142 << DeclName << MemExprE->getSourceRange();
5143 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5144 // FIXME: Leaking incoming expressions!
5148 Diag(MemExpr->getSourceRange().getBegin(),
5149 diag::err_ovl_deleted_member_call)
5150 << Best->Function->isDeleted()
5151 << DeclName << MemExprE->getSourceRange();
5152 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5153 // FIXME: Leaking incoming expressions!
5157 FixOverloadedFunctionReference(MemExpr, Method);
5159 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5162 assert(Method && "Member call to something that isn't a method?");
5163 ExprOwningPtr<CXXMemberCallExpr>
5164 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
5166 Method->getResultType().getNonReferenceType(),
5169 // Check for a valid return type.
5170 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5171 TheCall.get(), Method))
5174 // Convert the object argument (for a non-static member function call).
5175 if (!Method->isStatic() &&
5176 PerformObjectArgumentInitialization(ObjectArg, Method))
5178 MemExpr->setBase(ObjectArg);
5180 // Convert the rest of the arguments
5181 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
5182 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
5186 if (CheckFunctionCall(Method, TheCall.get()))
5189 return MaybeBindToTemporary(TheCall.release()).release();
5192 /// BuildCallToObjectOfClassType - Build a call to an object of class
5193 /// type (C++ [over.call.object]), which can end up invoking an
5194 /// overloaded function call operator (@c operator()) or performing a
5195 /// user-defined conversion on the object argument.
5197 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
5198 SourceLocation LParenLoc,
5199 Expr **Args, unsigned NumArgs,
5200 SourceLocation *CommaLocs,
5201 SourceLocation RParenLoc) {
5202 assert(Object->getType()->isRecordType() && "Requires object type argument");
5203 const RecordType *Record = Object->getType()->getAs<RecordType>();
5205 // C++ [over.call.object]p1:
5206 // If the primary-expression E in the function call syntax
5207 // evaluates to a class object of type "cv T", then the set of
5208 // candidate functions includes at least the function call
5209 // operators of T. The function call operators of T are obtained by
5210 // ordinary lookup of the name operator() in the context of
5212 OverloadCandidateSet CandidateSet;
5213 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
5214 DeclContext::lookup_const_iterator Oper, OperEnd;
5215 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
5216 Oper != OperEnd; ++Oper)
5217 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
5218 CandidateSet, /*SuppressUserConversions=*/false);
5220 if (RequireCompleteType(LParenLoc, Object->getType(),
5221 PartialDiagnostic(diag::err_incomplete_object_call)
5222 << Object->getSourceRange()))
5225 // C++ [over.call.object]p2:
5226 // In addition, for each conversion function declared in T of the
5229 // operator conversion-type-id () cv-qualifier;
5231 // where cv-qualifier is the same cv-qualification as, or a
5232 // greater cv-qualification than, cv, and where conversion-type-id
5233 // denotes the type "pointer to function of (P1,...,Pn) returning
5234 // R", or the type "reference to pointer to function of
5235 // (P1,...,Pn) returning R", or the type "reference to function
5236 // of (P1,...,Pn) returning R", a surrogate call function [...]
5237 // is also considered as a candidate function. Similarly,
5238 // surrogate call functions are added to the set of candidate
5239 // functions for each conversion function declared in an
5240 // accessible base class provided the function is not hidden
5241 // within T by another intervening declaration.
5242 // FIXME: Look in base classes for more conversion operators!
5243 OverloadedFunctionDecl *Conversions
5244 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
5245 for (OverloadedFunctionDecl::function_iterator
5246 Func = Conversions->function_begin(),
5247 FuncEnd = Conversions->function_end();
5248 Func != FuncEnd; ++Func) {
5249 CXXConversionDecl *Conv;
5250 FunctionTemplateDecl *ConvTemplate;
5251 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
5253 // Skip over templated conversion functions; they aren't
5258 // Strip the reference type (if any) and then the pointer type (if
5259 // any) to get down to what might be a function type.
5260 QualType ConvType = Conv->getConversionType().getNonReferenceType();
5261 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5262 ConvType = ConvPtrType->getPointeeType();
5264 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
5265 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
5268 // Perform overload resolution.
5269 OverloadCandidateSet::iterator Best;
5270 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
5272 // Overload resolution succeeded; we'll build the appropriate call
5276 case OR_No_Viable_Function:
5277 Diag(Object->getSourceRange().getBegin(),
5278 diag::err_ovl_no_viable_object_call)
5279 << Object->getType() << Object->getSourceRange();
5280 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5284 Diag(Object->getSourceRange().getBegin(),
5285 diag::err_ovl_ambiguous_object_call)
5286 << Object->getType() << Object->getSourceRange();
5287 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5291 Diag(Object->getSourceRange().getBegin(),
5292 diag::err_ovl_deleted_object_call)
5293 << Best->Function->isDeleted()
5294 << Object->getType() << Object->getSourceRange();
5295 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5299 if (Best == CandidateSet.end()) {
5300 // We had an error; delete all of the subexpressions and return
5302 Object->Destroy(Context);
5303 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5304 Args[ArgIdx]->Destroy(Context);
5308 if (Best->Function == 0) {
5309 // Since there is no function declaration, this is one of the
5310 // surrogate candidates. Dig out the conversion function.
5311 CXXConversionDecl *Conv
5312 = cast<CXXConversionDecl>(
5313 Best->Conversions[0].UserDefined.ConversionFunction);
5315 // We selected one of the surrogate functions that converts the
5316 // object parameter to a function pointer. Perform the conversion
5317 // on the object argument, then let ActOnCallExpr finish the job.
5319 // Create an implicit member expr to refer to the conversion operator.
5320 // and then call it.
5321 CXXMemberCallExpr *CE =
5322 BuildCXXMemberCallExpr(Object, Conv);
5324 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
5325 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
5326 CommaLocs, RParenLoc).release();
5329 // We found an overloaded operator(). Build a CXXOperatorCallExpr
5330 // that calls this method, using Object for the implicit object
5331 // parameter and passing along the remaining arguments.
5332 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
5333 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
5335 unsigned NumArgsInProto = Proto->getNumArgs();
5336 unsigned NumArgsToCheck = NumArgs;
5338 // Build the full argument list for the method call (the
5339 // implicit object parameter is placed at the beginning of the
5342 if (NumArgs < NumArgsInProto) {
5343 NumArgsToCheck = NumArgsInProto;
5344 MethodArgs = new Expr*[NumArgsInProto + 1];
5346 MethodArgs = new Expr*[NumArgs + 1];
5348 MethodArgs[0] = Object;
5349 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5350 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
5352 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
5354 UsualUnaryConversions(NewFn);
5356 // Once we've built TheCall, all of the expressions are properly
5358 QualType ResultTy = Method->getResultType().getNonReferenceType();
5359 ExprOwningPtr<CXXOperatorCallExpr>
5360 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
5361 MethodArgs, NumArgs + 1,
5362 ResultTy, RParenLoc));
5363 delete [] MethodArgs;
5365 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
5369 // We may have default arguments. If so, we need to allocate more
5370 // slots in the call for them.
5371 if (NumArgs < NumArgsInProto)
5372 TheCall->setNumArgs(Context, NumArgsInProto + 1);
5373 else if (NumArgs > NumArgsInProto)
5374 NumArgsToCheck = NumArgsInProto;
5376 bool IsError = false;
5378 // Initialize the implicit object parameter.
5379 IsError |= PerformObjectArgumentInitialization(Object, Method);
5380 TheCall->setArg(0, Object);
5383 // Check the argument types.
5384 for (unsigned i = 0; i != NumArgsToCheck; i++) {
5389 // Pass the argument.
5390 QualType ProtoArgType = Proto->getArgType(i);
5391 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
5393 Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
5396 TheCall->setArg(i + 1, Arg);
5399 // If this is a variadic call, handle args passed through "...".
5400 if (Proto->isVariadic()) {
5401 // Promote the arguments (C99 6.5.2.2p7).
5402 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
5403 Expr *Arg = Args[i];
5404 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
5405 TheCall->setArg(i + 1, Arg);
5409 if (IsError) return true;
5411 if (CheckFunctionCall(Method, TheCall.get()))
5414 return MaybeBindToTemporary(TheCall.release()).release();
5417 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
5418 /// (if one exists), where @c Base is an expression of class type and
5419 /// @c Member is the name of the member we're trying to find.
5420 Sema::OwningExprResult
5421 Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
5422 Expr *Base = static_cast<Expr *>(BaseIn.get());
5423 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
5425 // C++ [over.ref]p1:
5427 // [...] An expression x->m is interpreted as (x.operator->())->m
5428 // for a class object x of type T if T::operator->() exists and if
5429 // the operator is selected as the best match function by the
5430 // overload resolution mechanism (13.3).
5431 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
5432 OverloadCandidateSet CandidateSet;
5433 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
5436 LookupQualifiedName(R, BaseRecord->getDecl(), OpName, LookupOrdinaryName);
5438 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
5439 Oper != OperEnd; ++Oper)
5440 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
5441 /*SuppressUserConversions=*/false);
5443 // Perform overload resolution.
5444 OverloadCandidateSet::iterator Best;
5445 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
5447 // Overload resolution succeeded; we'll build the call below.
5450 case OR_No_Viable_Function:
5451 if (CandidateSet.empty())
5452 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
5453 << Base->getType() << Base->getSourceRange();
5455 Diag(OpLoc, diag::err_ovl_no_viable_oper)
5456 << "operator->" << Base->getSourceRange();
5457 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5461 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5462 << "->" << Base->getSourceRange();
5463 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5467 Diag(OpLoc, diag::err_ovl_deleted_oper)
5468 << Best->Function->isDeleted()
5469 << "->" << Base->getSourceRange();
5470 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5474 // Convert the object parameter.
5475 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
5476 if (PerformObjectArgumentInitialization(Base, Method))
5479 // No concerns about early exits now.
5482 // Build the operator call.
5483 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5485 UsualUnaryConversions(FnExpr);
5487 QualType ResultTy = Method->getResultType().getNonReferenceType();
5488 ExprOwningPtr<CXXOperatorCallExpr>
5489 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
5490 &Base, 1, ResultTy, OpLoc));
5492 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
5495 return move(TheCall);
5498 /// FixOverloadedFunctionReference - E is an expression that refers to
5499 /// a C++ overloaded function (possibly with some parentheses and
5500 /// perhaps a '&' around it). We have resolved the overloaded function
5501 /// to the function declaration Fn, so patch up the expression E to
5502 /// refer (possibly indirectly) to Fn. Returns the new expr.
5503 Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
5504 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
5505 Expr *NewExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
5506 PE->setSubExpr(NewExpr);
5507 PE->setType(NewExpr->getType());
5508 } else if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5509 Expr *NewExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
5510 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
5511 NewExpr->getType()) &&
5512 "Implicit cast type cannot be determined from overload");
5513 ICE->setSubExpr(NewExpr);
5514 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
5515 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
5516 "Can only take the address of an overloaded function");
5517 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5518 if (Method->isStatic()) {
5519 // Do nothing: static member functions aren't any different
5520 // from non-member functions.
5521 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr())) {
5522 if (DRE->getQualifier()) {
5523 // We have taken the address of a pointer to member
5524 // function. Perform the computation here so that we get the
5525 // appropriate pointer to member type.
5527 DRE->setType(Fn->getType());
5529 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
5530 E->setType(Context.getMemberPointerType(Fn->getType(),
5531 ClassType.getTypePtr()));
5535 // FIXME: TemplateIdRefExpr referring to a member function template
5538 Expr *NewExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5539 UnOp->setSubExpr(NewExpr);
5540 UnOp->setType(Context.getPointerType(NewExpr->getType()));
5543 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
5544 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
5545 isa<FunctionTemplateDecl>(DR->getDecl()) ||
5546 isa<FunctionDecl>(DR->getDecl())) &&
5547 "Expected function or function template");
5549 E->setType(Fn->getType());
5550 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
5551 MemExpr->setMemberDecl(Fn);
5552 E->setType(Fn->getType());
5553 } else if (TemplateIdRefExpr *TID = dyn_cast<TemplateIdRefExpr>(E)) {
5554 E = DeclRefExpr::Create(Context,
5555 TID->getQualifier(), TID->getQualifierRange(),
5556 Fn, TID->getTemplateNameLoc(),
5558 TID->getLAngleLoc(),
5559 TID->getTemplateArgs(),
5560 TID->getNumTemplateArgs(),
5561 TID->getRAngleLoc(),
5563 /*FIXME?*/false, /*FIXME?*/false);
5565 // FIXME: Don't destroy TID here, since we need its template arguments
5567 // TID->Destroy(Context);
5568 } else if (isa<UnresolvedFunctionNameExpr>(E)) {
5569 return DeclRefExpr::Create(Context,
5571 /*QualifierRange=*/SourceRange(),
5572 Fn, E->getLocStart(),
5573 Fn->getType(), false, false);
5575 assert(false && "Invalid reference to overloaded function");
5581 } // end namespace clang