rename test
[clang.git] / lib / Sema / SemaOverload.cpp
blob3d0608ea71f3201b16d3de608fd74c3f01252274
1 //===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides Sema routines for C++ overloading.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/Lookup.h"
16 #include "clang/Sema/Initialization.h"
17 #include "clang/Sema/Template.h"
18 #include "clang/Sema/TemplateDeduction.h"
19 #include "clang/Basic/Diagnostic.h"
20 #include "clang/Lex/Preprocessor.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/CXXInheritance.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "llvm/ADT/DenseSet.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include <algorithm>
34 namespace clang {
35 using namespace sema;
37 /// A convenience routine for creating a decayed reference to a
38 /// function.
39 static Expr *
40 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn,
41 SourceLocation Loc = SourceLocation()) {
42 Expr *E = new (S.Context) DeclRefExpr(Fn, Fn->getType(), VK_LValue, Loc);
43 S.DefaultFunctionArrayConversion(E);
44 return E;
47 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
48 bool InOverloadResolution,
49 StandardConversionSequence &SCS,
50 bool CStyle);
51 static OverloadingResult
52 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
53 UserDefinedConversionSequence& User,
54 OverloadCandidateSet& Conversions,
55 bool AllowExplicit);
58 static ImplicitConversionSequence::CompareKind
59 CompareStandardConversionSequences(Sema &S,
60 const StandardConversionSequence& SCS1,
61 const StandardConversionSequence& SCS2);
63 static ImplicitConversionSequence::CompareKind
64 CompareQualificationConversions(Sema &S,
65 const StandardConversionSequence& SCS1,
66 const StandardConversionSequence& SCS2);
68 static ImplicitConversionSequence::CompareKind
69 CompareDerivedToBaseConversions(Sema &S,
70 const StandardConversionSequence& SCS1,
71 const StandardConversionSequence& SCS2);
75 /// GetConversionCategory - Retrieve the implicit conversion
76 /// category corresponding to the given implicit conversion kind.
77 ImplicitConversionCategory
78 GetConversionCategory(ImplicitConversionKind Kind) {
79 static const ImplicitConversionCategory
80 Category[(int)ICK_Num_Conversion_Kinds] = {
81 ICC_Identity,
82 ICC_Lvalue_Transformation,
83 ICC_Lvalue_Transformation,
84 ICC_Lvalue_Transformation,
85 ICC_Identity,
86 ICC_Qualification_Adjustment,
87 ICC_Promotion,
88 ICC_Promotion,
89 ICC_Promotion,
90 ICC_Conversion,
91 ICC_Conversion,
92 ICC_Conversion,
93 ICC_Conversion,
94 ICC_Conversion,
95 ICC_Conversion,
96 ICC_Conversion,
97 ICC_Conversion,
98 ICC_Conversion,
99 ICC_Conversion,
100 ICC_Conversion,
101 ICC_Conversion
103 return Category[(int)Kind];
106 /// GetConversionRank - Retrieve the implicit conversion rank
107 /// corresponding to the given implicit conversion kind.
108 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
109 static const ImplicitConversionRank
110 Rank[(int)ICK_Num_Conversion_Kinds] = {
111 ICR_Exact_Match,
112 ICR_Exact_Match,
113 ICR_Exact_Match,
114 ICR_Exact_Match,
115 ICR_Exact_Match,
116 ICR_Exact_Match,
117 ICR_Promotion,
118 ICR_Promotion,
119 ICR_Promotion,
120 ICR_Conversion,
121 ICR_Conversion,
122 ICR_Conversion,
123 ICR_Conversion,
124 ICR_Conversion,
125 ICR_Conversion,
126 ICR_Conversion,
127 ICR_Conversion,
128 ICR_Conversion,
129 ICR_Conversion,
130 ICR_Conversion,
131 ICR_Complex_Real_Conversion
133 return Rank[(int)Kind];
136 /// GetImplicitConversionName - Return the name of this kind of
137 /// implicit conversion.
138 const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
139 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
140 "No conversion",
141 "Lvalue-to-rvalue",
142 "Array-to-pointer",
143 "Function-to-pointer",
144 "Noreturn adjustment",
145 "Qualification",
146 "Integral promotion",
147 "Floating point promotion",
148 "Complex promotion",
149 "Integral conversion",
150 "Floating conversion",
151 "Complex conversion",
152 "Floating-integral conversion",
153 "Pointer conversion",
154 "Pointer-to-member conversion",
155 "Boolean conversion",
156 "Compatible-types conversion",
157 "Derived-to-base conversion",
158 "Vector conversion",
159 "Vector splat",
160 "Complex-real conversion"
162 return Name[Kind];
165 /// StandardConversionSequence - Set the standard conversion
166 /// sequence to the identity conversion.
167 void StandardConversionSequence::setAsIdentityConversion() {
168 First = ICK_Identity;
169 Second = ICK_Identity;
170 Third = ICK_Identity;
171 DeprecatedStringLiteralToCharPtr = false;
172 ReferenceBinding = false;
173 DirectBinding = false;
174 IsLvalueReference = true;
175 BindsToFunctionLvalue = false;
176 BindsToRvalue = false;
177 BindsImplicitObjectArgumentWithoutRefQualifier = false;
178 CopyConstructor = 0;
181 /// getRank - Retrieve the rank of this standard conversion sequence
182 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
183 /// implicit conversions.
184 ImplicitConversionRank StandardConversionSequence::getRank() const {
185 ImplicitConversionRank Rank = ICR_Exact_Match;
186 if (GetConversionRank(First) > Rank)
187 Rank = GetConversionRank(First);
188 if (GetConversionRank(Second) > Rank)
189 Rank = GetConversionRank(Second);
190 if (GetConversionRank(Third) > Rank)
191 Rank = GetConversionRank(Third);
192 return Rank;
195 /// isPointerConversionToBool - Determines whether this conversion is
196 /// a conversion of a pointer or pointer-to-member to bool. This is
197 /// used as part of the ranking of standard conversion sequences
198 /// (C++ 13.3.3.2p4).
199 bool StandardConversionSequence::isPointerConversionToBool() const {
200 // Note that FromType has not necessarily been transformed by the
201 // array-to-pointer or function-to-pointer implicit conversions, so
202 // check for their presence as well as checking whether FromType is
203 // a pointer.
204 if (getToType(1)->isBooleanType() &&
205 (getFromType()->isPointerType() ||
206 getFromType()->isObjCObjectPointerType() ||
207 getFromType()->isBlockPointerType() ||
208 getFromType()->isNullPtrType() ||
209 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
210 return true;
212 return false;
215 /// isPointerConversionToVoidPointer - Determines whether this
216 /// conversion is a conversion of a pointer to a void pointer. This is
217 /// used as part of the ranking of standard conversion sequences (C++
218 /// 13.3.3.2p4).
219 bool
220 StandardConversionSequence::
221 isPointerConversionToVoidPointer(ASTContext& Context) const {
222 QualType FromType = getFromType();
223 QualType ToType = getToType(1);
225 // Note that FromType has not necessarily been transformed by the
226 // array-to-pointer implicit conversion, so check for its presence
227 // and redo the conversion to get a pointer.
228 if (First == ICK_Array_To_Pointer)
229 FromType = Context.getArrayDecayedType(FromType);
231 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
232 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
233 return ToPtrType->getPointeeType()->isVoidType();
235 return false;
238 /// DebugPrint - Print this standard conversion sequence to standard
239 /// error. Useful for debugging overloading issues.
240 void StandardConversionSequence::DebugPrint() const {
241 llvm::raw_ostream &OS = llvm::errs();
242 bool PrintedSomething = false;
243 if (First != ICK_Identity) {
244 OS << GetImplicitConversionName(First);
245 PrintedSomething = true;
248 if (Second != ICK_Identity) {
249 if (PrintedSomething) {
250 OS << " -> ";
252 OS << GetImplicitConversionName(Second);
254 if (CopyConstructor) {
255 OS << " (by copy constructor)";
256 } else if (DirectBinding) {
257 OS << " (direct reference binding)";
258 } else if (ReferenceBinding) {
259 OS << " (reference binding)";
261 PrintedSomething = true;
264 if (Third != ICK_Identity) {
265 if (PrintedSomething) {
266 OS << " -> ";
268 OS << GetImplicitConversionName(Third);
269 PrintedSomething = true;
272 if (!PrintedSomething) {
273 OS << "No conversions required";
277 /// DebugPrint - Print this user-defined conversion sequence to standard
278 /// error. Useful for debugging overloading issues.
279 void UserDefinedConversionSequence::DebugPrint() const {
280 llvm::raw_ostream &OS = llvm::errs();
281 if (Before.First || Before.Second || Before.Third) {
282 Before.DebugPrint();
283 OS << " -> ";
285 OS << '\'' << ConversionFunction << '\'';
286 if (After.First || After.Second || After.Third) {
287 OS << " -> ";
288 After.DebugPrint();
292 /// DebugPrint - Print this implicit conversion sequence to standard
293 /// error. Useful for debugging overloading issues.
294 void ImplicitConversionSequence::DebugPrint() const {
295 llvm::raw_ostream &OS = llvm::errs();
296 switch (ConversionKind) {
297 case StandardConversion:
298 OS << "Standard conversion: ";
299 Standard.DebugPrint();
300 break;
301 case UserDefinedConversion:
302 OS << "User-defined conversion: ";
303 UserDefined.DebugPrint();
304 break;
305 case EllipsisConversion:
306 OS << "Ellipsis conversion";
307 break;
308 case AmbiguousConversion:
309 OS << "Ambiguous conversion";
310 break;
311 case BadConversion:
312 OS << "Bad conversion";
313 break;
316 OS << "\n";
319 void AmbiguousConversionSequence::construct() {
320 new (&conversions()) ConversionSet();
323 void AmbiguousConversionSequence::destruct() {
324 conversions().~ConversionSet();
327 void
328 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
329 FromTypePtr = O.FromTypePtr;
330 ToTypePtr = O.ToTypePtr;
331 new (&conversions()) ConversionSet(O.conversions());
334 namespace {
335 // Structure used by OverloadCandidate::DeductionFailureInfo to store
336 // template parameter and template argument information.
337 struct DFIParamWithArguments {
338 TemplateParameter Param;
339 TemplateArgument FirstArg;
340 TemplateArgument SecondArg;
344 /// \brief Convert from Sema's representation of template deduction information
345 /// to the form used in overload-candidate information.
346 OverloadCandidate::DeductionFailureInfo
347 static MakeDeductionFailureInfo(ASTContext &Context,
348 Sema::TemplateDeductionResult TDK,
349 TemplateDeductionInfo &Info) {
350 OverloadCandidate::DeductionFailureInfo Result;
351 Result.Result = static_cast<unsigned>(TDK);
352 Result.Data = 0;
353 switch (TDK) {
354 case Sema::TDK_Success:
355 case Sema::TDK_InstantiationDepth:
356 case Sema::TDK_TooManyArguments:
357 case Sema::TDK_TooFewArguments:
358 break;
360 case Sema::TDK_Incomplete:
361 case Sema::TDK_InvalidExplicitArguments:
362 Result.Data = Info.Param.getOpaqueValue();
363 break;
365 case Sema::TDK_Inconsistent:
366 case Sema::TDK_Underqualified: {
367 // FIXME: Should allocate from normal heap so that we can free this later.
368 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
369 Saved->Param = Info.Param;
370 Saved->FirstArg = Info.FirstArg;
371 Saved->SecondArg = Info.SecondArg;
372 Result.Data = Saved;
373 break;
376 case Sema::TDK_SubstitutionFailure:
377 Result.Data = Info.take();
378 break;
380 case Sema::TDK_NonDeducedMismatch:
381 case Sema::TDK_FailedOverloadResolution:
382 break;
385 return Result;
388 void OverloadCandidate::DeductionFailureInfo::Destroy() {
389 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
390 case Sema::TDK_Success:
391 case Sema::TDK_InstantiationDepth:
392 case Sema::TDK_Incomplete:
393 case Sema::TDK_TooManyArguments:
394 case Sema::TDK_TooFewArguments:
395 case Sema::TDK_InvalidExplicitArguments:
396 break;
398 case Sema::TDK_Inconsistent:
399 case Sema::TDK_Underqualified:
400 // FIXME: Destroy the data?
401 Data = 0;
402 break;
404 case Sema::TDK_SubstitutionFailure:
405 // FIXME: Destroy the template arugment list?
406 Data = 0;
407 break;
409 // Unhandled
410 case Sema::TDK_NonDeducedMismatch:
411 case Sema::TDK_FailedOverloadResolution:
412 break;
416 TemplateParameter
417 OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
418 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
419 case Sema::TDK_Success:
420 case Sema::TDK_InstantiationDepth:
421 case Sema::TDK_TooManyArguments:
422 case Sema::TDK_TooFewArguments:
423 case Sema::TDK_SubstitutionFailure:
424 return TemplateParameter();
426 case Sema::TDK_Incomplete:
427 case Sema::TDK_InvalidExplicitArguments:
428 return TemplateParameter::getFromOpaqueValue(Data);
430 case Sema::TDK_Inconsistent:
431 case Sema::TDK_Underqualified:
432 return static_cast<DFIParamWithArguments*>(Data)->Param;
434 // Unhandled
435 case Sema::TDK_NonDeducedMismatch:
436 case Sema::TDK_FailedOverloadResolution:
437 break;
440 return TemplateParameter();
443 TemplateArgumentList *
444 OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
445 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
446 case Sema::TDK_Success:
447 case Sema::TDK_InstantiationDepth:
448 case Sema::TDK_TooManyArguments:
449 case Sema::TDK_TooFewArguments:
450 case Sema::TDK_Incomplete:
451 case Sema::TDK_InvalidExplicitArguments:
452 case Sema::TDK_Inconsistent:
453 case Sema::TDK_Underqualified:
454 return 0;
456 case Sema::TDK_SubstitutionFailure:
457 return static_cast<TemplateArgumentList*>(Data);
459 // Unhandled
460 case Sema::TDK_NonDeducedMismatch:
461 case Sema::TDK_FailedOverloadResolution:
462 break;
465 return 0;
468 const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
469 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
470 case Sema::TDK_Success:
471 case Sema::TDK_InstantiationDepth:
472 case Sema::TDK_Incomplete:
473 case Sema::TDK_TooManyArguments:
474 case Sema::TDK_TooFewArguments:
475 case Sema::TDK_InvalidExplicitArguments:
476 case Sema::TDK_SubstitutionFailure:
477 return 0;
479 case Sema::TDK_Inconsistent:
480 case Sema::TDK_Underqualified:
481 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
483 // Unhandled
484 case Sema::TDK_NonDeducedMismatch:
485 case Sema::TDK_FailedOverloadResolution:
486 break;
489 return 0;
492 const TemplateArgument *
493 OverloadCandidate::DeductionFailureInfo::getSecondArg() {
494 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
495 case Sema::TDK_Success:
496 case Sema::TDK_InstantiationDepth:
497 case Sema::TDK_Incomplete:
498 case Sema::TDK_TooManyArguments:
499 case Sema::TDK_TooFewArguments:
500 case Sema::TDK_InvalidExplicitArguments:
501 case Sema::TDK_SubstitutionFailure:
502 return 0;
504 case Sema::TDK_Inconsistent:
505 case Sema::TDK_Underqualified:
506 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
508 // Unhandled
509 case Sema::TDK_NonDeducedMismatch:
510 case Sema::TDK_FailedOverloadResolution:
511 break;
514 return 0;
517 void OverloadCandidateSet::clear() {
518 inherited::clear();
519 Functions.clear();
522 // IsOverload - Determine whether the given New declaration is an
523 // overload of the declarations in Old. This routine returns false if
524 // New and Old cannot be overloaded, e.g., if New has the same
525 // signature as some function in Old (C++ 1.3.10) or if the Old
526 // declarations aren't functions (or function templates) at all. When
527 // it does return false, MatchedDecl will point to the decl that New
528 // cannot be overloaded with. This decl may be a UsingShadowDecl on
529 // top of the underlying declaration.
531 // Example: Given the following input:
533 // void f(int, float); // #1
534 // void f(int, int); // #2
535 // int f(int, int); // #3
537 // When we process #1, there is no previous declaration of "f",
538 // so IsOverload will not be used.
540 // When we process #2, Old contains only the FunctionDecl for #1. By
541 // comparing the parameter types, we see that #1 and #2 are overloaded
542 // (since they have different signatures), so this routine returns
543 // false; MatchedDecl is unchanged.
545 // When we process #3, Old is an overload set containing #1 and #2. We
546 // compare the signatures of #3 to #1 (they're overloaded, so we do
547 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
548 // identical (return types of functions are not part of the
549 // signature), IsOverload returns false and MatchedDecl will be set to
550 // point to the FunctionDecl for #2.
552 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
553 // into a class by a using declaration. The rules for whether to hide
554 // shadow declarations ignore some properties which otherwise figure
555 // into a function template's signature.
556 Sema::OverloadKind
557 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
558 NamedDecl *&Match, bool NewIsUsingDecl) {
559 for (LookupResult::iterator I = Old.begin(), E = Old.end();
560 I != E; ++I) {
561 NamedDecl *OldD = *I;
563 bool OldIsUsingDecl = false;
564 if (isa<UsingShadowDecl>(OldD)) {
565 OldIsUsingDecl = true;
567 // We can always introduce two using declarations into the same
568 // context, even if they have identical signatures.
569 if (NewIsUsingDecl) continue;
571 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
574 // If either declaration was introduced by a using declaration,
575 // we'll need to use slightly different rules for matching.
576 // Essentially, these rules are the normal rules, except that
577 // function templates hide function templates with different
578 // return types or template parameter lists.
579 bool UseMemberUsingDeclRules =
580 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
582 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
583 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
584 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
585 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
586 continue;
589 Match = *I;
590 return Ovl_Match;
592 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
593 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
594 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
595 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
596 continue;
599 Match = *I;
600 return Ovl_Match;
602 } else if (isa<UsingDecl>(OldD)) {
603 // We can overload with these, which can show up when doing
604 // redeclaration checks for UsingDecls.
605 assert(Old.getLookupKind() == LookupUsingDeclName);
606 } else if (isa<TagDecl>(OldD)) {
607 // We can always overload with tags by hiding them.
608 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
609 // Optimistically assume that an unresolved using decl will
610 // overload; if it doesn't, we'll have to diagnose during
611 // template instantiation.
612 } else {
613 // (C++ 13p1):
614 // Only function declarations can be overloaded; object and type
615 // declarations cannot be overloaded.
616 Match = *I;
617 return Ovl_NonFunction;
621 return Ovl_Overload;
624 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
625 bool UseUsingDeclRules) {
626 // If both of the functions are extern "C", then they are not
627 // overloads.
628 if (Old->isExternC() && New->isExternC())
629 return false;
631 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
632 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
634 // C++ [temp.fct]p2:
635 // A function template can be overloaded with other function templates
636 // and with normal (non-template) functions.
637 if ((OldTemplate == 0) != (NewTemplate == 0))
638 return true;
640 // Is the function New an overload of the function Old?
641 QualType OldQType = Context.getCanonicalType(Old->getType());
642 QualType NewQType = Context.getCanonicalType(New->getType());
644 // Compare the signatures (C++ 1.3.10) of the two functions to
645 // determine whether they are overloads. If we find any mismatch
646 // in the signature, they are overloads.
648 // If either of these functions is a K&R-style function (no
649 // prototype), then we consider them to have matching signatures.
650 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
651 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
652 return false;
654 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
655 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
657 // The signature of a function includes the types of its
658 // parameters (C++ 1.3.10), which includes the presence or absence
659 // of the ellipsis; see C++ DR 357).
660 if (OldQType != NewQType &&
661 (OldType->getNumArgs() != NewType->getNumArgs() ||
662 OldType->isVariadic() != NewType->isVariadic() ||
663 !FunctionArgTypesAreEqual(OldType, NewType)))
664 return true;
666 // C++ [temp.over.link]p4:
667 // The signature of a function template consists of its function
668 // signature, its return type and its template parameter list. The names
669 // of the template parameters are significant only for establishing the
670 // relationship between the template parameters and the rest of the
671 // signature.
673 // We check the return type and template parameter lists for function
674 // templates first; the remaining checks follow.
676 // However, we don't consider either of these when deciding whether
677 // a member introduced by a shadow declaration is hidden.
678 if (!UseUsingDeclRules && NewTemplate &&
679 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
680 OldTemplate->getTemplateParameters(),
681 false, TPL_TemplateMatch) ||
682 OldType->getResultType() != NewType->getResultType()))
683 return true;
685 // If the function is a class member, its signature includes the
686 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
688 // As part of this, also check whether one of the member functions
689 // is static, in which case they are not overloads (C++
690 // 13.1p2). While not part of the definition of the signature,
691 // this check is important to determine whether these functions
692 // can be overloaded.
693 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
694 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
695 if (OldMethod && NewMethod &&
696 !OldMethod->isStatic() && !NewMethod->isStatic() &&
697 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
698 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
699 if (!UseUsingDeclRules &&
700 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
701 (OldMethod->getRefQualifier() == RQ_None ||
702 NewMethod->getRefQualifier() == RQ_None)) {
703 // C++0x [over.load]p2:
704 // - Member function declarations with the same name and the same
705 // parameter-type-list as well as member function template
706 // declarations with the same name, the same parameter-type-list, and
707 // the same template parameter lists cannot be overloaded if any of
708 // them, but not all, have a ref-qualifier (8.3.5).
709 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
710 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
711 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
714 return true;
717 // The signatures match; this is not an overload.
718 return false;
721 /// TryImplicitConversion - Attempt to perform an implicit conversion
722 /// from the given expression (Expr) to the given type (ToType). This
723 /// function returns an implicit conversion sequence that can be used
724 /// to perform the initialization. Given
726 /// void f(float f);
727 /// void g(int i) { f(i); }
729 /// this routine would produce an implicit conversion sequence to
730 /// describe the initialization of f from i, which will be a standard
731 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
732 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
734 /// Note that this routine only determines how the conversion can be
735 /// performed; it does not actually perform the conversion. As such,
736 /// it will not produce any diagnostics if no conversion is available,
737 /// but will instead return an implicit conversion sequence of kind
738 /// "BadConversion".
740 /// If @p SuppressUserConversions, then user-defined conversions are
741 /// not permitted.
742 /// If @p AllowExplicit, then explicit user-defined conversions are
743 /// permitted.
744 static ImplicitConversionSequence
745 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
746 bool SuppressUserConversions,
747 bool AllowExplicit,
748 bool InOverloadResolution,
749 bool CStyle) {
750 ImplicitConversionSequence ICS;
751 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
752 ICS.Standard, CStyle)) {
753 ICS.setStandard();
754 return ICS;
757 if (!S.getLangOptions().CPlusPlus) {
758 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
759 return ICS;
762 // C++ [over.ics.user]p4:
763 // A conversion of an expression of class type to the same class
764 // type is given Exact Match rank, and a conversion of an
765 // expression of class type to a base class of that type is
766 // given Conversion rank, in spite of the fact that a copy/move
767 // constructor (i.e., a user-defined conversion function) is
768 // called for those cases.
769 QualType FromType = From->getType();
770 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
771 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
772 S.IsDerivedFrom(FromType, ToType))) {
773 ICS.setStandard();
774 ICS.Standard.setAsIdentityConversion();
775 ICS.Standard.setFromType(FromType);
776 ICS.Standard.setAllToTypes(ToType);
778 // We don't actually check at this point whether there is a valid
779 // copy/move constructor, since overloading just assumes that it
780 // exists. When we actually perform initialization, we'll find the
781 // appropriate constructor to copy the returned object, if needed.
782 ICS.Standard.CopyConstructor = 0;
784 // Determine whether this is considered a derived-to-base conversion.
785 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
786 ICS.Standard.Second = ICK_Derived_To_Base;
788 return ICS;
791 if (SuppressUserConversions) {
792 // We're not in the case above, so there is no conversion that
793 // we can perform.
794 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
795 return ICS;
798 // Attempt user-defined conversion.
799 OverloadCandidateSet Conversions(From->getExprLoc());
800 OverloadingResult UserDefResult
801 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
802 AllowExplicit);
804 if (UserDefResult == OR_Success) {
805 ICS.setUserDefined();
806 // C++ [over.ics.user]p4:
807 // A conversion of an expression of class type to the same class
808 // type is given Exact Match rank, and a conversion of an
809 // expression of class type to a base class of that type is
810 // given Conversion rank, in spite of the fact that a copy
811 // constructor (i.e., a user-defined conversion function) is
812 // called for those cases.
813 if (CXXConstructorDecl *Constructor
814 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
815 QualType FromCanon
816 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
817 QualType ToCanon
818 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
819 if (Constructor->isCopyConstructor() &&
820 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
821 // Turn this into a "standard" conversion sequence, so that it
822 // gets ranked with standard conversion sequences.
823 ICS.setStandard();
824 ICS.Standard.setAsIdentityConversion();
825 ICS.Standard.setFromType(From->getType());
826 ICS.Standard.setAllToTypes(ToType);
827 ICS.Standard.CopyConstructor = Constructor;
828 if (ToCanon != FromCanon)
829 ICS.Standard.Second = ICK_Derived_To_Base;
833 // C++ [over.best.ics]p4:
834 // However, when considering the argument of a user-defined
835 // conversion function that is a candidate by 13.3.1.3 when
836 // invoked for the copying of the temporary in the second step
837 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
838 // 13.3.1.6 in all cases, only standard conversion sequences and
839 // ellipsis conversion sequences are allowed.
840 if (SuppressUserConversions && ICS.isUserDefined()) {
841 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
843 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
844 ICS.setAmbiguous();
845 ICS.Ambiguous.setFromType(From->getType());
846 ICS.Ambiguous.setToType(ToType);
847 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
848 Cand != Conversions.end(); ++Cand)
849 if (Cand->Viable)
850 ICS.Ambiguous.addConversion(Cand->Function);
851 } else {
852 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
855 return ICS;
858 bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
859 const InitializedEntity &Entity,
860 Expr *Initializer,
861 bool SuppressUserConversions,
862 bool AllowExplicitConversions,
863 bool InOverloadResolution,
864 bool CStyle) {
865 ImplicitConversionSequence ICS
866 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
867 SuppressUserConversions,
868 AllowExplicitConversions,
869 InOverloadResolution,
870 CStyle);
871 if (ICS.isBad()) return true;
873 // Perform the actual conversion.
874 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
875 return false;
878 /// PerformImplicitConversion - Perform an implicit conversion of the
879 /// expression From to the type ToType. Returns true if there was an
880 /// error, false otherwise. The expression From is replaced with the
881 /// converted expression. Flavor is the kind of conversion we're
882 /// performing, used in the error message. If @p AllowExplicit,
883 /// explicit user-defined conversions are permitted.
884 bool
885 Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
886 AssignmentAction Action, bool AllowExplicit) {
887 ImplicitConversionSequence ICS;
888 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
891 bool
892 Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
893 AssignmentAction Action, bool AllowExplicit,
894 ImplicitConversionSequence& ICS) {
895 ICS = clang::TryImplicitConversion(*this, From, ToType,
896 /*SuppressUserConversions=*/false,
897 AllowExplicit,
898 /*InOverloadResolution=*/false,
899 /*CStyle=*/false);
900 return PerformImplicitConversion(From, ToType, ICS, Action);
903 /// \brief Determine whether the conversion from FromType to ToType is a valid
904 /// conversion that strips "noreturn" off the nested function type.
905 static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
906 QualType ToType, QualType &ResultTy) {
907 if (Context.hasSameUnqualifiedType(FromType, ToType))
908 return false;
910 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
911 // where F adds one of the following at most once:
912 // - a pointer
913 // - a member pointer
914 // - a block pointer
915 CanQualType CanTo = Context.getCanonicalType(ToType);
916 CanQualType CanFrom = Context.getCanonicalType(FromType);
917 Type::TypeClass TyClass = CanTo->getTypeClass();
918 if (TyClass != CanFrom->getTypeClass()) return false;
919 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
920 if (TyClass == Type::Pointer) {
921 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
922 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
923 } else if (TyClass == Type::BlockPointer) {
924 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
925 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
926 } else if (TyClass == Type::MemberPointer) {
927 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
928 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
929 } else {
930 return false;
933 TyClass = CanTo->getTypeClass();
934 if (TyClass != CanFrom->getTypeClass()) return false;
935 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
936 return false;
939 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
940 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
941 if (!EInfo.getNoReturn()) return false;
943 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
944 assert(QualType(FromFn, 0).isCanonical());
945 if (QualType(FromFn, 0) != CanTo) return false;
947 ResultTy = ToType;
948 return true;
951 /// \brief Determine whether the conversion from FromType to ToType is a valid
952 /// vector conversion.
954 /// \param ICK Will be set to the vector conversion kind, if this is a vector
955 /// conversion.
956 static bool IsVectorConversion(ASTContext &Context, QualType FromType,
957 QualType ToType, ImplicitConversionKind &ICK) {
958 // We need at least one of these types to be a vector type to have a vector
959 // conversion.
960 if (!ToType->isVectorType() && !FromType->isVectorType())
961 return false;
963 // Identical types require no conversions.
964 if (Context.hasSameUnqualifiedType(FromType, ToType))
965 return false;
967 // There are no conversions between extended vector types, only identity.
968 if (ToType->isExtVectorType()) {
969 // There are no conversions between extended vector types other than the
970 // identity conversion.
971 if (FromType->isExtVectorType())
972 return false;
974 // Vector splat from any arithmetic type to a vector.
975 if (FromType->isArithmeticType()) {
976 ICK = ICK_Vector_Splat;
977 return true;
981 // We can perform the conversion between vector types in the following cases:
982 // 1)vector types are equivalent AltiVec and GCC vector types
983 // 2)lax vector conversions are permitted and the vector types are of the
984 // same size
985 if (ToType->isVectorType() && FromType->isVectorType()) {
986 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
987 (Context.getLangOptions().LaxVectorConversions &&
988 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
989 ICK = ICK_Vector_Conversion;
990 return true;
994 return false;
997 /// IsStandardConversion - Determines whether there is a standard
998 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
999 /// expression From to the type ToType. Standard conversion sequences
1000 /// only consider non-class types; for conversions that involve class
1001 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1002 /// contain the standard conversion sequence required to perform this
1003 /// conversion and this routine will return true. Otherwise, this
1004 /// routine will return false and the value of SCS is unspecified.
1005 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1006 bool InOverloadResolution,
1007 StandardConversionSequence &SCS,
1008 bool CStyle) {
1009 QualType FromType = From->getType();
1011 // Standard conversions (C++ [conv])
1012 SCS.setAsIdentityConversion();
1013 SCS.DeprecatedStringLiteralToCharPtr = false;
1014 SCS.IncompatibleObjC = false;
1015 SCS.setFromType(FromType);
1016 SCS.CopyConstructor = 0;
1018 // There are no standard conversions for class types in C++, so
1019 // abort early. When overloading in C, however, we do permit
1020 if (FromType->isRecordType() || ToType->isRecordType()) {
1021 if (S.getLangOptions().CPlusPlus)
1022 return false;
1024 // When we're overloading in C, we allow, as standard conversions,
1027 // The first conversion can be an lvalue-to-rvalue conversion,
1028 // array-to-pointer conversion, or function-to-pointer conversion
1029 // (C++ 4p1).
1031 if (FromType == S.Context.OverloadTy) {
1032 DeclAccessPair AccessPair;
1033 if (FunctionDecl *Fn
1034 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1035 AccessPair)) {
1036 // We were able to resolve the address of the overloaded function,
1037 // so we can convert to the type of that function.
1038 FromType = Fn->getType();
1039 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
1040 if (!Method->isStatic()) {
1041 const Type *ClassType
1042 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1043 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1047 // If the "from" expression takes the address of the overloaded
1048 // function, update the type of the resulting expression accordingly.
1049 if (FromType->getAs<FunctionType>())
1050 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
1051 if (UnOp->getOpcode() == UO_AddrOf)
1052 FromType = S.Context.getPointerType(FromType);
1054 // Check that we've computed the proper type after overload resolution.
1055 assert(S.Context.hasSameType(FromType,
1056 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1057 } else {
1058 return false;
1061 // Lvalue-to-rvalue conversion (C++ 4.1):
1062 // An lvalue (3.10) of a non-function, non-array type T can be
1063 // converted to an rvalue.
1064 bool argIsLValue = From->isLValue();
1065 if (argIsLValue &&
1066 !FromType->isFunctionType() && !FromType->isArrayType() &&
1067 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1068 SCS.First = ICK_Lvalue_To_Rvalue;
1070 // If T is a non-class type, the type of the rvalue is the
1071 // cv-unqualified version of T. Otherwise, the type of the rvalue
1072 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1073 // just strip the qualifiers because they don't matter.
1074 FromType = FromType.getUnqualifiedType();
1075 } else if (FromType->isArrayType()) {
1076 // Array-to-pointer conversion (C++ 4.2)
1077 SCS.First = ICK_Array_To_Pointer;
1079 // An lvalue or rvalue of type "array of N T" or "array of unknown
1080 // bound of T" can be converted to an rvalue of type "pointer to
1081 // T" (C++ 4.2p1).
1082 FromType = S.Context.getArrayDecayedType(FromType);
1084 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1085 // This conversion is deprecated. (C++ D.4).
1086 SCS.DeprecatedStringLiteralToCharPtr = true;
1088 // For the purpose of ranking in overload resolution
1089 // (13.3.3.1.1), this conversion is considered an
1090 // array-to-pointer conversion followed by a qualification
1091 // conversion (4.4). (C++ 4.2p2)
1092 SCS.Second = ICK_Identity;
1093 SCS.Third = ICK_Qualification;
1094 SCS.setAllToTypes(FromType);
1095 return true;
1097 } else if (FromType->isFunctionType() && argIsLValue) {
1098 // Function-to-pointer conversion (C++ 4.3).
1099 SCS.First = ICK_Function_To_Pointer;
1101 // An lvalue of function type T can be converted to an rvalue of
1102 // type "pointer to T." The result is a pointer to the
1103 // function. (C++ 4.3p1).
1104 FromType = S.Context.getPointerType(FromType);
1105 } else {
1106 // We don't require any conversions for the first step.
1107 SCS.First = ICK_Identity;
1109 SCS.setToType(0, FromType);
1111 // The second conversion can be an integral promotion, floating
1112 // point promotion, integral conversion, floating point conversion,
1113 // floating-integral conversion, pointer conversion,
1114 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1115 // For overloading in C, this can also be a "compatible-type"
1116 // conversion.
1117 bool IncompatibleObjC = false;
1118 ImplicitConversionKind SecondICK = ICK_Identity;
1119 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1120 // The unqualified versions of the types are the same: there's no
1121 // conversion to do.
1122 SCS.Second = ICK_Identity;
1123 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1124 // Integral promotion (C++ 4.5).
1125 SCS.Second = ICK_Integral_Promotion;
1126 FromType = ToType.getUnqualifiedType();
1127 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1128 // Floating point promotion (C++ 4.6).
1129 SCS.Second = ICK_Floating_Promotion;
1130 FromType = ToType.getUnqualifiedType();
1131 } else if (S.IsComplexPromotion(FromType, ToType)) {
1132 // Complex promotion (Clang extension)
1133 SCS.Second = ICK_Complex_Promotion;
1134 FromType = ToType.getUnqualifiedType();
1135 } else if (ToType->isBooleanType() &&
1136 (FromType->isArithmeticType() ||
1137 FromType->isAnyPointerType() ||
1138 FromType->isBlockPointerType() ||
1139 FromType->isMemberPointerType() ||
1140 FromType->isNullPtrType())) {
1141 // Boolean conversions (C++ 4.12).
1142 SCS.Second = ICK_Boolean_Conversion;
1143 FromType = S.Context.BoolTy;
1144 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1145 ToType->isIntegralType(S.Context)) {
1146 // Integral conversions (C++ 4.7).
1147 SCS.Second = ICK_Integral_Conversion;
1148 FromType = ToType.getUnqualifiedType();
1149 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
1150 // Complex conversions (C99 6.3.1.6)
1151 SCS.Second = ICK_Complex_Conversion;
1152 FromType = ToType.getUnqualifiedType();
1153 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1154 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1155 // Complex-real conversions (C99 6.3.1.7)
1156 SCS.Second = ICK_Complex_Real;
1157 FromType = ToType.getUnqualifiedType();
1158 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1159 // Floating point conversions (C++ 4.8).
1160 SCS.Second = ICK_Floating_Conversion;
1161 FromType = ToType.getUnqualifiedType();
1162 } else if ((FromType->isRealFloatingType() &&
1163 ToType->isIntegralType(S.Context)) ||
1164 (FromType->isIntegralOrUnscopedEnumerationType() &&
1165 ToType->isRealFloatingType())) {
1166 // Floating-integral conversions (C++ 4.9).
1167 SCS.Second = ICK_Floating_Integral;
1168 FromType = ToType.getUnqualifiedType();
1169 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1170 SCS.Second = ICK_Block_Pointer_Conversion;
1171 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1172 FromType, IncompatibleObjC)) {
1173 // Pointer conversions (C++ 4.10).
1174 SCS.Second = ICK_Pointer_Conversion;
1175 SCS.IncompatibleObjC = IncompatibleObjC;
1176 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1177 InOverloadResolution, FromType)) {
1178 // Pointer to member conversions (4.11).
1179 SCS.Second = ICK_Pointer_Member;
1180 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
1181 SCS.Second = SecondICK;
1182 FromType = ToType.getUnqualifiedType();
1183 } else if (!S.getLangOptions().CPlusPlus &&
1184 S.Context.typesAreCompatible(ToType, FromType)) {
1185 // Compatible conversions (Clang extension for C function overloading)
1186 SCS.Second = ICK_Compatible_Conversion;
1187 FromType = ToType.getUnqualifiedType();
1188 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
1189 // Treat a conversion that strips "noreturn" as an identity conversion.
1190 SCS.Second = ICK_NoReturn_Adjustment;
1191 } else {
1192 // No second conversion required.
1193 SCS.Second = ICK_Identity;
1195 SCS.setToType(1, FromType);
1197 QualType CanonFrom;
1198 QualType CanonTo;
1199 // The third conversion can be a qualification conversion (C++ 4p1).
1200 if (S.IsQualificationConversion(FromType, ToType, CStyle)) {
1201 SCS.Third = ICK_Qualification;
1202 FromType = ToType;
1203 CanonFrom = S.Context.getCanonicalType(FromType);
1204 CanonTo = S.Context.getCanonicalType(ToType);
1205 } else {
1206 // No conversion required
1207 SCS.Third = ICK_Identity;
1209 // C++ [over.best.ics]p6:
1210 // [...] Any difference in top-level cv-qualification is
1211 // subsumed by the initialization itself and does not constitute
1212 // a conversion. [...]
1213 CanonFrom = S.Context.getCanonicalType(FromType);
1214 CanonTo = S.Context.getCanonicalType(ToType);
1215 if (CanonFrom.getLocalUnqualifiedType()
1216 == CanonTo.getLocalUnqualifiedType() &&
1217 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1218 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
1219 FromType = ToType;
1220 CanonFrom = CanonTo;
1223 SCS.setToType(2, FromType);
1225 // If we have not converted the argument type to the parameter type,
1226 // this is a bad conversion sequence.
1227 if (CanonFrom != CanonTo)
1228 return false;
1230 return true;
1233 /// IsIntegralPromotion - Determines whether the conversion from the
1234 /// expression From (whose potentially-adjusted type is FromType) to
1235 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1236 /// sets PromotedType to the promoted type.
1237 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1238 const BuiltinType *To = ToType->getAs<BuiltinType>();
1239 // All integers are built-in.
1240 if (!To) {
1241 return false;
1244 // An rvalue of type char, signed char, unsigned char, short int, or
1245 // unsigned short int can be converted to an rvalue of type int if
1246 // int can represent all the values of the source type; otherwise,
1247 // the source rvalue can be converted to an rvalue of type unsigned
1248 // int (C++ 4.5p1).
1249 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1250 !FromType->isEnumeralType()) {
1251 if (// We can promote any signed, promotable integer type to an int
1252 (FromType->isSignedIntegerType() ||
1253 // We can promote any unsigned integer type whose size is
1254 // less than int to an int.
1255 (!FromType->isSignedIntegerType() &&
1256 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1257 return To->getKind() == BuiltinType::Int;
1260 return To->getKind() == BuiltinType::UInt;
1263 // C++0x [conv.prom]p3:
1264 // A prvalue of an unscoped enumeration type whose underlying type is not
1265 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1266 // following types that can represent all the values of the enumeration
1267 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1268 // unsigned int, long int, unsigned long int, long long int, or unsigned
1269 // long long int. If none of the types in that list can represent all the
1270 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1271 // type can be converted to an rvalue a prvalue of the extended integer type
1272 // with lowest integer conversion rank (4.13) greater than the rank of long
1273 // long in which all the values of the enumeration can be represented. If
1274 // there are two such extended types, the signed one is chosen.
1275 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1276 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1277 // provided for a scoped enumeration.
1278 if (FromEnumType->getDecl()->isScoped())
1279 return false;
1281 // We have already pre-calculated the promotion type, so this is trivial.
1282 if (ToType->isIntegerType() &&
1283 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
1284 return Context.hasSameUnqualifiedType(ToType,
1285 FromEnumType->getDecl()->getPromotionType());
1288 // C++0x [conv.prom]p2:
1289 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1290 // to an rvalue a prvalue of the first of the following types that can
1291 // represent all the values of its underlying type: int, unsigned int,
1292 // long int, unsigned long int, long long int, or unsigned long long int.
1293 // If none of the types in that list can represent all the values of its
1294 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1295 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1296 // type.
1297 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1298 ToType->isIntegerType()) {
1299 // Determine whether the type we're converting from is signed or
1300 // unsigned.
1301 bool FromIsSigned;
1302 uint64_t FromSize = Context.getTypeSize(FromType);
1304 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1305 FromIsSigned = true;
1307 // The types we'll try to promote to, in the appropriate
1308 // order. Try each of these types.
1309 QualType PromoteTypes[6] = {
1310 Context.IntTy, Context.UnsignedIntTy,
1311 Context.LongTy, Context.UnsignedLongTy ,
1312 Context.LongLongTy, Context.UnsignedLongLongTy
1314 for (int Idx = 0; Idx < 6; ++Idx) {
1315 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1316 if (FromSize < ToSize ||
1317 (FromSize == ToSize &&
1318 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1319 // We found the type that we can promote to. If this is the
1320 // type we wanted, we have a promotion. Otherwise, no
1321 // promotion.
1322 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1327 // An rvalue for an integral bit-field (9.6) can be converted to an
1328 // rvalue of type int if int can represent all the values of the
1329 // bit-field; otherwise, it can be converted to unsigned int if
1330 // unsigned int can represent all the values of the bit-field. If
1331 // the bit-field is larger yet, no integral promotion applies to
1332 // it. If the bit-field has an enumerated type, it is treated as any
1333 // other value of that type for promotion purposes (C++ 4.5p3).
1334 // FIXME: We should delay checking of bit-fields until we actually perform the
1335 // conversion.
1336 using llvm::APSInt;
1337 if (From)
1338 if (FieldDecl *MemberDecl = From->getBitField()) {
1339 APSInt BitWidth;
1340 if (FromType->isIntegralType(Context) &&
1341 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1342 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1343 ToSize = Context.getTypeSize(ToType);
1345 // Are we promoting to an int from a bitfield that fits in an int?
1346 if (BitWidth < ToSize ||
1347 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1348 return To->getKind() == BuiltinType::Int;
1351 // Are we promoting to an unsigned int from an unsigned bitfield
1352 // that fits into an unsigned int?
1353 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1354 return To->getKind() == BuiltinType::UInt;
1357 return false;
1361 // An rvalue of type bool can be converted to an rvalue of type int,
1362 // with false becoming zero and true becoming one (C++ 4.5p4).
1363 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1364 return true;
1367 return false;
1370 /// IsFloatingPointPromotion - Determines whether the conversion from
1371 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1372 /// returns true and sets PromotedType to the promoted type.
1373 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1374 /// An rvalue of type float can be converted to an rvalue of type
1375 /// double. (C++ 4.6p1).
1376 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1377 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1378 if (FromBuiltin->getKind() == BuiltinType::Float &&
1379 ToBuiltin->getKind() == BuiltinType::Double)
1380 return true;
1382 // C99 6.3.1.5p1:
1383 // When a float is promoted to double or long double, or a
1384 // double is promoted to long double [...].
1385 if (!getLangOptions().CPlusPlus &&
1386 (FromBuiltin->getKind() == BuiltinType::Float ||
1387 FromBuiltin->getKind() == BuiltinType::Double) &&
1388 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1389 return true;
1392 return false;
1395 /// \brief Determine if a conversion is a complex promotion.
1397 /// A complex promotion is defined as a complex -> complex conversion
1398 /// where the conversion between the underlying real types is a
1399 /// floating-point or integral promotion.
1400 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1401 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1402 if (!FromComplex)
1403 return false;
1405 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1406 if (!ToComplex)
1407 return false;
1409 return IsFloatingPointPromotion(FromComplex->getElementType(),
1410 ToComplex->getElementType()) ||
1411 IsIntegralPromotion(0, FromComplex->getElementType(),
1412 ToComplex->getElementType());
1415 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1416 /// the pointer type FromPtr to a pointer to type ToPointee, with the
1417 /// same type qualifiers as FromPtr has on its pointee type. ToType,
1418 /// if non-empty, will be a pointer to ToType that may or may not have
1419 /// the right set of qualifiers on its pointee.
1420 static QualType
1421 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1422 QualType ToPointee, QualType ToType,
1423 ASTContext &Context) {
1424 assert((FromPtr->getTypeClass() == Type::Pointer ||
1425 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1426 "Invalid similarly-qualified pointer type");
1428 /// \brief Conversions to 'id' subsume cv-qualifier conversions.
1429 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1430 return ToType.getUnqualifiedType();
1432 QualType CanonFromPointee
1433 = Context.getCanonicalType(FromPtr->getPointeeType());
1434 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1435 Qualifiers Quals = CanonFromPointee.getQualifiers();
1437 // Exact qualifier match -> return the pointer type we're converting to.
1438 if (CanonToPointee.getLocalQualifiers() == Quals) {
1439 // ToType is exactly what we need. Return it.
1440 if (!ToType.isNull())
1441 return ToType.getUnqualifiedType();
1443 // Build a pointer to ToPointee. It has the right qualifiers
1444 // already.
1445 if (isa<ObjCObjectPointerType>(ToType))
1446 return Context.getObjCObjectPointerType(ToPointee);
1447 return Context.getPointerType(ToPointee);
1450 // Just build a canonical type that has the right qualifiers.
1451 QualType QualifiedCanonToPointee
1452 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1454 if (isa<ObjCObjectPointerType>(ToType))
1455 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1456 return Context.getPointerType(QualifiedCanonToPointee);
1459 static bool isNullPointerConstantForConversion(Expr *Expr,
1460 bool InOverloadResolution,
1461 ASTContext &Context) {
1462 // Handle value-dependent integral null pointer constants correctly.
1463 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1464 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1465 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1466 return !InOverloadResolution;
1468 return Expr->isNullPointerConstant(Context,
1469 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1470 : Expr::NPC_ValueDependentIsNull);
1473 /// IsPointerConversion - Determines whether the conversion of the
1474 /// expression From, which has the (possibly adjusted) type FromType,
1475 /// can be converted to the type ToType via a pointer conversion (C++
1476 /// 4.10). If so, returns true and places the converted type (that
1477 /// might differ from ToType in its cv-qualifiers at some level) into
1478 /// ConvertedType.
1480 /// This routine also supports conversions to and from block pointers
1481 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
1482 /// pointers to interfaces. FIXME: Once we've determined the
1483 /// appropriate overloading rules for Objective-C, we may want to
1484 /// split the Objective-C checks into a different routine; however,
1485 /// GCC seems to consider all of these conversions to be pointer
1486 /// conversions, so for now they live here. IncompatibleObjC will be
1487 /// set if the conversion is an allowed Objective-C conversion that
1488 /// should result in a warning.
1489 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1490 bool InOverloadResolution,
1491 QualType& ConvertedType,
1492 bool &IncompatibleObjC) {
1493 IncompatibleObjC = false;
1494 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1495 IncompatibleObjC))
1496 return true;
1498 // Conversion from a null pointer constant to any Objective-C pointer type.
1499 if (ToType->isObjCObjectPointerType() &&
1500 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1501 ConvertedType = ToType;
1502 return true;
1505 // Blocks: Block pointers can be converted to void*.
1506 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
1507 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
1508 ConvertedType = ToType;
1509 return true;
1511 // Blocks: A null pointer constant can be converted to a block
1512 // pointer type.
1513 if (ToType->isBlockPointerType() &&
1514 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1515 ConvertedType = ToType;
1516 return true;
1519 // If the left-hand-side is nullptr_t, the right side can be a null
1520 // pointer constant.
1521 if (ToType->isNullPtrType() &&
1522 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1523 ConvertedType = ToType;
1524 return true;
1527 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
1528 if (!ToTypePtr)
1529 return false;
1531 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
1532 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1533 ConvertedType = ToType;
1534 return true;
1537 // Beyond this point, both types need to be pointers
1538 // , including objective-c pointers.
1539 QualType ToPointeeType = ToTypePtr->getPointeeType();
1540 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1541 ConvertedType = BuildSimilarlyQualifiedPointerType(
1542 FromType->getAs<ObjCObjectPointerType>(),
1543 ToPointeeType,
1544 ToType, Context);
1545 return true;
1547 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
1548 if (!FromTypePtr)
1549 return false;
1551 QualType FromPointeeType = FromTypePtr->getPointeeType();
1553 // If the unqualified pointee types are the same, this can't be a
1554 // pointer conversion, so don't do all of the work below.
1555 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1556 return false;
1558 // An rvalue of type "pointer to cv T," where T is an object type,
1559 // can be converted to an rvalue of type "pointer to cv void" (C++
1560 // 4.10p2).
1561 if (FromPointeeType->isIncompleteOrObjectType() &&
1562 ToPointeeType->isVoidType()) {
1563 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1564 ToPointeeType,
1565 ToType, Context);
1566 return true;
1569 // When we're overloading in C, we allow a special kind of pointer
1570 // conversion for compatible-but-not-identical pointee types.
1571 if (!getLangOptions().CPlusPlus &&
1572 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
1573 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1574 ToPointeeType,
1575 ToType, Context);
1576 return true;
1579 // C++ [conv.ptr]p3:
1581 // An rvalue of type "pointer to cv D," where D is a class type,
1582 // can be converted to an rvalue of type "pointer to cv B," where
1583 // B is a base class (clause 10) of D. If B is an inaccessible
1584 // (clause 11) or ambiguous (10.2) base class of D, a program that
1585 // necessitates this conversion is ill-formed. The result of the
1586 // conversion is a pointer to the base class sub-object of the
1587 // derived class object. The null pointer value is converted to
1588 // the null pointer value of the destination type.
1590 // Note that we do not check for ambiguity or inaccessibility
1591 // here. That is handled by CheckPointerConversion.
1592 if (getLangOptions().CPlusPlus &&
1593 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1594 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
1595 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
1596 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
1597 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1598 ToPointeeType,
1599 ToType, Context);
1600 return true;
1603 return false;
1606 /// isObjCPointerConversion - Determines whether this is an
1607 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1608 /// with the same arguments and return values.
1609 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
1610 QualType& ConvertedType,
1611 bool &IncompatibleObjC) {
1612 if (!getLangOptions().ObjC1)
1613 return false;
1615 // First, we handle all conversions on ObjC object pointer types.
1616 const ObjCObjectPointerType* ToObjCPtr =
1617 ToType->getAs<ObjCObjectPointerType>();
1618 const ObjCObjectPointerType *FromObjCPtr =
1619 FromType->getAs<ObjCObjectPointerType>();
1621 if (ToObjCPtr && FromObjCPtr) {
1622 // If the pointee types are the same (ignoring qualifications),
1623 // then this is not a pointer conversion.
1624 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1625 FromObjCPtr->getPointeeType()))
1626 return false;
1628 // Objective C++: We're able to convert between "id" or "Class" and a
1629 // pointer to any interface (in both directions).
1630 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
1631 ConvertedType = ToType;
1632 return true;
1634 // Conversions with Objective-C's id<...>.
1635 if ((FromObjCPtr->isObjCQualifiedIdType() ||
1636 ToObjCPtr->isObjCQualifiedIdType()) &&
1637 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
1638 /*compare=*/false)) {
1639 ConvertedType = ToType;
1640 return true;
1642 // Objective C++: We're able to convert from a pointer to an
1643 // interface to a pointer to a different interface.
1644 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1645 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1646 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1647 if (getLangOptions().CPlusPlus && LHS && RHS &&
1648 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1649 FromObjCPtr->getPointeeType()))
1650 return false;
1651 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1652 ToObjCPtr->getPointeeType(),
1653 ToType, Context);
1654 return true;
1657 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1658 // Okay: this is some kind of implicit downcast of Objective-C
1659 // interfaces, which is permitted. However, we're going to
1660 // complain about it.
1661 IncompatibleObjC = true;
1662 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1663 ToObjCPtr->getPointeeType(),
1664 ToType, Context);
1665 return true;
1668 // Beyond this point, both types need to be C pointers or block pointers.
1669 QualType ToPointeeType;
1670 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
1671 ToPointeeType = ToCPtr->getPointeeType();
1672 else if (const BlockPointerType *ToBlockPtr =
1673 ToType->getAs<BlockPointerType>()) {
1674 // Objective C++: We're able to convert from a pointer to any object
1675 // to a block pointer type.
1676 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1677 ConvertedType = ToType;
1678 return true;
1680 ToPointeeType = ToBlockPtr->getPointeeType();
1682 else if (FromType->getAs<BlockPointerType>() &&
1683 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1684 // Objective C++: We're able to convert from a block pointer type to a
1685 // pointer to any object.
1686 ConvertedType = ToType;
1687 return true;
1689 else
1690 return false;
1692 QualType FromPointeeType;
1693 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
1694 FromPointeeType = FromCPtr->getPointeeType();
1695 else if (const BlockPointerType *FromBlockPtr =
1696 FromType->getAs<BlockPointerType>())
1697 FromPointeeType = FromBlockPtr->getPointeeType();
1698 else
1699 return false;
1701 // If we have pointers to pointers, recursively check whether this
1702 // is an Objective-C conversion.
1703 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1704 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1705 IncompatibleObjC)) {
1706 // We always complain about this conversion.
1707 IncompatibleObjC = true;
1708 ConvertedType = Context.getPointerType(ConvertedType);
1709 return true;
1711 // Allow conversion of pointee being objective-c pointer to another one;
1712 // as in I* to id.
1713 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1714 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1715 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1716 IncompatibleObjC)) {
1717 ConvertedType = Context.getPointerType(ConvertedType);
1718 return true;
1721 // If we have pointers to functions or blocks, check whether the only
1722 // differences in the argument and result types are in Objective-C
1723 // pointer conversions. If so, we permit the conversion (but
1724 // complain about it).
1725 const FunctionProtoType *FromFunctionType
1726 = FromPointeeType->getAs<FunctionProtoType>();
1727 const FunctionProtoType *ToFunctionType
1728 = ToPointeeType->getAs<FunctionProtoType>();
1729 if (FromFunctionType && ToFunctionType) {
1730 // If the function types are exactly the same, this isn't an
1731 // Objective-C pointer conversion.
1732 if (Context.getCanonicalType(FromPointeeType)
1733 == Context.getCanonicalType(ToPointeeType))
1734 return false;
1736 // Perform the quick checks that will tell us whether these
1737 // function types are obviously different.
1738 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1739 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1740 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1741 return false;
1743 bool HasObjCConversion = false;
1744 if (Context.getCanonicalType(FromFunctionType->getResultType())
1745 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1746 // Okay, the types match exactly. Nothing to do.
1747 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1748 ToFunctionType->getResultType(),
1749 ConvertedType, IncompatibleObjC)) {
1750 // Okay, we have an Objective-C pointer conversion.
1751 HasObjCConversion = true;
1752 } else {
1753 // Function types are too different. Abort.
1754 return false;
1757 // Check argument types.
1758 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1759 ArgIdx != NumArgs; ++ArgIdx) {
1760 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1761 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1762 if (Context.getCanonicalType(FromArgType)
1763 == Context.getCanonicalType(ToArgType)) {
1764 // Okay, the types match exactly. Nothing to do.
1765 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1766 ConvertedType, IncompatibleObjC)) {
1767 // Okay, we have an Objective-C pointer conversion.
1768 HasObjCConversion = true;
1769 } else {
1770 // Argument types are too different. Abort.
1771 return false;
1775 if (HasObjCConversion) {
1776 // We had an Objective-C conversion. Allow this pointer
1777 // conversion, but complain about it.
1778 ConvertedType = ToType;
1779 IncompatibleObjC = true;
1780 return true;
1784 return false;
1787 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
1788 QualType& ConvertedType) {
1789 QualType ToPointeeType;
1790 if (const BlockPointerType *ToBlockPtr =
1791 ToType->getAs<BlockPointerType>())
1792 ToPointeeType = ToBlockPtr->getPointeeType();
1793 else
1794 return false;
1796 QualType FromPointeeType;
1797 if (const BlockPointerType *FromBlockPtr =
1798 FromType->getAs<BlockPointerType>())
1799 FromPointeeType = FromBlockPtr->getPointeeType();
1800 else
1801 return false;
1802 // We have pointer to blocks, check whether the only
1803 // differences in the argument and result types are in Objective-C
1804 // pointer conversions. If so, we permit the conversion.
1806 const FunctionProtoType *FromFunctionType
1807 = FromPointeeType->getAs<FunctionProtoType>();
1808 const FunctionProtoType *ToFunctionType
1809 = ToPointeeType->getAs<FunctionProtoType>();
1811 if (!FromFunctionType || !ToFunctionType)
1812 return false;
1814 if (Context.hasSameType(FromPointeeType, ToPointeeType))
1815 return true;
1817 // Perform the quick checks that will tell us whether these
1818 // function types are obviously different.
1819 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1820 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
1821 return false;
1823 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
1824 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
1825 if (FromEInfo != ToEInfo)
1826 return false;
1828 bool IncompatibleObjC = false;
1829 if (Context.hasSameType(FromFunctionType->getResultType(),
1830 ToFunctionType->getResultType())) {
1831 // Okay, the types match exactly. Nothing to do.
1832 } else {
1833 QualType RHS = FromFunctionType->getResultType();
1834 QualType LHS = ToFunctionType->getResultType();
1835 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
1836 !RHS.hasQualifiers() && LHS.hasQualifiers())
1837 LHS = LHS.getUnqualifiedType();
1839 if (Context.hasSameType(RHS,LHS)) {
1840 // OK exact match.
1841 } else if (isObjCPointerConversion(RHS, LHS,
1842 ConvertedType, IncompatibleObjC)) {
1843 if (IncompatibleObjC)
1844 return false;
1845 // Okay, we have an Objective-C pointer conversion.
1847 else
1848 return false;
1851 // Check argument types.
1852 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1853 ArgIdx != NumArgs; ++ArgIdx) {
1854 IncompatibleObjC = false;
1855 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1856 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1857 if (Context.hasSameType(FromArgType, ToArgType)) {
1858 // Okay, the types match exactly. Nothing to do.
1859 } else if (isObjCPointerConversion(ToArgType, FromArgType,
1860 ConvertedType, IncompatibleObjC)) {
1861 if (IncompatibleObjC)
1862 return false;
1863 // Okay, we have an Objective-C pointer conversion.
1864 } else
1865 // Argument types are too different. Abort.
1866 return false;
1868 ConvertedType = ToType;
1869 return true;
1872 /// FunctionArgTypesAreEqual - This routine checks two function proto types
1873 /// for equlity of their argument types. Caller has already checked that
1874 /// they have same number of arguments. This routine assumes that Objective-C
1875 /// pointer types which only differ in their protocol qualifiers are equal.
1876 bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
1877 const FunctionProtoType *NewType) {
1878 if (!getLangOptions().ObjC1)
1879 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1880 NewType->arg_type_begin());
1882 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1883 N = NewType->arg_type_begin(),
1884 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1885 QualType ToType = (*O);
1886 QualType FromType = (*N);
1887 if (ToType != FromType) {
1888 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1889 if (const PointerType *PTFr = FromType->getAs<PointerType>())
1890 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1891 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1892 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1893 PTFr->getPointeeType()->isObjCQualifiedClassType()))
1894 continue;
1896 else if (const ObjCObjectPointerType *PTTo =
1897 ToType->getAs<ObjCObjectPointerType>()) {
1898 if (const ObjCObjectPointerType *PTFr =
1899 FromType->getAs<ObjCObjectPointerType>())
1900 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1901 continue;
1903 return false;
1906 return true;
1909 /// CheckPointerConversion - Check the pointer conversion from the
1910 /// expression From to the type ToType. This routine checks for
1911 /// ambiguous or inaccessible derived-to-base pointer
1912 /// conversions for which IsPointerConversion has already returned
1913 /// true. It returns true and produces a diagnostic if there was an
1914 /// error, or returns false otherwise.
1915 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
1916 CastKind &Kind,
1917 CXXCastPath& BasePath,
1918 bool IgnoreBaseAccess) {
1919 QualType FromType = From->getType();
1920 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
1922 Kind = CK_BitCast;
1924 if (CXXBoolLiteralExpr* LitBool
1925 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
1926 if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false)
1927 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1928 << ToType;
1930 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1931 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
1932 QualType FromPointeeType = FromPtrType->getPointeeType(),
1933 ToPointeeType = ToPtrType->getPointeeType();
1935 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1936 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
1937 // We must have a derived-to-base conversion. Check an
1938 // ambiguous or inaccessible conversion.
1939 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1940 From->getExprLoc(),
1941 From->getSourceRange(), &BasePath,
1942 IgnoreBaseAccess))
1943 return true;
1945 // The conversion was successful.
1946 Kind = CK_DerivedToBase;
1949 if (const ObjCObjectPointerType *FromPtrType =
1950 FromType->getAs<ObjCObjectPointerType>()) {
1951 if (const ObjCObjectPointerType *ToPtrType =
1952 ToType->getAs<ObjCObjectPointerType>()) {
1953 // Objective-C++ conversions are always okay.
1954 // FIXME: We should have a different class of conversions for the
1955 // Objective-C++ implicit conversions.
1956 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
1957 return false;
1961 // We shouldn't fall into this case unless it's valid for other
1962 // reasons.
1963 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
1964 Kind = CK_NullToPointer;
1966 return false;
1969 /// IsMemberPointerConversion - Determines whether the conversion of the
1970 /// expression From, which has the (possibly adjusted) type FromType, can be
1971 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
1972 /// If so, returns true and places the converted type (that might differ from
1973 /// ToType in its cv-qualifiers at some level) into ConvertedType.
1974 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1975 QualType ToType,
1976 bool InOverloadResolution,
1977 QualType &ConvertedType) {
1978 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
1979 if (!ToTypePtr)
1980 return false;
1982 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1983 if (From->isNullPointerConstant(Context,
1984 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1985 : Expr::NPC_ValueDependentIsNull)) {
1986 ConvertedType = ToType;
1987 return true;
1990 // Otherwise, both types have to be member pointers.
1991 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
1992 if (!FromTypePtr)
1993 return false;
1995 // A pointer to member of B can be converted to a pointer to member of D,
1996 // where D is derived from B (C++ 4.11p2).
1997 QualType FromClass(FromTypePtr->getClass(), 0);
1998 QualType ToClass(ToTypePtr->getClass(), 0);
2000 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2001 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2002 IsDerivedFrom(ToClass, FromClass)) {
2003 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2004 ToClass.getTypePtr());
2005 return true;
2008 return false;
2011 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2012 /// expression From to the type ToType. This routine checks for ambiguous or
2013 /// virtual or inaccessible base-to-derived member pointer conversions
2014 /// for which IsMemberPointerConversion has already returned true. It returns
2015 /// true and produces a diagnostic if there was an error, or returns false
2016 /// otherwise.
2017 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2018 CastKind &Kind,
2019 CXXCastPath &BasePath,
2020 bool IgnoreBaseAccess) {
2021 QualType FromType = From->getType();
2022 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2023 if (!FromPtrType) {
2024 // This must be a null pointer to member pointer conversion
2025 assert(From->isNullPointerConstant(Context,
2026 Expr::NPC_ValueDependentIsNull) &&
2027 "Expr must be null pointer constant!");
2028 Kind = CK_NullToMemberPointer;
2029 return false;
2032 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2033 assert(ToPtrType && "No member pointer cast has a target type "
2034 "that is not a member pointer.");
2036 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2037 QualType ToClass = QualType(ToPtrType->getClass(), 0);
2039 // FIXME: What about dependent types?
2040 assert(FromClass->isRecordType() && "Pointer into non-class.");
2041 assert(ToClass->isRecordType() && "Pointer into non-class.");
2043 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2044 /*DetectVirtual=*/true);
2045 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2046 assert(DerivationOkay &&
2047 "Should not have been called if derivation isn't OK.");
2048 (void)DerivationOkay;
2050 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2051 getUnqualifiedType())) {
2052 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2053 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2054 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2055 return true;
2058 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2059 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2060 << FromClass << ToClass << QualType(VBase, 0)
2061 << From->getSourceRange();
2062 return true;
2065 if (!IgnoreBaseAccess)
2066 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2067 Paths.front(),
2068 diag::err_downcast_from_inaccessible_base);
2070 // Must be a base to derived member conversion.
2071 BuildBasePathArray(Paths, BasePath);
2072 Kind = CK_BaseToDerivedMemberPointer;
2073 return false;
2076 /// IsQualificationConversion - Determines whether the conversion from
2077 /// an rvalue of type FromType to ToType is a qualification conversion
2078 /// (C++ 4.4).
2079 bool
2080 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2081 bool CStyle) {
2082 FromType = Context.getCanonicalType(FromType);
2083 ToType = Context.getCanonicalType(ToType);
2085 // If FromType and ToType are the same type, this is not a
2086 // qualification conversion.
2087 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2088 return false;
2090 // (C++ 4.4p4):
2091 // A conversion can add cv-qualifiers at levels other than the first
2092 // in multi-level pointers, subject to the following rules: [...]
2093 bool PreviousToQualsIncludeConst = true;
2094 bool UnwrappedAnyPointer = false;
2095 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2096 // Within each iteration of the loop, we check the qualifiers to
2097 // determine if this still looks like a qualification
2098 // conversion. Then, if all is well, we unwrap one more level of
2099 // pointers or pointers-to-members and do it all again
2100 // until there are no more pointers or pointers-to-members left to
2101 // unwrap.
2102 UnwrappedAnyPointer = true;
2104 // -- for every j > 0, if const is in cv 1,j then const is in cv
2105 // 2,j, and similarly for volatile.
2106 if (!CStyle && !ToType.isAtLeastAsQualifiedAs(FromType))
2107 return false;
2109 // -- if the cv 1,j and cv 2,j are different, then const is in
2110 // every cv for 0 < k < j.
2111 if (!CStyle && FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
2112 && !PreviousToQualsIncludeConst)
2113 return false;
2115 // Keep track of whether all prior cv-qualifiers in the "to" type
2116 // include const.
2117 PreviousToQualsIncludeConst
2118 = PreviousToQualsIncludeConst && ToType.isConstQualified();
2121 // We are left with FromType and ToType being the pointee types
2122 // after unwrapping the original FromType and ToType the same number
2123 // of types. If we unwrapped any pointers, and if FromType and
2124 // ToType have the same unqualified type (since we checked
2125 // qualifiers above), then this is a qualification conversion.
2126 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2129 /// Determines whether there is a user-defined conversion sequence
2130 /// (C++ [over.ics.user]) that converts expression From to the type
2131 /// ToType. If such a conversion exists, User will contain the
2132 /// user-defined conversion sequence that performs such a conversion
2133 /// and this routine will return true. Otherwise, this routine returns
2134 /// false and User is unspecified.
2136 /// \param AllowExplicit true if the conversion should consider C++0x
2137 /// "explicit" conversion functions as well as non-explicit conversion
2138 /// functions (C++0x [class.conv.fct]p2).
2139 static OverloadingResult
2140 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2141 UserDefinedConversionSequence& User,
2142 OverloadCandidateSet& CandidateSet,
2143 bool AllowExplicit) {
2144 // Whether we will only visit constructors.
2145 bool ConstructorsOnly = false;
2147 // If the type we are conversion to is a class type, enumerate its
2148 // constructors.
2149 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
2150 // C++ [over.match.ctor]p1:
2151 // When objects of class type are direct-initialized (8.5), or
2152 // copy-initialized from an expression of the same or a
2153 // derived class type (8.5), overload resolution selects the
2154 // constructor. [...] For copy-initialization, the candidate
2155 // functions are all the converting constructors (12.3.1) of
2156 // that class. The argument list is the expression-list within
2157 // the parentheses of the initializer.
2158 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
2159 (From->getType()->getAs<RecordType>() &&
2160 S.IsDerivedFrom(From->getType(), ToType)))
2161 ConstructorsOnly = true;
2163 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
2164 // We're not going to find any constructors.
2165 } else if (CXXRecordDecl *ToRecordDecl
2166 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
2167 DeclContext::lookup_iterator Con, ConEnd;
2168 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
2169 Con != ConEnd; ++Con) {
2170 NamedDecl *D = *Con;
2171 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2173 // Find the constructor (which may be a template).
2174 CXXConstructorDecl *Constructor = 0;
2175 FunctionTemplateDecl *ConstructorTmpl
2176 = dyn_cast<FunctionTemplateDecl>(D);
2177 if (ConstructorTmpl)
2178 Constructor
2179 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2180 else
2181 Constructor = cast<CXXConstructorDecl>(D);
2183 if (!Constructor->isInvalidDecl() &&
2184 Constructor->isConvertingConstructor(AllowExplicit)) {
2185 if (ConstructorTmpl)
2186 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2187 /*ExplicitArgs*/ 0,
2188 &From, 1, CandidateSet,
2189 /*SuppressUserConversions=*/
2190 !ConstructorsOnly);
2191 else
2192 // Allow one user-defined conversion when user specifies a
2193 // From->ToType conversion via an static cast (c-style, etc).
2194 S.AddOverloadCandidate(Constructor, FoundDecl,
2195 &From, 1, CandidateSet,
2196 /*SuppressUserConversions=*/
2197 !ConstructorsOnly);
2203 // Enumerate conversion functions, if we're allowed to.
2204 if (ConstructorsOnly) {
2205 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2206 S.PDiag(0) << From->getSourceRange())) {
2207 // No conversion functions from incomplete types.
2208 } else if (const RecordType *FromRecordType
2209 = From->getType()->getAs<RecordType>()) {
2210 if (CXXRecordDecl *FromRecordDecl
2211 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2212 // Add all of the conversion functions as candidates.
2213 const UnresolvedSetImpl *Conversions
2214 = FromRecordDecl->getVisibleConversionFunctions();
2215 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2216 E = Conversions->end(); I != E; ++I) {
2217 DeclAccessPair FoundDecl = I.getPair();
2218 NamedDecl *D = FoundDecl.getDecl();
2219 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2220 if (isa<UsingShadowDecl>(D))
2221 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2223 CXXConversionDecl *Conv;
2224 FunctionTemplateDecl *ConvTemplate;
2225 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2226 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2227 else
2228 Conv = cast<CXXConversionDecl>(D);
2230 if (AllowExplicit || !Conv->isExplicit()) {
2231 if (ConvTemplate)
2232 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2233 ActingContext, From, ToType,
2234 CandidateSet);
2235 else
2236 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2237 From, ToType, CandidateSet);
2243 OverloadCandidateSet::iterator Best;
2244 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2245 case OR_Success:
2246 // Record the standard conversion we used and the conversion function.
2247 if (CXXConstructorDecl *Constructor
2248 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2249 // C++ [over.ics.user]p1:
2250 // If the user-defined conversion is specified by a
2251 // constructor (12.3.1), the initial standard conversion
2252 // sequence converts the source type to the type required by
2253 // the argument of the constructor.
2255 QualType ThisType = Constructor->getThisType(S.Context);
2256 if (Best->Conversions[0].isEllipsis())
2257 User.EllipsisConversion = true;
2258 else {
2259 User.Before = Best->Conversions[0].Standard;
2260 User.EllipsisConversion = false;
2262 User.ConversionFunction = Constructor;
2263 User.FoundConversionFunction = Best->FoundDecl.getDecl();
2264 User.After.setAsIdentityConversion();
2265 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2266 User.After.setAllToTypes(ToType);
2267 return OR_Success;
2268 } else if (CXXConversionDecl *Conversion
2269 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2270 // C++ [over.ics.user]p1:
2272 // [...] If the user-defined conversion is specified by a
2273 // conversion function (12.3.2), the initial standard
2274 // conversion sequence converts the source type to the
2275 // implicit object parameter of the conversion function.
2276 User.Before = Best->Conversions[0].Standard;
2277 User.ConversionFunction = Conversion;
2278 User.FoundConversionFunction = Best->FoundDecl.getDecl();
2279 User.EllipsisConversion = false;
2281 // C++ [over.ics.user]p2:
2282 // The second standard conversion sequence converts the
2283 // result of the user-defined conversion to the target type
2284 // for the sequence. Since an implicit conversion sequence
2285 // is an initialization, the special rules for
2286 // initialization by user-defined conversion apply when
2287 // selecting the best user-defined conversion for a
2288 // user-defined conversion sequence (see 13.3.3 and
2289 // 13.3.3.1).
2290 User.After = Best->FinalConversion;
2291 return OR_Success;
2292 } else {
2293 llvm_unreachable("Not a constructor or conversion function?");
2294 return OR_No_Viable_Function;
2297 case OR_No_Viable_Function:
2298 return OR_No_Viable_Function;
2299 case OR_Deleted:
2300 // No conversion here! We're done.
2301 return OR_Deleted;
2303 case OR_Ambiguous:
2304 return OR_Ambiguous;
2307 return OR_No_Viable_Function;
2310 bool
2311 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
2312 ImplicitConversionSequence ICS;
2313 OverloadCandidateSet CandidateSet(From->getExprLoc());
2314 OverloadingResult OvResult =
2315 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
2316 CandidateSet, false);
2317 if (OvResult == OR_Ambiguous)
2318 Diag(From->getSourceRange().getBegin(),
2319 diag::err_typecheck_ambiguous_condition)
2320 << From->getType() << ToType << From->getSourceRange();
2321 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2322 Diag(From->getSourceRange().getBegin(),
2323 diag::err_typecheck_nonviable_condition)
2324 << From->getType() << ToType << From->getSourceRange();
2325 else
2326 return false;
2327 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
2328 return true;
2331 /// CompareImplicitConversionSequences - Compare two implicit
2332 /// conversion sequences to determine whether one is better than the
2333 /// other or if they are indistinguishable (C++ 13.3.3.2).
2334 static ImplicitConversionSequence::CompareKind
2335 CompareImplicitConversionSequences(Sema &S,
2336 const ImplicitConversionSequence& ICS1,
2337 const ImplicitConversionSequence& ICS2)
2339 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2340 // conversion sequences (as defined in 13.3.3.1)
2341 // -- a standard conversion sequence (13.3.3.1.1) is a better
2342 // conversion sequence than a user-defined conversion sequence or
2343 // an ellipsis conversion sequence, and
2344 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2345 // conversion sequence than an ellipsis conversion sequence
2346 // (13.3.3.1.3).
2348 // C++0x [over.best.ics]p10:
2349 // For the purpose of ranking implicit conversion sequences as
2350 // described in 13.3.3.2, the ambiguous conversion sequence is
2351 // treated as a user-defined sequence that is indistinguishable
2352 // from any other user-defined conversion sequence.
2353 if (ICS1.getKindRank() < ICS2.getKindRank())
2354 return ImplicitConversionSequence::Better;
2355 else if (ICS2.getKindRank() < ICS1.getKindRank())
2356 return ImplicitConversionSequence::Worse;
2358 // The following checks require both conversion sequences to be of
2359 // the same kind.
2360 if (ICS1.getKind() != ICS2.getKind())
2361 return ImplicitConversionSequence::Indistinguishable;
2363 // Two implicit conversion sequences of the same form are
2364 // indistinguishable conversion sequences unless one of the
2365 // following rules apply: (C++ 13.3.3.2p3):
2366 if (ICS1.isStandard())
2367 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
2368 else if (ICS1.isUserDefined()) {
2369 // User-defined conversion sequence U1 is a better conversion
2370 // sequence than another user-defined conversion sequence U2 if
2371 // they contain the same user-defined conversion function or
2372 // constructor and if the second standard conversion sequence of
2373 // U1 is better than the second standard conversion sequence of
2374 // U2 (C++ 13.3.3.2p3).
2375 if (ICS1.UserDefined.ConversionFunction ==
2376 ICS2.UserDefined.ConversionFunction)
2377 return CompareStandardConversionSequences(S,
2378 ICS1.UserDefined.After,
2379 ICS2.UserDefined.After);
2382 return ImplicitConversionSequence::Indistinguishable;
2385 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2386 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2387 Qualifiers Quals;
2388 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2389 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2392 return Context.hasSameUnqualifiedType(T1, T2);
2395 // Per 13.3.3.2p3, compare the given standard conversion sequences to
2396 // determine if one is a proper subset of the other.
2397 static ImplicitConversionSequence::CompareKind
2398 compareStandardConversionSubsets(ASTContext &Context,
2399 const StandardConversionSequence& SCS1,
2400 const StandardConversionSequence& SCS2) {
2401 ImplicitConversionSequence::CompareKind Result
2402 = ImplicitConversionSequence::Indistinguishable;
2404 // the identity conversion sequence is considered to be a subsequence of
2405 // any non-identity conversion sequence
2406 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2407 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2408 return ImplicitConversionSequence::Better;
2409 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2410 return ImplicitConversionSequence::Worse;
2413 if (SCS1.Second != SCS2.Second) {
2414 if (SCS1.Second == ICK_Identity)
2415 Result = ImplicitConversionSequence::Better;
2416 else if (SCS2.Second == ICK_Identity)
2417 Result = ImplicitConversionSequence::Worse;
2418 else
2419 return ImplicitConversionSequence::Indistinguishable;
2420 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
2421 return ImplicitConversionSequence::Indistinguishable;
2423 if (SCS1.Third == SCS2.Third) {
2424 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2425 : ImplicitConversionSequence::Indistinguishable;
2428 if (SCS1.Third == ICK_Identity)
2429 return Result == ImplicitConversionSequence::Worse
2430 ? ImplicitConversionSequence::Indistinguishable
2431 : ImplicitConversionSequence::Better;
2433 if (SCS2.Third == ICK_Identity)
2434 return Result == ImplicitConversionSequence::Better
2435 ? ImplicitConversionSequence::Indistinguishable
2436 : ImplicitConversionSequence::Worse;
2438 return ImplicitConversionSequence::Indistinguishable;
2441 /// \brief Determine whether one of the given reference bindings is better
2442 /// than the other based on what kind of bindings they are.
2443 static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2444 const StandardConversionSequence &SCS2) {
2445 // C++0x [over.ics.rank]p3b4:
2446 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2447 // implicit object parameter of a non-static member function declared
2448 // without a ref-qualifier, and *either* S1 binds an rvalue reference
2449 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
2450 // lvalue reference to a function lvalue and S2 binds an rvalue
2451 // reference*.
2453 // FIXME: Rvalue references. We're going rogue with the above edits,
2454 // because the semantics in the current C++0x working paper (N3225 at the
2455 // time of this writing) break the standard definition of std::forward
2456 // and std::reference_wrapper when dealing with references to functions.
2457 // Proposed wording changes submitted to CWG for consideration.
2458 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2459 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2460 return false;
2462 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2463 SCS2.IsLvalueReference) ||
2464 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2465 !SCS2.IsLvalueReference);
2468 /// CompareStandardConversionSequences - Compare two standard
2469 /// conversion sequences to determine whether one is better than the
2470 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
2471 static ImplicitConversionSequence::CompareKind
2472 CompareStandardConversionSequences(Sema &S,
2473 const StandardConversionSequence& SCS1,
2474 const StandardConversionSequence& SCS2)
2476 // Standard conversion sequence S1 is a better conversion sequence
2477 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2479 // -- S1 is a proper subsequence of S2 (comparing the conversion
2480 // sequences in the canonical form defined by 13.3.3.1.1,
2481 // excluding any Lvalue Transformation; the identity conversion
2482 // sequence is considered to be a subsequence of any
2483 // non-identity conversion sequence) or, if not that,
2484 if (ImplicitConversionSequence::CompareKind CK
2485 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
2486 return CK;
2488 // -- the rank of S1 is better than the rank of S2 (by the rules
2489 // defined below), or, if not that,
2490 ImplicitConversionRank Rank1 = SCS1.getRank();
2491 ImplicitConversionRank Rank2 = SCS2.getRank();
2492 if (Rank1 < Rank2)
2493 return ImplicitConversionSequence::Better;
2494 else if (Rank2 < Rank1)
2495 return ImplicitConversionSequence::Worse;
2497 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2498 // are indistinguishable unless one of the following rules
2499 // applies:
2501 // A conversion that is not a conversion of a pointer, or
2502 // pointer to member, to bool is better than another conversion
2503 // that is such a conversion.
2504 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2505 return SCS2.isPointerConversionToBool()
2506 ? ImplicitConversionSequence::Better
2507 : ImplicitConversionSequence::Worse;
2509 // C++ [over.ics.rank]p4b2:
2511 // If class B is derived directly or indirectly from class A,
2512 // conversion of B* to A* is better than conversion of B* to
2513 // void*, and conversion of A* to void* is better than conversion
2514 // of B* to void*.
2515 bool SCS1ConvertsToVoid
2516 = SCS1.isPointerConversionToVoidPointer(S.Context);
2517 bool SCS2ConvertsToVoid
2518 = SCS2.isPointerConversionToVoidPointer(S.Context);
2519 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2520 // Exactly one of the conversion sequences is a conversion to
2521 // a void pointer; it's the worse conversion.
2522 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2523 : ImplicitConversionSequence::Worse;
2524 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2525 // Neither conversion sequence converts to a void pointer; compare
2526 // their derived-to-base conversions.
2527 if (ImplicitConversionSequence::CompareKind DerivedCK
2528 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
2529 return DerivedCK;
2530 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2531 // Both conversion sequences are conversions to void
2532 // pointers. Compare the source types to determine if there's an
2533 // inheritance relationship in their sources.
2534 QualType FromType1 = SCS1.getFromType();
2535 QualType FromType2 = SCS2.getFromType();
2537 // Adjust the types we're converting from via the array-to-pointer
2538 // conversion, if we need to.
2539 if (SCS1.First == ICK_Array_To_Pointer)
2540 FromType1 = S.Context.getArrayDecayedType(FromType1);
2541 if (SCS2.First == ICK_Array_To_Pointer)
2542 FromType2 = S.Context.getArrayDecayedType(FromType2);
2544 QualType FromPointee1
2545 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2546 QualType FromPointee2
2547 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2549 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
2550 return ImplicitConversionSequence::Better;
2551 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
2552 return ImplicitConversionSequence::Worse;
2554 // Objective-C++: If one interface is more specific than the
2555 // other, it is the better one.
2556 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2557 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2558 if (FromIface1 && FromIface1) {
2559 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2560 return ImplicitConversionSequence::Better;
2561 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2562 return ImplicitConversionSequence::Worse;
2566 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2567 // bullet 3).
2568 if (ImplicitConversionSequence::CompareKind QualCK
2569 = CompareQualificationConversions(S, SCS1, SCS2))
2570 return QualCK;
2572 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
2573 // Check for a better reference binding based on the kind of bindings.
2574 if (isBetterReferenceBindingKind(SCS1, SCS2))
2575 return ImplicitConversionSequence::Better;
2576 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2577 return ImplicitConversionSequence::Worse;
2579 // C++ [over.ics.rank]p3b4:
2580 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2581 // which the references refer are the same type except for
2582 // top-level cv-qualifiers, and the type to which the reference
2583 // initialized by S2 refers is more cv-qualified than the type
2584 // to which the reference initialized by S1 refers.
2585 QualType T1 = SCS1.getToType(2);
2586 QualType T2 = SCS2.getToType(2);
2587 T1 = S.Context.getCanonicalType(T1);
2588 T2 = S.Context.getCanonicalType(T2);
2589 Qualifiers T1Quals, T2Quals;
2590 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2591 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
2592 if (UnqualT1 == UnqualT2) {
2593 // If the type is an array type, promote the element qualifiers to the
2594 // type for comparison.
2595 if (isa<ArrayType>(T1) && T1Quals)
2596 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
2597 if (isa<ArrayType>(T2) && T2Quals)
2598 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
2599 if (T2.isMoreQualifiedThan(T1))
2600 return ImplicitConversionSequence::Better;
2601 else if (T1.isMoreQualifiedThan(T2))
2602 return ImplicitConversionSequence::Worse;
2606 return ImplicitConversionSequence::Indistinguishable;
2609 /// CompareQualificationConversions - Compares two standard conversion
2610 /// sequences to determine whether they can be ranked based on their
2611 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2612 ImplicitConversionSequence::CompareKind
2613 CompareQualificationConversions(Sema &S,
2614 const StandardConversionSequence& SCS1,
2615 const StandardConversionSequence& SCS2) {
2616 // C++ 13.3.3.2p3:
2617 // -- S1 and S2 differ only in their qualification conversion and
2618 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2619 // cv-qualification signature of type T1 is a proper subset of
2620 // the cv-qualification signature of type T2, and S1 is not the
2621 // deprecated string literal array-to-pointer conversion (4.2).
2622 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2623 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2624 return ImplicitConversionSequence::Indistinguishable;
2626 // FIXME: the example in the standard doesn't use a qualification
2627 // conversion (!)
2628 QualType T1 = SCS1.getToType(2);
2629 QualType T2 = SCS2.getToType(2);
2630 T1 = S.Context.getCanonicalType(T1);
2631 T2 = S.Context.getCanonicalType(T2);
2632 Qualifiers T1Quals, T2Quals;
2633 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2634 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
2636 // If the types are the same, we won't learn anything by unwrapped
2637 // them.
2638 if (UnqualT1 == UnqualT2)
2639 return ImplicitConversionSequence::Indistinguishable;
2641 // If the type is an array type, promote the element qualifiers to the type
2642 // for comparison.
2643 if (isa<ArrayType>(T1) && T1Quals)
2644 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
2645 if (isa<ArrayType>(T2) && T2Quals)
2646 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
2648 ImplicitConversionSequence::CompareKind Result
2649 = ImplicitConversionSequence::Indistinguishable;
2650 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
2651 // Within each iteration of the loop, we check the qualifiers to
2652 // determine if this still looks like a qualification
2653 // conversion. Then, if all is well, we unwrap one more level of
2654 // pointers or pointers-to-members and do it all again
2655 // until there are no more pointers or pointers-to-members left
2656 // to unwrap. This essentially mimics what
2657 // IsQualificationConversion does, but here we're checking for a
2658 // strict subset of qualifiers.
2659 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2660 // The qualifiers are the same, so this doesn't tell us anything
2661 // about how the sequences rank.
2663 else if (T2.isMoreQualifiedThan(T1)) {
2664 // T1 has fewer qualifiers, so it could be the better sequence.
2665 if (Result == ImplicitConversionSequence::Worse)
2666 // Neither has qualifiers that are a subset of the other's
2667 // qualifiers.
2668 return ImplicitConversionSequence::Indistinguishable;
2670 Result = ImplicitConversionSequence::Better;
2671 } else if (T1.isMoreQualifiedThan(T2)) {
2672 // T2 has fewer qualifiers, so it could be the better sequence.
2673 if (Result == ImplicitConversionSequence::Better)
2674 // Neither has qualifiers that are a subset of the other's
2675 // qualifiers.
2676 return ImplicitConversionSequence::Indistinguishable;
2678 Result = ImplicitConversionSequence::Worse;
2679 } else {
2680 // Qualifiers are disjoint.
2681 return ImplicitConversionSequence::Indistinguishable;
2684 // If the types after this point are equivalent, we're done.
2685 if (S.Context.hasSameUnqualifiedType(T1, T2))
2686 break;
2689 // Check that the winning standard conversion sequence isn't using
2690 // the deprecated string literal array to pointer conversion.
2691 switch (Result) {
2692 case ImplicitConversionSequence::Better:
2693 if (SCS1.DeprecatedStringLiteralToCharPtr)
2694 Result = ImplicitConversionSequence::Indistinguishable;
2695 break;
2697 case ImplicitConversionSequence::Indistinguishable:
2698 break;
2700 case ImplicitConversionSequence::Worse:
2701 if (SCS2.DeprecatedStringLiteralToCharPtr)
2702 Result = ImplicitConversionSequence::Indistinguishable;
2703 break;
2706 return Result;
2709 /// CompareDerivedToBaseConversions - Compares two standard conversion
2710 /// sequences to determine whether they can be ranked based on their
2711 /// various kinds of derived-to-base conversions (C++
2712 /// [over.ics.rank]p4b3). As part of these checks, we also look at
2713 /// conversions between Objective-C interface types.
2714 ImplicitConversionSequence::CompareKind
2715 CompareDerivedToBaseConversions(Sema &S,
2716 const StandardConversionSequence& SCS1,
2717 const StandardConversionSequence& SCS2) {
2718 QualType FromType1 = SCS1.getFromType();
2719 QualType ToType1 = SCS1.getToType(1);
2720 QualType FromType2 = SCS2.getFromType();
2721 QualType ToType2 = SCS2.getToType(1);
2723 // Adjust the types we're converting from via the array-to-pointer
2724 // conversion, if we need to.
2725 if (SCS1.First == ICK_Array_To_Pointer)
2726 FromType1 = S.Context.getArrayDecayedType(FromType1);
2727 if (SCS2.First == ICK_Array_To_Pointer)
2728 FromType2 = S.Context.getArrayDecayedType(FromType2);
2730 // Canonicalize all of the types.
2731 FromType1 = S.Context.getCanonicalType(FromType1);
2732 ToType1 = S.Context.getCanonicalType(ToType1);
2733 FromType2 = S.Context.getCanonicalType(FromType2);
2734 ToType2 = S.Context.getCanonicalType(ToType2);
2736 // C++ [over.ics.rank]p4b3:
2738 // If class B is derived directly or indirectly from class A and
2739 // class C is derived directly or indirectly from B,
2741 // Compare based on pointer conversions.
2742 if (SCS1.Second == ICK_Pointer_Conversion &&
2743 SCS2.Second == ICK_Pointer_Conversion &&
2744 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2745 FromType1->isPointerType() && FromType2->isPointerType() &&
2746 ToType1->isPointerType() && ToType2->isPointerType()) {
2747 QualType FromPointee1
2748 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2749 QualType ToPointee1
2750 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2751 QualType FromPointee2
2752 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2753 QualType ToPointee2
2754 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2756 // -- conversion of C* to B* is better than conversion of C* to A*,
2757 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2758 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
2759 return ImplicitConversionSequence::Better;
2760 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
2761 return ImplicitConversionSequence::Worse;
2764 // -- conversion of B* to A* is better than conversion of C* to A*,
2765 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2766 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
2767 return ImplicitConversionSequence::Better;
2768 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
2769 return ImplicitConversionSequence::Worse;
2771 } else if (SCS1.Second == ICK_Pointer_Conversion &&
2772 SCS2.Second == ICK_Pointer_Conversion) {
2773 const ObjCObjectPointerType *FromPtr1
2774 = FromType1->getAs<ObjCObjectPointerType>();
2775 const ObjCObjectPointerType *FromPtr2
2776 = FromType2->getAs<ObjCObjectPointerType>();
2777 const ObjCObjectPointerType *ToPtr1
2778 = ToType1->getAs<ObjCObjectPointerType>();
2779 const ObjCObjectPointerType *ToPtr2
2780 = ToType2->getAs<ObjCObjectPointerType>();
2782 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
2783 // Apply the same conversion ranking rules for Objective-C pointer types
2784 // that we do for C++ pointers to class types. However, we employ the
2785 // Objective-C pseudo-subtyping relationship used for assignment of
2786 // Objective-C pointer types.
2787 bool FromAssignLeft
2788 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
2789 bool FromAssignRight
2790 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
2791 bool ToAssignLeft
2792 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
2793 bool ToAssignRight
2794 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
2796 // A conversion to an a non-id object pointer type or qualified 'id'
2797 // type is better than a conversion to 'id'.
2798 if (ToPtr1->isObjCIdType() &&
2799 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
2800 return ImplicitConversionSequence::Worse;
2801 if (ToPtr2->isObjCIdType() &&
2802 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
2803 return ImplicitConversionSequence::Better;
2805 // A conversion to a non-id object pointer type is better than a
2806 // conversion to a qualified 'id' type
2807 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
2808 return ImplicitConversionSequence::Worse;
2809 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
2810 return ImplicitConversionSequence::Better;
2812 // A conversion to an a non-Class object pointer type or qualified 'Class'
2813 // type is better than a conversion to 'Class'.
2814 if (ToPtr1->isObjCClassType() &&
2815 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
2816 return ImplicitConversionSequence::Worse;
2817 if (ToPtr2->isObjCClassType() &&
2818 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
2819 return ImplicitConversionSequence::Better;
2821 // A conversion to a non-Class object pointer type is better than a
2822 // conversion to a qualified 'Class' type.
2823 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
2824 return ImplicitConversionSequence::Worse;
2825 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
2826 return ImplicitConversionSequence::Better;
2828 // -- "conversion of C* to B* is better than conversion of C* to A*,"
2829 if (S.Context.hasSameType(FromType1, FromType2) &&
2830 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
2831 (ToAssignLeft != ToAssignRight))
2832 return ToAssignLeft? ImplicitConversionSequence::Worse
2833 : ImplicitConversionSequence::Better;
2835 // -- "conversion of B* to A* is better than conversion of C* to A*,"
2836 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
2837 (FromAssignLeft != FromAssignRight))
2838 return FromAssignLeft? ImplicitConversionSequence::Better
2839 : ImplicitConversionSequence::Worse;
2843 // Ranking of member-pointer types.
2844 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2845 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2846 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2847 const MemberPointerType * FromMemPointer1 =
2848 FromType1->getAs<MemberPointerType>();
2849 const MemberPointerType * ToMemPointer1 =
2850 ToType1->getAs<MemberPointerType>();
2851 const MemberPointerType * FromMemPointer2 =
2852 FromType2->getAs<MemberPointerType>();
2853 const MemberPointerType * ToMemPointer2 =
2854 ToType2->getAs<MemberPointerType>();
2855 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2856 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2857 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2858 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2859 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2860 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2861 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2862 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
2863 // conversion of A::* to B::* is better than conversion of A::* to C::*,
2864 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2865 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
2866 return ImplicitConversionSequence::Worse;
2867 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
2868 return ImplicitConversionSequence::Better;
2870 // conversion of B::* to C::* is better than conversion of A::* to C::*
2871 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2872 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
2873 return ImplicitConversionSequence::Better;
2874 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
2875 return ImplicitConversionSequence::Worse;
2879 if (SCS1.Second == ICK_Derived_To_Base) {
2880 // -- conversion of C to B is better than conversion of C to A,
2881 // -- binding of an expression of type C to a reference of type
2882 // B& is better than binding an expression of type C to a
2883 // reference of type A&,
2884 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2885 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2886 if (S.IsDerivedFrom(ToType1, ToType2))
2887 return ImplicitConversionSequence::Better;
2888 else if (S.IsDerivedFrom(ToType2, ToType1))
2889 return ImplicitConversionSequence::Worse;
2892 // -- conversion of B to A is better than conversion of C to A.
2893 // -- binding of an expression of type B to a reference of type
2894 // A& is better than binding an expression of type C to a
2895 // reference of type A&,
2896 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2897 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2898 if (S.IsDerivedFrom(FromType2, FromType1))
2899 return ImplicitConversionSequence::Better;
2900 else if (S.IsDerivedFrom(FromType1, FromType2))
2901 return ImplicitConversionSequence::Worse;
2905 return ImplicitConversionSequence::Indistinguishable;
2908 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
2909 /// determine whether they are reference-related,
2910 /// reference-compatible, reference-compatible with added
2911 /// qualification, or incompatible, for use in C++ initialization by
2912 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2913 /// type, and the first type (T1) is the pointee type of the reference
2914 /// type being initialized.
2915 Sema::ReferenceCompareResult
2916 Sema::CompareReferenceRelationship(SourceLocation Loc,
2917 QualType OrigT1, QualType OrigT2,
2918 bool &DerivedToBase,
2919 bool &ObjCConversion) {
2920 assert(!OrigT1->isReferenceType() &&
2921 "T1 must be the pointee type of the reference type");
2922 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2924 QualType T1 = Context.getCanonicalType(OrigT1);
2925 QualType T2 = Context.getCanonicalType(OrigT2);
2926 Qualifiers T1Quals, T2Quals;
2927 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2928 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2930 // C++ [dcl.init.ref]p4:
2931 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2932 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2933 // T1 is a base class of T2.
2934 DerivedToBase = false;
2935 ObjCConversion = false;
2936 if (UnqualT1 == UnqualT2) {
2937 // Nothing to do.
2938 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
2939 IsDerivedFrom(UnqualT2, UnqualT1))
2940 DerivedToBase = true;
2941 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2942 UnqualT2->isObjCObjectOrInterfaceType() &&
2943 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2944 ObjCConversion = true;
2945 else
2946 return Ref_Incompatible;
2948 // At this point, we know that T1 and T2 are reference-related (at
2949 // least).
2951 // If the type is an array type, promote the element qualifiers to the type
2952 // for comparison.
2953 if (isa<ArrayType>(T1) && T1Quals)
2954 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2955 if (isa<ArrayType>(T2) && T2Quals)
2956 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2958 // C++ [dcl.init.ref]p4:
2959 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2960 // reference-related to T2 and cv1 is the same cv-qualification
2961 // as, or greater cv-qualification than, cv2. For purposes of
2962 // overload resolution, cases for which cv1 is greater
2963 // cv-qualification than cv2 are identified as
2964 // reference-compatible with added qualification (see 13.3.3.2).
2965 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2966 return Ref_Compatible;
2967 else if (T1.isMoreQualifiedThan(T2))
2968 return Ref_Compatible_With_Added_Qualification;
2969 else
2970 return Ref_Related;
2973 /// \brief Look for a user-defined conversion to an value reference-compatible
2974 /// with DeclType. Return true if something definite is found.
2975 static bool
2976 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2977 QualType DeclType, SourceLocation DeclLoc,
2978 Expr *Init, QualType T2, bool AllowRvalues,
2979 bool AllowExplicit) {
2980 assert(T2->isRecordType() && "Can only find conversions of record types.");
2981 CXXRecordDecl *T2RecordDecl
2982 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2984 OverloadCandidateSet CandidateSet(DeclLoc);
2985 const UnresolvedSetImpl *Conversions
2986 = T2RecordDecl->getVisibleConversionFunctions();
2987 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2988 E = Conversions->end(); I != E; ++I) {
2989 NamedDecl *D = *I;
2990 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2991 if (isa<UsingShadowDecl>(D))
2992 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2994 FunctionTemplateDecl *ConvTemplate
2995 = dyn_cast<FunctionTemplateDecl>(D);
2996 CXXConversionDecl *Conv;
2997 if (ConvTemplate)
2998 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2999 else
3000 Conv = cast<CXXConversionDecl>(D);
3002 // If this is an explicit conversion, and we're not allowed to consider
3003 // explicit conversions, skip it.
3004 if (!AllowExplicit && Conv->isExplicit())
3005 continue;
3007 if (AllowRvalues) {
3008 bool DerivedToBase = false;
3009 bool ObjCConversion = false;
3010 if (!ConvTemplate &&
3011 S.CompareReferenceRelationship(
3012 DeclLoc,
3013 Conv->getConversionType().getNonReferenceType()
3014 .getUnqualifiedType(),
3015 DeclType.getNonReferenceType().getUnqualifiedType(),
3016 DerivedToBase, ObjCConversion) ==
3017 Sema::Ref_Incompatible)
3018 continue;
3019 } else {
3020 // If the conversion function doesn't return a reference type,
3021 // it can't be considered for this conversion. An rvalue reference
3022 // is only acceptable if its referencee is a function type.
3024 const ReferenceType *RefType =
3025 Conv->getConversionType()->getAs<ReferenceType>();
3026 if (!RefType ||
3027 (!RefType->isLValueReferenceType() &&
3028 !RefType->getPointeeType()->isFunctionType()))
3029 continue;
3032 if (ConvTemplate)
3033 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
3034 Init, DeclType, CandidateSet);
3035 else
3036 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
3037 DeclType, CandidateSet);
3040 OverloadCandidateSet::iterator Best;
3041 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
3042 case OR_Success:
3043 // C++ [over.ics.ref]p1:
3045 // [...] If the parameter binds directly to the result of
3046 // applying a conversion function to the argument
3047 // expression, the implicit conversion sequence is a
3048 // user-defined conversion sequence (13.3.3.1.2), with the
3049 // second standard conversion sequence either an identity
3050 // conversion or, if the conversion function returns an
3051 // entity of a type that is a derived class of the parameter
3052 // type, a derived-to-base Conversion.
3053 if (!Best->FinalConversion.DirectBinding)
3054 return false;
3056 ICS.setUserDefined();
3057 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3058 ICS.UserDefined.After = Best->FinalConversion;
3059 ICS.UserDefined.ConversionFunction = Best->Function;
3060 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl.getDecl();
3061 ICS.UserDefined.EllipsisConversion = false;
3062 assert(ICS.UserDefined.After.ReferenceBinding &&
3063 ICS.UserDefined.After.DirectBinding &&
3064 "Expected a direct reference binding!");
3065 return true;
3067 case OR_Ambiguous:
3068 ICS.setAmbiguous();
3069 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3070 Cand != CandidateSet.end(); ++Cand)
3071 if (Cand->Viable)
3072 ICS.Ambiguous.addConversion(Cand->Function);
3073 return true;
3075 case OR_No_Viable_Function:
3076 case OR_Deleted:
3077 // There was no suitable conversion, or we found a deleted
3078 // conversion; continue with other checks.
3079 return false;
3082 return false;
3085 /// \brief Compute an implicit conversion sequence for reference
3086 /// initialization.
3087 static ImplicitConversionSequence
3088 TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
3089 SourceLocation DeclLoc,
3090 bool SuppressUserConversions,
3091 bool AllowExplicit) {
3092 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3094 // Most paths end in a failed conversion.
3095 ImplicitConversionSequence ICS;
3096 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3098 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3099 QualType T2 = Init->getType();
3101 // If the initializer is the address of an overloaded function, try
3102 // to resolve the overloaded function. If all goes well, T2 is the
3103 // type of the resulting function.
3104 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3105 DeclAccessPair Found;
3106 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3107 false, Found))
3108 T2 = Fn->getType();
3111 // Compute some basic properties of the types and the initializer.
3112 bool isRValRef = DeclType->isRValueReferenceType();
3113 bool DerivedToBase = false;
3114 bool ObjCConversion = false;
3115 Expr::Classification InitCategory = Init->Classify(S.Context);
3116 Sema::ReferenceCompareResult RefRelationship
3117 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
3118 ObjCConversion);
3121 // C++0x [dcl.init.ref]p5:
3122 // A reference to type "cv1 T1" is initialized by an expression
3123 // of type "cv2 T2" as follows:
3125 // -- If reference is an lvalue reference and the initializer expression
3126 if (!isRValRef) {
3127 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3128 // reference-compatible with "cv2 T2," or
3130 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3131 if (InitCategory.isLValue() &&
3132 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
3133 // C++ [over.ics.ref]p1:
3134 // When a parameter of reference type binds directly (8.5.3)
3135 // to an argument expression, the implicit conversion sequence
3136 // is the identity conversion, unless the argument expression
3137 // has a type that is a derived class of the parameter type,
3138 // in which case the implicit conversion sequence is a
3139 // derived-to-base Conversion (13.3.3.1).
3140 ICS.setStandard();
3141 ICS.Standard.First = ICK_Identity;
3142 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3143 : ObjCConversion? ICK_Compatible_Conversion
3144 : ICK_Identity;
3145 ICS.Standard.Third = ICK_Identity;
3146 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3147 ICS.Standard.setToType(0, T2);
3148 ICS.Standard.setToType(1, T1);
3149 ICS.Standard.setToType(2, T1);
3150 ICS.Standard.ReferenceBinding = true;
3151 ICS.Standard.DirectBinding = true;
3152 ICS.Standard.IsLvalueReference = !isRValRef;
3153 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3154 ICS.Standard.BindsToRvalue = false;
3155 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3156 ICS.Standard.CopyConstructor = 0;
3158 // Nothing more to do: the inaccessibility/ambiguity check for
3159 // derived-to-base conversions is suppressed when we're
3160 // computing the implicit conversion sequence (C++
3161 // [over.best.ics]p2).
3162 return ICS;
3165 // -- has a class type (i.e., T2 is a class type), where T1 is
3166 // not reference-related to T2, and can be implicitly
3167 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3168 // is reference-compatible with "cv3 T3" 92) (this
3169 // conversion is selected by enumerating the applicable
3170 // conversion functions (13.3.1.6) and choosing the best
3171 // one through overload resolution (13.3)),
3172 if (!SuppressUserConversions && T2->isRecordType() &&
3173 !S.RequireCompleteType(DeclLoc, T2, 0) &&
3174 RefRelationship == Sema::Ref_Incompatible) {
3175 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3176 Init, T2, /*AllowRvalues=*/false,
3177 AllowExplicit))
3178 return ICS;
3182 // -- Otherwise, the reference shall be an lvalue reference to a
3183 // non-volatile const type (i.e., cv1 shall be const), or the reference
3184 // shall be an rvalue reference.
3186 // We actually handle one oddity of C++ [over.ics.ref] at this
3187 // point, which is that, due to p2 (which short-circuits reference
3188 // binding by only attempting a simple conversion for non-direct
3189 // bindings) and p3's strange wording, we allow a const volatile
3190 // reference to bind to an rvalue. Hence the check for the presence
3191 // of "const" rather than checking for "const" being the only
3192 // qualifier.
3193 // This is also the point where rvalue references and lvalue inits no longer
3194 // go together.
3195 if (!isRValRef && !T1.isConstQualified())
3196 return ICS;
3198 // -- If the initializer expression
3200 // -- is an xvalue, class prvalue, array prvalue or function
3201 // lvalue and "cv1T1" is reference-compatible with "cv2 T2", or
3202 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3203 (InitCategory.isXValue() ||
3204 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3205 (InitCategory.isLValue() && T2->isFunctionType()))) {
3206 ICS.setStandard();
3207 ICS.Standard.First = ICK_Identity;
3208 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3209 : ObjCConversion? ICK_Compatible_Conversion
3210 : ICK_Identity;
3211 ICS.Standard.Third = ICK_Identity;
3212 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3213 ICS.Standard.setToType(0, T2);
3214 ICS.Standard.setToType(1, T1);
3215 ICS.Standard.setToType(2, T1);
3216 ICS.Standard.ReferenceBinding = true;
3217 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3218 // binding unless we're binding to a class prvalue.
3219 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3220 // allow the use of rvalue references in C++98/03 for the benefit of
3221 // standard library implementors; therefore, we need the xvalue check here.
3222 ICS.Standard.DirectBinding =
3223 S.getLangOptions().CPlusPlus0x ||
3224 (InitCategory.isPRValue() && !T2->isRecordType());
3225 ICS.Standard.IsLvalueReference = !isRValRef;
3226 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3227 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
3228 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3229 ICS.Standard.CopyConstructor = 0;
3230 return ICS;
3233 // -- has a class type (i.e., T2 is a class type), where T1 is not
3234 // reference-related to T2, and can be implicitly converted to
3235 // an xvalue, class prvalue, or function lvalue of type
3236 // "cv3 T3", where "cv1 T1" is reference-compatible with
3237 // "cv3 T3",
3239 // then the reference is bound to the value of the initializer
3240 // expression in the first case and to the result of the conversion
3241 // in the second case (or, in either case, to an appropriate base
3242 // class subobject).
3243 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3244 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
3245 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3246 Init, T2, /*AllowRvalues=*/true,
3247 AllowExplicit)) {
3248 // In the second case, if the reference is an rvalue reference
3249 // and the second standard conversion sequence of the
3250 // user-defined conversion sequence includes an lvalue-to-rvalue
3251 // conversion, the program is ill-formed.
3252 if (ICS.isUserDefined() && isRValRef &&
3253 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3254 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3256 return ICS;
3259 // -- Otherwise, a temporary of type "cv1 T1" is created and
3260 // initialized from the initializer expression using the
3261 // rules for a non-reference copy initialization (8.5). The
3262 // reference is then bound to the temporary. If T1 is
3263 // reference-related to T2, cv1 must be the same
3264 // cv-qualification as, or greater cv-qualification than,
3265 // cv2; otherwise, the program is ill-formed.
3266 if (RefRelationship == Sema::Ref_Related) {
3267 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3268 // we would be reference-compatible or reference-compatible with
3269 // added qualification. But that wasn't the case, so the reference
3270 // initialization fails.
3271 return ICS;
3274 // If at least one of the types is a class type, the types are not
3275 // related, and we aren't allowed any user conversions, the
3276 // reference binding fails. This case is important for breaking
3277 // recursion, since TryImplicitConversion below will attempt to
3278 // create a temporary through the use of a copy constructor.
3279 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3280 (T1->isRecordType() || T2->isRecordType()))
3281 return ICS;
3283 // If T1 is reference-related to T2 and the reference is an rvalue
3284 // reference, the initializer expression shall not be an lvalue.
3285 if (RefRelationship >= Sema::Ref_Related &&
3286 isRValRef && Init->Classify(S.Context).isLValue())
3287 return ICS;
3289 // C++ [over.ics.ref]p2:
3290 // When a parameter of reference type is not bound directly to
3291 // an argument expression, the conversion sequence is the one
3292 // required to convert the argument expression to the
3293 // underlying type of the reference according to
3294 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3295 // to copy-initializing a temporary of the underlying type with
3296 // the argument expression. Any difference in top-level
3297 // cv-qualification is subsumed by the initialization itself
3298 // and does not constitute a conversion.
3299 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3300 /*AllowExplicit=*/false,
3301 /*InOverloadResolution=*/false,
3302 /*CStyle=*/false);
3304 // Of course, that's still a reference binding.
3305 if (ICS.isStandard()) {
3306 ICS.Standard.ReferenceBinding = true;
3307 ICS.Standard.IsLvalueReference = !isRValRef;
3308 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3309 ICS.Standard.BindsToRvalue = true;
3310 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3311 } else if (ICS.isUserDefined()) {
3312 ICS.UserDefined.After.ReferenceBinding = true;
3313 ICS.Standard.IsLvalueReference = !isRValRef;
3314 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3315 ICS.Standard.BindsToRvalue = true;
3316 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3319 return ICS;
3322 /// TryCopyInitialization - Try to copy-initialize a value of type
3323 /// ToType from the expression From. Return the implicit conversion
3324 /// sequence required to pass this argument, which may be a bad
3325 /// conversion sequence (meaning that the argument cannot be passed to
3326 /// a parameter of this type). If @p SuppressUserConversions, then we
3327 /// do not permit any user-defined conversion sequences.
3328 static ImplicitConversionSequence
3329 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
3330 bool SuppressUserConversions,
3331 bool InOverloadResolution) {
3332 if (ToType->isReferenceType())
3333 return TryReferenceInit(S, From, ToType,
3334 /*FIXME:*/From->getLocStart(),
3335 SuppressUserConversions,
3336 /*AllowExplicit=*/false);
3338 return TryImplicitConversion(S, From, ToType,
3339 SuppressUserConversions,
3340 /*AllowExplicit=*/false,
3341 InOverloadResolution,
3342 /*CStyle=*/false);
3345 /// TryObjectArgumentInitialization - Try to initialize the object
3346 /// parameter of the given member function (@c Method) from the
3347 /// expression @p From.
3348 static ImplicitConversionSequence
3349 TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
3350 Expr::Classification FromClassification,
3351 CXXMethodDecl *Method,
3352 CXXRecordDecl *ActingContext) {
3353 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
3354 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3355 // const volatile object.
3356 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3357 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
3358 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
3360 // Set up the conversion sequence as a "bad" conversion, to allow us
3361 // to exit early.
3362 ImplicitConversionSequence ICS;
3364 // We need to have an object of class type.
3365 QualType FromType = OrigFromType;
3366 if (const PointerType *PT = FromType->getAs<PointerType>()) {
3367 FromType = PT->getPointeeType();
3369 // When we had a pointer, it's implicitly dereferenced, so we
3370 // better have an lvalue.
3371 assert(FromClassification.isLValue());
3374 assert(FromType->isRecordType());
3376 // C++0x [over.match.funcs]p4:
3377 // For non-static member functions, the type of the implicit object
3378 // parameter is
3380 // - "lvalue reference to cv X" for functions declared without a
3381 // ref-qualifier or with the & ref-qualifier
3382 // - "rvalue reference to cv X" for functions declared with the &&
3383 // ref-qualifier
3385 // where X is the class of which the function is a member and cv is the
3386 // cv-qualification on the member function declaration.
3388 // However, when finding an implicit conversion sequence for the argument, we
3389 // are not allowed to create temporaries or perform user-defined conversions
3390 // (C++ [over.match.funcs]p5). We perform a simplified version of
3391 // reference binding here, that allows class rvalues to bind to
3392 // non-constant references.
3394 // First check the qualifiers.
3395 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
3396 if (ImplicitParamType.getCVRQualifiers()
3397 != FromTypeCanon.getLocalCVRQualifiers() &&
3398 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
3399 ICS.setBad(BadConversionSequence::bad_qualifiers,
3400 OrigFromType, ImplicitParamType);
3401 return ICS;
3404 // Check that we have either the same type or a derived type. It
3405 // affects the conversion rank.
3406 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
3407 ImplicitConversionKind SecondKind;
3408 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3409 SecondKind = ICK_Identity;
3410 } else if (S.IsDerivedFrom(FromType, ClassType))
3411 SecondKind = ICK_Derived_To_Base;
3412 else {
3413 ICS.setBad(BadConversionSequence::unrelated_class,
3414 FromType, ImplicitParamType);
3415 return ICS;
3418 // Check the ref-qualifier.
3419 switch (Method->getRefQualifier()) {
3420 case RQ_None:
3421 // Do nothing; we don't care about lvalueness or rvalueness.
3422 break;
3424 case RQ_LValue:
3425 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3426 // non-const lvalue reference cannot bind to an rvalue
3427 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
3428 ImplicitParamType);
3429 return ICS;
3431 break;
3433 case RQ_RValue:
3434 if (!FromClassification.isRValue()) {
3435 // rvalue reference cannot bind to an lvalue
3436 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
3437 ImplicitParamType);
3438 return ICS;
3440 break;
3443 // Success. Mark this as a reference binding.
3444 ICS.setStandard();
3445 ICS.Standard.setAsIdentityConversion();
3446 ICS.Standard.Second = SecondKind;
3447 ICS.Standard.setFromType(FromType);
3448 ICS.Standard.setAllToTypes(ImplicitParamType);
3449 ICS.Standard.ReferenceBinding = true;
3450 ICS.Standard.DirectBinding = true;
3451 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
3452 ICS.Standard.BindsToFunctionLvalue = false;
3453 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
3454 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
3455 = (Method->getRefQualifier() == RQ_None);
3456 return ICS;
3459 /// PerformObjectArgumentInitialization - Perform initialization of
3460 /// the implicit object parameter for the given Method with the given
3461 /// expression.
3462 bool
3463 Sema::PerformObjectArgumentInitialization(Expr *&From,
3464 NestedNameSpecifier *Qualifier,
3465 NamedDecl *FoundDecl,
3466 CXXMethodDecl *Method) {
3467 QualType FromRecordType, DestType;
3468 QualType ImplicitParamRecordType =
3469 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
3471 Expr::Classification FromClassification;
3472 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
3473 FromRecordType = PT->getPointeeType();
3474 DestType = Method->getThisType(Context);
3475 FromClassification = Expr::Classification::makeSimpleLValue();
3476 } else {
3477 FromRecordType = From->getType();
3478 DestType = ImplicitParamRecordType;
3479 FromClassification = From->Classify(Context);
3482 // Note that we always use the true parent context when performing
3483 // the actual argument initialization.
3484 ImplicitConversionSequence ICS
3485 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
3486 Method, Method->getParent());
3487 if (ICS.isBad()) {
3488 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3489 Qualifiers FromQs = FromRecordType.getQualifiers();
3490 Qualifiers ToQs = DestType.getQualifiers();
3491 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3492 if (CVR) {
3493 Diag(From->getSourceRange().getBegin(),
3494 diag::err_member_function_call_bad_cvr)
3495 << Method->getDeclName() << FromRecordType << (CVR - 1)
3496 << From->getSourceRange();
3497 Diag(Method->getLocation(), diag::note_previous_decl)
3498 << Method->getDeclName();
3499 return true;
3503 return Diag(From->getSourceRange().getBegin(),
3504 diag::err_implicit_object_parameter_init)
3505 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
3508 if (ICS.Standard.Second == ICK_Derived_To_Base)
3509 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
3511 if (!Context.hasSameType(From->getType(), DestType))
3512 ImpCastExprToType(From, DestType, CK_NoOp,
3513 From->getType()->isPointerType() ? VK_RValue : VK_LValue);
3514 return false;
3517 /// TryContextuallyConvertToBool - Attempt to contextually convert the
3518 /// expression From to bool (C++0x [conv]p3).
3519 static ImplicitConversionSequence
3520 TryContextuallyConvertToBool(Sema &S, Expr *From) {
3521 // FIXME: This is pretty broken.
3522 return TryImplicitConversion(S, From, S.Context.BoolTy,
3523 // FIXME: Are these flags correct?
3524 /*SuppressUserConversions=*/false,
3525 /*AllowExplicit=*/true,
3526 /*InOverloadResolution=*/false,
3527 /*CStyle=*/false);
3530 /// PerformContextuallyConvertToBool - Perform a contextual conversion
3531 /// of the expression From to bool (C++0x [conv]p3).
3532 bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
3533 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
3534 if (!ICS.isBad())
3535 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
3537 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
3538 return Diag(From->getSourceRange().getBegin(),
3539 diag::err_typecheck_bool_condition)
3540 << From->getType() << From->getSourceRange();
3541 return true;
3544 /// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3545 /// expression From to 'id'.
3546 static ImplicitConversionSequence
3547 TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3548 QualType Ty = S.Context.getObjCIdType();
3549 return TryImplicitConversion(S, From, Ty,
3550 // FIXME: Are these flags correct?
3551 /*SuppressUserConversions=*/false,
3552 /*AllowExplicit=*/true,
3553 /*InOverloadResolution=*/false,
3554 /*CStyle=*/false);
3557 /// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3558 /// of the expression From to 'id'.
3559 bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
3560 QualType Ty = Context.getObjCIdType();
3561 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
3562 if (!ICS.isBad())
3563 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3564 return true;
3567 /// \brief Attempt to convert the given expression to an integral or
3568 /// enumeration type.
3570 /// This routine will attempt to convert an expression of class type to an
3571 /// integral or enumeration type, if that class type only has a single
3572 /// conversion to an integral or enumeration type.
3574 /// \param Loc The source location of the construct that requires the
3575 /// conversion.
3577 /// \param FromE The expression we're converting from.
3579 /// \param NotIntDiag The diagnostic to be emitted if the expression does not
3580 /// have integral or enumeration type.
3582 /// \param IncompleteDiag The diagnostic to be emitted if the expression has
3583 /// incomplete class type.
3585 /// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3586 /// explicit conversion function (because no implicit conversion functions
3587 /// were available). This is a recovery mode.
3589 /// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3590 /// showing which conversion was picked.
3592 /// \param AmbigDiag The diagnostic to be emitted if there is more than one
3593 /// conversion function that could convert to integral or enumeration type.
3595 /// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3596 /// usable conversion function.
3598 /// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3599 /// function, which may be an extension in this case.
3601 /// \returns The expression, converted to an integral or enumeration type if
3602 /// successful.
3603 ExprResult
3604 Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
3605 const PartialDiagnostic &NotIntDiag,
3606 const PartialDiagnostic &IncompleteDiag,
3607 const PartialDiagnostic &ExplicitConvDiag,
3608 const PartialDiagnostic &ExplicitConvNote,
3609 const PartialDiagnostic &AmbigDiag,
3610 const PartialDiagnostic &AmbigNote,
3611 const PartialDiagnostic &ConvDiag) {
3612 // We can't perform any more checking for type-dependent expressions.
3613 if (From->isTypeDependent())
3614 return Owned(From);
3616 // If the expression already has integral or enumeration type, we're golden.
3617 QualType T = From->getType();
3618 if (T->isIntegralOrEnumerationType())
3619 return Owned(From);
3621 // FIXME: Check for missing '()' if T is a function type?
3623 // If we don't have a class type in C++, there's no way we can get an
3624 // expression of integral or enumeration type.
3625 const RecordType *RecordTy = T->getAs<RecordType>();
3626 if (!RecordTy || !getLangOptions().CPlusPlus) {
3627 Diag(Loc, NotIntDiag)
3628 << T << From->getSourceRange();
3629 return Owned(From);
3632 // We must have a complete class type.
3633 if (RequireCompleteType(Loc, T, IncompleteDiag))
3634 return Owned(From);
3636 // Look for a conversion to an integral or enumeration type.
3637 UnresolvedSet<4> ViableConversions;
3638 UnresolvedSet<4> ExplicitConversions;
3639 const UnresolvedSetImpl *Conversions
3640 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3642 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3643 E = Conversions->end();
3644 I != E;
3645 ++I) {
3646 if (CXXConversionDecl *Conversion
3647 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3648 if (Conversion->getConversionType().getNonReferenceType()
3649 ->isIntegralOrEnumerationType()) {
3650 if (Conversion->isExplicit())
3651 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3652 else
3653 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3657 switch (ViableConversions.size()) {
3658 case 0:
3659 if (ExplicitConversions.size() == 1) {
3660 DeclAccessPair Found = ExplicitConversions[0];
3661 CXXConversionDecl *Conversion
3662 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3664 // The user probably meant to invoke the given explicit
3665 // conversion; use it.
3666 QualType ConvTy
3667 = Conversion->getConversionType().getNonReferenceType();
3668 std::string TypeStr;
3669 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3671 Diag(Loc, ExplicitConvDiag)
3672 << T << ConvTy
3673 << FixItHint::CreateInsertion(From->getLocStart(),
3674 "static_cast<" + TypeStr + ">(")
3675 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3676 ")");
3677 Diag(Conversion->getLocation(), ExplicitConvNote)
3678 << ConvTy->isEnumeralType() << ConvTy;
3680 // If we aren't in a SFINAE context, build a call to the
3681 // explicit conversion function.
3682 if (isSFINAEContext())
3683 return ExprError();
3685 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
3686 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion);
3687 if (Result.isInvalid())
3688 return ExprError();
3690 From = Result.get();
3693 // We'll complain below about a non-integral condition type.
3694 break;
3696 case 1: {
3697 // Apply this conversion.
3698 DeclAccessPair Found = ViableConversions[0];
3699 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
3701 CXXConversionDecl *Conversion
3702 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3703 QualType ConvTy
3704 = Conversion->getConversionType().getNonReferenceType();
3705 if (ConvDiag.getDiagID()) {
3706 if (isSFINAEContext())
3707 return ExprError();
3709 Diag(Loc, ConvDiag)
3710 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3713 ExprResult Result = BuildCXXMemberCallExpr(From, Found,
3714 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
3715 if (Result.isInvalid())
3716 return ExprError();
3718 From = Result.get();
3719 break;
3722 default:
3723 Diag(Loc, AmbigDiag)
3724 << T << From->getSourceRange();
3725 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3726 CXXConversionDecl *Conv
3727 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3728 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3729 Diag(Conv->getLocation(), AmbigNote)
3730 << ConvTy->isEnumeralType() << ConvTy;
3732 return Owned(From);
3735 if (!From->getType()->isIntegralOrEnumerationType())
3736 Diag(Loc, NotIntDiag)
3737 << From->getType() << From->getSourceRange();
3739 return Owned(From);
3742 /// AddOverloadCandidate - Adds the given function to the set of
3743 /// candidate functions, using the given function call arguments. If
3744 /// @p SuppressUserConversions, then don't allow user-defined
3745 /// conversions via constructors or conversion operators.
3747 /// \para PartialOverloading true if we are performing "partial" overloading
3748 /// based on an incomplete set of function arguments. This feature is used by
3749 /// code completion.
3750 void
3751 Sema::AddOverloadCandidate(FunctionDecl *Function,
3752 DeclAccessPair FoundDecl,
3753 Expr **Args, unsigned NumArgs,
3754 OverloadCandidateSet& CandidateSet,
3755 bool SuppressUserConversions,
3756 bool PartialOverloading) {
3757 const FunctionProtoType* Proto
3758 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
3759 assert(Proto && "Functions without a prototype cannot be overloaded");
3760 assert(!Function->getDescribedFunctionTemplate() &&
3761 "Use AddTemplateOverloadCandidate for function templates");
3763 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3764 if (!isa<CXXConstructorDecl>(Method)) {
3765 // If we get here, it's because we're calling a member function
3766 // that is named without a member access expression (e.g.,
3767 // "this->f") that was either written explicitly or created
3768 // implicitly. This can happen with a qualified call to a member
3769 // function, e.g., X::f(). We use an empty type for the implied
3770 // object argument (C++ [over.call.func]p3), and the acting context
3771 // is irrelevant.
3772 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
3773 QualType(), Expr::Classification::makeSimpleLValue(),
3774 Args, NumArgs, CandidateSet,
3775 SuppressUserConversions);
3776 return;
3778 // We treat a constructor like a non-member function, since its object
3779 // argument doesn't participate in overload resolution.
3782 if (!CandidateSet.isNewCandidate(Function))
3783 return;
3785 // Overload resolution is always an unevaluated context.
3786 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
3788 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3789 // C++ [class.copy]p3:
3790 // A member function template is never instantiated to perform the copy
3791 // of a class object to an object of its class type.
3792 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3793 if (NumArgs == 1 &&
3794 Constructor->isSpecializationCopyingObject() &&
3795 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3796 IsDerivedFrom(Args[0]->getType(), ClassType)))
3797 return;
3800 // Add this candidate
3801 CandidateSet.push_back(OverloadCandidate());
3802 OverloadCandidate& Candidate = CandidateSet.back();
3803 Candidate.FoundDecl = FoundDecl;
3804 Candidate.Function = Function;
3805 Candidate.Viable = true;
3806 Candidate.IsSurrogate = false;
3807 Candidate.IgnoreObjectArgument = false;
3808 Candidate.ExplicitCallArguments = NumArgs;
3810 unsigned NumArgsInProto = Proto->getNumArgs();
3812 // (C++ 13.3.2p2): A candidate function having fewer than m
3813 // parameters is viable only if it has an ellipsis in its parameter
3814 // list (8.3.5).
3815 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3816 !Proto->isVariadic()) {
3817 Candidate.Viable = false;
3818 Candidate.FailureKind = ovl_fail_too_many_arguments;
3819 return;
3822 // (C++ 13.3.2p2): A candidate function having more than m parameters
3823 // is viable only if the (m+1)st parameter has a default argument
3824 // (8.3.6). For the purposes of overload resolution, the
3825 // parameter list is truncated on the right, so that there are
3826 // exactly m parameters.
3827 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
3828 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
3829 // Not enough arguments.
3830 Candidate.Viable = false;
3831 Candidate.FailureKind = ovl_fail_too_few_arguments;
3832 return;
3835 // Determine the implicit conversion sequences for each of the
3836 // arguments.
3837 Candidate.Conversions.resize(NumArgs);
3838 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3839 if (ArgIdx < NumArgsInProto) {
3840 // (C++ 13.3.2p3): for F to be a viable function, there shall
3841 // exist for each argument an implicit conversion sequence
3842 // (13.3.3.1) that converts that argument to the corresponding
3843 // parameter of F.
3844 QualType ParamType = Proto->getArgType(ArgIdx);
3845 Candidate.Conversions[ArgIdx]
3846 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
3847 SuppressUserConversions,
3848 /*InOverloadResolution=*/true);
3849 if (Candidate.Conversions[ArgIdx].isBad()) {
3850 Candidate.Viable = false;
3851 Candidate.FailureKind = ovl_fail_bad_conversion;
3852 break;
3854 } else {
3855 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3856 // argument for which there is no corresponding parameter is
3857 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
3858 Candidate.Conversions[ArgIdx].setEllipsis();
3863 /// \brief Add all of the function declarations in the given function set to
3864 /// the overload canddiate set.
3865 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
3866 Expr **Args, unsigned NumArgs,
3867 OverloadCandidateSet& CandidateSet,
3868 bool SuppressUserConversions) {
3869 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
3870 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3871 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3872 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
3873 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
3874 cast<CXXMethodDecl>(FD)->getParent(),
3875 Args[0]->getType(), Args[0]->Classify(Context),
3876 Args + 1, NumArgs - 1,
3877 CandidateSet, SuppressUserConversions);
3878 else
3879 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
3880 SuppressUserConversions);
3881 } else {
3882 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
3883 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3884 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
3885 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
3886 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
3887 /*FIXME: explicit args */ 0,
3888 Args[0]->getType(),
3889 Args[0]->Classify(Context),
3890 Args + 1, NumArgs - 1,
3891 CandidateSet,
3892 SuppressUserConversions);
3893 else
3894 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
3895 /*FIXME: explicit args */ 0,
3896 Args, NumArgs, CandidateSet,
3897 SuppressUserConversions);
3902 /// AddMethodCandidate - Adds a named decl (which is some kind of
3903 /// method) as a method candidate to the given overload set.
3904 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
3905 QualType ObjectType,
3906 Expr::Classification ObjectClassification,
3907 Expr **Args, unsigned NumArgs,
3908 OverloadCandidateSet& CandidateSet,
3909 bool SuppressUserConversions) {
3910 NamedDecl *Decl = FoundDecl.getDecl();
3911 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
3913 if (isa<UsingShadowDecl>(Decl))
3914 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3916 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3917 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3918 "Expected a member function template");
3919 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3920 /*ExplicitArgs*/ 0,
3921 ObjectType, ObjectClassification, Args, NumArgs,
3922 CandidateSet,
3923 SuppressUserConversions);
3924 } else {
3925 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
3926 ObjectType, ObjectClassification, Args, NumArgs,
3927 CandidateSet, SuppressUserConversions);
3931 /// AddMethodCandidate - Adds the given C++ member function to the set
3932 /// of candidate functions, using the given function call arguments
3933 /// and the object argument (@c Object). For example, in a call
3934 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3935 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3936 /// allow user-defined conversions via constructors or conversion
3937 /// operators.
3938 void
3939 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
3940 CXXRecordDecl *ActingContext, QualType ObjectType,
3941 Expr::Classification ObjectClassification,
3942 Expr **Args, unsigned NumArgs,
3943 OverloadCandidateSet& CandidateSet,
3944 bool SuppressUserConversions) {
3945 const FunctionProtoType* Proto
3946 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
3947 assert(Proto && "Methods without a prototype cannot be overloaded");
3948 assert(!isa<CXXConstructorDecl>(Method) &&
3949 "Use AddOverloadCandidate for constructors");
3951 if (!CandidateSet.isNewCandidate(Method))
3952 return;
3954 // Overload resolution is always an unevaluated context.
3955 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
3957 // Add this candidate
3958 CandidateSet.push_back(OverloadCandidate());
3959 OverloadCandidate& Candidate = CandidateSet.back();
3960 Candidate.FoundDecl = FoundDecl;
3961 Candidate.Function = Method;
3962 Candidate.IsSurrogate = false;
3963 Candidate.IgnoreObjectArgument = false;
3964 Candidate.ExplicitCallArguments = NumArgs;
3966 unsigned NumArgsInProto = Proto->getNumArgs();
3968 // (C++ 13.3.2p2): A candidate function having fewer than m
3969 // parameters is viable only if it has an ellipsis in its parameter
3970 // list (8.3.5).
3971 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3972 Candidate.Viable = false;
3973 Candidate.FailureKind = ovl_fail_too_many_arguments;
3974 return;
3977 // (C++ 13.3.2p2): A candidate function having more than m parameters
3978 // is viable only if the (m+1)st parameter has a default argument
3979 // (8.3.6). For the purposes of overload resolution, the
3980 // parameter list is truncated on the right, so that there are
3981 // exactly m parameters.
3982 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3983 if (NumArgs < MinRequiredArgs) {
3984 // Not enough arguments.
3985 Candidate.Viable = false;
3986 Candidate.FailureKind = ovl_fail_too_few_arguments;
3987 return;
3990 Candidate.Viable = true;
3991 Candidate.Conversions.resize(NumArgs + 1);
3993 if (Method->isStatic() || ObjectType.isNull())
3994 // The implicit object argument is ignored.
3995 Candidate.IgnoreObjectArgument = true;
3996 else {
3997 // Determine the implicit conversion sequence for the object
3998 // parameter.
3999 Candidate.Conversions[0]
4000 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4001 Method, ActingContext);
4002 if (Candidate.Conversions[0].isBad()) {
4003 Candidate.Viable = false;
4004 Candidate.FailureKind = ovl_fail_bad_conversion;
4005 return;
4009 // Determine the implicit conversion sequences for each of the
4010 // arguments.
4011 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4012 if (ArgIdx < NumArgsInProto) {
4013 // (C++ 13.3.2p3): for F to be a viable function, there shall
4014 // exist for each argument an implicit conversion sequence
4015 // (13.3.3.1) that converts that argument to the corresponding
4016 // parameter of F.
4017 QualType ParamType = Proto->getArgType(ArgIdx);
4018 Candidate.Conversions[ArgIdx + 1]
4019 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
4020 SuppressUserConversions,
4021 /*InOverloadResolution=*/true);
4022 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
4023 Candidate.Viable = false;
4024 Candidate.FailureKind = ovl_fail_bad_conversion;
4025 break;
4027 } else {
4028 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4029 // argument for which there is no corresponding parameter is
4030 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
4031 Candidate.Conversions[ArgIdx + 1].setEllipsis();
4036 /// \brief Add a C++ member function template as a candidate to the candidate
4037 /// set, using template argument deduction to produce an appropriate member
4038 /// function template specialization.
4039 void
4040 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
4041 DeclAccessPair FoundDecl,
4042 CXXRecordDecl *ActingContext,
4043 const TemplateArgumentListInfo *ExplicitTemplateArgs,
4044 QualType ObjectType,
4045 Expr::Classification ObjectClassification,
4046 Expr **Args, unsigned NumArgs,
4047 OverloadCandidateSet& CandidateSet,
4048 bool SuppressUserConversions) {
4049 if (!CandidateSet.isNewCandidate(MethodTmpl))
4050 return;
4052 // C++ [over.match.funcs]p7:
4053 // In each case where a candidate is a function template, candidate
4054 // function template specializations are generated using template argument
4055 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
4056 // candidate functions in the usual way.113) A given name can refer to one
4057 // or more function templates and also to a set of overloaded non-template
4058 // functions. In such a case, the candidate functions generated from each
4059 // function template are combined with the set of non-template candidate
4060 // functions.
4061 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
4062 FunctionDecl *Specialization = 0;
4063 if (TemplateDeductionResult Result
4064 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
4065 Args, NumArgs, Specialization, Info)) {
4066 CandidateSet.push_back(OverloadCandidate());
4067 OverloadCandidate &Candidate = CandidateSet.back();
4068 Candidate.FoundDecl = FoundDecl;
4069 Candidate.Function = MethodTmpl->getTemplatedDecl();
4070 Candidate.Viable = false;
4071 Candidate.FailureKind = ovl_fail_bad_deduction;
4072 Candidate.IsSurrogate = false;
4073 Candidate.IgnoreObjectArgument = false;
4074 Candidate.ExplicitCallArguments = NumArgs;
4075 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
4076 Info);
4077 return;
4080 // Add the function template specialization produced by template argument
4081 // deduction as a candidate.
4082 assert(Specialization && "Missing member function template specialization?");
4083 assert(isa<CXXMethodDecl>(Specialization) &&
4084 "Specialization is not a member function?");
4085 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
4086 ActingContext, ObjectType, ObjectClassification,
4087 Args, NumArgs, CandidateSet, SuppressUserConversions);
4090 /// \brief Add a C++ function template specialization as a candidate
4091 /// in the candidate set, using template argument deduction to produce
4092 /// an appropriate function template specialization.
4093 void
4094 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
4095 DeclAccessPair FoundDecl,
4096 const TemplateArgumentListInfo *ExplicitTemplateArgs,
4097 Expr **Args, unsigned NumArgs,
4098 OverloadCandidateSet& CandidateSet,
4099 bool SuppressUserConversions) {
4100 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4101 return;
4103 // C++ [over.match.funcs]p7:
4104 // In each case where a candidate is a function template, candidate
4105 // function template specializations are generated using template argument
4106 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
4107 // candidate functions in the usual way.113) A given name can refer to one
4108 // or more function templates and also to a set of overloaded non-template
4109 // functions. In such a case, the candidate functions generated from each
4110 // function template are combined with the set of non-template candidate
4111 // functions.
4112 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
4113 FunctionDecl *Specialization = 0;
4114 if (TemplateDeductionResult Result
4115 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
4116 Args, NumArgs, Specialization, Info)) {
4117 CandidateSet.push_back(OverloadCandidate());
4118 OverloadCandidate &Candidate = CandidateSet.back();
4119 Candidate.FoundDecl = FoundDecl;
4120 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4121 Candidate.Viable = false;
4122 Candidate.FailureKind = ovl_fail_bad_deduction;
4123 Candidate.IsSurrogate = false;
4124 Candidate.IgnoreObjectArgument = false;
4125 Candidate.ExplicitCallArguments = NumArgs;
4126 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
4127 Info);
4128 return;
4131 // Add the function template specialization produced by template argument
4132 // deduction as a candidate.
4133 assert(Specialization && "Missing function template specialization?");
4134 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
4135 SuppressUserConversions);
4138 /// AddConversionCandidate - Add a C++ conversion function as a
4139 /// candidate in the candidate set (C++ [over.match.conv],
4140 /// C++ [over.match.copy]). From is the expression we're converting from,
4141 /// and ToType is the type that we're eventually trying to convert to
4142 /// (which may or may not be the same type as the type that the
4143 /// conversion function produces).
4144 void
4145 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
4146 DeclAccessPair FoundDecl,
4147 CXXRecordDecl *ActingContext,
4148 Expr *From, QualType ToType,
4149 OverloadCandidateSet& CandidateSet) {
4150 assert(!Conversion->getDescribedFunctionTemplate() &&
4151 "Conversion function templates use AddTemplateConversionCandidate");
4152 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
4153 if (!CandidateSet.isNewCandidate(Conversion))
4154 return;
4156 // Overload resolution is always an unevaluated context.
4157 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
4159 // Add this candidate
4160 CandidateSet.push_back(OverloadCandidate());
4161 OverloadCandidate& Candidate = CandidateSet.back();
4162 Candidate.FoundDecl = FoundDecl;
4163 Candidate.Function = Conversion;
4164 Candidate.IsSurrogate = false;
4165 Candidate.IgnoreObjectArgument = false;
4166 Candidate.FinalConversion.setAsIdentityConversion();
4167 Candidate.FinalConversion.setFromType(ConvType);
4168 Candidate.FinalConversion.setAllToTypes(ToType);
4169 Candidate.Viable = true;
4170 Candidate.Conversions.resize(1);
4171 Candidate.ExplicitCallArguments = 1;
4173 // C++ [over.match.funcs]p4:
4174 // For conversion functions, the function is considered to be a member of
4175 // the class of the implicit implied object argument for the purpose of
4176 // defining the type of the implicit object parameter.
4178 // Determine the implicit conversion sequence for the implicit
4179 // object parameter.
4180 QualType ImplicitParamType = From->getType();
4181 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4182 ImplicitParamType = FromPtrType->getPointeeType();
4183 CXXRecordDecl *ConversionContext
4184 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
4186 Candidate.Conversions[0]
4187 = TryObjectArgumentInitialization(*this, From->getType(),
4188 From->Classify(Context),
4189 Conversion, ConversionContext);
4191 if (Candidate.Conversions[0].isBad()) {
4192 Candidate.Viable = false;
4193 Candidate.FailureKind = ovl_fail_bad_conversion;
4194 return;
4197 // We won't go through a user-define type conversion function to convert a
4198 // derived to base as such conversions are given Conversion Rank. They only
4199 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4200 QualType FromCanon
4201 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4202 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4203 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4204 Candidate.Viable = false;
4205 Candidate.FailureKind = ovl_fail_trivial_conversion;
4206 return;
4209 // To determine what the conversion from the result of calling the
4210 // conversion function to the type we're eventually trying to
4211 // convert to (ToType), we need to synthesize a call to the
4212 // conversion function and attempt copy initialization from it. This
4213 // makes sure that we get the right semantics with respect to
4214 // lvalues/rvalues and the type. Fortunately, we can allocate this
4215 // call on the stack and we don't need its arguments to be
4216 // well-formed.
4217 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
4218 VK_LValue, From->getLocStart());
4219 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4220 Context.getPointerType(Conversion->getType()),
4221 CK_FunctionToPointerDecay,
4222 &ConversionRef, VK_RValue);
4224 QualType CallResultType
4225 = Conversion->getConversionType().getNonLValueExprType(Context);
4226 if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
4227 Candidate.Viable = false;
4228 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4229 return;
4232 ExprValueKind VK = Expr::getValueKindForType(Conversion->getConversionType());
4234 // Note that it is safe to allocate CallExpr on the stack here because
4235 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4236 // allocator).
4237 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
4238 From->getLocStart());
4239 ImplicitConversionSequence ICS =
4240 TryCopyInitialization(*this, &Call, ToType,
4241 /*SuppressUserConversions=*/true,
4242 /*InOverloadResolution=*/false);
4244 switch (ICS.getKind()) {
4245 case ImplicitConversionSequence::StandardConversion:
4246 Candidate.FinalConversion = ICS.Standard;
4248 // C++ [over.ics.user]p3:
4249 // If the user-defined conversion is specified by a specialization of a
4250 // conversion function template, the second standard conversion sequence
4251 // shall have exact match rank.
4252 if (Conversion->getPrimaryTemplate() &&
4253 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4254 Candidate.Viable = false;
4255 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4258 // C++0x [dcl.init.ref]p5:
4259 // In the second case, if the reference is an rvalue reference and
4260 // the second standard conversion sequence of the user-defined
4261 // conversion sequence includes an lvalue-to-rvalue conversion, the
4262 // program is ill-formed.
4263 if (ToType->isRValueReferenceType() &&
4264 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4265 Candidate.Viable = false;
4266 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4268 break;
4270 case ImplicitConversionSequence::BadConversion:
4271 Candidate.Viable = false;
4272 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4273 break;
4275 default:
4276 assert(false &&
4277 "Can only end up with a standard conversion sequence or failure");
4281 /// \brief Adds a conversion function template specialization
4282 /// candidate to the overload set, using template argument deduction
4283 /// to deduce the template arguments of the conversion function
4284 /// template from the type that we are converting to (C++
4285 /// [temp.deduct.conv]).
4286 void
4287 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
4288 DeclAccessPair FoundDecl,
4289 CXXRecordDecl *ActingDC,
4290 Expr *From, QualType ToType,
4291 OverloadCandidateSet &CandidateSet) {
4292 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4293 "Only conversion function templates permitted here");
4295 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4296 return;
4298 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
4299 CXXConversionDecl *Specialization = 0;
4300 if (TemplateDeductionResult Result
4301 = DeduceTemplateArguments(FunctionTemplate, ToType,
4302 Specialization, Info)) {
4303 CandidateSet.push_back(OverloadCandidate());
4304 OverloadCandidate &Candidate = CandidateSet.back();
4305 Candidate.FoundDecl = FoundDecl;
4306 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4307 Candidate.Viable = false;
4308 Candidate.FailureKind = ovl_fail_bad_deduction;
4309 Candidate.IsSurrogate = false;
4310 Candidate.IgnoreObjectArgument = false;
4311 Candidate.ExplicitCallArguments = 1;
4312 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
4313 Info);
4314 return;
4317 // Add the conversion function template specialization produced by
4318 // template argument deduction as a candidate.
4319 assert(Specialization && "Missing function template specialization?");
4320 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
4321 CandidateSet);
4324 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4325 /// converts the given @c Object to a function pointer via the
4326 /// conversion function @c Conversion, and then attempts to call it
4327 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
4328 /// the type of function that we'll eventually be calling.
4329 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
4330 DeclAccessPair FoundDecl,
4331 CXXRecordDecl *ActingContext,
4332 const FunctionProtoType *Proto,
4333 Expr *Object,
4334 Expr **Args, unsigned NumArgs,
4335 OverloadCandidateSet& CandidateSet) {
4336 if (!CandidateSet.isNewCandidate(Conversion))
4337 return;
4339 // Overload resolution is always an unevaluated context.
4340 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
4342 CandidateSet.push_back(OverloadCandidate());
4343 OverloadCandidate& Candidate = CandidateSet.back();
4344 Candidate.FoundDecl = FoundDecl;
4345 Candidate.Function = 0;
4346 Candidate.Surrogate = Conversion;
4347 Candidate.Viable = true;
4348 Candidate.IsSurrogate = true;
4349 Candidate.IgnoreObjectArgument = false;
4350 Candidate.Conversions.resize(NumArgs + 1);
4351 Candidate.ExplicitCallArguments = NumArgs;
4353 // Determine the implicit conversion sequence for the implicit
4354 // object parameter.
4355 ImplicitConversionSequence ObjectInit
4356 = TryObjectArgumentInitialization(*this, Object->getType(),
4357 Object->Classify(Context),
4358 Conversion, ActingContext);
4359 if (ObjectInit.isBad()) {
4360 Candidate.Viable = false;
4361 Candidate.FailureKind = ovl_fail_bad_conversion;
4362 Candidate.Conversions[0] = ObjectInit;
4363 return;
4366 // The first conversion is actually a user-defined conversion whose
4367 // first conversion is ObjectInit's standard conversion (which is
4368 // effectively a reference binding). Record it as such.
4369 Candidate.Conversions[0].setUserDefined();
4370 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
4371 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
4372 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
4373 Candidate.Conversions[0].UserDefined.FoundConversionFunction
4374 = FoundDecl.getDecl();
4375 Candidate.Conversions[0].UserDefined.After
4376 = Candidate.Conversions[0].UserDefined.Before;
4377 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4379 // Find the
4380 unsigned NumArgsInProto = Proto->getNumArgs();
4382 // (C++ 13.3.2p2): A candidate function having fewer than m
4383 // parameters is viable only if it has an ellipsis in its parameter
4384 // list (8.3.5).
4385 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4386 Candidate.Viable = false;
4387 Candidate.FailureKind = ovl_fail_too_many_arguments;
4388 return;
4391 // Function types don't have any default arguments, so just check if
4392 // we have enough arguments.
4393 if (NumArgs < NumArgsInProto) {
4394 // Not enough arguments.
4395 Candidate.Viable = false;
4396 Candidate.FailureKind = ovl_fail_too_few_arguments;
4397 return;
4400 // Determine the implicit conversion sequences for each of the
4401 // arguments.
4402 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4403 if (ArgIdx < NumArgsInProto) {
4404 // (C++ 13.3.2p3): for F to be a viable function, there shall
4405 // exist for each argument an implicit conversion sequence
4406 // (13.3.3.1) that converts that argument to the corresponding
4407 // parameter of F.
4408 QualType ParamType = Proto->getArgType(ArgIdx);
4409 Candidate.Conversions[ArgIdx + 1]
4410 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
4411 /*SuppressUserConversions=*/false,
4412 /*InOverloadResolution=*/false);
4413 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
4414 Candidate.Viable = false;
4415 Candidate.FailureKind = ovl_fail_bad_conversion;
4416 break;
4418 } else {
4419 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4420 // argument for which there is no corresponding parameter is
4421 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
4422 Candidate.Conversions[ArgIdx + 1].setEllipsis();
4427 /// \brief Add overload candidates for overloaded operators that are
4428 /// member functions.
4430 /// Add the overloaded operator candidates that are member functions
4431 /// for the operator Op that was used in an operator expression such
4432 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
4433 /// CandidateSet will store the added overload candidates. (C++
4434 /// [over.match.oper]).
4435 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4436 SourceLocation OpLoc,
4437 Expr **Args, unsigned NumArgs,
4438 OverloadCandidateSet& CandidateSet,
4439 SourceRange OpRange) {
4440 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4442 // C++ [over.match.oper]p3:
4443 // For a unary operator @ with an operand of a type whose
4444 // cv-unqualified version is T1, and for a binary operator @ with
4445 // a left operand of a type whose cv-unqualified version is T1 and
4446 // a right operand of a type whose cv-unqualified version is T2,
4447 // three sets of candidate functions, designated member
4448 // candidates, non-member candidates and built-in candidates, are
4449 // constructed as follows:
4450 QualType T1 = Args[0]->getType();
4452 // -- If T1 is a class type, the set of member candidates is the
4453 // result of the qualified lookup of T1::operator@
4454 // (13.3.1.1.1); otherwise, the set of member candidates is
4455 // empty.
4456 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
4457 // Complete the type if it can be completed. Otherwise, we're done.
4458 if (RequireCompleteType(OpLoc, T1, PDiag()))
4459 return;
4461 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4462 LookupQualifiedName(Operators, T1Rec->getDecl());
4463 Operators.suppressDiagnostics();
4465 for (LookupResult::iterator Oper = Operators.begin(),
4466 OperEnd = Operators.end();
4467 Oper != OperEnd;
4468 ++Oper)
4469 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
4470 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
4471 CandidateSet,
4472 /* SuppressUserConversions = */ false);
4476 /// AddBuiltinCandidate - Add a candidate for a built-in
4477 /// operator. ResultTy and ParamTys are the result and parameter types
4478 /// of the built-in candidate, respectively. Args and NumArgs are the
4479 /// arguments being passed to the candidate. IsAssignmentOperator
4480 /// should be true when this built-in candidate is an assignment
4481 /// operator. NumContextualBoolArguments is the number of arguments
4482 /// (at the beginning of the argument list) that will be contextually
4483 /// converted to bool.
4484 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
4485 Expr **Args, unsigned NumArgs,
4486 OverloadCandidateSet& CandidateSet,
4487 bool IsAssignmentOperator,
4488 unsigned NumContextualBoolArguments) {
4489 // Overload resolution is always an unevaluated context.
4490 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
4492 // Add this candidate
4493 CandidateSet.push_back(OverloadCandidate());
4494 OverloadCandidate& Candidate = CandidateSet.back();
4495 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
4496 Candidate.Function = 0;
4497 Candidate.IsSurrogate = false;
4498 Candidate.IgnoreObjectArgument = false;
4499 Candidate.BuiltinTypes.ResultTy = ResultTy;
4500 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4501 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4503 // Determine the implicit conversion sequences for each of the
4504 // arguments.
4505 Candidate.Viable = true;
4506 Candidate.Conversions.resize(NumArgs);
4507 Candidate.ExplicitCallArguments = NumArgs;
4508 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4509 // C++ [over.match.oper]p4:
4510 // For the built-in assignment operators, conversions of the
4511 // left operand are restricted as follows:
4512 // -- no temporaries are introduced to hold the left operand, and
4513 // -- no user-defined conversions are applied to the left
4514 // operand to achieve a type match with the left-most
4515 // parameter of a built-in candidate.
4517 // We block these conversions by turning off user-defined
4518 // conversions, since that is the only way that initialization of
4519 // a reference to a non-class type can occur from something that
4520 // is not of the same type.
4521 if (ArgIdx < NumContextualBoolArguments) {
4522 assert(ParamTys[ArgIdx] == Context.BoolTy &&
4523 "Contextual conversion to bool requires bool type");
4524 Candidate.Conversions[ArgIdx]
4525 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
4526 } else {
4527 Candidate.Conversions[ArgIdx]
4528 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
4529 ArgIdx == 0 && IsAssignmentOperator,
4530 /*InOverloadResolution=*/false);
4532 if (Candidate.Conversions[ArgIdx].isBad()) {
4533 Candidate.Viable = false;
4534 Candidate.FailureKind = ovl_fail_bad_conversion;
4535 break;
4540 /// BuiltinCandidateTypeSet - A set of types that will be used for the
4541 /// candidate operator functions for built-in operators (C++
4542 /// [over.built]). The types are separated into pointer types and
4543 /// enumeration types.
4544 class BuiltinCandidateTypeSet {
4545 /// TypeSet - A set of types.
4546 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
4548 /// PointerTypes - The set of pointer types that will be used in the
4549 /// built-in candidates.
4550 TypeSet PointerTypes;
4552 /// MemberPointerTypes - The set of member pointer types that will be
4553 /// used in the built-in candidates.
4554 TypeSet MemberPointerTypes;
4556 /// EnumerationTypes - The set of enumeration types that will be
4557 /// used in the built-in candidates.
4558 TypeSet EnumerationTypes;
4560 /// \brief The set of vector types that will be used in the built-in
4561 /// candidates.
4562 TypeSet VectorTypes;
4564 /// \brief A flag indicating non-record types are viable candidates
4565 bool HasNonRecordTypes;
4567 /// \brief A flag indicating whether either arithmetic or enumeration types
4568 /// were present in the candidate set.
4569 bool HasArithmeticOrEnumeralTypes;
4571 /// Sema - The semantic analysis instance where we are building the
4572 /// candidate type set.
4573 Sema &SemaRef;
4575 /// Context - The AST context in which we will build the type sets.
4576 ASTContext &Context;
4578 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4579 const Qualifiers &VisibleQuals);
4580 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
4582 public:
4583 /// iterator - Iterates through the types that are part of the set.
4584 typedef TypeSet::iterator iterator;
4586 BuiltinCandidateTypeSet(Sema &SemaRef)
4587 : HasNonRecordTypes(false),
4588 HasArithmeticOrEnumeralTypes(false),
4589 SemaRef(SemaRef),
4590 Context(SemaRef.Context) { }
4592 void AddTypesConvertedFrom(QualType Ty,
4593 SourceLocation Loc,
4594 bool AllowUserConversions,
4595 bool AllowExplicitConversions,
4596 const Qualifiers &VisibleTypeConversionsQuals);
4598 /// pointer_begin - First pointer type found;
4599 iterator pointer_begin() { return PointerTypes.begin(); }
4601 /// pointer_end - Past the last pointer type found;
4602 iterator pointer_end() { return PointerTypes.end(); }
4604 /// member_pointer_begin - First member pointer type found;
4605 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4607 /// member_pointer_end - Past the last member pointer type found;
4608 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4610 /// enumeration_begin - First enumeration type found;
4611 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4613 /// enumeration_end - Past the last enumeration type found;
4614 iterator enumeration_end() { return EnumerationTypes.end(); }
4616 iterator vector_begin() { return VectorTypes.begin(); }
4617 iterator vector_end() { return VectorTypes.end(); }
4619 bool hasNonRecordTypes() { return HasNonRecordTypes; }
4620 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
4623 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
4624 /// the set of pointer types along with any more-qualified variants of
4625 /// that type. For example, if @p Ty is "int const *", this routine
4626 /// will add "int const *", "int const volatile *", "int const
4627 /// restrict *", and "int const volatile restrict *" to the set of
4628 /// pointer types. Returns true if the add of @p Ty itself succeeded,
4629 /// false otherwise.
4631 /// FIXME: what to do about extended qualifiers?
4632 bool
4633 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4634 const Qualifiers &VisibleQuals) {
4636 // Insert this type.
4637 if (!PointerTypes.insert(Ty))
4638 return false;
4640 QualType PointeeTy;
4641 const PointerType *PointerTy = Ty->getAs<PointerType>();
4642 bool buildObjCPtr = false;
4643 if (!PointerTy) {
4644 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
4645 PointeeTy = PTy->getPointeeType();
4646 buildObjCPtr = true;
4648 else
4649 assert(false && "type was not a pointer type!");
4651 else
4652 PointeeTy = PointerTy->getPointeeType();
4654 // Don't add qualified variants of arrays. For one, they're not allowed
4655 // (the qualifier would sink to the element type), and for another, the
4656 // only overload situation where it matters is subscript or pointer +- int,
4657 // and those shouldn't have qualifier variants anyway.
4658 if (PointeeTy->isArrayType())
4659 return true;
4660 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4661 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
4662 BaseCVR = Array->getElementType().getCVRQualifiers();
4663 bool hasVolatile = VisibleQuals.hasVolatile();
4664 bool hasRestrict = VisibleQuals.hasRestrict();
4666 // Iterate through all strict supersets of BaseCVR.
4667 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4668 if ((CVR | BaseCVR) != CVR) continue;
4669 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4670 // in the types.
4671 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4672 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
4673 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4674 if (!buildObjCPtr)
4675 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4676 else
4677 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
4680 return true;
4683 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4684 /// to the set of pointer types along with any more-qualified variants of
4685 /// that type. For example, if @p Ty is "int const *", this routine
4686 /// will add "int const *", "int const volatile *", "int const
4687 /// restrict *", and "int const volatile restrict *" to the set of
4688 /// pointer types. Returns true if the add of @p Ty itself succeeded,
4689 /// false otherwise.
4691 /// FIXME: what to do about extended qualifiers?
4692 bool
4693 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4694 QualType Ty) {
4695 // Insert this type.
4696 if (!MemberPointerTypes.insert(Ty))
4697 return false;
4699 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4700 assert(PointerTy && "type was not a member pointer type!");
4702 QualType PointeeTy = PointerTy->getPointeeType();
4703 // Don't add qualified variants of arrays. For one, they're not allowed
4704 // (the qualifier would sink to the element type), and for another, the
4705 // only overload situation where it matters is subscript or pointer +- int,
4706 // and those shouldn't have qualifier variants anyway.
4707 if (PointeeTy->isArrayType())
4708 return true;
4709 const Type *ClassTy = PointerTy->getClass();
4711 // Iterate through all strict supersets of the pointee type's CVR
4712 // qualifiers.
4713 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4714 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4715 if ((CVR | BaseCVR) != CVR) continue;
4717 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4718 MemberPointerTypes.insert(
4719 Context.getMemberPointerType(QPointeeTy, ClassTy));
4722 return true;
4725 /// AddTypesConvertedFrom - Add each of the types to which the type @p
4726 /// Ty can be implicit converted to the given set of @p Types. We're
4727 /// primarily interested in pointer types and enumeration types. We also
4728 /// take member pointer types, for the conditional operator.
4729 /// AllowUserConversions is true if we should look at the conversion
4730 /// functions of a class type, and AllowExplicitConversions if we
4731 /// should also include the explicit conversion functions of a class
4732 /// type.
4733 void
4734 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
4735 SourceLocation Loc,
4736 bool AllowUserConversions,
4737 bool AllowExplicitConversions,
4738 const Qualifiers &VisibleQuals) {
4739 // Only deal with canonical types.
4740 Ty = Context.getCanonicalType(Ty);
4742 // Look through reference types; they aren't part of the type of an
4743 // expression for the purposes of conversions.
4744 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
4745 Ty = RefTy->getPointeeType();
4747 // If we're dealing with an array type, decay to the pointer.
4748 if (Ty->isArrayType())
4749 Ty = SemaRef.Context.getArrayDecayedType(Ty);
4751 // Otherwise, we don't care about qualifiers on the type.
4752 Ty = Ty.getLocalUnqualifiedType();
4754 // Flag if we ever add a non-record type.
4755 const RecordType *TyRec = Ty->getAs<RecordType>();
4756 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
4758 // Flag if we encounter an arithmetic type.
4759 HasArithmeticOrEnumeralTypes =
4760 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
4762 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4763 PointerTypes.insert(Ty);
4764 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
4765 // Insert our type, and its more-qualified variants, into the set
4766 // of types.
4767 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
4768 return;
4769 } else if (Ty->isMemberPointerType()) {
4770 // Member pointers are far easier, since the pointee can't be converted.
4771 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4772 return;
4773 } else if (Ty->isEnumeralType()) {
4774 HasArithmeticOrEnumeralTypes = true;
4775 EnumerationTypes.insert(Ty);
4776 } else if (Ty->isVectorType()) {
4777 // We treat vector types as arithmetic types in many contexts as an
4778 // extension.
4779 HasArithmeticOrEnumeralTypes = true;
4780 VectorTypes.insert(Ty);
4781 } else if (AllowUserConversions && TyRec) {
4782 // No conversion functions in incomplete types.
4783 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
4784 return;
4786 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
4787 const UnresolvedSetImpl *Conversions
4788 = ClassDecl->getVisibleConversionFunctions();
4789 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4790 E = Conversions->end(); I != E; ++I) {
4791 NamedDecl *D = I.getDecl();
4792 if (isa<UsingShadowDecl>(D))
4793 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4795 // Skip conversion function templates; they don't tell us anything
4796 // about which builtin types we can convert to.
4797 if (isa<FunctionTemplateDecl>(D))
4798 continue;
4800 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
4801 if (AllowExplicitConversions || !Conv->isExplicit()) {
4802 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
4803 VisibleQuals);
4809 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4810 /// the volatile- and non-volatile-qualified assignment operators for the
4811 /// given type to the candidate set.
4812 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4813 QualType T,
4814 Expr **Args,
4815 unsigned NumArgs,
4816 OverloadCandidateSet &CandidateSet) {
4817 QualType ParamTypes[2];
4819 // T& operator=(T&, T)
4820 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4821 ParamTypes[1] = T;
4822 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4823 /*IsAssignmentOperator=*/true);
4825 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4826 // volatile T& operator=(volatile T&, T)
4827 ParamTypes[0]
4828 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
4829 ParamTypes[1] = T;
4830 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4831 /*IsAssignmentOperator=*/true);
4835 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4836 /// if any, found in visible type conversion functions found in ArgExpr's type.
4837 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4838 Qualifiers VRQuals;
4839 const RecordType *TyRec;
4840 if (const MemberPointerType *RHSMPType =
4841 ArgExpr->getType()->getAs<MemberPointerType>())
4842 TyRec = RHSMPType->getClass()->getAs<RecordType>();
4843 else
4844 TyRec = ArgExpr->getType()->getAs<RecordType>();
4845 if (!TyRec) {
4846 // Just to be safe, assume the worst case.
4847 VRQuals.addVolatile();
4848 VRQuals.addRestrict();
4849 return VRQuals;
4852 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
4853 if (!ClassDecl->hasDefinition())
4854 return VRQuals;
4856 const UnresolvedSetImpl *Conversions =
4857 ClassDecl->getVisibleConversionFunctions();
4859 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4860 E = Conversions->end(); I != E; ++I) {
4861 NamedDecl *D = I.getDecl();
4862 if (isa<UsingShadowDecl>(D))
4863 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4864 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
4865 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4866 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4867 CanTy = ResTypeRef->getPointeeType();
4868 // Need to go down the pointer/mempointer chain and add qualifiers
4869 // as see them.
4870 bool done = false;
4871 while (!done) {
4872 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4873 CanTy = ResTypePtr->getPointeeType();
4874 else if (const MemberPointerType *ResTypeMPtr =
4875 CanTy->getAs<MemberPointerType>())
4876 CanTy = ResTypeMPtr->getPointeeType();
4877 else
4878 done = true;
4879 if (CanTy.isVolatileQualified())
4880 VRQuals.addVolatile();
4881 if (CanTy.isRestrictQualified())
4882 VRQuals.addRestrict();
4883 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4884 return VRQuals;
4888 return VRQuals;
4891 namespace {
4893 /// \brief Helper class to manage the addition of builtin operator overload
4894 /// candidates. It provides shared state and utility methods used throughout
4895 /// the process, as well as a helper method to add each group of builtin
4896 /// operator overloads from the standard to a candidate set.
4897 class BuiltinOperatorOverloadBuilder {
4898 // Common instance state available to all overload candidate addition methods.
4899 Sema &S;
4900 Expr **Args;
4901 unsigned NumArgs;
4902 Qualifiers VisibleTypeConversionsQuals;
4903 bool HasArithmeticOrEnumeralCandidateType;
4904 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
4905 OverloadCandidateSet &CandidateSet;
4907 // Define some constants used to index and iterate over the arithemetic types
4908 // provided via the getArithmeticType() method below.
4909 // The "promoted arithmetic types" are the arithmetic
4910 // types are that preserved by promotion (C++ [over.built]p2).
4911 static const unsigned FirstIntegralType = 3;
4912 static const unsigned LastIntegralType = 18;
4913 static const unsigned FirstPromotedIntegralType = 3,
4914 LastPromotedIntegralType = 9;
4915 static const unsigned FirstPromotedArithmeticType = 0,
4916 LastPromotedArithmeticType = 9;
4917 static const unsigned NumArithmeticTypes = 18;
4919 /// \brief Get the canonical type for a given arithmetic type index.
4920 CanQualType getArithmeticType(unsigned index) {
4921 assert(index < NumArithmeticTypes);
4922 static CanQualType ASTContext::* const
4923 ArithmeticTypes[NumArithmeticTypes] = {
4924 // Start of promoted types.
4925 &ASTContext::FloatTy,
4926 &ASTContext::DoubleTy,
4927 &ASTContext::LongDoubleTy,
4929 // Start of integral types.
4930 &ASTContext::IntTy,
4931 &ASTContext::LongTy,
4932 &ASTContext::LongLongTy,
4933 &ASTContext::UnsignedIntTy,
4934 &ASTContext::UnsignedLongTy,
4935 &ASTContext::UnsignedLongLongTy,
4936 // End of promoted types.
4938 &ASTContext::BoolTy,
4939 &ASTContext::CharTy,
4940 &ASTContext::WCharTy,
4941 &ASTContext::Char16Ty,
4942 &ASTContext::Char32Ty,
4943 &ASTContext::SignedCharTy,
4944 &ASTContext::ShortTy,
4945 &ASTContext::UnsignedCharTy,
4946 &ASTContext::UnsignedShortTy,
4947 // End of integral types.
4948 // FIXME: What about complex?
4950 return S.Context.*ArithmeticTypes[index];
4953 /// \brief Gets the canonical type resulting from the usual arithemetic
4954 /// converions for the given arithmetic types.
4955 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
4956 // Accelerator table for performing the usual arithmetic conversions.
4957 // The rules are basically:
4958 // - if either is floating-point, use the wider floating-point
4959 // - if same signedness, use the higher rank
4960 // - if same size, use unsigned of the higher rank
4961 // - use the larger type
4962 // These rules, together with the axiom that higher ranks are
4963 // never smaller, are sufficient to precompute all of these results
4964 // *except* when dealing with signed types of higher rank.
4965 // (we could precompute SLL x UI for all known platforms, but it's
4966 // better not to make any assumptions).
4967 enum PromotedType {
4968 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
4970 static PromotedType ConversionsTable[LastPromotedArithmeticType]
4971 [LastPromotedArithmeticType] = {
4972 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
4973 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
4974 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
4975 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
4976 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
4977 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
4978 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
4979 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
4980 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
4983 assert(L < LastPromotedArithmeticType);
4984 assert(R < LastPromotedArithmeticType);
4985 int Idx = ConversionsTable[L][R];
4987 // Fast path: the table gives us a concrete answer.
4988 if (Idx != Dep) return getArithmeticType(Idx);
4990 // Slow path: we need to compare widths.
4991 // An invariant is that the signed type has higher rank.
4992 CanQualType LT = getArithmeticType(L),
4993 RT = getArithmeticType(R);
4994 unsigned LW = S.Context.getIntWidth(LT),
4995 RW = S.Context.getIntWidth(RT);
4997 // If they're different widths, use the signed type.
4998 if (LW > RW) return LT;
4999 else if (LW < RW) return RT;
5001 // Otherwise, use the unsigned type of the signed type's rank.
5002 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5003 assert(L == SLL || R == SLL);
5004 return S.Context.UnsignedLongLongTy;
5007 /// \brief Helper method to factor out the common pattern of adding overloads
5008 /// for '++' and '--' builtin operators.
5009 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5010 bool HasVolatile) {
5011 QualType ParamTypes[2] = {
5012 S.Context.getLValueReferenceType(CandidateTy),
5013 S.Context.IntTy
5016 // Non-volatile version.
5017 if (NumArgs == 1)
5018 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5019 else
5020 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5022 // Use a heuristic to reduce number of builtin candidates in the set:
5023 // add volatile version only if there are conversions to a volatile type.
5024 if (HasVolatile) {
5025 ParamTypes[0] =
5026 S.Context.getLValueReferenceType(
5027 S.Context.getVolatileType(CandidateTy));
5028 if (NumArgs == 1)
5029 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5030 else
5031 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5035 public:
5036 BuiltinOperatorOverloadBuilder(
5037 Sema &S, Expr **Args, unsigned NumArgs,
5038 Qualifiers VisibleTypeConversionsQuals,
5039 bool HasArithmeticOrEnumeralCandidateType,
5040 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
5041 OverloadCandidateSet &CandidateSet)
5042 : S(S), Args(Args), NumArgs(NumArgs),
5043 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
5044 HasArithmeticOrEnumeralCandidateType(
5045 HasArithmeticOrEnumeralCandidateType),
5046 CandidateTypes(CandidateTypes),
5047 CandidateSet(CandidateSet) {
5048 // Validate some of our static helper constants in debug builds.
5049 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
5050 "Invalid first promoted integral type");
5051 assert(getArithmeticType(LastPromotedIntegralType - 1)
5052 == S.Context.UnsignedLongLongTy &&
5053 "Invalid last promoted integral type");
5054 assert(getArithmeticType(FirstPromotedArithmeticType)
5055 == S.Context.FloatTy &&
5056 "Invalid first promoted arithmetic type");
5057 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5058 == S.Context.UnsignedLongLongTy &&
5059 "Invalid last promoted arithmetic type");
5062 // C++ [over.built]p3:
5064 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5065 // is either volatile or empty, there exist candidate operator
5066 // functions of the form
5068 // VQ T& operator++(VQ T&);
5069 // T operator++(VQ T&, int);
5071 // C++ [over.built]p4:
5073 // For every pair (T, VQ), where T is an arithmetic type other
5074 // than bool, and VQ is either volatile or empty, there exist
5075 // candidate operator functions of the form
5077 // VQ T& operator--(VQ T&);
5078 // T operator--(VQ T&, int);
5079 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
5080 if (!HasArithmeticOrEnumeralCandidateType)
5081 return;
5083 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5084 Arith < NumArithmeticTypes; ++Arith) {
5085 addPlusPlusMinusMinusStyleOverloads(
5086 getArithmeticType(Arith),
5087 VisibleTypeConversionsQuals.hasVolatile());
5091 // C++ [over.built]p5:
5093 // For every pair (T, VQ), where T is a cv-qualified or
5094 // cv-unqualified object type, and VQ is either volatile or
5095 // empty, there exist candidate operator functions of the form
5097 // T*VQ& operator++(T*VQ&);
5098 // T*VQ& operator--(T*VQ&);
5099 // T* operator++(T*VQ&, int);
5100 // T* operator--(T*VQ&, int);
5101 void addPlusPlusMinusMinusPointerOverloads() {
5102 for (BuiltinCandidateTypeSet::iterator
5103 Ptr = CandidateTypes[0].pointer_begin(),
5104 PtrEnd = CandidateTypes[0].pointer_end();
5105 Ptr != PtrEnd; ++Ptr) {
5106 // Skip pointer types that aren't pointers to object types.
5107 if (!(*Ptr)->getPointeeType()->isObjectType())
5108 continue;
5110 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5111 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5112 VisibleTypeConversionsQuals.hasVolatile()));
5116 // C++ [over.built]p6:
5117 // For every cv-qualified or cv-unqualified object type T, there
5118 // exist candidate operator functions of the form
5120 // T& operator*(T*);
5122 // C++ [over.built]p7:
5123 // For every function type T that does not have cv-qualifiers or a
5124 // ref-qualifier, there exist candidate operator functions of the form
5125 // T& operator*(T*);
5126 void addUnaryStarPointerOverloads() {
5127 for (BuiltinCandidateTypeSet::iterator
5128 Ptr = CandidateTypes[0].pointer_begin(),
5129 PtrEnd = CandidateTypes[0].pointer_end();
5130 Ptr != PtrEnd; ++Ptr) {
5131 QualType ParamTy = *Ptr;
5132 QualType PointeeTy = ParamTy->getPointeeType();
5133 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5134 continue;
5136 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5137 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5138 continue;
5140 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5141 &ParamTy, Args, 1, CandidateSet);
5145 // C++ [over.built]p9:
5146 // For every promoted arithmetic type T, there exist candidate
5147 // operator functions of the form
5149 // T operator+(T);
5150 // T operator-(T);
5151 void addUnaryPlusOrMinusArithmeticOverloads() {
5152 if (!HasArithmeticOrEnumeralCandidateType)
5153 return;
5155 for (unsigned Arith = FirstPromotedArithmeticType;
5156 Arith < LastPromotedArithmeticType; ++Arith) {
5157 QualType ArithTy = getArithmeticType(Arith);
5158 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5161 // Extension: We also add these operators for vector types.
5162 for (BuiltinCandidateTypeSet::iterator
5163 Vec = CandidateTypes[0].vector_begin(),
5164 VecEnd = CandidateTypes[0].vector_end();
5165 Vec != VecEnd; ++Vec) {
5166 QualType VecTy = *Vec;
5167 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5171 // C++ [over.built]p8:
5172 // For every type T, there exist candidate operator functions of
5173 // the form
5175 // T* operator+(T*);
5176 void addUnaryPlusPointerOverloads() {
5177 for (BuiltinCandidateTypeSet::iterator
5178 Ptr = CandidateTypes[0].pointer_begin(),
5179 PtrEnd = CandidateTypes[0].pointer_end();
5180 Ptr != PtrEnd; ++Ptr) {
5181 QualType ParamTy = *Ptr;
5182 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5186 // C++ [over.built]p10:
5187 // For every promoted integral type T, there exist candidate
5188 // operator functions of the form
5190 // T operator~(T);
5191 void addUnaryTildePromotedIntegralOverloads() {
5192 if (!HasArithmeticOrEnumeralCandidateType)
5193 return;
5195 for (unsigned Int = FirstPromotedIntegralType;
5196 Int < LastPromotedIntegralType; ++Int) {
5197 QualType IntTy = getArithmeticType(Int);
5198 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5201 // Extension: We also add this operator for vector types.
5202 for (BuiltinCandidateTypeSet::iterator
5203 Vec = CandidateTypes[0].vector_begin(),
5204 VecEnd = CandidateTypes[0].vector_end();
5205 Vec != VecEnd; ++Vec) {
5206 QualType VecTy = *Vec;
5207 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5211 // C++ [over.match.oper]p16:
5212 // For every pointer to member type T, there exist candidate operator
5213 // functions of the form
5215 // bool operator==(T,T);
5216 // bool operator!=(T,T);
5217 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5218 /// Set of (canonical) types that we've already handled.
5219 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5221 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5222 for (BuiltinCandidateTypeSet::iterator
5223 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5224 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5225 MemPtr != MemPtrEnd;
5226 ++MemPtr) {
5227 // Don't add the same builtin candidate twice.
5228 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5229 continue;
5231 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5232 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5233 CandidateSet);
5238 // C++ [over.built]p15:
5240 // For every pointer or enumeration type T, there exist
5241 // candidate operator functions of the form
5243 // bool operator<(T, T);
5244 // bool operator>(T, T);
5245 // bool operator<=(T, T);
5246 // bool operator>=(T, T);
5247 // bool operator==(T, T);
5248 // bool operator!=(T, T);
5249 void addRelationalPointerOrEnumeralOverloads() {
5250 // C++ [over.built]p1:
5251 // If there is a user-written candidate with the same name and parameter
5252 // types as a built-in candidate operator function, the built-in operator
5253 // function is hidden and is not included in the set of candidate
5254 // functions.
5256 // The text is actually in a note, but if we don't implement it then we end
5257 // up with ambiguities when the user provides an overloaded operator for
5258 // an enumeration type. Note that only enumeration types have this problem,
5259 // so we track which enumeration types we've seen operators for. Also, the
5260 // only other overloaded operator with enumeration argumenst, operator=,
5261 // cannot be overloaded for enumeration types, so this is the only place
5262 // where we must suppress candidates like this.
5263 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5264 UserDefinedBinaryOperators;
5266 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5267 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5268 CandidateTypes[ArgIdx].enumeration_end()) {
5269 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5270 CEnd = CandidateSet.end();
5271 C != CEnd; ++C) {
5272 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5273 continue;
5275 QualType FirstParamType =
5276 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5277 QualType SecondParamType =
5278 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5280 // Skip if either parameter isn't of enumeral type.
5281 if (!FirstParamType->isEnumeralType() ||
5282 !SecondParamType->isEnumeralType())
5283 continue;
5285 // Add this operator to the set of known user-defined operators.
5286 UserDefinedBinaryOperators.insert(
5287 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5288 S.Context.getCanonicalType(SecondParamType)));
5293 /// Set of (canonical) types that we've already handled.
5294 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5296 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5297 for (BuiltinCandidateTypeSet::iterator
5298 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5299 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5300 Ptr != PtrEnd; ++Ptr) {
5301 // Don't add the same builtin candidate twice.
5302 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5303 continue;
5305 QualType ParamTypes[2] = { *Ptr, *Ptr };
5306 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5307 CandidateSet);
5309 for (BuiltinCandidateTypeSet::iterator
5310 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5311 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5312 Enum != EnumEnd; ++Enum) {
5313 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5315 // Don't add the same builtin candidate twice, or if a user defined
5316 // candidate exists.
5317 if (!AddedTypes.insert(CanonType) ||
5318 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5319 CanonType)))
5320 continue;
5322 QualType ParamTypes[2] = { *Enum, *Enum };
5323 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5324 CandidateSet);
5329 // C++ [over.built]p13:
5331 // For every cv-qualified or cv-unqualified object type T
5332 // there exist candidate operator functions of the form
5334 // T* operator+(T*, ptrdiff_t);
5335 // T& operator[](T*, ptrdiff_t); [BELOW]
5336 // T* operator-(T*, ptrdiff_t);
5337 // T* operator+(ptrdiff_t, T*);
5338 // T& operator[](ptrdiff_t, T*); [BELOW]
5340 // C++ [over.built]p14:
5342 // For every T, where T is a pointer to object type, there
5343 // exist candidate operator functions of the form
5345 // ptrdiff_t operator-(T, T);
5346 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5347 /// Set of (canonical) types that we've already handled.
5348 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5350 for (int Arg = 0; Arg < 2; ++Arg) {
5351 QualType AsymetricParamTypes[2] = {
5352 S.Context.getPointerDiffType(),
5353 S.Context.getPointerDiffType(),
5355 for (BuiltinCandidateTypeSet::iterator
5356 Ptr = CandidateTypes[Arg].pointer_begin(),
5357 PtrEnd = CandidateTypes[Arg].pointer_end();
5358 Ptr != PtrEnd; ++Ptr) {
5359 QualType PointeeTy = (*Ptr)->getPointeeType();
5360 if (!PointeeTy->isObjectType())
5361 continue;
5363 AsymetricParamTypes[Arg] = *Ptr;
5364 if (Arg == 0 || Op == OO_Plus) {
5365 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5366 // T* operator+(ptrdiff_t, T*);
5367 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5368 CandidateSet);
5370 if (Op == OO_Minus) {
5371 // ptrdiff_t operator-(T, T);
5372 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5373 continue;
5375 QualType ParamTypes[2] = { *Ptr, *Ptr };
5376 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5377 Args, 2, CandidateSet);
5383 // C++ [over.built]p12:
5385 // For every pair of promoted arithmetic types L and R, there
5386 // exist candidate operator functions of the form
5388 // LR operator*(L, R);
5389 // LR operator/(L, R);
5390 // LR operator+(L, R);
5391 // LR operator-(L, R);
5392 // bool operator<(L, R);
5393 // bool operator>(L, R);
5394 // bool operator<=(L, R);
5395 // bool operator>=(L, R);
5396 // bool operator==(L, R);
5397 // bool operator!=(L, R);
5399 // where LR is the result of the usual arithmetic conversions
5400 // between types L and R.
5402 // C++ [over.built]p24:
5404 // For every pair of promoted arithmetic types L and R, there exist
5405 // candidate operator functions of the form
5407 // LR operator?(bool, L, R);
5409 // where LR is the result of the usual arithmetic conversions
5410 // between types L and R.
5411 // Our candidates ignore the first parameter.
5412 void addGenericBinaryArithmeticOverloads(bool isComparison) {
5413 if (!HasArithmeticOrEnumeralCandidateType)
5414 return;
5416 for (unsigned Left = FirstPromotedArithmeticType;
5417 Left < LastPromotedArithmeticType; ++Left) {
5418 for (unsigned Right = FirstPromotedArithmeticType;
5419 Right < LastPromotedArithmeticType; ++Right) {
5420 QualType LandR[2] = { getArithmeticType(Left),
5421 getArithmeticType(Right) };
5422 QualType Result =
5423 isComparison ? S.Context.BoolTy
5424 : getUsualArithmeticConversions(Left, Right);
5425 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5429 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5430 // conditional operator for vector types.
5431 for (BuiltinCandidateTypeSet::iterator
5432 Vec1 = CandidateTypes[0].vector_begin(),
5433 Vec1End = CandidateTypes[0].vector_end();
5434 Vec1 != Vec1End; ++Vec1) {
5435 for (BuiltinCandidateTypeSet::iterator
5436 Vec2 = CandidateTypes[1].vector_begin(),
5437 Vec2End = CandidateTypes[1].vector_end();
5438 Vec2 != Vec2End; ++Vec2) {
5439 QualType LandR[2] = { *Vec1, *Vec2 };
5440 QualType Result = S.Context.BoolTy;
5441 if (!isComparison) {
5442 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5443 Result = *Vec1;
5444 else
5445 Result = *Vec2;
5448 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5453 // C++ [over.built]p17:
5455 // For every pair of promoted integral types L and R, there
5456 // exist candidate operator functions of the form
5458 // LR operator%(L, R);
5459 // LR operator&(L, R);
5460 // LR operator^(L, R);
5461 // LR operator|(L, R);
5462 // L operator<<(L, R);
5463 // L operator>>(L, R);
5465 // where LR is the result of the usual arithmetic conversions
5466 // between types L and R.
5467 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
5468 if (!HasArithmeticOrEnumeralCandidateType)
5469 return;
5471 for (unsigned Left = FirstPromotedIntegralType;
5472 Left < LastPromotedIntegralType; ++Left) {
5473 for (unsigned Right = FirstPromotedIntegralType;
5474 Right < LastPromotedIntegralType; ++Right) {
5475 QualType LandR[2] = { getArithmeticType(Left),
5476 getArithmeticType(Right) };
5477 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5478 ? LandR[0]
5479 : getUsualArithmeticConversions(Left, Right);
5480 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5485 // C++ [over.built]p20:
5487 // For every pair (T, VQ), where T is an enumeration or
5488 // pointer to member type and VQ is either volatile or
5489 // empty, there exist candidate operator functions of the form
5491 // VQ T& operator=(VQ T&, T);
5492 void addAssignmentMemberPointerOrEnumeralOverloads() {
5493 /// Set of (canonical) types that we've already handled.
5494 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5496 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5497 for (BuiltinCandidateTypeSet::iterator
5498 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5499 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5500 Enum != EnumEnd; ++Enum) {
5501 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5502 continue;
5504 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5505 CandidateSet);
5508 for (BuiltinCandidateTypeSet::iterator
5509 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5510 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5511 MemPtr != MemPtrEnd; ++MemPtr) {
5512 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5513 continue;
5515 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5516 CandidateSet);
5521 // C++ [over.built]p19:
5523 // For every pair (T, VQ), where T is any type and VQ is either
5524 // volatile or empty, there exist candidate operator functions
5525 // of the form
5527 // T*VQ& operator=(T*VQ&, T*);
5529 // C++ [over.built]p21:
5531 // For every pair (T, VQ), where T is a cv-qualified or
5532 // cv-unqualified object type and VQ is either volatile or
5533 // empty, there exist candidate operator functions of the form
5535 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5536 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5537 void addAssignmentPointerOverloads(bool isEqualOp) {
5538 /// Set of (canonical) types that we've already handled.
5539 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5541 for (BuiltinCandidateTypeSet::iterator
5542 Ptr = CandidateTypes[0].pointer_begin(),
5543 PtrEnd = CandidateTypes[0].pointer_end();
5544 Ptr != PtrEnd; ++Ptr) {
5545 // If this is operator=, keep track of the builtin candidates we added.
5546 if (isEqualOp)
5547 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
5548 else if (!(*Ptr)->getPointeeType()->isObjectType())
5549 continue;
5551 // non-volatile version
5552 QualType ParamTypes[2] = {
5553 S.Context.getLValueReferenceType(*Ptr),
5554 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5556 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5557 /*IsAssigmentOperator=*/ isEqualOp);
5559 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5560 VisibleTypeConversionsQuals.hasVolatile()) {
5561 // volatile version
5562 ParamTypes[0] =
5563 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5564 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5565 /*IsAssigmentOperator=*/isEqualOp);
5569 if (isEqualOp) {
5570 for (BuiltinCandidateTypeSet::iterator
5571 Ptr = CandidateTypes[1].pointer_begin(),
5572 PtrEnd = CandidateTypes[1].pointer_end();
5573 Ptr != PtrEnd; ++Ptr) {
5574 // Make sure we don't add the same candidate twice.
5575 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5576 continue;
5578 QualType ParamTypes[2] = {
5579 S.Context.getLValueReferenceType(*Ptr),
5580 *Ptr,
5583 // non-volatile version
5584 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5585 /*IsAssigmentOperator=*/true);
5587 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5588 VisibleTypeConversionsQuals.hasVolatile()) {
5589 // volatile version
5590 ParamTypes[0] =
5591 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5592 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5593 CandidateSet, /*IsAssigmentOperator=*/true);
5599 // C++ [over.built]p18:
5601 // For every triple (L, VQ, R), where L is an arithmetic type,
5602 // VQ is either volatile or empty, and R is a promoted
5603 // arithmetic type, there exist candidate operator functions of
5604 // the form
5606 // VQ L& operator=(VQ L&, R);
5607 // VQ L& operator*=(VQ L&, R);
5608 // VQ L& operator/=(VQ L&, R);
5609 // VQ L& operator+=(VQ L&, R);
5610 // VQ L& operator-=(VQ L&, R);
5611 void addAssignmentArithmeticOverloads(bool isEqualOp) {
5612 if (!HasArithmeticOrEnumeralCandidateType)
5613 return;
5615 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
5616 for (unsigned Right = FirstPromotedArithmeticType;
5617 Right < LastPromotedArithmeticType; ++Right) {
5618 QualType ParamTypes[2];
5619 ParamTypes[1] = getArithmeticType(Right);
5621 // Add this built-in operator as a candidate (VQ is empty).
5622 ParamTypes[0] =
5623 S.Context.getLValueReferenceType(getArithmeticType(Left));
5624 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5625 /*IsAssigmentOperator=*/isEqualOp);
5627 // Add this built-in operator as a candidate (VQ is 'volatile').
5628 if (VisibleTypeConversionsQuals.hasVolatile()) {
5629 ParamTypes[0] =
5630 S.Context.getVolatileType(getArithmeticType(Left));
5631 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5632 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5633 CandidateSet,
5634 /*IsAssigmentOperator=*/isEqualOp);
5639 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5640 for (BuiltinCandidateTypeSet::iterator
5641 Vec1 = CandidateTypes[0].vector_begin(),
5642 Vec1End = CandidateTypes[0].vector_end();
5643 Vec1 != Vec1End; ++Vec1) {
5644 for (BuiltinCandidateTypeSet::iterator
5645 Vec2 = CandidateTypes[1].vector_begin(),
5646 Vec2End = CandidateTypes[1].vector_end();
5647 Vec2 != Vec2End; ++Vec2) {
5648 QualType ParamTypes[2];
5649 ParamTypes[1] = *Vec2;
5650 // Add this built-in operator as a candidate (VQ is empty).
5651 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
5652 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5653 /*IsAssigmentOperator=*/isEqualOp);
5655 // Add this built-in operator as a candidate (VQ is 'volatile').
5656 if (VisibleTypeConversionsQuals.hasVolatile()) {
5657 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
5658 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5659 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5660 CandidateSet,
5661 /*IsAssigmentOperator=*/isEqualOp);
5667 // C++ [over.built]p22:
5669 // For every triple (L, VQ, R), where L is an integral type, VQ
5670 // is either volatile or empty, and R is a promoted integral
5671 // type, there exist candidate operator functions of the form
5673 // VQ L& operator%=(VQ L&, R);
5674 // VQ L& operator<<=(VQ L&, R);
5675 // VQ L& operator>>=(VQ L&, R);
5676 // VQ L& operator&=(VQ L&, R);
5677 // VQ L& operator^=(VQ L&, R);
5678 // VQ L& operator|=(VQ L&, R);
5679 void addAssignmentIntegralOverloads() {
5680 if (!HasArithmeticOrEnumeralCandidateType)
5681 return;
5683 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
5684 for (unsigned Right = FirstPromotedIntegralType;
5685 Right < LastPromotedIntegralType; ++Right) {
5686 QualType ParamTypes[2];
5687 ParamTypes[1] = getArithmeticType(Right);
5689 // Add this built-in operator as a candidate (VQ is empty).
5690 ParamTypes[0] =
5691 S.Context.getLValueReferenceType(getArithmeticType(Left));
5692 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5693 if (VisibleTypeConversionsQuals.hasVolatile()) {
5694 // Add this built-in operator as a candidate (VQ is 'volatile').
5695 ParamTypes[0] = getArithmeticType(Left);
5696 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
5697 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5698 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5699 CandidateSet);
5705 // C++ [over.operator]p23:
5707 // There also exist candidate operator functions of the form
5709 // bool operator!(bool);
5710 // bool operator&&(bool, bool);
5711 // bool operator||(bool, bool);
5712 void addExclaimOverload() {
5713 QualType ParamTy = S.Context.BoolTy;
5714 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5715 /*IsAssignmentOperator=*/false,
5716 /*NumContextualBoolArguments=*/1);
5718 void addAmpAmpOrPipePipeOverload() {
5719 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
5720 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5721 /*IsAssignmentOperator=*/false,
5722 /*NumContextualBoolArguments=*/2);
5725 // C++ [over.built]p13:
5727 // For every cv-qualified or cv-unqualified object type T there
5728 // exist candidate operator functions of the form
5730 // T* operator+(T*, ptrdiff_t); [ABOVE]
5731 // T& operator[](T*, ptrdiff_t);
5732 // T* operator-(T*, ptrdiff_t); [ABOVE]
5733 // T* operator+(ptrdiff_t, T*); [ABOVE]
5734 // T& operator[](ptrdiff_t, T*);
5735 void addSubscriptOverloads() {
5736 for (BuiltinCandidateTypeSet::iterator
5737 Ptr = CandidateTypes[0].pointer_begin(),
5738 PtrEnd = CandidateTypes[0].pointer_end();
5739 Ptr != PtrEnd; ++Ptr) {
5740 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
5741 QualType PointeeType = (*Ptr)->getPointeeType();
5742 if (!PointeeType->isObjectType())
5743 continue;
5745 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5747 // T& operator[](T*, ptrdiff_t)
5748 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5751 for (BuiltinCandidateTypeSet::iterator
5752 Ptr = CandidateTypes[1].pointer_begin(),
5753 PtrEnd = CandidateTypes[1].pointer_end();
5754 Ptr != PtrEnd; ++Ptr) {
5755 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
5756 QualType PointeeType = (*Ptr)->getPointeeType();
5757 if (!PointeeType->isObjectType())
5758 continue;
5760 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5762 // T& operator[](ptrdiff_t, T*)
5763 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5767 // C++ [over.built]p11:
5768 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5769 // C1 is the same type as C2 or is a derived class of C2, T is an object
5770 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5771 // there exist candidate operator functions of the form
5773 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5775 // where CV12 is the union of CV1 and CV2.
5776 void addArrowStarOverloads() {
5777 for (BuiltinCandidateTypeSet::iterator
5778 Ptr = CandidateTypes[0].pointer_begin(),
5779 PtrEnd = CandidateTypes[0].pointer_end();
5780 Ptr != PtrEnd; ++Ptr) {
5781 QualType C1Ty = (*Ptr);
5782 QualType C1;
5783 QualifierCollector Q1;
5784 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5785 if (!isa<RecordType>(C1))
5786 continue;
5787 // heuristic to reduce number of builtin candidates in the set.
5788 // Add volatile/restrict version only if there are conversions to a
5789 // volatile/restrict type.
5790 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5791 continue;
5792 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5793 continue;
5794 for (BuiltinCandidateTypeSet::iterator
5795 MemPtr = CandidateTypes[1].member_pointer_begin(),
5796 MemPtrEnd = CandidateTypes[1].member_pointer_end();
5797 MemPtr != MemPtrEnd; ++MemPtr) {
5798 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5799 QualType C2 = QualType(mptr->getClass(), 0);
5800 C2 = C2.getUnqualifiedType();
5801 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
5802 break;
5803 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5804 // build CV12 T&
5805 QualType T = mptr->getPointeeType();
5806 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5807 T.isVolatileQualified())
5808 continue;
5809 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5810 T.isRestrictQualified())
5811 continue;
5812 T = Q1.apply(S.Context, T);
5813 QualType ResultTy = S.Context.getLValueReferenceType(T);
5814 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5819 // Note that we don't consider the first argument, since it has been
5820 // contextually converted to bool long ago. The candidates below are
5821 // therefore added as binary.
5823 // C++ [over.built]p25:
5824 // For every type T, where T is a pointer, pointer-to-member, or scoped
5825 // enumeration type, there exist candidate operator functions of the form
5827 // T operator?(bool, T, T);
5829 void addConditionalOperatorOverloads() {
5830 /// Set of (canonical) types that we've already handled.
5831 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5833 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5834 for (BuiltinCandidateTypeSet::iterator
5835 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5836 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5837 Ptr != PtrEnd; ++Ptr) {
5838 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5839 continue;
5841 QualType ParamTypes[2] = { *Ptr, *Ptr };
5842 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5845 for (BuiltinCandidateTypeSet::iterator
5846 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5847 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5848 MemPtr != MemPtrEnd; ++MemPtr) {
5849 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5850 continue;
5852 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5853 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5856 if (S.getLangOptions().CPlusPlus0x) {
5857 for (BuiltinCandidateTypeSet::iterator
5858 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5859 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5860 Enum != EnumEnd; ++Enum) {
5861 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5862 continue;
5864 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5865 continue;
5867 QualType ParamTypes[2] = { *Enum, *Enum };
5868 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5875 } // end anonymous namespace
5877 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
5878 /// operator overloads to the candidate set (C++ [over.built]), based
5879 /// on the operator @p Op and the arguments given. For example, if the
5880 /// operator is a binary '+', this routine might add "int
5881 /// operator+(int, int)" to cover integer addition.
5882 void
5883 Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
5884 SourceLocation OpLoc,
5885 Expr **Args, unsigned NumArgs,
5886 OverloadCandidateSet& CandidateSet) {
5887 // Find all of the types that the arguments can convert to, but only
5888 // if the operator we're looking at has built-in operator candidates
5889 // that make use of these types. Also record whether we encounter non-record
5890 // candidate types or either arithmetic or enumeral candidate types.
5891 Qualifiers VisibleTypeConversionsQuals;
5892 VisibleTypeConversionsQuals.addConst();
5893 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5894 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
5896 bool HasNonRecordCandidateType = false;
5897 bool HasArithmeticOrEnumeralCandidateType = false;
5898 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
5899 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5900 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
5901 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
5902 OpLoc,
5903 true,
5904 (Op == OO_Exclaim ||
5905 Op == OO_AmpAmp ||
5906 Op == OO_PipePipe),
5907 VisibleTypeConversionsQuals);
5908 HasNonRecordCandidateType = HasNonRecordCandidateType ||
5909 CandidateTypes[ArgIdx].hasNonRecordTypes();
5910 HasArithmeticOrEnumeralCandidateType =
5911 HasArithmeticOrEnumeralCandidateType ||
5912 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
5915 // Exit early when no non-record types have been added to the candidate set
5916 // for any of the arguments to the operator.
5917 if (!HasNonRecordCandidateType)
5918 return;
5920 // Setup an object to manage the common state for building overloads.
5921 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
5922 VisibleTypeConversionsQuals,
5923 HasArithmeticOrEnumeralCandidateType,
5924 CandidateTypes, CandidateSet);
5926 // Dispatch over the operation to add in only those overloads which apply.
5927 switch (Op) {
5928 case OO_None:
5929 case NUM_OVERLOADED_OPERATORS:
5930 assert(false && "Expected an overloaded operator");
5931 break;
5933 case OO_New:
5934 case OO_Delete:
5935 case OO_Array_New:
5936 case OO_Array_Delete:
5937 case OO_Call:
5938 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
5939 break;
5941 case OO_Comma:
5942 case OO_Arrow:
5943 // C++ [over.match.oper]p3:
5944 // -- For the operator ',', the unary operator '&', or the
5945 // operator '->', the built-in candidates set is empty.
5946 break;
5948 case OO_Plus: // '+' is either unary or binary
5949 if (NumArgs == 1)
5950 OpBuilder.addUnaryPlusPointerOverloads();
5951 // Fall through.
5953 case OO_Minus: // '-' is either unary or binary
5954 if (NumArgs == 1) {
5955 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
5956 } else {
5957 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
5958 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5960 break;
5962 case OO_Star: // '*' is either unary or binary
5963 if (NumArgs == 1)
5964 OpBuilder.addUnaryStarPointerOverloads();
5965 else
5966 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5967 break;
5969 case OO_Slash:
5970 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5971 break;
5973 case OO_PlusPlus:
5974 case OO_MinusMinus:
5975 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
5976 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
5977 break;
5979 case OO_EqualEqual:
5980 case OO_ExclaimEqual:
5981 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
5982 // Fall through.
5984 case OO_Less:
5985 case OO_Greater:
5986 case OO_LessEqual:
5987 case OO_GreaterEqual:
5988 OpBuilder.addRelationalPointerOrEnumeralOverloads();
5989 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
5990 break;
5992 case OO_Percent:
5993 case OO_Caret:
5994 case OO_Pipe:
5995 case OO_LessLess:
5996 case OO_GreaterGreater:
5997 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
5998 break;
6000 case OO_Amp: // '&' is either unary or binary
6001 if (NumArgs == 1)
6002 // C++ [over.match.oper]p3:
6003 // -- For the operator ',', the unary operator '&', or the
6004 // operator '->', the built-in candidates set is empty.
6005 break;
6007 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6008 break;
6010 case OO_Tilde:
6011 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6012 break;
6014 case OO_Equal:
6015 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
6016 // Fall through.
6018 case OO_PlusEqual:
6019 case OO_MinusEqual:
6020 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
6021 // Fall through.
6023 case OO_StarEqual:
6024 case OO_SlashEqual:
6025 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
6026 break;
6028 case OO_PercentEqual:
6029 case OO_LessLessEqual:
6030 case OO_GreaterGreaterEqual:
6031 case OO_AmpEqual:
6032 case OO_CaretEqual:
6033 case OO_PipeEqual:
6034 OpBuilder.addAssignmentIntegralOverloads();
6035 break;
6037 case OO_Exclaim:
6038 OpBuilder.addExclaimOverload();
6039 break;
6041 case OO_AmpAmp:
6042 case OO_PipePipe:
6043 OpBuilder.addAmpAmpOrPipePipeOverload();
6044 break;
6046 case OO_Subscript:
6047 OpBuilder.addSubscriptOverloads();
6048 break;
6050 case OO_ArrowStar:
6051 OpBuilder.addArrowStarOverloads();
6052 break;
6054 case OO_Conditional:
6055 OpBuilder.addConditionalOperatorOverloads();
6056 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6057 break;
6061 /// \brief Add function candidates found via argument-dependent lookup
6062 /// to the set of overloading candidates.
6064 /// This routine performs argument-dependent name lookup based on the
6065 /// given function name (which may also be an operator name) and adds
6066 /// all of the overload candidates found by ADL to the overload
6067 /// candidate set (C++ [basic.lookup.argdep]).
6068 void
6069 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
6070 bool Operator,
6071 Expr **Args, unsigned NumArgs,
6072 const TemplateArgumentListInfo *ExplicitTemplateArgs,
6073 OverloadCandidateSet& CandidateSet,
6074 bool PartialOverloading) {
6075 ADLResult Fns;
6077 // FIXME: This approach for uniquing ADL results (and removing
6078 // redundant candidates from the set) relies on pointer-equality,
6079 // which means we need to key off the canonical decl. However,
6080 // always going back to the canonical decl might not get us the
6081 // right set of default arguments. What default arguments are
6082 // we supposed to consider on ADL candidates, anyway?
6084 // FIXME: Pass in the explicit template arguments?
6085 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
6087 // Erase all of the candidates we already knew about.
6088 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6089 CandEnd = CandidateSet.end();
6090 Cand != CandEnd; ++Cand)
6091 if (Cand->Function) {
6092 Fns.erase(Cand->Function);
6093 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
6094 Fns.erase(FunTmpl);
6097 // For each of the ADL candidates we found, add it to the overload
6098 // set.
6099 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
6100 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
6101 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
6102 if (ExplicitTemplateArgs)
6103 continue;
6105 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
6106 false, PartialOverloading);
6107 } else
6108 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
6109 FoundDecl, ExplicitTemplateArgs,
6110 Args, NumArgs, CandidateSet);
6114 /// isBetterOverloadCandidate - Determines whether the first overload
6115 /// candidate is a better candidate than the second (C++ 13.3.3p1).
6116 bool
6117 isBetterOverloadCandidate(Sema &S,
6118 const OverloadCandidate &Cand1,
6119 const OverloadCandidate &Cand2,
6120 SourceLocation Loc,
6121 bool UserDefinedConversion) {
6122 // Define viable functions to be better candidates than non-viable
6123 // functions.
6124 if (!Cand2.Viable)
6125 return Cand1.Viable;
6126 else if (!Cand1.Viable)
6127 return false;
6129 // C++ [over.match.best]p1:
6131 // -- if F is a static member function, ICS1(F) is defined such
6132 // that ICS1(F) is neither better nor worse than ICS1(G) for
6133 // any function G, and, symmetrically, ICS1(G) is neither
6134 // better nor worse than ICS1(F).
6135 unsigned StartArg = 0;
6136 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6137 StartArg = 1;
6139 // C++ [over.match.best]p1:
6140 // A viable function F1 is defined to be a better function than another
6141 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
6142 // conversion sequence than ICSi(F2), and then...
6143 unsigned NumArgs = Cand1.Conversions.size();
6144 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6145 bool HasBetterConversion = false;
6146 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
6147 switch (CompareImplicitConversionSequences(S,
6148 Cand1.Conversions[ArgIdx],
6149 Cand2.Conversions[ArgIdx])) {
6150 case ImplicitConversionSequence::Better:
6151 // Cand1 has a better conversion sequence.
6152 HasBetterConversion = true;
6153 break;
6155 case ImplicitConversionSequence::Worse:
6156 // Cand1 can't be better than Cand2.
6157 return false;
6159 case ImplicitConversionSequence::Indistinguishable:
6160 // Do nothing.
6161 break;
6165 // -- for some argument j, ICSj(F1) is a better conversion sequence than
6166 // ICSj(F2), or, if not that,
6167 if (HasBetterConversion)
6168 return true;
6170 // - F1 is a non-template function and F2 is a function template
6171 // specialization, or, if not that,
6172 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
6173 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6174 return true;
6176 // -- F1 and F2 are function template specializations, and the function
6177 // template for F1 is more specialized than the template for F2
6178 // according to the partial ordering rules described in 14.5.5.2, or,
6179 // if not that,
6180 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
6181 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
6182 if (FunctionTemplateDecl *BetterTemplate
6183 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6184 Cand2.Function->getPrimaryTemplate(),
6185 Loc,
6186 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
6187 : TPOC_Call,
6188 Cand1.ExplicitCallArguments))
6189 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
6192 // -- the context is an initialization by user-defined conversion
6193 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6194 // from the return type of F1 to the destination type (i.e.,
6195 // the type of the entity being initialized) is a better
6196 // conversion sequence than the standard conversion sequence
6197 // from the return type of F2 to the destination type.
6198 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
6199 isa<CXXConversionDecl>(Cand1.Function) &&
6200 isa<CXXConversionDecl>(Cand2.Function)) {
6201 switch (CompareStandardConversionSequences(S,
6202 Cand1.FinalConversion,
6203 Cand2.FinalConversion)) {
6204 case ImplicitConversionSequence::Better:
6205 // Cand1 has a better conversion sequence.
6206 return true;
6208 case ImplicitConversionSequence::Worse:
6209 // Cand1 can't be better than Cand2.
6210 return false;
6212 case ImplicitConversionSequence::Indistinguishable:
6213 // Do nothing
6214 break;
6218 return false;
6221 /// \brief Computes the best viable function (C++ 13.3.3)
6222 /// within an overload candidate set.
6224 /// \param CandidateSet the set of candidate functions.
6226 /// \param Loc the location of the function name (or operator symbol) for
6227 /// which overload resolution occurs.
6229 /// \param Best f overload resolution was successful or found a deleted
6230 /// function, Best points to the candidate function found.
6232 /// \returns The result of overload resolution.
6233 OverloadingResult
6234 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
6235 iterator &Best,
6236 bool UserDefinedConversion) {
6237 // Find the best viable function.
6238 Best = end();
6239 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6240 if (Cand->Viable)
6241 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
6242 UserDefinedConversion))
6243 Best = Cand;
6246 // If we didn't find any viable functions, abort.
6247 if (Best == end())
6248 return OR_No_Viable_Function;
6250 // Make sure that this function is better than every other viable
6251 // function. If not, we have an ambiguity.
6252 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6253 if (Cand->Viable &&
6254 Cand != Best &&
6255 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
6256 UserDefinedConversion)) {
6257 Best = end();
6258 return OR_Ambiguous;
6262 // Best is the best viable function.
6263 if (Best->Function &&
6264 (Best->Function->isDeleted() ||
6265 Best->Function->getAttr<UnavailableAttr>()))
6266 return OR_Deleted;
6268 // C++ [basic.def.odr]p2:
6269 // An overloaded function is used if it is selected by overload resolution
6270 // when referred to from a potentially-evaluated expression. [Note: this
6271 // covers calls to named functions (5.2.2), operator overloading
6272 // (clause 13), user-defined conversions (12.3.2), allocation function for
6273 // placement new (5.3.4), as well as non-default initialization (8.5).
6274 if (Best->Function)
6275 S.MarkDeclarationReferenced(Loc, Best->Function);
6277 return OR_Success;
6280 namespace {
6282 enum OverloadCandidateKind {
6283 oc_function,
6284 oc_method,
6285 oc_constructor,
6286 oc_function_template,
6287 oc_method_template,
6288 oc_constructor_template,
6289 oc_implicit_default_constructor,
6290 oc_implicit_copy_constructor,
6291 oc_implicit_copy_assignment,
6292 oc_implicit_inherited_constructor
6295 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6296 FunctionDecl *Fn,
6297 std::string &Description) {
6298 bool isTemplate = false;
6300 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6301 isTemplate = true;
6302 Description = S.getTemplateArgumentBindingsText(
6303 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6306 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
6307 if (!Ctor->isImplicit())
6308 return isTemplate ? oc_constructor_template : oc_constructor;
6310 if (Ctor->getInheritedConstructor())
6311 return oc_implicit_inherited_constructor;
6313 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
6314 : oc_implicit_default_constructor;
6317 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6318 // This actually gets spelled 'candidate function' for now, but
6319 // it doesn't hurt to split it out.
6320 if (!Meth->isImplicit())
6321 return isTemplate ? oc_method_template : oc_method;
6323 assert(Meth->isCopyAssignmentOperator()
6324 && "implicit method is not copy assignment operator?");
6325 return oc_implicit_copy_assignment;
6328 return isTemplate ? oc_function_template : oc_function;
6331 void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
6332 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
6333 if (!Ctor) return;
6335 Ctor = Ctor->getInheritedConstructor();
6336 if (!Ctor) return;
6338 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
6341 } // end anonymous namespace
6343 // Notes the location of an overload candidate.
6344 void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
6345 std::string FnDesc;
6346 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6347 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6348 << (unsigned) K << FnDesc;
6349 MaybeEmitInheritedConstructorNote(*this, Fn);
6352 /// Diagnoses an ambiguous conversion. The partial diagnostic is the
6353 /// "lead" diagnostic; it will be given two arguments, the source and
6354 /// target types of the conversion.
6355 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6356 Sema &S,
6357 SourceLocation CaretLoc,
6358 const PartialDiagnostic &PDiag) const {
6359 S.Diag(CaretLoc, PDiag)
6360 << Ambiguous.getFromType() << Ambiguous.getToType();
6361 for (AmbiguousConversionSequence::const_iterator
6362 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6363 S.NoteOverloadCandidate(*I);
6367 namespace {
6369 void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6370 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6371 assert(Conv.isBad());
6372 assert(Cand->Function && "for now, candidate must be a function");
6373 FunctionDecl *Fn = Cand->Function;
6375 // There's a conversion slot for the object argument if this is a
6376 // non-constructor method. Note that 'I' corresponds the
6377 // conversion-slot index.
6378 bool isObjectArgument = false;
6379 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
6380 if (I == 0)
6381 isObjectArgument = true;
6382 else
6383 I--;
6386 std::string FnDesc;
6387 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6389 Expr *FromExpr = Conv.Bad.FromExpr;
6390 QualType FromTy = Conv.Bad.getFromType();
6391 QualType ToTy = Conv.Bad.getToType();
6393 if (FromTy == S.Context.OverloadTy) {
6394 assert(FromExpr && "overload set argument came from implicit argument?");
6395 Expr *E = FromExpr->IgnoreParens();
6396 if (isa<UnaryOperator>(E))
6397 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
6398 DeclarationName Name = cast<OverloadExpr>(E)->getName();
6400 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6401 << (unsigned) FnKind << FnDesc
6402 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6403 << ToTy << Name << I+1;
6404 MaybeEmitInheritedConstructorNote(S, Fn);
6405 return;
6408 // Do some hand-waving analysis to see if the non-viability is due
6409 // to a qualifier mismatch.
6410 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6411 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6412 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6413 CToTy = RT->getPointeeType();
6414 else {
6415 // TODO: detect and diagnose the full richness of const mismatches.
6416 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6417 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6418 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6421 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6422 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6423 // It is dumb that we have to do this here.
6424 while (isa<ArrayType>(CFromTy))
6425 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6426 while (isa<ArrayType>(CToTy))
6427 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6429 Qualifiers FromQs = CFromTy.getQualifiers();
6430 Qualifiers ToQs = CToTy.getQualifiers();
6432 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6433 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6434 << (unsigned) FnKind << FnDesc
6435 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6436 << FromTy
6437 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6438 << (unsigned) isObjectArgument << I+1;
6439 MaybeEmitInheritedConstructorNote(S, Fn);
6440 return;
6443 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6444 assert(CVR && "unexpected qualifiers mismatch");
6446 if (isObjectArgument) {
6447 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6448 << (unsigned) FnKind << FnDesc
6449 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6450 << FromTy << (CVR - 1);
6451 } else {
6452 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6453 << (unsigned) FnKind << FnDesc
6454 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6455 << FromTy << (CVR - 1) << I+1;
6457 MaybeEmitInheritedConstructorNote(S, Fn);
6458 return;
6461 // Diagnose references or pointers to incomplete types differently,
6462 // since it's far from impossible that the incompleteness triggered
6463 // the failure.
6464 QualType TempFromTy = FromTy.getNonReferenceType();
6465 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6466 TempFromTy = PTy->getPointeeType();
6467 if (TempFromTy->isIncompleteType()) {
6468 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6469 << (unsigned) FnKind << FnDesc
6470 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6471 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
6472 MaybeEmitInheritedConstructorNote(S, Fn);
6473 return;
6476 // Diagnose base -> derived pointer conversions.
6477 unsigned BaseToDerivedConversion = 0;
6478 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6479 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6480 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6481 FromPtrTy->getPointeeType()) &&
6482 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6483 !ToPtrTy->getPointeeType()->isIncompleteType() &&
6484 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
6485 FromPtrTy->getPointeeType()))
6486 BaseToDerivedConversion = 1;
6488 } else if (const ObjCObjectPointerType *FromPtrTy
6489 = FromTy->getAs<ObjCObjectPointerType>()) {
6490 if (const ObjCObjectPointerType *ToPtrTy
6491 = ToTy->getAs<ObjCObjectPointerType>())
6492 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6493 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6494 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6495 FromPtrTy->getPointeeType()) &&
6496 FromIface->isSuperClassOf(ToIface))
6497 BaseToDerivedConversion = 2;
6498 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6499 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6500 !FromTy->isIncompleteType() &&
6501 !ToRefTy->getPointeeType()->isIncompleteType() &&
6502 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6503 BaseToDerivedConversion = 3;
6506 if (BaseToDerivedConversion) {
6507 S.Diag(Fn->getLocation(),
6508 diag::note_ovl_candidate_bad_base_to_derived_conv)
6509 << (unsigned) FnKind << FnDesc
6510 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6511 << (BaseToDerivedConversion - 1)
6512 << FromTy << ToTy << I+1;
6513 MaybeEmitInheritedConstructorNote(S, Fn);
6514 return;
6517 // TODO: specialize more based on the kind of mismatch
6518 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
6519 << (unsigned) FnKind << FnDesc
6520 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6521 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
6522 MaybeEmitInheritedConstructorNote(S, Fn);
6525 void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6526 unsigned NumFormalArgs) {
6527 // TODO: treat calls to a missing default constructor as a special case
6529 FunctionDecl *Fn = Cand->Function;
6530 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6532 unsigned MinParams = Fn->getMinRequiredArguments();
6534 // at least / at most / exactly
6535 unsigned mode, modeCount;
6536 if (NumFormalArgs < MinParams) {
6537 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6538 (Cand->FailureKind == ovl_fail_bad_deduction &&
6539 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
6540 if (MinParams != FnTy->getNumArgs() ||
6541 FnTy->isVariadic() || FnTy->isTemplateVariadic())
6542 mode = 0; // "at least"
6543 else
6544 mode = 2; // "exactly"
6545 modeCount = MinParams;
6546 } else {
6547 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6548 (Cand->FailureKind == ovl_fail_bad_deduction &&
6549 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
6550 if (MinParams != FnTy->getNumArgs())
6551 mode = 1; // "at most"
6552 else
6553 mode = 2; // "exactly"
6554 modeCount = FnTy->getNumArgs();
6557 std::string Description;
6558 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6560 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
6561 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
6562 << modeCount << NumFormalArgs;
6563 MaybeEmitInheritedConstructorNote(S, Fn);
6566 /// Diagnose a failed template-argument deduction.
6567 void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6568 Expr **Args, unsigned NumArgs) {
6569 FunctionDecl *Fn = Cand->Function; // pattern
6571 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
6572 NamedDecl *ParamD;
6573 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6574 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6575 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
6576 switch (Cand->DeductionFailure.Result) {
6577 case Sema::TDK_Success:
6578 llvm_unreachable("TDK_success while diagnosing bad deduction");
6580 case Sema::TDK_Incomplete: {
6581 assert(ParamD && "no parameter found for incomplete deduction result");
6582 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6583 << ParamD->getDeclName();
6584 MaybeEmitInheritedConstructorNote(S, Fn);
6585 return;
6588 case Sema::TDK_Underqualified: {
6589 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6590 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6592 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6594 // Param will have been canonicalized, but it should just be a
6595 // qualified version of ParamD, so move the qualifiers to that.
6596 QualifierCollector Qs;
6597 Qs.strip(Param);
6598 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
6599 assert(S.Context.hasSameType(Param, NonCanonParam));
6601 // Arg has also been canonicalized, but there's nothing we can do
6602 // about that. It also doesn't matter as much, because it won't
6603 // have any template parameters in it (because deduction isn't
6604 // done on dependent types).
6605 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6607 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6608 << ParamD->getDeclName() << Arg << NonCanonParam;
6609 MaybeEmitInheritedConstructorNote(S, Fn);
6610 return;
6613 case Sema::TDK_Inconsistent: {
6614 assert(ParamD && "no parameter found for inconsistent deduction result");
6615 int which = 0;
6616 if (isa<TemplateTypeParmDecl>(ParamD))
6617 which = 0;
6618 else if (isa<NonTypeTemplateParmDecl>(ParamD))
6619 which = 1;
6620 else {
6621 which = 2;
6624 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
6625 << which << ParamD->getDeclName()
6626 << *Cand->DeductionFailure.getFirstArg()
6627 << *Cand->DeductionFailure.getSecondArg();
6628 MaybeEmitInheritedConstructorNote(S, Fn);
6629 return;
6632 case Sema::TDK_InvalidExplicitArguments:
6633 assert(ParamD && "no parameter found for invalid explicit arguments");
6634 if (ParamD->getDeclName())
6635 S.Diag(Fn->getLocation(),
6636 diag::note_ovl_candidate_explicit_arg_mismatch_named)
6637 << ParamD->getDeclName();
6638 else {
6639 int index = 0;
6640 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6641 index = TTP->getIndex();
6642 else if (NonTypeTemplateParmDecl *NTTP
6643 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6644 index = NTTP->getIndex();
6645 else
6646 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
6647 S.Diag(Fn->getLocation(),
6648 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6649 << (index + 1);
6651 MaybeEmitInheritedConstructorNote(S, Fn);
6652 return;
6654 case Sema::TDK_TooManyArguments:
6655 case Sema::TDK_TooFewArguments:
6656 DiagnoseArityMismatch(S, Cand, NumArgs);
6657 return;
6659 case Sema::TDK_InstantiationDepth:
6660 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
6661 MaybeEmitInheritedConstructorNote(S, Fn);
6662 return;
6664 case Sema::TDK_SubstitutionFailure: {
6665 std::string ArgString;
6666 if (TemplateArgumentList *Args
6667 = Cand->DeductionFailure.getTemplateArgumentList())
6668 ArgString = S.getTemplateArgumentBindingsText(
6669 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6670 *Args);
6671 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6672 << ArgString;
6673 MaybeEmitInheritedConstructorNote(S, Fn);
6674 return;
6677 // TODO: diagnose these individually, then kill off
6678 // note_ovl_candidate_bad_deduction, which is uselessly vague.
6679 case Sema::TDK_NonDeducedMismatch:
6680 case Sema::TDK_FailedOverloadResolution:
6681 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
6682 MaybeEmitInheritedConstructorNote(S, Fn);
6683 return;
6687 /// Generates a 'note' diagnostic for an overload candidate. We've
6688 /// already generated a primary error at the call site.
6690 /// It really does need to be a single diagnostic with its caret
6691 /// pointed at the candidate declaration. Yes, this creates some
6692 /// major challenges of technical writing. Yes, this makes pointing
6693 /// out problems with specific arguments quite awkward. It's still
6694 /// better than generating twenty screens of text for every failed
6695 /// overload.
6697 /// It would be great to be able to express per-candidate problems
6698 /// more richly for those diagnostic clients that cared, but we'd
6699 /// still have to be just as careful with the default diagnostics.
6700 void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6701 Expr **Args, unsigned NumArgs) {
6702 FunctionDecl *Fn = Cand->Function;
6704 // Note deleted candidates, but only if they're viable.
6705 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
6706 std::string FnDesc;
6707 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6709 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
6710 << FnKind << FnDesc << Fn->isDeleted();
6711 MaybeEmitInheritedConstructorNote(S, Fn);
6712 return;
6715 // We don't really have anything else to say about viable candidates.
6716 if (Cand->Viable) {
6717 S.NoteOverloadCandidate(Fn);
6718 return;
6721 switch (Cand->FailureKind) {
6722 case ovl_fail_too_many_arguments:
6723 case ovl_fail_too_few_arguments:
6724 return DiagnoseArityMismatch(S, Cand, NumArgs);
6726 case ovl_fail_bad_deduction:
6727 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6729 case ovl_fail_trivial_conversion:
6730 case ovl_fail_bad_final_conversion:
6731 case ovl_fail_final_conversion_not_exact:
6732 return S.NoteOverloadCandidate(Fn);
6734 case ovl_fail_bad_conversion: {
6735 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6736 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
6737 if (Cand->Conversions[I].isBad())
6738 return DiagnoseBadConversion(S, Cand, I);
6740 // FIXME: this currently happens when we're called from SemaInit
6741 // when user-conversion overload fails. Figure out how to handle
6742 // those conditions and diagnose them well.
6743 return S.NoteOverloadCandidate(Fn);
6748 void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6749 // Desugar the type of the surrogate down to a function type,
6750 // retaining as many typedefs as possible while still showing
6751 // the function type (and, therefore, its parameter types).
6752 QualType FnType = Cand->Surrogate->getConversionType();
6753 bool isLValueReference = false;
6754 bool isRValueReference = false;
6755 bool isPointer = false;
6756 if (const LValueReferenceType *FnTypeRef =
6757 FnType->getAs<LValueReferenceType>()) {
6758 FnType = FnTypeRef->getPointeeType();
6759 isLValueReference = true;
6760 } else if (const RValueReferenceType *FnTypeRef =
6761 FnType->getAs<RValueReferenceType>()) {
6762 FnType = FnTypeRef->getPointeeType();
6763 isRValueReference = true;
6765 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6766 FnType = FnTypePtr->getPointeeType();
6767 isPointer = true;
6769 // Desugar down to a function type.
6770 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6771 // Reconstruct the pointer/reference as appropriate.
6772 if (isPointer) FnType = S.Context.getPointerType(FnType);
6773 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6774 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6776 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6777 << FnType;
6778 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
6781 void NoteBuiltinOperatorCandidate(Sema &S,
6782 const char *Opc,
6783 SourceLocation OpLoc,
6784 OverloadCandidate *Cand) {
6785 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6786 std::string TypeStr("operator");
6787 TypeStr += Opc;
6788 TypeStr += "(";
6789 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6790 if (Cand->Conversions.size() == 1) {
6791 TypeStr += ")";
6792 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6793 } else {
6794 TypeStr += ", ";
6795 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6796 TypeStr += ")";
6797 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6801 void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6802 OverloadCandidate *Cand) {
6803 unsigned NoOperands = Cand->Conversions.size();
6804 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6805 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
6806 if (ICS.isBad()) break; // all meaningless after first invalid
6807 if (!ICS.isAmbiguous()) continue;
6809 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
6810 S.PDiag(diag::note_ambiguous_type_conversion));
6814 SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6815 if (Cand->Function)
6816 return Cand->Function->getLocation();
6817 if (Cand->IsSurrogate)
6818 return Cand->Surrogate->getLocation();
6819 return SourceLocation();
6822 struct CompareOverloadCandidatesForDisplay {
6823 Sema &S;
6824 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
6826 bool operator()(const OverloadCandidate *L,
6827 const OverloadCandidate *R) {
6828 // Fast-path this check.
6829 if (L == R) return false;
6831 // Order first by viability.
6832 if (L->Viable) {
6833 if (!R->Viable) return true;
6835 // TODO: introduce a tri-valued comparison for overload
6836 // candidates. Would be more worthwhile if we had a sort
6837 // that could exploit it.
6838 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6839 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
6840 } else if (R->Viable)
6841 return false;
6843 assert(L->Viable == R->Viable);
6845 // Criteria by which we can sort non-viable candidates:
6846 if (!L->Viable) {
6847 // 1. Arity mismatches come after other candidates.
6848 if (L->FailureKind == ovl_fail_too_many_arguments ||
6849 L->FailureKind == ovl_fail_too_few_arguments)
6850 return false;
6851 if (R->FailureKind == ovl_fail_too_many_arguments ||
6852 R->FailureKind == ovl_fail_too_few_arguments)
6853 return true;
6855 // 2. Bad conversions come first and are ordered by the number
6856 // of bad conversions and quality of good conversions.
6857 if (L->FailureKind == ovl_fail_bad_conversion) {
6858 if (R->FailureKind != ovl_fail_bad_conversion)
6859 return true;
6861 // If there's any ordering between the defined conversions...
6862 // FIXME: this might not be transitive.
6863 assert(L->Conversions.size() == R->Conversions.size());
6865 int leftBetter = 0;
6866 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6867 for (unsigned E = L->Conversions.size(); I != E; ++I) {
6868 switch (CompareImplicitConversionSequences(S,
6869 L->Conversions[I],
6870 R->Conversions[I])) {
6871 case ImplicitConversionSequence::Better:
6872 leftBetter++;
6873 break;
6875 case ImplicitConversionSequence::Worse:
6876 leftBetter--;
6877 break;
6879 case ImplicitConversionSequence::Indistinguishable:
6880 break;
6883 if (leftBetter > 0) return true;
6884 if (leftBetter < 0) return false;
6886 } else if (R->FailureKind == ovl_fail_bad_conversion)
6887 return false;
6889 // TODO: others?
6892 // Sort everything else by location.
6893 SourceLocation LLoc = GetLocationForCandidate(L);
6894 SourceLocation RLoc = GetLocationForCandidate(R);
6896 // Put candidates without locations (e.g. builtins) at the end.
6897 if (LLoc.isInvalid()) return false;
6898 if (RLoc.isInvalid()) return true;
6900 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
6904 /// CompleteNonViableCandidate - Normally, overload resolution only
6905 /// computes up to the first
6906 void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6907 Expr **Args, unsigned NumArgs) {
6908 assert(!Cand->Viable);
6910 // Don't do anything on failures other than bad conversion.
6911 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6913 // Skip forward to the first bad conversion.
6914 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
6915 unsigned ConvCount = Cand->Conversions.size();
6916 while (true) {
6917 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6918 ConvIdx++;
6919 if (Cand->Conversions[ConvIdx - 1].isBad())
6920 break;
6923 if (ConvIdx == ConvCount)
6924 return;
6926 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6927 "remaining conversion is initialized?");
6929 // FIXME: this should probably be preserved from the overload
6930 // operation somehow.
6931 bool SuppressUserConversions = false;
6933 const FunctionProtoType* Proto;
6934 unsigned ArgIdx = ConvIdx;
6936 if (Cand->IsSurrogate) {
6937 QualType ConvType
6938 = Cand->Surrogate->getConversionType().getNonReferenceType();
6939 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6940 ConvType = ConvPtrType->getPointeeType();
6941 Proto = ConvType->getAs<FunctionProtoType>();
6942 ArgIdx--;
6943 } else if (Cand->Function) {
6944 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6945 if (isa<CXXMethodDecl>(Cand->Function) &&
6946 !isa<CXXConstructorDecl>(Cand->Function))
6947 ArgIdx--;
6948 } else {
6949 // Builtin binary operator with a bad first conversion.
6950 assert(ConvCount <= 3);
6951 for (; ConvIdx != ConvCount; ++ConvIdx)
6952 Cand->Conversions[ConvIdx]
6953 = TryCopyInitialization(S, Args[ConvIdx],
6954 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6955 SuppressUserConversions,
6956 /*InOverloadResolution*/ true);
6957 return;
6960 // Fill in the rest of the conversions.
6961 unsigned NumArgsInProto = Proto->getNumArgs();
6962 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6963 if (ArgIdx < NumArgsInProto)
6964 Cand->Conversions[ConvIdx]
6965 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6966 SuppressUserConversions,
6967 /*InOverloadResolution=*/true);
6968 else
6969 Cand->Conversions[ConvIdx].setEllipsis();
6973 } // end anonymous namespace
6975 /// PrintOverloadCandidates - When overload resolution fails, prints
6976 /// diagnostic messages containing the candidates in the candidate
6977 /// set.
6978 void OverloadCandidateSet::NoteCandidates(Sema &S,
6979 OverloadCandidateDisplayKind OCD,
6980 Expr **Args, unsigned NumArgs,
6981 const char *Opc,
6982 SourceLocation OpLoc) {
6983 // Sort the candidates by viability and position. Sorting directly would
6984 // be prohibitive, so we make a set of pointers and sort those.
6985 llvm::SmallVector<OverloadCandidate*, 32> Cands;
6986 if (OCD == OCD_AllCandidates) Cands.reserve(size());
6987 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
6988 if (Cand->Viable)
6989 Cands.push_back(Cand);
6990 else if (OCD == OCD_AllCandidates) {
6991 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
6992 if (Cand->Function || Cand->IsSurrogate)
6993 Cands.push_back(Cand);
6994 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6995 // want to list every possible builtin candidate.
6999 std::sort(Cands.begin(), Cands.end(),
7000 CompareOverloadCandidatesForDisplay(S));
7002 bool ReportedAmbiguousConversions = false;
7004 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
7005 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
7006 unsigned CandsShown = 0;
7007 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
7008 OverloadCandidate *Cand = *I;
7010 // Set an arbitrary limit on the number of candidate functions we'll spam
7011 // the user with. FIXME: This limit should depend on details of the
7012 // candidate list.
7013 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
7014 break;
7016 ++CandsShown;
7018 if (Cand->Function)
7019 NoteFunctionCandidate(S, Cand, Args, NumArgs);
7020 else if (Cand->IsSurrogate)
7021 NoteSurrogateCandidate(S, Cand);
7022 else {
7023 assert(Cand->Viable &&
7024 "Non-viable built-in candidates are not added to Cands.");
7025 // Generally we only see ambiguities including viable builtin
7026 // operators if overload resolution got screwed up by an
7027 // ambiguous user-defined conversion.
7029 // FIXME: It's quite possible for different conversions to see
7030 // different ambiguities, though.
7031 if (!ReportedAmbiguousConversions) {
7032 NoteAmbiguousUserConversions(S, OpLoc, Cand);
7033 ReportedAmbiguousConversions = true;
7036 // If this is a viable builtin, print it.
7037 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
7041 if (I != E)
7042 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
7045 static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
7046 if (isa<UnresolvedLookupExpr>(E))
7047 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
7049 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
7052 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
7053 /// an overloaded function (C++ [over.over]), where @p From is an
7054 /// expression with overloaded function type and @p ToType is the type
7055 /// we're trying to resolve to. For example:
7057 /// @code
7058 /// int f(double);
7059 /// int f(int);
7061 /// int (*pfd)(double) = f; // selects f(double)
7062 /// @endcode
7064 /// This routine returns the resulting FunctionDecl if it could be
7065 /// resolved, and NULL otherwise. When @p Complain is true, this
7066 /// routine will emit diagnostics if there is an error.
7067 FunctionDecl *
7068 Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
7069 bool Complain,
7070 DeclAccessPair &FoundResult) {
7071 QualType FunctionType = ToType;
7072 bool IsMember = false;
7073 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
7074 FunctionType = ToTypePtr->getPointeeType();
7075 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
7076 FunctionType = ToTypeRef->getPointeeType();
7077 else if (const MemberPointerType *MemTypePtr =
7078 ToType->getAs<MemberPointerType>()) {
7079 FunctionType = MemTypePtr->getPointeeType();
7080 IsMember = true;
7083 // C++ [over.over]p1:
7084 // [...] [Note: any redundant set of parentheses surrounding the
7085 // overloaded function name is ignored (5.1). ]
7086 // C++ [over.over]p1:
7087 // [...] The overloaded function name can be preceded by the &
7088 // operator.
7089 // However, remember whether the expression has member-pointer form:
7090 // C++ [expr.unary.op]p4:
7091 // A pointer to member is only formed when an explicit & is used
7092 // and its operand is a qualified-id not enclosed in
7093 // parentheses.
7094 OverloadExpr::FindResult Ovl = OverloadExpr::find(From);
7095 OverloadExpr *OvlExpr = Ovl.Expression;
7097 // We expect a pointer or reference to function, or a function pointer.
7098 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
7099 if (!FunctionType->isFunctionType()) {
7100 if (Complain)
7101 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
7102 << OvlExpr->getName() << ToType;
7104 return 0;
7107 // If the overload expression doesn't have the form of a pointer to
7108 // member, don't try to convert it to a pointer-to-member type.
7109 if (IsMember && !Ovl.HasFormOfMemberPointer) {
7110 if (!Complain) return 0;
7112 // TODO: Should we condition this on whether any functions might
7113 // have matched, or is it more appropriate to do that in callers?
7114 // TODO: a fixit wouldn't hurt.
7115 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
7116 << ToType << OvlExpr->getSourceRange();
7117 return 0;
7120 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
7121 if (OvlExpr->hasExplicitTemplateArgs()) {
7122 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
7123 ExplicitTemplateArgs = &ETABuffer;
7126 assert(From->getType() == Context.OverloadTy);
7128 // Look through all of the overloaded functions, searching for one
7129 // whose type matches exactly.
7130 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
7131 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
7133 bool FoundNonTemplateFunction = false;
7134 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7135 E = OvlExpr->decls_end(); I != E; ++I) {
7136 // Look through any using declarations to find the underlying function.
7137 NamedDecl *Fn = (*I)->getUnderlyingDecl();
7139 // C++ [over.over]p3:
7140 // Non-member functions and static member functions match
7141 // targets of type "pointer-to-function" or "reference-to-function."
7142 // Nonstatic member functions match targets of
7143 // type "pointer-to-member-function."
7144 // Note that according to DR 247, the containing class does not matter.
7146 if (FunctionTemplateDecl *FunctionTemplate
7147 = dyn_cast<FunctionTemplateDecl>(Fn)) {
7148 if (CXXMethodDecl *Method
7149 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
7150 // Skip non-static function templates when converting to pointer, and
7151 // static when converting to member pointer.
7152 if (Method->isStatic() == IsMember)
7153 continue;
7154 } else if (IsMember)
7155 continue;
7157 // C++ [over.over]p2:
7158 // If the name is a function template, template argument deduction is
7159 // done (14.8.2.2), and if the argument deduction succeeds, the
7160 // resulting template argument list is used to generate a single
7161 // function template specialization, which is added to the set of
7162 // overloaded functions considered.
7163 FunctionDecl *Specialization = 0;
7164 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
7165 if (TemplateDeductionResult Result
7166 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
7167 FunctionType, Specialization, Info)) {
7168 // FIXME: make a note of the failed deduction for diagnostics.
7169 (void)Result;
7170 } else {
7171 // Template argument deduction ensures that we have an exact match.
7172 // This function template specicalization works.
7173 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
7174 assert(FunctionType
7175 == Context.getCanonicalType(Specialization->getType()));
7176 Matches.push_back(std::make_pair(I.getPair(), Specialization));
7179 continue;
7182 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7183 // Skip non-static functions when converting to pointer, and static
7184 // when converting to member pointer.
7185 if (Method->isStatic() == IsMember)
7186 continue;
7188 // If we have explicit template arguments, skip non-templates.
7189 if (OvlExpr->hasExplicitTemplateArgs())
7190 continue;
7191 } else if (IsMember)
7192 continue;
7194 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
7195 QualType ResultTy;
7196 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
7197 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
7198 ResultTy)) {
7199 Matches.push_back(std::make_pair(I.getPair(),
7200 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
7201 FoundNonTemplateFunction = true;
7206 // If there were 0 or 1 matches, we're done.
7207 if (Matches.empty()) {
7208 if (Complain) {
7209 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
7210 << OvlExpr->getName() << FunctionType;
7211 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7212 E = OvlExpr->decls_end();
7213 I != E; ++I)
7214 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
7215 NoteOverloadCandidate(F);
7218 return 0;
7219 } else if (Matches.size() == 1) {
7220 FunctionDecl *Result = Matches[0].second;
7221 FoundResult = Matches[0].first;
7222 MarkDeclarationReferenced(From->getLocStart(), Result);
7223 if (Complain) {
7224 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
7226 return Result;
7229 // C++ [over.over]p4:
7230 // If more than one function is selected, [...]
7231 if (!FoundNonTemplateFunction) {
7232 // [...] and any given function template specialization F1 is
7233 // eliminated if the set contains a second function template
7234 // specialization whose function template is more specialized
7235 // than the function template of F1 according to the partial
7236 // ordering rules of 14.5.5.2.
7238 // The algorithm specified above is quadratic. We instead use a
7239 // two-pass algorithm (similar to the one used to identify the
7240 // best viable function in an overload set) that identifies the
7241 // best function template (if it exists).
7243 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
7244 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7245 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
7247 UnresolvedSetIterator Result =
7248 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
7249 TPOC_Other, 0, From->getLocStart(),
7250 PDiag(),
7251 PDiag(diag::err_addr_ovl_ambiguous)
7252 << Matches[0].second->getDeclName(),
7253 PDiag(diag::note_ovl_candidate)
7254 << (unsigned) oc_function_template);
7255 if (Result == MatchesCopy.end())
7256 return 0;
7258 MarkDeclarationReferenced(From->getLocStart(), *Result);
7259 FoundResult = Matches[Result - MatchesCopy.begin()].first;
7260 if (Complain)
7261 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
7262 return cast<FunctionDecl>(*Result);
7265 // [...] any function template specializations in the set are
7266 // eliminated if the set also contains a non-template function, [...]
7267 for (unsigned I = 0, N = Matches.size(); I != N; ) {
7268 if (Matches[I].second->getPrimaryTemplate() == 0)
7269 ++I;
7270 else {
7271 Matches[I] = Matches[--N];
7272 Matches.set_size(N);
7276 // [...] After such eliminations, if any, there shall remain exactly one
7277 // selected function.
7278 if (Matches.size() == 1) {
7279 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
7280 FoundResult = Matches[0].first;
7281 if (Complain)
7282 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
7283 return cast<FunctionDecl>(Matches[0].second);
7286 // FIXME: We should probably return the same thing that BestViableFunction
7287 // returns (even if we issue the diagnostics here).
7288 if (Complain) {
7289 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
7290 << Matches[0].second->getDeclName();
7291 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7292 NoteOverloadCandidate(Matches[I].second);
7295 return 0;
7298 /// \brief Given an expression that refers to an overloaded function, try to
7299 /// resolve that overloaded function expression down to a single function.
7301 /// This routine can only resolve template-ids that refer to a single function
7302 /// template, where that template-id refers to a single template whose template
7303 /// arguments are either provided by the template-id or have defaults,
7304 /// as described in C++0x [temp.arg.explicit]p3.
7305 FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
7306 // C++ [over.over]p1:
7307 // [...] [Note: any redundant set of parentheses surrounding the
7308 // overloaded function name is ignored (5.1). ]
7309 // C++ [over.over]p1:
7310 // [...] The overloaded function name can be preceded by the &
7311 // operator.
7313 if (From->getType() != Context.OverloadTy)
7314 return 0;
7316 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
7318 // If we didn't actually find any template-ids, we're done.
7319 if (!OvlExpr->hasExplicitTemplateArgs())
7320 return 0;
7322 TemplateArgumentListInfo ExplicitTemplateArgs;
7323 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
7325 // Look through all of the overloaded functions, searching for one
7326 // whose type matches exactly.
7327 FunctionDecl *Matched = 0;
7328 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7329 E = OvlExpr->decls_end(); I != E; ++I) {
7330 // C++0x [temp.arg.explicit]p3:
7331 // [...] In contexts where deduction is done and fails, or in contexts
7332 // where deduction is not done, if a template argument list is
7333 // specified and it, along with any default template arguments,
7334 // identifies a single function template specialization, then the
7335 // template-id is an lvalue for the function template specialization.
7336 FunctionTemplateDecl *FunctionTemplate
7337 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
7339 // C++ [over.over]p2:
7340 // If the name is a function template, template argument deduction is
7341 // done (14.8.2.2), and if the argument deduction succeeds, the
7342 // resulting template argument list is used to generate a single
7343 // function template specialization, which is added to the set of
7344 // overloaded functions considered.
7345 FunctionDecl *Specialization = 0;
7346 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
7347 if (TemplateDeductionResult Result
7348 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
7349 Specialization, Info)) {
7350 // FIXME: make a note of the failed deduction for diagnostics.
7351 (void)Result;
7352 continue;
7355 // Multiple matches; we can't resolve to a single declaration.
7356 if (Matched)
7357 return 0;
7359 Matched = Specialization;
7362 return Matched;
7365 /// \brief Add a single candidate to the overload set.
7366 static void AddOverloadedCallCandidate(Sema &S,
7367 DeclAccessPair FoundDecl,
7368 const TemplateArgumentListInfo *ExplicitTemplateArgs,
7369 Expr **Args, unsigned NumArgs,
7370 OverloadCandidateSet &CandidateSet,
7371 bool PartialOverloading) {
7372 NamedDecl *Callee = FoundDecl.getDecl();
7373 if (isa<UsingShadowDecl>(Callee))
7374 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
7376 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
7377 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
7378 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
7379 false, PartialOverloading);
7380 return;
7383 if (FunctionTemplateDecl *FuncTemplate
7384 = dyn_cast<FunctionTemplateDecl>(Callee)) {
7385 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
7386 ExplicitTemplateArgs,
7387 Args, NumArgs, CandidateSet);
7388 return;
7391 assert(false && "unhandled case in overloaded call candidate");
7393 // do nothing?
7396 /// \brief Add the overload candidates named by callee and/or found by argument
7397 /// dependent lookup to the given overload set.
7398 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
7399 Expr **Args, unsigned NumArgs,
7400 OverloadCandidateSet &CandidateSet,
7401 bool PartialOverloading) {
7403 #ifndef NDEBUG
7404 // Verify that ArgumentDependentLookup is consistent with the rules
7405 // in C++0x [basic.lookup.argdep]p3:
7407 // Let X be the lookup set produced by unqualified lookup (3.4.1)
7408 // and let Y be the lookup set produced by argument dependent
7409 // lookup (defined as follows). If X contains
7411 // -- a declaration of a class member, or
7413 // -- a block-scope function declaration that is not a
7414 // using-declaration, or
7416 // -- a declaration that is neither a function or a function
7417 // template
7419 // then Y is empty.
7421 if (ULE->requiresADL()) {
7422 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7423 E = ULE->decls_end(); I != E; ++I) {
7424 assert(!(*I)->getDeclContext()->isRecord());
7425 assert(isa<UsingShadowDecl>(*I) ||
7426 !(*I)->getDeclContext()->isFunctionOrMethod());
7427 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
7430 #endif
7432 // It would be nice to avoid this copy.
7433 TemplateArgumentListInfo TABuffer;
7434 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7435 if (ULE->hasExplicitTemplateArgs()) {
7436 ULE->copyTemplateArgumentsInto(TABuffer);
7437 ExplicitTemplateArgs = &TABuffer;
7440 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7441 E = ULE->decls_end(); I != E; ++I)
7442 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
7443 Args, NumArgs, CandidateSet,
7444 PartialOverloading);
7446 if (ULE->requiresADL())
7447 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
7448 Args, NumArgs,
7449 ExplicitTemplateArgs,
7450 CandidateSet,
7451 PartialOverloading);
7454 /// Attempts to recover from a call where no functions were found.
7456 /// Returns true if new candidates were found.
7457 static ExprResult
7458 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
7459 UnresolvedLookupExpr *ULE,
7460 SourceLocation LParenLoc,
7461 Expr **Args, unsigned NumArgs,
7462 SourceLocation RParenLoc) {
7464 CXXScopeSpec SS;
7465 if (ULE->getQualifier()) {
7466 SS.setScopeRep(ULE->getQualifier());
7467 SS.setRange(ULE->getQualifierRange());
7470 TemplateArgumentListInfo TABuffer;
7471 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7472 if (ULE->hasExplicitTemplateArgs()) {
7473 ULE->copyTemplateArgumentsInto(TABuffer);
7474 ExplicitTemplateArgs = &TABuffer;
7477 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
7478 Sema::LookupOrdinaryName);
7479 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
7480 return ExprError();
7482 assert(!R.empty() && "lookup results empty despite recovery");
7484 // Build an implicit member call if appropriate. Just drop the
7485 // casts and such from the call, we don't really care.
7486 ExprResult NewFn = ExprError();
7487 if ((*R.begin())->isCXXClassMember())
7488 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
7489 ExplicitTemplateArgs);
7490 else if (ExplicitTemplateArgs)
7491 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
7492 else
7493 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
7495 if (NewFn.isInvalid())
7496 return ExprError();
7498 // This shouldn't cause an infinite loop because we're giving it
7499 // an expression with non-empty lookup results, which should never
7500 // end up here.
7501 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
7502 MultiExprArg(Args, NumArgs), RParenLoc);
7505 /// ResolveOverloadedCallFn - Given the call expression that calls Fn
7506 /// (which eventually refers to the declaration Func) and the call
7507 /// arguments Args/NumArgs, attempt to resolve the function call down
7508 /// to a specific function. If overload resolution succeeds, returns
7509 /// the function declaration produced by overload
7510 /// resolution. Otherwise, emits diagnostics, deletes all of the
7511 /// arguments and Fn, and returns NULL.
7512 ExprResult
7513 Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
7514 SourceLocation LParenLoc,
7515 Expr **Args, unsigned NumArgs,
7516 SourceLocation RParenLoc,
7517 Expr *ExecConfig) {
7518 #ifndef NDEBUG
7519 if (ULE->requiresADL()) {
7520 // To do ADL, we must have found an unqualified name.
7521 assert(!ULE->getQualifier() && "qualified name with ADL");
7523 // We don't perform ADL for implicit declarations of builtins.
7524 // Verify that this was correctly set up.
7525 FunctionDecl *F;
7526 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
7527 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
7528 F->getBuiltinID() && F->isImplicit())
7529 assert(0 && "performing ADL for builtin");
7531 // We don't perform ADL in C.
7532 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
7534 #endif
7536 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
7538 // Add the functions denoted by the callee to the set of candidate
7539 // functions, including those from argument-dependent lookup.
7540 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
7542 // If we found nothing, try to recover.
7543 // AddRecoveryCallCandidates diagnoses the error itself, so we just
7544 // bailout out if it fails.
7545 if (CandidateSet.empty())
7546 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
7547 RParenLoc);
7549 OverloadCandidateSet::iterator Best;
7550 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
7551 case OR_Success: {
7552 FunctionDecl *FDecl = Best->Function;
7553 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
7554 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
7555 ULE->getNameLoc());
7556 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
7557 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
7558 ExecConfig);
7561 case OR_No_Viable_Function:
7562 Diag(Fn->getSourceRange().getBegin(),
7563 diag::err_ovl_no_viable_function_in_call)
7564 << ULE->getName() << Fn->getSourceRange();
7565 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
7566 break;
7568 case OR_Ambiguous:
7569 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
7570 << ULE->getName() << Fn->getSourceRange();
7571 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
7572 break;
7574 case OR_Deleted:
7575 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
7576 << Best->Function->isDeleted()
7577 << ULE->getName()
7578 << Fn->getSourceRange();
7579 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
7580 break;
7583 // Overload resolution failed.
7584 return ExprError();
7587 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
7588 return Functions.size() > 1 ||
7589 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
7592 /// \brief Create a unary operation that may resolve to an overloaded
7593 /// operator.
7595 /// \param OpLoc The location of the operator itself (e.g., '*').
7597 /// \param OpcIn The UnaryOperator::Opcode that describes this
7598 /// operator.
7600 /// \param Functions The set of non-member functions that will be
7601 /// considered by overload resolution. The caller needs to build this
7602 /// set based on the context using, e.g.,
7603 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7604 /// set should not contain any member functions; those will be added
7605 /// by CreateOverloadedUnaryOp().
7607 /// \param input The input argument.
7608 ExprResult
7609 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
7610 const UnresolvedSetImpl &Fns,
7611 Expr *Input) {
7612 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
7614 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
7615 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
7616 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7617 // TODO: provide better source location info.
7618 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
7620 if (Input->getObjectKind() == OK_ObjCProperty)
7621 ConvertPropertyForRValue(Input);
7623 Expr *Args[2] = { Input, 0 };
7624 unsigned NumArgs = 1;
7626 // For post-increment and post-decrement, add the implicit '0' as
7627 // the second argument, so that we know this is a post-increment or
7628 // post-decrement.
7629 if (Opc == UO_PostInc || Opc == UO_PostDec) {
7630 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
7631 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
7632 SourceLocation());
7633 NumArgs = 2;
7636 if (Input->isTypeDependent()) {
7637 if (Fns.empty())
7638 return Owned(new (Context) UnaryOperator(Input,
7639 Opc,
7640 Context.DependentTy,
7641 VK_RValue, OK_Ordinary,
7642 OpLoc));
7644 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
7645 UnresolvedLookupExpr *Fn
7646 = UnresolvedLookupExpr::Create(Context, NamingClass,
7647 0, SourceRange(), OpNameInfo,
7648 /*ADL*/ true, IsOverloaded(Fns),
7649 Fns.begin(), Fns.end());
7650 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
7651 &Args[0], NumArgs,
7652 Context.DependentTy,
7653 VK_RValue,
7654 OpLoc));
7657 // Build an empty overload set.
7658 OverloadCandidateSet CandidateSet(OpLoc);
7660 // Add the candidates from the given function set.
7661 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
7663 // Add operator candidates that are member functions.
7664 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7666 // Add candidates from ADL.
7667 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7668 Args, NumArgs,
7669 /*ExplicitTemplateArgs*/ 0,
7670 CandidateSet);
7672 // Add builtin operator candidates.
7673 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7675 // Perform overload resolution.
7676 OverloadCandidateSet::iterator Best;
7677 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
7678 case OR_Success: {
7679 // We found a built-in operator or an overloaded operator.
7680 FunctionDecl *FnDecl = Best->Function;
7682 if (FnDecl) {
7683 // We matched an overloaded operator. Build a call to that
7684 // operator.
7686 // Convert the arguments.
7687 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
7688 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
7690 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
7691 Best->FoundDecl, Method))
7692 return ExprError();
7693 } else {
7694 // Convert the arguments.
7695 ExprResult InputInit
7696 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7697 Context,
7698 FnDecl->getParamDecl(0)),
7699 SourceLocation(),
7700 Input);
7701 if (InputInit.isInvalid())
7702 return ExprError();
7703 Input = InputInit.take();
7706 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7708 // Determine the result type.
7709 QualType ResultTy = FnDecl->getResultType();
7710 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7711 ResultTy = ResultTy.getNonLValueExprType(Context);
7713 // Build the actual expression node.
7714 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl);
7716 Args[0] = Input;
7717 CallExpr *TheCall =
7718 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
7719 Args, NumArgs, ResultTy, VK, OpLoc);
7721 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
7722 FnDecl))
7723 return ExprError();
7725 return MaybeBindToTemporary(TheCall);
7726 } else {
7727 // We matched a built-in operator. Convert the arguments, then
7728 // break out so that we will build the appropriate built-in
7729 // operator node.
7730 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
7731 Best->Conversions[0], AA_Passing))
7732 return ExprError();
7734 break;
7738 case OR_No_Viable_Function:
7739 // No viable function; fall through to handling this as a
7740 // built-in operator, which will produce an error message for us.
7741 break;
7743 case OR_Ambiguous:
7744 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
7745 << UnaryOperator::getOpcodeStr(Opc)
7746 << Input->getType()
7747 << Input->getSourceRange();
7748 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
7749 Args, NumArgs,
7750 UnaryOperator::getOpcodeStr(Opc), OpLoc);
7751 return ExprError();
7753 case OR_Deleted:
7754 Diag(OpLoc, diag::err_ovl_deleted_oper)
7755 << Best->Function->isDeleted()
7756 << UnaryOperator::getOpcodeStr(Opc)
7757 << Input->getSourceRange();
7758 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
7759 return ExprError();
7762 // Either we found no viable overloaded operator or we matched a
7763 // built-in operator. In either case, fall through to trying to
7764 // build a built-in operation.
7765 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
7768 /// \brief Create a binary operation that may resolve to an overloaded
7769 /// operator.
7771 /// \param OpLoc The location of the operator itself (e.g., '+').
7773 /// \param OpcIn The BinaryOperator::Opcode that describes this
7774 /// operator.
7776 /// \param Functions The set of non-member functions that will be
7777 /// considered by overload resolution. The caller needs to build this
7778 /// set based on the context using, e.g.,
7779 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7780 /// set should not contain any member functions; those will be added
7781 /// by CreateOverloadedBinOp().
7783 /// \param LHS Left-hand argument.
7784 /// \param RHS Right-hand argument.
7785 ExprResult
7786 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
7787 unsigned OpcIn,
7788 const UnresolvedSetImpl &Fns,
7789 Expr *LHS, Expr *RHS) {
7790 Expr *Args[2] = { LHS, RHS };
7791 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
7793 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
7794 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
7795 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7797 // If either side is type-dependent, create an appropriate dependent
7798 // expression.
7799 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7800 if (Fns.empty()) {
7801 // If there are no functions to store, just build a dependent
7802 // BinaryOperator or CompoundAssignment.
7803 if (Opc <= BO_Assign || Opc > BO_OrAssign)
7804 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
7805 Context.DependentTy,
7806 VK_RValue, OK_Ordinary,
7807 OpLoc));
7809 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
7810 Context.DependentTy,
7811 VK_LValue,
7812 OK_Ordinary,
7813 Context.DependentTy,
7814 Context.DependentTy,
7815 OpLoc));
7818 // FIXME: save results of ADL from here?
7819 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
7820 // TODO: provide better source location info in DNLoc component.
7821 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
7822 UnresolvedLookupExpr *Fn
7823 = UnresolvedLookupExpr::Create(Context, NamingClass, 0, SourceRange(),
7824 OpNameInfo, /*ADL*/ true, IsOverloaded(Fns),
7825 Fns.begin(), Fns.end());
7826 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
7827 Args, 2,
7828 Context.DependentTy,
7829 VK_RValue,
7830 OpLoc));
7833 // Always do property rvalue conversions on the RHS.
7834 if (Args[1]->getObjectKind() == OK_ObjCProperty)
7835 ConvertPropertyForRValue(Args[1]);
7837 // The LHS is more complicated.
7838 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
7840 // There's a tension for assignment operators between primitive
7841 // property assignment and the overloaded operators.
7842 if (BinaryOperator::isAssignmentOp(Opc)) {
7843 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7845 // Is the property "logically" settable?
7846 bool Settable = (PRE->isExplicitProperty() ||
7847 PRE->getImplicitPropertySetter());
7849 // To avoid gratuitously inventing semantics, use the primitive
7850 // unless it isn't. Thoughts in case we ever really care:
7851 // - If the property isn't logically settable, we have to
7852 // load and hope.
7853 // - If the property is settable and this is simple assignment,
7854 // we really should use the primitive.
7855 // - If the property is settable, then we could try overloading
7856 // on a generic lvalue of the appropriate type; if it works
7857 // out to a builtin candidate, we would do that same operation
7858 // on the property, and otherwise just error.
7859 if (Settable)
7860 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7863 ConvertPropertyForRValue(Args[0]);
7866 // If this is the assignment operator, we only perform overload resolution
7867 // if the left-hand side is a class or enumeration type. This is actually
7868 // a hack. The standard requires that we do overload resolution between the
7869 // various built-in candidates, but as DR507 points out, this can lead to
7870 // problems. So we do it this way, which pretty much follows what GCC does.
7871 // Note that we go the traditional code path for compound assignment forms.
7872 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
7873 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7875 // If this is the .* operator, which is not overloadable, just
7876 // create a built-in binary operator.
7877 if (Opc == BO_PtrMemD)
7878 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7880 // Build an empty overload set.
7881 OverloadCandidateSet CandidateSet(OpLoc);
7883 // Add the candidates from the given function set.
7884 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
7886 // Add operator candidates that are member functions.
7887 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7889 // Add candidates from ADL.
7890 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7891 Args, 2,
7892 /*ExplicitTemplateArgs*/ 0,
7893 CandidateSet);
7895 // Add builtin operator candidates.
7896 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7898 // Perform overload resolution.
7899 OverloadCandidateSet::iterator Best;
7900 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
7901 case OR_Success: {
7902 // We found a built-in operator or an overloaded operator.
7903 FunctionDecl *FnDecl = Best->Function;
7905 if (FnDecl) {
7906 // We matched an overloaded operator. Build a call to that
7907 // operator.
7909 // Convert the arguments.
7910 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
7911 // Best->Access is only meaningful for class members.
7912 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
7914 ExprResult Arg1 =
7915 PerformCopyInitialization(
7916 InitializedEntity::InitializeParameter(Context,
7917 FnDecl->getParamDecl(0)),
7918 SourceLocation(), Owned(Args[1]));
7919 if (Arg1.isInvalid())
7920 return ExprError();
7922 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
7923 Best->FoundDecl, Method))
7924 return ExprError();
7926 Args[1] = RHS = Arg1.takeAs<Expr>();
7927 } else {
7928 // Convert the arguments.
7929 ExprResult Arg0 = PerformCopyInitialization(
7930 InitializedEntity::InitializeParameter(Context,
7931 FnDecl->getParamDecl(0)),
7932 SourceLocation(), Owned(Args[0]));
7933 if (Arg0.isInvalid())
7934 return ExprError();
7936 ExprResult Arg1 =
7937 PerformCopyInitialization(
7938 InitializedEntity::InitializeParameter(Context,
7939 FnDecl->getParamDecl(1)),
7940 SourceLocation(), Owned(Args[1]));
7941 if (Arg1.isInvalid())
7942 return ExprError();
7943 Args[0] = LHS = Arg0.takeAs<Expr>();
7944 Args[1] = RHS = Arg1.takeAs<Expr>();
7947 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7949 // Determine the result type.
7950 QualType ResultTy = FnDecl->getResultType();
7951 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7952 ResultTy = ResultTy.getNonLValueExprType(Context);
7954 // Build the actual expression node.
7955 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
7957 CXXOperatorCallExpr *TheCall =
7958 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
7959 Args, 2, ResultTy, VK, OpLoc);
7961 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
7962 FnDecl))
7963 return ExprError();
7965 return MaybeBindToTemporary(TheCall);
7966 } else {
7967 // We matched a built-in operator. Convert the arguments, then
7968 // break out so that we will build the appropriate built-in
7969 // operator node.
7970 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
7971 Best->Conversions[0], AA_Passing) ||
7972 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
7973 Best->Conversions[1], AA_Passing))
7974 return ExprError();
7976 break;
7980 case OR_No_Viable_Function: {
7981 // C++ [over.match.oper]p9:
7982 // If the operator is the operator , [...] and there are no
7983 // viable functions, then the operator is assumed to be the
7984 // built-in operator and interpreted according to clause 5.
7985 if (Opc == BO_Comma)
7986 break;
7988 // For class as left operand for assignment or compound assigment
7989 // operator do not fall through to handling in built-in, but report that
7990 // no overloaded assignment operator found
7991 ExprResult Result = ExprError();
7992 if (Args[0]->getType()->isRecordType() &&
7993 Opc >= BO_Assign && Opc <= BO_OrAssign) {
7994 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7995 << BinaryOperator::getOpcodeStr(Opc)
7996 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7997 } else {
7998 // No viable function; try to create a built-in operation, which will
7999 // produce an error. Then, show the non-viable candidates.
8000 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8002 assert(Result.isInvalid() &&
8003 "C++ binary operator overloading is missing candidates!");
8004 if (Result.isInvalid())
8005 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8006 BinaryOperator::getOpcodeStr(Opc), OpLoc);
8007 return move(Result);
8010 case OR_Ambiguous:
8011 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
8012 << BinaryOperator::getOpcodeStr(Opc)
8013 << Args[0]->getType() << Args[1]->getType()
8014 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8015 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8016 BinaryOperator::getOpcodeStr(Opc), OpLoc);
8017 return ExprError();
8019 case OR_Deleted:
8020 Diag(OpLoc, diag::err_ovl_deleted_oper)
8021 << Best->Function->isDeleted()
8022 << BinaryOperator::getOpcodeStr(Opc)
8023 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8024 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
8025 return ExprError();
8028 // We matched a built-in operator; build it.
8029 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8032 ExprResult
8033 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
8034 SourceLocation RLoc,
8035 Expr *Base, Expr *Idx) {
8036 Expr *Args[2] = { Base, Idx };
8037 DeclarationName OpName =
8038 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
8040 // If either side is type-dependent, create an appropriate dependent
8041 // expression.
8042 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
8044 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
8045 // CHECKME: no 'operator' keyword?
8046 DeclarationNameInfo OpNameInfo(OpName, LLoc);
8047 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
8048 UnresolvedLookupExpr *Fn
8049 = UnresolvedLookupExpr::Create(Context, NamingClass,
8050 0, SourceRange(), OpNameInfo,
8051 /*ADL*/ true, /*Overloaded*/ false,
8052 UnresolvedSetIterator(),
8053 UnresolvedSetIterator());
8054 // Can't add any actual overloads yet
8056 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
8057 Args, 2,
8058 Context.DependentTy,
8059 VK_RValue,
8060 RLoc));
8063 if (Args[0]->getObjectKind() == OK_ObjCProperty)
8064 ConvertPropertyForRValue(Args[0]);
8065 if (Args[1]->getObjectKind() == OK_ObjCProperty)
8066 ConvertPropertyForRValue(Args[1]);
8068 // Build an empty overload set.
8069 OverloadCandidateSet CandidateSet(LLoc);
8071 // Subscript can only be overloaded as a member function.
8073 // Add operator candidates that are member functions.
8074 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8076 // Add builtin operator candidates.
8077 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8079 // Perform overload resolution.
8080 OverloadCandidateSet::iterator Best;
8081 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
8082 case OR_Success: {
8083 // We found a built-in operator or an overloaded operator.
8084 FunctionDecl *FnDecl = Best->Function;
8086 if (FnDecl) {
8087 // We matched an overloaded operator. Build a call to that
8088 // operator.
8090 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
8091 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
8093 // Convert the arguments.
8094 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
8095 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8096 Best->FoundDecl, Method))
8097 return ExprError();
8099 // Convert the arguments.
8100 ExprResult InputInit
8101 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
8102 Context,
8103 FnDecl->getParamDecl(0)),
8104 SourceLocation(),
8105 Owned(Args[1]));
8106 if (InputInit.isInvalid())
8107 return ExprError();
8109 Args[1] = InputInit.takeAs<Expr>();
8111 // Determine the result type
8112 QualType ResultTy = FnDecl->getResultType();
8113 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8114 ResultTy = ResultTy.getNonLValueExprType(Context);
8116 // Build the actual expression node.
8117 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
8119 CXXOperatorCallExpr *TheCall =
8120 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
8121 FnExpr, Args, 2,
8122 ResultTy, VK, RLoc);
8124 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
8125 FnDecl))
8126 return ExprError();
8128 return MaybeBindToTemporary(TheCall);
8129 } else {
8130 // We matched a built-in operator. Convert the arguments, then
8131 // break out so that we will build the appropriate built-in
8132 // operator node.
8133 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8134 Best->Conversions[0], AA_Passing) ||
8135 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
8136 Best->Conversions[1], AA_Passing))
8137 return ExprError();
8139 break;
8143 case OR_No_Viable_Function: {
8144 if (CandidateSet.empty())
8145 Diag(LLoc, diag::err_ovl_no_oper)
8146 << Args[0]->getType() << /*subscript*/ 0
8147 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8148 else
8149 Diag(LLoc, diag::err_ovl_no_viable_subscript)
8150 << Args[0]->getType()
8151 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8152 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8153 "[]", LLoc);
8154 return ExprError();
8157 case OR_Ambiguous:
8158 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
8159 << "[]"
8160 << Args[0]->getType() << Args[1]->getType()
8161 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8162 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8163 "[]", LLoc);
8164 return ExprError();
8166 case OR_Deleted:
8167 Diag(LLoc, diag::err_ovl_deleted_oper)
8168 << Best->Function->isDeleted() << "[]"
8169 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8170 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8171 "[]", LLoc);
8172 return ExprError();
8175 // We matched a built-in operator; build it.
8176 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
8179 /// BuildCallToMemberFunction - Build a call to a member
8180 /// function. MemExpr is the expression that refers to the member
8181 /// function (and includes the object parameter), Args/NumArgs are the
8182 /// arguments to the function call (not including the object
8183 /// parameter). The caller needs to validate that the member
8184 /// expression refers to a member function or an overloaded member
8185 /// function.
8186 ExprResult
8187 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
8188 SourceLocation LParenLoc, Expr **Args,
8189 unsigned NumArgs, SourceLocation RParenLoc) {
8190 // Dig out the member expression. This holds both the object
8191 // argument and the member function we're referring to.
8192 Expr *NakedMemExpr = MemExprE->IgnoreParens();
8194 MemberExpr *MemExpr;
8195 CXXMethodDecl *Method = 0;
8196 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
8197 NestedNameSpecifier *Qualifier = 0;
8198 if (isa<MemberExpr>(NakedMemExpr)) {
8199 MemExpr = cast<MemberExpr>(NakedMemExpr);
8200 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
8201 FoundDecl = MemExpr->getFoundDecl();
8202 Qualifier = MemExpr->getQualifier();
8203 } else {
8204 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
8205 Qualifier = UnresExpr->getQualifier();
8207 QualType ObjectType = UnresExpr->getBaseType();
8208 Expr::Classification ObjectClassification
8209 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
8210 : UnresExpr->getBase()->Classify(Context);
8212 // Add overload candidates
8213 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
8215 // FIXME: avoid copy.
8216 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8217 if (UnresExpr->hasExplicitTemplateArgs()) {
8218 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8219 TemplateArgs = &TemplateArgsBuffer;
8222 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
8223 E = UnresExpr->decls_end(); I != E; ++I) {
8225 NamedDecl *Func = *I;
8226 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
8227 if (isa<UsingShadowDecl>(Func))
8228 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
8231 // Microsoft supports direct constructor calls.
8232 if (getLangOptions().Microsoft && isa<CXXConstructorDecl>(Func)) {
8233 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
8234 CandidateSet);
8235 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
8236 // If explicit template arguments were provided, we can't call a
8237 // non-template member function.
8238 if (TemplateArgs)
8239 continue;
8241 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
8242 ObjectClassification,
8243 Args, NumArgs, CandidateSet,
8244 /*SuppressUserConversions=*/false);
8245 } else {
8246 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
8247 I.getPair(), ActingDC, TemplateArgs,
8248 ObjectType, ObjectClassification,
8249 Args, NumArgs, CandidateSet,
8250 /*SuppressUsedConversions=*/false);
8254 DeclarationName DeclName = UnresExpr->getMemberName();
8256 OverloadCandidateSet::iterator Best;
8257 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
8258 Best)) {
8259 case OR_Success:
8260 Method = cast<CXXMethodDecl>(Best->Function);
8261 FoundDecl = Best->FoundDecl;
8262 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
8263 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
8264 break;
8266 case OR_No_Viable_Function:
8267 Diag(UnresExpr->getMemberLoc(),
8268 diag::err_ovl_no_viable_member_function_in_call)
8269 << DeclName << MemExprE->getSourceRange();
8270 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8271 // FIXME: Leaking incoming expressions!
8272 return ExprError();
8274 case OR_Ambiguous:
8275 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
8276 << DeclName << MemExprE->getSourceRange();
8277 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8278 // FIXME: Leaking incoming expressions!
8279 return ExprError();
8281 case OR_Deleted:
8282 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
8283 << Best->Function->isDeleted()
8284 << DeclName << MemExprE->getSourceRange();
8285 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8286 // FIXME: Leaking incoming expressions!
8287 return ExprError();
8290 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
8292 // If overload resolution picked a static member, build a
8293 // non-member call based on that function.
8294 if (Method->isStatic()) {
8295 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
8296 Args, NumArgs, RParenLoc);
8299 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
8302 QualType ResultType = Method->getResultType();
8303 ExprValueKind VK = Expr::getValueKindForType(ResultType);
8304 ResultType = ResultType.getNonLValueExprType(Context);
8306 assert(Method && "Member call to something that isn't a method?");
8307 CXXMemberCallExpr *TheCall =
8308 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
8309 ResultType, VK, RParenLoc);
8311 // Check for a valid return type.
8312 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
8313 TheCall, Method))
8314 return ExprError();
8316 // Convert the object argument (for a non-static member function call).
8317 // We only need to do this if there was actually an overload; otherwise
8318 // it was done at lookup.
8319 Expr *ObjectArg = MemExpr->getBase();
8320 if (!Method->isStatic() &&
8321 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
8322 FoundDecl, Method))
8323 return ExprError();
8324 MemExpr->setBase(ObjectArg);
8326 // Convert the rest of the arguments
8327 const FunctionProtoType *Proto =
8328 Method->getType()->getAs<FunctionProtoType>();
8329 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
8330 RParenLoc))
8331 return ExprError();
8333 if (CheckFunctionCall(Method, TheCall))
8334 return ExprError();
8336 return MaybeBindToTemporary(TheCall);
8339 /// BuildCallToObjectOfClassType - Build a call to an object of class
8340 /// type (C++ [over.call.object]), which can end up invoking an
8341 /// overloaded function call operator (@c operator()) or performing a
8342 /// user-defined conversion on the object argument.
8343 ExprResult
8344 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
8345 SourceLocation LParenLoc,
8346 Expr **Args, unsigned NumArgs,
8347 SourceLocation RParenLoc) {
8348 if (Object->getObjectKind() == OK_ObjCProperty)
8349 ConvertPropertyForRValue(Object);
8351 assert(Object->getType()->isRecordType() && "Requires object type argument");
8352 const RecordType *Record = Object->getType()->getAs<RecordType>();
8354 // C++ [over.call.object]p1:
8355 // If the primary-expression E in the function call syntax
8356 // evaluates to a class object of type "cv T", then the set of
8357 // candidate functions includes at least the function call
8358 // operators of T. The function call operators of T are obtained by
8359 // ordinary lookup of the name operator() in the context of
8360 // (E).operator().
8361 OverloadCandidateSet CandidateSet(LParenLoc);
8362 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
8364 if (RequireCompleteType(LParenLoc, Object->getType(),
8365 PDiag(diag::err_incomplete_object_call)
8366 << Object->getSourceRange()))
8367 return true;
8369 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
8370 LookupQualifiedName(R, Record->getDecl());
8371 R.suppressDiagnostics();
8373 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
8374 Oper != OperEnd; ++Oper) {
8375 AddMethodCandidate(Oper.getPair(), Object->getType(),
8376 Object->Classify(Context), Args, NumArgs, CandidateSet,
8377 /*SuppressUserConversions=*/ false);
8380 // C++ [over.call.object]p2:
8381 // In addition, for each conversion function declared in T of the
8382 // form
8384 // operator conversion-type-id () cv-qualifier;
8386 // where cv-qualifier is the same cv-qualification as, or a
8387 // greater cv-qualification than, cv, and where conversion-type-id
8388 // denotes the type "pointer to function of (P1,...,Pn) returning
8389 // R", or the type "reference to pointer to function of
8390 // (P1,...,Pn) returning R", or the type "reference to function
8391 // of (P1,...,Pn) returning R", a surrogate call function [...]
8392 // is also considered as a candidate function. Similarly,
8393 // surrogate call functions are added to the set of candidate
8394 // functions for each conversion function declared in an
8395 // accessible base class provided the function is not hidden
8396 // within T by another intervening declaration.
8397 const UnresolvedSetImpl *Conversions
8398 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
8399 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
8400 E = Conversions->end(); I != E; ++I) {
8401 NamedDecl *D = *I;
8402 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
8403 if (isa<UsingShadowDecl>(D))
8404 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8406 // Skip over templated conversion functions; they aren't
8407 // surrogates.
8408 if (isa<FunctionTemplateDecl>(D))
8409 continue;
8411 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8413 // Strip the reference type (if any) and then the pointer type (if
8414 // any) to get down to what might be a function type.
8415 QualType ConvType = Conv->getConversionType().getNonReferenceType();
8416 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8417 ConvType = ConvPtrType->getPointeeType();
8419 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
8420 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
8421 Object, Args, NumArgs, CandidateSet);
8424 // Perform overload resolution.
8425 OverloadCandidateSet::iterator Best;
8426 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
8427 Best)) {
8428 case OR_Success:
8429 // Overload resolution succeeded; we'll build the appropriate call
8430 // below.
8431 break;
8433 case OR_No_Viable_Function:
8434 if (CandidateSet.empty())
8435 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
8436 << Object->getType() << /*call*/ 1
8437 << Object->getSourceRange();
8438 else
8439 Diag(Object->getSourceRange().getBegin(),
8440 diag::err_ovl_no_viable_object_call)
8441 << Object->getType() << Object->getSourceRange();
8442 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8443 break;
8445 case OR_Ambiguous:
8446 Diag(Object->getSourceRange().getBegin(),
8447 diag::err_ovl_ambiguous_object_call)
8448 << Object->getType() << Object->getSourceRange();
8449 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
8450 break;
8452 case OR_Deleted:
8453 Diag(Object->getSourceRange().getBegin(),
8454 diag::err_ovl_deleted_object_call)
8455 << Best->Function->isDeleted()
8456 << Object->getType() << Object->getSourceRange();
8457 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8458 break;
8461 if (Best == CandidateSet.end())
8462 return true;
8464 if (Best->Function == 0) {
8465 // Since there is no function declaration, this is one of the
8466 // surrogate candidates. Dig out the conversion function.
8467 CXXConversionDecl *Conv
8468 = cast<CXXConversionDecl>(
8469 Best->Conversions[0].UserDefined.ConversionFunction);
8471 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
8472 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
8474 // We selected one of the surrogate functions that converts the
8475 // object parameter to a function pointer. Perform the conversion
8476 // on the object argument, then let ActOnCallExpr finish the job.
8478 // Create an implicit member expr to refer to the conversion operator.
8479 // and then call it.
8480 ExprResult Call = BuildCXXMemberCallExpr(Object, Best->FoundDecl, Conv);
8481 if (Call.isInvalid())
8482 return ExprError();
8484 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
8485 RParenLoc);
8488 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
8489 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
8491 // We found an overloaded operator(). Build a CXXOperatorCallExpr
8492 // that calls this method, using Object for the implicit object
8493 // parameter and passing along the remaining arguments.
8494 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
8495 const FunctionProtoType *Proto =
8496 Method->getType()->getAs<FunctionProtoType>();
8498 unsigned NumArgsInProto = Proto->getNumArgs();
8499 unsigned NumArgsToCheck = NumArgs;
8501 // Build the full argument list for the method call (the
8502 // implicit object parameter is placed at the beginning of the
8503 // list).
8504 Expr **MethodArgs;
8505 if (NumArgs < NumArgsInProto) {
8506 NumArgsToCheck = NumArgsInProto;
8507 MethodArgs = new Expr*[NumArgsInProto + 1];
8508 } else {
8509 MethodArgs = new Expr*[NumArgs + 1];
8511 MethodArgs[0] = Object;
8512 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
8513 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
8515 Expr *NewFn = CreateFunctionRefExpr(*this, Method);
8517 // Once we've built TheCall, all of the expressions are properly
8518 // owned.
8519 QualType ResultTy = Method->getResultType();
8520 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8521 ResultTy = ResultTy.getNonLValueExprType(Context);
8523 CXXOperatorCallExpr *TheCall =
8524 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
8525 MethodArgs, NumArgs + 1,
8526 ResultTy, VK, RParenLoc);
8527 delete [] MethodArgs;
8529 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
8530 Method))
8531 return true;
8533 // We may have default arguments. If so, we need to allocate more
8534 // slots in the call for them.
8535 if (NumArgs < NumArgsInProto)
8536 TheCall->setNumArgs(Context, NumArgsInProto + 1);
8537 else if (NumArgs > NumArgsInProto)
8538 NumArgsToCheck = NumArgsInProto;
8540 bool IsError = false;
8542 // Initialize the implicit object parameter.
8543 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
8544 Best->FoundDecl, Method);
8545 TheCall->setArg(0, Object);
8548 // Check the argument types.
8549 for (unsigned i = 0; i != NumArgsToCheck; i++) {
8550 Expr *Arg;
8551 if (i < NumArgs) {
8552 Arg = Args[i];
8554 // Pass the argument.
8556 ExprResult InputInit
8557 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
8558 Context,
8559 Method->getParamDecl(i)),
8560 SourceLocation(), Arg);
8562 IsError |= InputInit.isInvalid();
8563 Arg = InputInit.takeAs<Expr>();
8564 } else {
8565 ExprResult DefArg
8566 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
8567 if (DefArg.isInvalid()) {
8568 IsError = true;
8569 break;
8572 Arg = DefArg.takeAs<Expr>();
8575 TheCall->setArg(i + 1, Arg);
8578 // If this is a variadic call, handle args passed through "...".
8579 if (Proto->isVariadic()) {
8580 // Promote the arguments (C99 6.5.2.2p7).
8581 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
8582 Expr *Arg = Args[i];
8583 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
8584 TheCall->setArg(i + 1, Arg);
8588 if (IsError) return true;
8590 if (CheckFunctionCall(Method, TheCall))
8591 return true;
8593 return MaybeBindToTemporary(TheCall);
8596 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
8597 /// (if one exists), where @c Base is an expression of class type and
8598 /// @c Member is the name of the member we're trying to find.
8599 ExprResult
8600 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
8601 assert(Base->getType()->isRecordType() &&
8602 "left-hand side must have class type");
8604 if (Base->getObjectKind() == OK_ObjCProperty)
8605 ConvertPropertyForRValue(Base);
8607 SourceLocation Loc = Base->getExprLoc();
8609 // C++ [over.ref]p1:
8611 // [...] An expression x->m is interpreted as (x.operator->())->m
8612 // for a class object x of type T if T::operator->() exists and if
8613 // the operator is selected as the best match function by the
8614 // overload resolution mechanism (13.3).
8615 DeclarationName OpName =
8616 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
8617 OverloadCandidateSet CandidateSet(Loc);
8618 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
8620 if (RequireCompleteType(Loc, Base->getType(),
8621 PDiag(diag::err_typecheck_incomplete_tag)
8622 << Base->getSourceRange()))
8623 return ExprError();
8625 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
8626 LookupQualifiedName(R, BaseRecord->getDecl());
8627 R.suppressDiagnostics();
8629 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
8630 Oper != OperEnd; ++Oper) {
8631 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
8632 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
8635 // Perform overload resolution.
8636 OverloadCandidateSet::iterator Best;
8637 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
8638 case OR_Success:
8639 // Overload resolution succeeded; we'll build the call below.
8640 break;
8642 case OR_No_Viable_Function:
8643 if (CandidateSet.empty())
8644 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
8645 << Base->getType() << Base->getSourceRange();
8646 else
8647 Diag(OpLoc, diag::err_ovl_no_viable_oper)
8648 << "operator->" << Base->getSourceRange();
8649 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
8650 return ExprError();
8652 case OR_Ambiguous:
8653 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8654 << "->" << Base->getType() << Base->getSourceRange();
8655 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
8656 return ExprError();
8658 case OR_Deleted:
8659 Diag(OpLoc, diag::err_ovl_deleted_oper)
8660 << Best->Function->isDeleted()
8661 << "->" << Base->getSourceRange();
8662 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
8663 return ExprError();
8666 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
8667 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8669 // Convert the object parameter.
8670 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
8671 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
8672 Best->FoundDecl, Method))
8673 return ExprError();
8675 // Build the operator call.
8676 Expr *FnExpr = CreateFunctionRefExpr(*this, Method);
8678 QualType ResultTy = Method->getResultType();
8679 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8680 ResultTy = ResultTy.getNonLValueExprType(Context);
8681 CXXOperatorCallExpr *TheCall =
8682 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
8683 &Base, 1, ResultTy, VK, OpLoc);
8685 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
8686 Method))
8687 return ExprError();
8688 return Owned(TheCall);
8691 /// FixOverloadedFunctionReference - E is an expression that refers to
8692 /// a C++ overloaded function (possibly with some parentheses and
8693 /// perhaps a '&' around it). We have resolved the overloaded function
8694 /// to the function declaration Fn, so patch up the expression E to
8695 /// refer (possibly indirectly) to Fn. Returns the new expr.
8696 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
8697 FunctionDecl *Fn) {
8698 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
8699 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
8700 Found, Fn);
8701 if (SubExpr == PE->getSubExpr())
8702 return PE;
8704 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
8707 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8708 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
8709 Found, Fn);
8710 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
8711 SubExpr->getType()) &&
8712 "Implicit cast type cannot be determined from overload");
8713 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
8714 if (SubExpr == ICE->getSubExpr())
8715 return ICE;
8717 return ImplicitCastExpr::Create(Context, ICE->getType(),
8718 ICE->getCastKind(),
8719 SubExpr, 0,
8720 ICE->getValueKind());
8723 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
8724 assert(UnOp->getOpcode() == UO_AddrOf &&
8725 "Can only take the address of an overloaded function");
8726 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8727 if (Method->isStatic()) {
8728 // Do nothing: static member functions aren't any different
8729 // from non-member functions.
8730 } else {
8731 // Fix the sub expression, which really has to be an
8732 // UnresolvedLookupExpr holding an overloaded member function
8733 // or template.
8734 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8735 Found, Fn);
8736 if (SubExpr == UnOp->getSubExpr())
8737 return UnOp;
8739 assert(isa<DeclRefExpr>(SubExpr)
8740 && "fixed to something other than a decl ref");
8741 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
8742 && "fixed to a member ref with no nested name qualifier");
8744 // We have taken the address of a pointer to member
8745 // function. Perform the computation here so that we get the
8746 // appropriate pointer to member type.
8747 QualType ClassType
8748 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
8749 QualType MemPtrType
8750 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
8752 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
8753 VK_RValue, OK_Ordinary,
8754 UnOp->getOperatorLoc());
8757 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8758 Found, Fn);
8759 if (SubExpr == UnOp->getSubExpr())
8760 return UnOp;
8762 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
8763 Context.getPointerType(SubExpr->getType()),
8764 VK_RValue, OK_Ordinary,
8765 UnOp->getOperatorLoc());
8768 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8769 // FIXME: avoid copy.
8770 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8771 if (ULE->hasExplicitTemplateArgs()) {
8772 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
8773 TemplateArgs = &TemplateArgsBuffer;
8776 return DeclRefExpr::Create(Context,
8777 ULE->getQualifier(),
8778 ULE->getQualifierRange(),
8780 ULE->getNameLoc(),
8781 Fn->getType(),
8782 VK_LValue,
8783 TemplateArgs);
8786 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
8787 // FIXME: avoid copy.
8788 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8789 if (MemExpr->hasExplicitTemplateArgs()) {
8790 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8791 TemplateArgs = &TemplateArgsBuffer;
8794 Expr *Base;
8796 // If we're filling in a static method where we used to have an
8797 // implicit member access, rewrite to a simple decl ref.
8798 if (MemExpr->isImplicitAccess()) {
8799 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
8800 return DeclRefExpr::Create(Context,
8801 MemExpr->getQualifier(),
8802 MemExpr->getQualifierRange(),
8804 MemExpr->getMemberLoc(),
8805 Fn->getType(),
8806 VK_LValue,
8807 TemplateArgs);
8808 } else {
8809 SourceLocation Loc = MemExpr->getMemberLoc();
8810 if (MemExpr->getQualifier())
8811 Loc = MemExpr->getQualifierRange().getBegin();
8812 Base = new (Context) CXXThisExpr(Loc,
8813 MemExpr->getBaseType(),
8814 /*isImplicit=*/true);
8816 } else
8817 Base = MemExpr->getBase();
8819 return MemberExpr::Create(Context, Base,
8820 MemExpr->isArrow(),
8821 MemExpr->getQualifier(),
8822 MemExpr->getQualifierRange(),
8824 Found,
8825 MemExpr->getMemberNameInfo(),
8826 TemplateArgs,
8827 Fn->getType(),
8828 cast<CXXMethodDecl>(Fn)->isStatic()
8829 ? VK_LValue : VK_RValue,
8830 OK_Ordinary);
8833 llvm_unreachable("Invalid reference to overloaded function");
8834 return E;
8837 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
8838 DeclAccessPair Found,
8839 FunctionDecl *Fn) {
8840 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
8843 } // end namespace clang