blob: ed0d137d806c2164cd4ae6ec2a2eea477758a26f [file] [log] [blame]
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001//===--- 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.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor4c2458a2009-12-22 21:44:34 +000016#include "SemaInit.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000017#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000019#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000021#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000023#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000025#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000027#include <algorithm>
28
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000034GetConversionCategory(ImplicitConversionKind Kind) {
35 static const ImplicitConversionCategory
36 Category[(int)ICK_Num_Conversion_Kinds] = {
37 ICC_Identity,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +000041 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000042 ICC_Qualification_Adjustment,
43 ICC_Promotion,
44 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000045 ICC_Promotion,
46 ICC_Conversion,
47 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000048 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000053 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000054 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000055 ICC_Conversion
56 };
57 return Category[(int)Kind];
58}
59
60/// GetConversionRank - Retrieve the implicit conversion rank
61/// corresponding to the given implicit conversion kind.
62ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
63 static const ImplicitConversionRank
64 Rank[(int)ICK_Num_Conversion_Kinds] = {
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +000070 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000071 ICR_Promotion,
72 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000073 ICR_Promotion,
74 ICR_Conversion,
75 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000076 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000081 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000082 ICR_Conversion,
Chandler Carruth23a370f2010-02-25 07:20:54 +000083 ICR_Complex_Real_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000084 };
85 return Rank[(int)Kind];
86}
87
88/// GetImplicitConversionName - Return the name of this kind of
89/// implicit conversion.
90const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +000091 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000092 "No conversion",
93 "Lvalue-to-rvalue",
94 "Array-to-pointer",
95 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +000096 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000097 "Qualification",
98 "Integral promotion",
99 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000100 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000101 "Integral conversion",
102 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000103 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000104 "Floating-integral conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000105 "Complex-real conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000106 "Pointer conversion",
107 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000108 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000109 "Compatible-types conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000110 "Derived-to-base conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000111 };
112 return Name[Kind];
113}
114
Douglas Gregor60d62c22008-10-31 16:23:19 +0000115/// StandardConversionSequence - Set the standard conversion
116/// sequence to the identity conversion.
117void StandardConversionSequence::setAsIdentityConversion() {
118 First = ICK_Identity;
119 Second = ICK_Identity;
120 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000121 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000122 ReferenceBinding = false;
123 DirectBinding = false;
Sebastian Redl85002392009-03-29 22:46:24 +0000124 RRefBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000125 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000126}
127
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000128/// getRank - Retrieve the rank of this standard conversion sequence
129/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
130/// implicit conversions.
131ImplicitConversionRank StandardConversionSequence::getRank() const {
132 ImplicitConversionRank Rank = ICR_Exact_Match;
133 if (GetConversionRank(First) > Rank)
134 Rank = GetConversionRank(First);
135 if (GetConversionRank(Second) > Rank)
136 Rank = GetConversionRank(Second);
137 if (GetConversionRank(Third) > Rank)
138 Rank = GetConversionRank(Third);
139 return Rank;
140}
141
142/// isPointerConversionToBool - Determines whether this conversion is
143/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000144/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000145/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000146bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000147 // Note that FromType has not necessarily been transformed by the
148 // array-to-pointer or function-to-pointer implicit conversions, so
149 // check for their presence as well as checking whether FromType is
150 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000151 if (getToType(1)->isBooleanType() &&
John McCall1d318332010-01-12 00:44:57 +0000152 (getFromType()->isPointerType() || getFromType()->isBlockPointerType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000153 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
154 return true;
155
156 return false;
157}
158
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000159/// isPointerConversionToVoidPointer - Determines whether this
160/// conversion is a conversion of a pointer to a void pointer. This is
161/// used as part of the ranking of standard conversion sequences (C++
162/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000163bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000164StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000165isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000166 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000167 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000168
169 // Note that FromType has not necessarily been transformed by the
170 // array-to-pointer implicit conversion, so check for its presence
171 // and redo the conversion to get a pointer.
172 if (First == ICK_Array_To_Pointer)
173 FromType = Context.getArrayDecayedType(FromType);
174
Douglas Gregor01919692009-12-13 21:37:05 +0000175 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000176 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000185 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000186 bool PrintedSomething = false;
187 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000188 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000189 PrintedSomething = true;
190 }
191
192 if (Second != ICK_Identity) {
193 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000194 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000195 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000196 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000197
198 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000199 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000200 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000201 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000202 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000203 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000204 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000205 PrintedSomething = true;
206 }
207
208 if (Third != ICK_Identity) {
209 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000210 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000211 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000212 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000213 PrintedSomething = true;
214 }
215
216 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000217 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000218 }
219}
220
221/// DebugPrint - Print this user-defined conversion sequence to standard
222/// error. Useful for debugging overloading issues.
223void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000224 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000225 if (Before.First || Before.Second || Before.Third) {
226 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000227 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000228 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000229 OS << "'" << ConversionFunction->getNameAsString() << "'";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000230 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000231 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000232 After.DebugPrint();
233 }
234}
235
236/// DebugPrint - Print this implicit conversion sequence to standard
237/// error. Useful for debugging overloading issues.
238void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000239 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000240 switch (ConversionKind) {
241 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000242 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000243 Standard.DebugPrint();
244 break;
245 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000246 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000247 UserDefined.DebugPrint();
248 break;
249 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000250 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000251 break;
John McCall1d318332010-01-12 00:44:57 +0000252 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000253 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000254 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000255 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000256 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000257 break;
258 }
259
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000260 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000261}
262
John McCall1d318332010-01-12 00:44:57 +0000263void AmbiguousConversionSequence::construct() {
264 new (&conversions()) ConversionSet();
265}
266
267void AmbiguousConversionSequence::destruct() {
268 conversions().~ConversionSet();
269}
270
271void
272AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
273 FromTypePtr = O.FromTypePtr;
274 ToTypePtr = O.ToTypePtr;
275 new (&conversions()) ConversionSet(O.conversions());
276}
277
278
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000279// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000280// overload of the declarations in Old. This routine returns false if
281// New and Old cannot be overloaded, e.g., if New has the same
282// signature as some function in Old (C++ 1.3.10) or if the Old
283// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000284// it does return false, MatchedDecl will point to the decl that New
285// cannot be overloaded with. This decl may be a UsingShadowDecl on
286// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000287//
288// Example: Given the following input:
289//
290// void f(int, float); // #1
291// void f(int, int); // #2
292// int f(int, int); // #3
293//
294// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000295// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000296//
John McCall51fa86f2009-12-02 08:47:38 +0000297// When we process #2, Old contains only the FunctionDecl for #1. By
298// comparing the parameter types, we see that #1 and #2 are overloaded
299// (since they have different signatures), so this routine returns
300// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000301//
John McCall51fa86f2009-12-02 08:47:38 +0000302// When we process #3, Old is an overload set containing #1 and #2. We
303// compare the signatures of #3 to #1 (they're overloaded, so we do
304// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
305// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000306// signature), IsOverload returns false and MatchedDecl will be set to
307// point to the FunctionDecl for #2.
John McCall871b2e72009-12-09 03:35:25 +0000308Sema::OverloadKind
John McCall9f54ad42009-12-10 09:41:52 +0000309Sema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
310 NamedDecl *&Match) {
John McCall51fa86f2009-12-02 08:47:38 +0000311 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000312 I != E; ++I) {
John McCall51fa86f2009-12-02 08:47:38 +0000313 NamedDecl *OldD = (*I)->getUnderlyingDecl();
314 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCall68263142009-11-18 22:49:29 +0000315 if (!IsOverload(New, OldT->getTemplatedDecl())) {
John McCall871b2e72009-12-09 03:35:25 +0000316 Match = *I;
317 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000318 }
John McCall51fa86f2009-12-02 08:47:38 +0000319 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCall68263142009-11-18 22:49:29 +0000320 if (!IsOverload(New, OldF)) {
John McCall871b2e72009-12-09 03:35:25 +0000321 Match = *I;
322 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000323 }
John McCall9f54ad42009-12-10 09:41:52 +0000324 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
325 // We can overload with these, which can show up when doing
326 // redeclaration checks for UsingDecls.
327 assert(Old.getLookupKind() == LookupUsingDeclName);
328 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
329 // Optimistically assume that an unresolved using decl will
330 // overload; if it doesn't, we'll have to diagnose during
331 // template instantiation.
332 } else {
John McCall68263142009-11-18 22:49:29 +0000333 // (C++ 13p1):
334 // Only function declarations can be overloaded; object and type
335 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000336 Match = *I;
337 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000338 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000339 }
John McCall68263142009-11-18 22:49:29 +0000340
John McCall871b2e72009-12-09 03:35:25 +0000341 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000342}
343
344bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
345 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
346 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
347
348 // C++ [temp.fct]p2:
349 // A function template can be overloaded with other function templates
350 // and with normal (non-template) functions.
351 if ((OldTemplate == 0) != (NewTemplate == 0))
352 return true;
353
354 // Is the function New an overload of the function Old?
355 QualType OldQType = Context.getCanonicalType(Old->getType());
356 QualType NewQType = Context.getCanonicalType(New->getType());
357
358 // Compare the signatures (C++ 1.3.10) of the two functions to
359 // determine whether they are overloads. If we find any mismatch
360 // in the signature, they are overloads.
361
362 // If either of these functions is a K&R-style function (no
363 // prototype), then we consider them to have matching signatures.
364 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
365 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
366 return false;
367
368 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
369 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
370
371 // The signature of a function includes the types of its
372 // parameters (C++ 1.3.10), which includes the presence or absence
373 // of the ellipsis; see C++ DR 357).
374 if (OldQType != NewQType &&
375 (OldType->getNumArgs() != NewType->getNumArgs() ||
376 OldType->isVariadic() != NewType->isVariadic() ||
377 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
378 NewType->arg_type_begin())))
379 return true;
380
381 // C++ [temp.over.link]p4:
382 // The signature of a function template consists of its function
383 // signature, its return type and its template parameter list. The names
384 // of the template parameters are significant only for establishing the
385 // relationship between the template parameters and the rest of the
386 // signature.
387 //
388 // We check the return type and template parameter lists for function
389 // templates first; the remaining checks follow.
390 if (NewTemplate &&
391 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
392 OldTemplate->getTemplateParameters(),
393 false, TPL_TemplateMatch) ||
394 OldType->getResultType() != NewType->getResultType()))
395 return true;
396
397 // If the function is a class member, its signature includes the
398 // cv-qualifiers (if any) on the function itself.
399 //
400 // As part of this, also check whether one of the member functions
401 // is static, in which case they are not overloads (C++
402 // 13.1p2). While not part of the definition of the signature,
403 // this check is important to determine whether these functions
404 // can be overloaded.
405 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
406 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
407 if (OldMethod && NewMethod &&
408 !OldMethod->isStatic() && !NewMethod->isStatic() &&
409 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
410 return true;
411
412 // The signatures match; this is not an overload.
413 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000414}
415
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000416/// TryImplicitConversion - Attempt to perform an implicit conversion
417/// from the given expression (Expr) to the given type (ToType). This
418/// function returns an implicit conversion sequence that can be used
419/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000420///
421/// void f(float f);
422/// void g(int i) { f(i); }
423///
424/// this routine would produce an implicit conversion sequence to
425/// describe the initialization of f from i, which will be a standard
426/// conversion sequence containing an lvalue-to-rvalue conversion (C++
427/// 4.1) followed by a floating-integral conversion (C++ 4.9).
428//
429/// Note that this routine only determines how the conversion can be
430/// performed; it does not actually perform the conversion. As such,
431/// it will not produce any diagnostics if no conversion is available,
432/// but will instead return an implicit conversion sequence of kind
433/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000434///
435/// If @p SuppressUserConversions, then user-defined conversions are
436/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000437/// If @p AllowExplicit, then explicit user-defined conversions are
438/// permitted.
Sebastian Redle2b68332009-04-12 17:16:29 +0000439/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
440/// no matter its actual lvalueness.
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000441/// If @p UserCast, the implicit conversion is being done for a user-specified
442/// cast.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000443ImplicitConversionSequence
Anders Carlsson2974b5c2009-08-27 17:14:02 +0000444Sema::TryImplicitConversion(Expr* From, QualType ToType,
445 bool SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +0000446 bool AllowExplicit, bool ForceRValue,
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000447 bool InOverloadResolution,
448 bool UserCast) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000449 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +0000450 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall1d318332010-01-12 00:44:57 +0000451 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +0000452 return ICS;
453 }
454
455 if (!getLangOptions().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +0000456 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +0000457 return ICS;
458 }
459
460 OverloadCandidateSet Conversions(From->getExprLoc());
461 OverloadingResult UserDefResult
462 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
463 !SuppressUserConversions, AllowExplicit,
464 ForceRValue, UserCast);
465
466 if (UserDefResult == OR_Success) {
John McCall1d318332010-01-12 00:44:57 +0000467 ICS.setUserDefined();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000468 // C++ [over.ics.user]p4:
469 // A conversion of an expression of class type to the same class
470 // type is given Exact Match rank, and a conversion of an
471 // expression of class type to a base class of that type is
472 // given Conversion rank, in spite of the fact that a copy
473 // constructor (i.e., a user-defined conversion function) is
474 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000475 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000476 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000477 QualType FromCanon
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000478 = Context.getCanonicalType(From->getType().getUnqualifiedType());
479 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000480 if (Constructor->isCopyConstructor() &&
Douglas Gregor0d6d12b2009-12-22 00:21:20 +0000481 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000482 // Turn this into a "standard" conversion sequence, so that it
483 // gets ranked with standard conversion sequences.
John McCall1d318332010-01-12 00:44:57 +0000484 ICS.setStandard();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000485 ICS.Standard.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +0000486 ICS.Standard.setFromType(From->getType());
Douglas Gregorad323a82010-01-27 03:51:04 +0000487 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000488 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000489 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000490 ICS.Standard.Second = ICK_Derived_To_Base;
491 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000492 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000493
494 // C++ [over.best.ics]p4:
495 // However, when considering the argument of a user-defined
496 // conversion function that is a candidate by 13.3.1.3 when
497 // invoked for the copying of the temporary in the second step
498 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
499 // 13.3.1.6 in all cases, only standard conversion sequences and
500 // ellipsis conversion sequences are allowed.
John McCalladbb8f82010-01-13 09:16:55 +0000501 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCallb1bdc622010-02-25 01:37:24 +0000502 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCalladbb8f82010-01-13 09:16:55 +0000503 }
John McCallcefd3ad2010-01-13 22:30:33 +0000504 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall1d318332010-01-12 00:44:57 +0000505 ICS.setAmbiguous();
506 ICS.Ambiguous.setFromType(From->getType());
507 ICS.Ambiguous.setToType(ToType);
508 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
509 Cand != Conversions.end(); ++Cand)
510 if (Cand->Viable)
511 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000512 } else {
John McCallb1bdc622010-02-25 01:37:24 +0000513 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000514 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000515
516 return ICS;
517}
518
Douglas Gregor43c79c22009-12-09 00:47:37 +0000519/// \brief Determine whether the conversion from FromType to ToType is a valid
520/// conversion that strips "noreturn" off the nested function type.
521static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
522 QualType ToType, QualType &ResultTy) {
523 if (Context.hasSameUnqualifiedType(FromType, ToType))
524 return false;
525
526 // Strip the noreturn off the type we're converting from; noreturn can
527 // safely be removed.
528 FromType = Context.getNoReturnType(FromType, false);
529 if (!Context.hasSameUnqualifiedType(FromType, ToType))
530 return false;
531
532 ResultTy = FromType;
533 return true;
534}
535
Douglas Gregor60d62c22008-10-31 16:23:19 +0000536/// IsStandardConversion - Determines whether there is a standard
537/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
538/// expression From to the type ToType. Standard conversion sequences
539/// only consider non-class types; for conversions that involve class
540/// types, use TryImplicitConversion. If a conversion exists, SCS will
541/// contain the standard conversion sequence required to perform this
542/// conversion and this routine will return true. Otherwise, this
543/// routine will return false and the value of SCS is unspecified.
Mike Stump1eb44332009-09-09 15:08:12 +0000544bool
545Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000546 bool InOverloadResolution,
Mike Stump1eb44332009-09-09 15:08:12 +0000547 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000548 QualType FromType = From->getType();
549
Douglas Gregor60d62c22008-10-31 16:23:19 +0000550 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000551 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +0000552 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000553 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +0000554 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000555 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000556
Douglas Gregorf9201e02009-02-11 23:02:49 +0000557 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000558 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000559 if (FromType->isRecordType() || ToType->isRecordType()) {
560 if (getLangOptions().CPlusPlus)
561 return false;
562
Mike Stump1eb44332009-09-09 15:08:12 +0000563 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000564 }
565
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000566 // The first conversion can be an lvalue-to-rvalue conversion,
567 // array-to-pointer conversion, or function-to-pointer conversion
568 // (C++ 4p1).
569
Mike Stump1eb44332009-09-09 15:08:12 +0000570 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000571 // An lvalue (3.10) of a non-function, non-array type T can be
572 // converted to an rvalue.
573 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000574 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000575 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor063daf62009-03-13 18:40:31 +0000576 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000577 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000578
579 // If T is a non-class type, the type of the rvalue is the
580 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +0000581 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
582 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000583 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000584 } else if (FromType->isArrayType()) {
585 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000586 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000587
588 // An lvalue or rvalue of type "array of N T" or "array of unknown
589 // bound of T" can be converted to an rvalue of type "pointer to
590 // T" (C++ 4.2p1).
591 FromType = Context.getArrayDecayedType(FromType);
592
593 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
594 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +0000595 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000596
597 // For the purpose of ranking in overload resolution
598 // (13.3.3.1.1), this conversion is considered an
599 // array-to-pointer conversion followed by a qualification
600 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000601 SCS.Second = ICK_Identity;
602 SCS.Third = ICK_Qualification;
Douglas Gregorad323a82010-01-27 03:51:04 +0000603 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000604 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000605 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000606 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
607 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000608 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000609
610 // An lvalue of function type T can be converted to an rvalue of
611 // type "pointer to T." The result is a pointer to the
612 // function. (C++ 4.3p1).
613 FromType = Context.getPointerType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000614 } else if (FunctionDecl *Fn
Douglas Gregor43c79c22009-12-09 00:47:37 +0000615 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000616 // Address of overloaded function (C++ [over.over]).
Douglas Gregor904eed32008-11-10 20:40:00 +0000617 SCS.First = ICK_Function_To_Pointer;
618
619 // We were able to resolve the address of the overloaded function,
620 // so we can convert to the type of that function.
621 FromType = Fn->getType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000622 if (ToType->isLValueReferenceType())
623 FromType = Context.getLValueReferenceType(FromType);
624 else if (ToType->isRValueReferenceType())
625 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl33b399a2009-02-04 21:23:32 +0000626 else if (ToType->isMemberPointerType()) {
627 // Resolve address only succeeds if both sides are member pointers,
628 // but it doesn't have to be the same class. See DR 247.
629 // Note that this means that the type of &Derived::fn can be
630 // Ret (Base::*)(Args) if the fn overload actually found is from the
631 // base class, even if it was brought into the derived class via a
632 // using declaration. The standard isn't clear on this issue at all.
633 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
634 FromType = Context.getMemberPointerType(FromType,
635 Context.getTypeDeclType(M->getParent()).getTypePtr());
636 } else
Douglas Gregor904eed32008-11-10 20:40:00 +0000637 FromType = Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000638 } else {
639 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000640 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000641 }
Douglas Gregorad323a82010-01-27 03:51:04 +0000642 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000643
644 // The second conversion can be an integral promotion, floating
645 // point promotion, integral conversion, floating point conversion,
646 // floating-integral conversion, pointer conversion,
647 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +0000648 // For overloading in C, this can also be a "compatible-type"
649 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +0000650 bool IncompatibleObjC = false;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000651 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000652 // The unqualified versions of the types are the same: there's no
653 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000654 SCS.Second = ICK_Identity;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000655 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000656 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000657 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000658 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000659 } else if (IsFloatingPointPromotion(FromType, ToType)) {
660 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000661 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000662 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000663 } else if (IsComplexPromotion(FromType, ToType)) {
664 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000665 SCS.Second = ICK_Complex_Promotion;
666 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000667 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000668 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000669 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000670 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000671 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000672 } else if (FromType->isComplexType() && ToType->isComplexType()) {
673 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000674 SCS.Second = ICK_Complex_Conversion;
675 FromType = ToType.getUnqualifiedType();
Chandler Carruth23a370f2010-02-25 07:20:54 +0000676 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
677 (ToType->isComplexType() && FromType->isArithmeticType())) {
678 // Complex-real conversions (C99 6.3.1.7)
679 SCS.Second = ICK_Complex_Real;
680 FromType = ToType.getUnqualifiedType();
681 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
682 // Floating point conversions (C++ 4.8).
683 SCS.Second = ICK_Floating_Conversion;
684 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000685 } else if ((FromType->isFloatingType() &&
686 ToType->isIntegralType() && (!ToType->isBooleanType() &&
687 !ToType->isEnumeralType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000688 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000689 ToType->isFloatingType())) {
690 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000691 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000692 FromType = ToType.getUnqualifiedType();
Anders Carlsson08972922009-08-28 15:33:32 +0000693 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
694 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000695 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000696 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000697 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregorce940492009-09-25 04:25:58 +0000698 } else if (IsMemberPointerConversion(From, FromType, ToType,
699 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000700 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000701 SCS.Second = ICK_Pointer_Member;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000702 } else if (ToType->isBooleanType() &&
703 (FromType->isArithmeticType() ||
704 FromType->isEnumeralType() ||
Fariborz Jahanian1f7711d2009-12-11 21:23:13 +0000705 FromType->isAnyPointerType() ||
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000706 FromType->isBlockPointerType() ||
707 FromType->isMemberPointerType() ||
708 FromType->isNullPtrType())) {
709 // Boolean conversions (C++ 4.12).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000710 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000711 FromType = Context.BoolTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000712 } else if (!getLangOptions().CPlusPlus &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000713 Context.typesAreCompatible(ToType, FromType)) {
714 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000715 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor43c79c22009-12-09 00:47:37 +0000716 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
717 // Treat a conversion that strips "noreturn" as an identity conversion.
718 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000719 } else {
720 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000721 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000722 }
Douglas Gregorad323a82010-01-27 03:51:04 +0000723 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000724
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000725 QualType CanonFrom;
726 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000727 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000728 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000729 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000730 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000731 CanonFrom = Context.getCanonicalType(FromType);
732 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000733 } else {
734 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000735 SCS.Third = ICK_Identity;
736
Mike Stump1eb44332009-09-09 15:08:12 +0000737 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +0000738 // [...] Any difference in top-level cv-qualification is
739 // subsumed by the initialization itself and does not constitute
740 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000741 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000742 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregora4923eb2009-11-16 21:35:15 +0000743 if (CanonFrom.getLocalUnqualifiedType()
744 == CanonTo.getLocalUnqualifiedType() &&
745 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000746 FromType = ToType;
747 CanonFrom = CanonTo;
748 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000749 }
Douglas Gregorad323a82010-01-27 03:51:04 +0000750 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000751
752 // If we have not converted the argument type to the parameter type,
753 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000754 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000755 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000756
Douglas Gregor60d62c22008-10-31 16:23:19 +0000757 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000758}
759
760/// IsIntegralPromotion - Determines whether the conversion from the
761/// expression From (whose potentially-adjusted type is FromType) to
762/// ToType is an integral promotion (C++ 4.5). If so, returns true and
763/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000764bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +0000765 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000766 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000767 if (!To) {
768 return false;
769 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000770
771 // An rvalue of type char, signed char, unsigned char, short int, or
772 // unsigned short int can be converted to an rvalue of type int if
773 // int can represent all the values of the source type; otherwise,
774 // the source rvalue can be converted to an rvalue of type unsigned
775 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +0000776 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
777 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000778 if (// We can promote any signed, promotable integer type to an int
779 (FromType->isSignedIntegerType() ||
780 // We can promote any unsigned integer type whose size is
781 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +0000782 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000783 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000784 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000785 }
786
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000787 return To->getKind() == BuiltinType::UInt;
788 }
789
790 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
791 // can be converted to an rvalue of the first of the following types
792 // that can represent all the values of its underlying type: int,
793 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall842aef82009-12-09 09:09:27 +0000794
795 // We pre-calculate the promotion type for enum types.
796 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
797 if (ToType->isIntegerType())
798 return Context.hasSameUnqualifiedType(ToType,
799 FromEnumType->getDecl()->getPromotionType());
800
801 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000802 // Determine whether the type we're converting from is signed or
803 // unsigned.
804 bool FromIsSigned;
805 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall842aef82009-12-09 09:09:27 +0000806
807 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
808 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000809
810 // The types we'll try to promote to, in the appropriate
811 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +0000812 QualType PromoteTypes[6] = {
813 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000814 Context.LongTy, Context.UnsignedLongTy ,
815 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000816 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000817 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000818 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
819 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +0000820 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000821 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
822 // We found the type that we can promote to. If this is the
823 // type we wanted, we have a promotion. Otherwise, no
824 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000825 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000826 }
827 }
828 }
829
830 // An rvalue for an integral bit-field (9.6) can be converted to an
831 // rvalue of type int if int can represent all the values of the
832 // bit-field; otherwise, it can be converted to unsigned int if
833 // unsigned int can represent all the values of the bit-field. If
834 // the bit-field is larger yet, no integral promotion applies to
835 // it. If the bit-field has an enumerated type, it is treated as any
836 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +0000837 // FIXME: We should delay checking of bit-fields until we actually perform the
838 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000839 using llvm::APSInt;
840 if (From)
841 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +0000842 APSInt BitWidth;
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000843 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
844 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
845 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
846 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +0000847
Douglas Gregor86f19402008-12-20 23:49:58 +0000848 // Are we promoting to an int from a bitfield that fits in an int?
849 if (BitWidth < ToSize ||
850 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
851 return To->getKind() == BuiltinType::Int;
852 }
Mike Stump1eb44332009-09-09 15:08:12 +0000853
Douglas Gregor86f19402008-12-20 23:49:58 +0000854 // Are we promoting to an unsigned int from an unsigned bitfield
855 // that fits into an unsigned int?
856 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
857 return To->getKind() == BuiltinType::UInt;
858 }
Mike Stump1eb44332009-09-09 15:08:12 +0000859
Douglas Gregor86f19402008-12-20 23:49:58 +0000860 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000861 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000862 }
Mike Stump1eb44332009-09-09 15:08:12 +0000863
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000864 // An rvalue of type bool can be converted to an rvalue of type int,
865 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000866 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000867 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000868 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000869
870 return false;
871}
872
873/// IsFloatingPointPromotion - Determines whether the conversion from
874/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
875/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000876bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000877 /// An rvalue of type float can be converted to an rvalue of type
878 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +0000879 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
880 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000881 if (FromBuiltin->getKind() == BuiltinType::Float &&
882 ToBuiltin->getKind() == BuiltinType::Double)
883 return true;
884
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000885 // C99 6.3.1.5p1:
886 // When a float is promoted to double or long double, or a
887 // double is promoted to long double [...].
888 if (!getLangOptions().CPlusPlus &&
889 (FromBuiltin->getKind() == BuiltinType::Float ||
890 FromBuiltin->getKind() == BuiltinType::Double) &&
891 (ToBuiltin->getKind() == BuiltinType::LongDouble))
892 return true;
893 }
894
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000895 return false;
896}
897
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000898/// \brief Determine if a conversion is a complex promotion.
899///
900/// A complex promotion is defined as a complex -> complex conversion
901/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000902/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000903bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +0000904 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000905 if (!FromComplex)
906 return false;
907
John McCall183700f2009-09-21 23:43:11 +0000908 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000909 if (!ToComplex)
910 return false;
911
912 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000913 ToComplex->getElementType()) ||
914 IsIntegralPromotion(0, FromComplex->getElementType(),
915 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000916}
917
Douglas Gregorcb7de522008-11-26 23:31:11 +0000918/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
919/// the pointer type FromPtr to a pointer to type ToPointee, with the
920/// same type qualifiers as FromPtr has on its pointee type. ToType,
921/// if non-empty, will be a pointer to ToType that may or may not have
922/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +0000923static QualType
924BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000925 QualType ToPointee, QualType ToType,
926 ASTContext &Context) {
927 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
928 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +0000929 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +0000930
931 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000932 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +0000933 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +0000934 if (!ToType.isNull())
Douglas Gregorcb7de522008-11-26 23:31:11 +0000935 return ToType;
936
937 // Build a pointer to ToPointee. It has the right qualifiers
938 // already.
939 return Context.getPointerType(ToPointee);
940 }
941
942 // Just build a canonical type that has the right qualifiers.
John McCall0953e762009-09-24 19:53:00 +0000943 return Context.getPointerType(
Douglas Gregora4923eb2009-11-16 21:35:15 +0000944 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
945 Quals));
Douglas Gregorcb7de522008-11-26 23:31:11 +0000946}
947
Fariborz Jahanianadcfab12009-12-16 23:13:33 +0000948/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
949/// the FromType, which is an objective-c pointer, to ToType, which may or may
950/// not have the right set of qualifiers.
951static QualType
952BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
953 QualType ToType,
954 ASTContext &Context) {
955 QualType CanonFromType = Context.getCanonicalType(FromType);
956 QualType CanonToType = Context.getCanonicalType(ToType);
957 Qualifiers Quals = CanonFromType.getQualifiers();
958
959 // Exact qualifier match -> return the pointer type we're converting to.
960 if (CanonToType.getLocalQualifiers() == Quals)
961 return ToType;
962
963 // Just build a canonical type that has the right qualifiers.
964 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
965}
966
Mike Stump1eb44332009-09-09 15:08:12 +0000967static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000968 bool InOverloadResolution,
969 ASTContext &Context) {
970 // Handle value-dependent integral null pointer constants correctly.
971 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
972 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
973 Expr->getType()->isIntegralType())
974 return !InOverloadResolution;
975
Douglas Gregorce940492009-09-25 04:25:58 +0000976 return Expr->isNullPointerConstant(Context,
977 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
978 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000979}
Mike Stump1eb44332009-09-09 15:08:12 +0000980
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000981/// IsPointerConversion - Determines whether the conversion of the
982/// expression From, which has the (possibly adjusted) type FromType,
983/// can be converted to the type ToType via a pointer conversion (C++
984/// 4.10). If so, returns true and places the converted type (that
985/// might differ from ToType in its cv-qualifiers at some level) into
986/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000987///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000988/// This routine also supports conversions to and from block pointers
989/// and conversions with Objective-C's 'id', 'id<protocols...>', and
990/// pointers to interfaces. FIXME: Once we've determined the
991/// appropriate overloading rules for Objective-C, we may want to
992/// split the Objective-C checks into a different routine; however,
993/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000994/// conversions, so for now they live here. IncompatibleObjC will be
995/// set if the conversion is an allowed Objective-C conversion that
996/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000997bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000998 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +0000999 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001000 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001001 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +00001002 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1003 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001004
Mike Stump1eb44332009-09-09 15:08:12 +00001005 // Conversion from a null pointer constant to any Objective-C pointer type.
1006 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001007 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001008 ConvertedType = ToType;
1009 return true;
1010 }
1011
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001012 // Blocks: Block pointers can be converted to void*.
1013 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001014 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001015 ConvertedType = ToType;
1016 return true;
1017 }
1018 // Blocks: A null pointer constant can be converted to a block
1019 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001020 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001021 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001022 ConvertedType = ToType;
1023 return true;
1024 }
1025
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001026 // If the left-hand-side is nullptr_t, the right side can be a null
1027 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001028 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001029 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001030 ConvertedType = ToType;
1031 return true;
1032 }
1033
Ted Kremenek6217b802009-07-29 21:53:49 +00001034 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001035 if (!ToTypePtr)
1036 return false;
1037
1038 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001039 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001040 ConvertedType = ToType;
1041 return true;
1042 }
Sebastian Redl07779722008-10-31 14:43:28 +00001043
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001044 // Beyond this point, both types need to be pointers
1045 // , including objective-c pointers.
1046 QualType ToPointeeType = ToTypePtr->getPointeeType();
1047 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1048 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1049 ToType, Context);
1050 return true;
1051
1052 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001053 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001054 if (!FromTypePtr)
1055 return false;
1056
1057 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001058
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001059 // An rvalue of type "pointer to cv T," where T is an object type,
1060 // can be converted to an rvalue of type "pointer to cv void" (C++
1061 // 4.10p2).
Douglas Gregorbad0e652009-03-24 20:32:41 +00001062 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001063 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001064 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001065 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001066 return true;
1067 }
1068
Douglas Gregorf9201e02009-02-11 23:02:49 +00001069 // When we're overloading in C, we allow a special kind of pointer
1070 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001071 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001072 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001073 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001074 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001075 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001076 return true;
1077 }
1078
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001079 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001080 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001081 // An rvalue of type "pointer to cv D," where D is a class type,
1082 // can be converted to an rvalue of type "pointer to cv B," where
1083 // B is a base class (clause 10) of D. If B is an inaccessible
1084 // (clause 11) or ambiguous (10.2) base class of D, a program that
1085 // necessitates this conversion is ill-formed. The result of the
1086 // conversion is a pointer to the base class sub-object of the
1087 // derived class object. The null pointer value is converted to
1088 // the null pointer value of the destination type.
1089 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001090 // Note that we do not check for ambiguity or inaccessibility
1091 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001092 if (getLangOptions().CPlusPlus &&
1093 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001094 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001095 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001096 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001097 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001098 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001099 ToType, Context);
1100 return true;
1101 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001102
Douglas Gregorc7887512008-12-19 19:13:09 +00001103 return false;
1104}
1105
1106/// isObjCPointerConversion - Determines whether this is an
1107/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1108/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001109bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001110 QualType& ConvertedType,
1111 bool &IncompatibleObjC) {
1112 if (!getLangOptions().ObjC1)
1113 return false;
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001114
Steve Naroff14108da2009-07-10 23:34:53 +00001115 // First, we handle all conversions on ObjC object pointer types.
John McCall183700f2009-09-21 23:43:11 +00001116 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001117 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001118 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001119
Steve Naroff14108da2009-07-10 23:34:53 +00001120 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001121 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001122 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001123 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001124 ConvertedType = ToType;
1125 return true;
1126 }
1127 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001128 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001129 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001130 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001131 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001132 ConvertedType = ToType;
1133 return true;
1134 }
1135 // Objective C++: We're able to convert from a pointer to an
1136 // interface to a pointer to a different interface.
1137 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1138 ConvertedType = ToType;
1139 return true;
1140 }
1141
1142 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1143 // Okay: this is some kind of implicit downcast of Objective-C
1144 // interfaces, which is permitted. However, we're going to
1145 // complain about it.
1146 IncompatibleObjC = true;
1147 ConvertedType = FromType;
1148 return true;
1149 }
Mike Stump1eb44332009-09-09 15:08:12 +00001150 }
Steve Naroff14108da2009-07-10 23:34:53 +00001151 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001152 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001153 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001154 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001155 else if (const BlockPointerType *ToBlockPtr =
1156 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001157 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001158 // to a block pointer type.
1159 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1160 ConvertedType = ToType;
1161 return true;
1162 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001163 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001164 }
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001165 else if (FromType->getAs<BlockPointerType>() &&
1166 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1167 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001168 // pointer to any object.
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001169 ConvertedType = ToType;
1170 return true;
1171 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001172 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001173 return false;
1174
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001175 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001176 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001177 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001178 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001179 FromPointeeType = FromBlockPtr->getPointeeType();
1180 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001181 return false;
1182
Douglas Gregorc7887512008-12-19 19:13:09 +00001183 // If we have pointers to pointers, recursively check whether this
1184 // is an Objective-C conversion.
1185 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1186 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1187 IncompatibleObjC)) {
1188 // We always complain about this conversion.
1189 IncompatibleObjC = true;
1190 ConvertedType = ToType;
1191 return true;
1192 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001193 // Allow conversion of pointee being objective-c pointer to another one;
1194 // as in I* to id.
1195 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1196 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1197 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1198 IncompatibleObjC)) {
1199 ConvertedType = ToType;
1200 return true;
1201 }
1202
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001203 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001204 // differences in the argument and result types are in Objective-C
1205 // pointer conversions. If so, we permit the conversion (but
1206 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001207 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001208 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001209 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001210 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001211 if (FromFunctionType && ToFunctionType) {
1212 // If the function types are exactly the same, this isn't an
1213 // Objective-C pointer conversion.
1214 if (Context.getCanonicalType(FromPointeeType)
1215 == Context.getCanonicalType(ToPointeeType))
1216 return false;
1217
1218 // Perform the quick checks that will tell us whether these
1219 // function types are obviously different.
1220 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1221 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1222 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1223 return false;
1224
1225 bool HasObjCConversion = false;
1226 if (Context.getCanonicalType(FromFunctionType->getResultType())
1227 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1228 // Okay, the types match exactly. Nothing to do.
1229 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1230 ToFunctionType->getResultType(),
1231 ConvertedType, IncompatibleObjC)) {
1232 // Okay, we have an Objective-C pointer conversion.
1233 HasObjCConversion = true;
1234 } else {
1235 // Function types are too different. Abort.
1236 return false;
1237 }
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Douglas Gregorc7887512008-12-19 19:13:09 +00001239 // Check argument types.
1240 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1241 ArgIdx != NumArgs; ++ArgIdx) {
1242 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1243 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1244 if (Context.getCanonicalType(FromArgType)
1245 == Context.getCanonicalType(ToArgType)) {
1246 // Okay, the types match exactly. Nothing to do.
1247 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1248 ConvertedType, IncompatibleObjC)) {
1249 // Okay, we have an Objective-C pointer conversion.
1250 HasObjCConversion = true;
1251 } else {
1252 // Argument types are too different. Abort.
1253 return false;
1254 }
1255 }
1256
1257 if (HasObjCConversion) {
1258 // We had an Objective-C conversion. Allow this pointer
1259 // conversion, but complain about it.
1260 ConvertedType = ToType;
1261 IncompatibleObjC = true;
1262 return true;
1263 }
1264 }
1265
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001266 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001267}
1268
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001269/// CheckPointerConversion - Check the pointer conversion from the
1270/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001271/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001272/// conversions for which IsPointerConversion has already returned
1273/// true. It returns true and produces a diagnostic if there was an
1274/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001275bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001276 CastExpr::CastKind &Kind,
1277 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001278 QualType FromType = From->getType();
1279
Ted Kremenek6217b802009-07-29 21:53:49 +00001280 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1281 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001282 QualType FromPointeeType = FromPtrType->getPointeeType(),
1283 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001284
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001285 if (FromPointeeType->isRecordType() &&
1286 ToPointeeType->isRecordType()) {
1287 // We must have a derived-to-base conversion. Check an
1288 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001289 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1290 From->getExprLoc(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001291 From->getSourceRange(),
1292 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001293 return true;
1294
1295 // The conversion was successful.
1296 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001297 }
1298 }
Mike Stump1eb44332009-09-09 15:08:12 +00001299 if (const ObjCObjectPointerType *FromPtrType =
John McCall183700f2009-09-21 23:43:11 +00001300 FromType->getAs<ObjCObjectPointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001301 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001302 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001303 // Objective-C++ conversions are always okay.
1304 // FIXME: We should have a different class of conversions for the
1305 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001306 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001307 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001308
Steve Naroff14108da2009-07-10 23:34:53 +00001309 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001310 return false;
1311}
1312
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001313/// IsMemberPointerConversion - Determines whether the conversion of the
1314/// expression From, which has the (possibly adjusted) type FromType, can be
1315/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1316/// If so, returns true and places the converted type (that might differ from
1317/// ToType in its cv-qualifiers at some level) into ConvertedType.
1318bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001319 QualType ToType,
1320 bool InOverloadResolution,
1321 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001322 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001323 if (!ToTypePtr)
1324 return false;
1325
1326 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001327 if (From->isNullPointerConstant(Context,
1328 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1329 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001330 ConvertedType = ToType;
1331 return true;
1332 }
1333
1334 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001335 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001336 if (!FromTypePtr)
1337 return false;
1338
1339 // A pointer to member of B can be converted to a pointer to member of D,
1340 // where D is derived from B (C++ 4.11p2).
1341 QualType FromClass(FromTypePtr->getClass(), 0);
1342 QualType ToClass(ToTypePtr->getClass(), 0);
1343 // FIXME: What happens when these are dependent? Is this function even called?
1344
1345 if (IsDerivedFrom(ToClass, FromClass)) {
1346 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1347 ToClass.getTypePtr());
1348 return true;
1349 }
1350
1351 return false;
1352}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001353
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001354/// CheckMemberPointerConversion - Check the member pointer conversion from the
1355/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00001356/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001357/// for which IsMemberPointerConversion has already returned true. It returns
1358/// true and produces a diagnostic if there was an error, or returns false
1359/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001360bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001361 CastExpr::CastKind &Kind,
1362 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001363 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001364 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001365 if (!FromPtrType) {
1366 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001367 assert(From->isNullPointerConstant(Context,
1368 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001369 "Expr must be null pointer constant!");
1370 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001371 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001372 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001373
Ted Kremenek6217b802009-07-29 21:53:49 +00001374 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001375 assert(ToPtrType && "No member pointer cast has a target type "
1376 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001377
Sebastian Redl21593ac2009-01-28 18:33:18 +00001378 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1379 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001380
Sebastian Redl21593ac2009-01-28 18:33:18 +00001381 // FIXME: What about dependent types?
1382 assert(FromClass->isRecordType() && "Pointer into non-class.");
1383 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001384
John McCall6b2accb2010-02-10 09:31:12 +00001385 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/ true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001386 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001387 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1388 assert(DerivationOkay &&
1389 "Should not have been called if derivation isn't OK.");
1390 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001391
Sebastian Redl21593ac2009-01-28 18:33:18 +00001392 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1393 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001394 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1395 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1396 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1397 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001398 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001399
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001400 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001401 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1402 << FromClass << ToClass << QualType(VBase, 0)
1403 << From->getSourceRange();
1404 return true;
1405 }
1406
John McCall6b2accb2010-02-10 09:31:12 +00001407 if (!IgnoreBaseAccess)
1408 CheckBaseClassAccess(From->getExprLoc(), /*BaseToDerived*/ true,
1409 FromClass, ToClass, Paths.front());
1410
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001411 // Must be a base to derived member conversion.
1412 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001413 return false;
1414}
1415
Douglas Gregor98cd5992008-10-21 23:43:52 +00001416/// IsQualificationConversion - Determines whether the conversion from
1417/// an rvalue of type FromType to ToType is a qualification conversion
1418/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001419bool
1420Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001421 FromType = Context.getCanonicalType(FromType);
1422 ToType = Context.getCanonicalType(ToType);
1423
1424 // If FromType and ToType are the same type, this is not a
1425 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00001426 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00001427 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001428
Douglas Gregor98cd5992008-10-21 23:43:52 +00001429 // (C++ 4.4p4):
1430 // A conversion can add cv-qualifiers at levels other than the first
1431 // in multi-level pointers, subject to the following rules: [...]
1432 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001433 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001434 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001435 // Within each iteration of the loop, we check the qualifiers to
1436 // determine if this still looks like a qualification
1437 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001438 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001439 // until there are no more pointers or pointers-to-members left to
1440 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001441 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001442
1443 // -- for every j > 0, if const is in cv 1,j then const is in cv
1444 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001445 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001446 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001447
Douglas Gregor98cd5992008-10-21 23:43:52 +00001448 // -- if the cv 1,j and cv 2,j are different, then const is in
1449 // every cv for 0 < k < j.
1450 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001451 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001452 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001453
Douglas Gregor98cd5992008-10-21 23:43:52 +00001454 // Keep track of whether all prior cv-qualifiers in the "to" type
1455 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001456 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001457 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001458 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001459
1460 // We are left with FromType and ToType being the pointee types
1461 // after unwrapping the original FromType and ToType the same number
1462 // of types. If we unwrapped any pointers, and if FromType and
1463 // ToType have the same unqualified type (since we checked
1464 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001465 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00001466}
1467
Douglas Gregor734d9862009-01-30 23:27:23 +00001468/// Determines whether there is a user-defined conversion sequence
1469/// (C++ [over.ics.user]) that converts expression From to the type
1470/// ToType. If such a conversion exists, User will contain the
1471/// user-defined conversion sequence that performs such a conversion
1472/// and this routine will return true. Otherwise, this routine returns
1473/// false and User is unspecified.
1474///
1475/// \param AllowConversionFunctions true if the conversion should
1476/// consider conversion functions at all. If false, only constructors
1477/// will be considered.
1478///
1479/// \param AllowExplicit true if the conversion should consider C++0x
1480/// "explicit" conversion functions as well as non-explicit conversion
1481/// functions (C++0x [class.conv.fct]p2).
Sebastian Redle2b68332009-04-12 17:16:29 +00001482///
1483/// \param ForceRValue true if the expression should be treated as an rvalue
1484/// for overload resolution.
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001485/// \param UserCast true if looking for user defined conversion for a static
1486/// cast.
Douglas Gregor20093b42009-12-09 23:02:17 +00001487OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1488 UserDefinedConversionSequence& User,
1489 OverloadCandidateSet& CandidateSet,
1490 bool AllowConversionFunctions,
1491 bool AllowExplicit,
1492 bool ForceRValue,
1493 bool UserCast) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001494 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00001495 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1496 // We're not going to find any constructors.
1497 } else if (CXXRecordDecl *ToRecordDecl
1498 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001499 // C++ [over.match.ctor]p1:
1500 // When objects of class type are direct-initialized (8.5), or
1501 // copy-initialized from an expression of the same or a
1502 // derived class type (8.5), overload resolution selects the
1503 // constructor. [...] For copy-initialization, the candidate
1504 // functions are all the converting constructors (12.3.1) of
1505 // that class. The argument list is the expression-list within
1506 // the parentheses of the initializer.
Douglas Gregor79b680e2009-11-13 18:44:21 +00001507 bool SuppressUserConversions = !UserCast;
1508 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1509 IsDerivedFrom(From->getType(), ToType)) {
1510 SuppressUserConversions = false;
1511 AllowConversionFunctions = false;
1512 }
1513
Mike Stump1eb44332009-09-09 15:08:12 +00001514 DeclarationName ConstructorName
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001515 = Context.DeclarationNames.getCXXConstructorName(
1516 Context.getCanonicalType(ToType).getUnqualifiedType());
1517 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump1eb44332009-09-09 15:08:12 +00001518 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001519 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001520 Con != ConEnd; ++Con) {
Douglas Gregordec06662009-08-21 18:42:58 +00001521 // Find the constructor (which may be a template).
1522 CXXConstructorDecl *Constructor = 0;
1523 FunctionTemplateDecl *ConstructorTmpl
1524 = dyn_cast<FunctionTemplateDecl>(*Con);
1525 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001526 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00001527 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1528 else
1529 Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001530
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00001531 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00001532 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001533 if (ConstructorTmpl)
John McCall86820f52010-01-26 01:37:31 +00001534 AddTemplateOverloadCandidate(ConstructorTmpl,
1535 ConstructorTmpl->getAccess(),
1536 /*ExplicitArgs*/ 0,
John McCalld5532b62009-11-23 01:53:49 +00001537 &From, 1, CandidateSet,
Douglas Gregor79b680e2009-11-13 18:44:21 +00001538 SuppressUserConversions, ForceRValue);
Douglas Gregordec06662009-08-21 18:42:58 +00001539 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001540 // Allow one user-defined conversion when user specifies a
1541 // From->ToType conversion via an static cast (c-style, etc).
John McCall86820f52010-01-26 01:37:31 +00001542 AddOverloadCandidate(Constructor, Constructor->getAccess(),
1543 &From, 1, CandidateSet,
Douglas Gregor79b680e2009-11-13 18:44:21 +00001544 SuppressUserConversions, ForceRValue);
Douglas Gregordec06662009-08-21 18:42:58 +00001545 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001546 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001547 }
1548 }
1549
Douglas Gregor734d9862009-01-30 23:27:23 +00001550 if (!AllowConversionFunctions) {
1551 // Don't allow any conversion functions to enter the overload set.
Mike Stump1eb44332009-09-09 15:08:12 +00001552 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1553 PDiag(0)
Anders Carlssonb7906612009-08-26 23:45:07 +00001554 << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00001555 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00001556 } else if (const RecordType *FromRecordType
Ted Kremenek6217b802009-07-29 21:53:49 +00001557 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001558 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001559 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1560 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00001561 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00001562 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001563 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001564 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00001565 NamedDecl *D = *I;
1566 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1567 if (isa<UsingShadowDecl>(D))
1568 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1569
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001570 CXXConversionDecl *Conv;
1571 FunctionTemplateDecl *ConvTemplate;
John McCallba135432009-11-21 08:51:07 +00001572 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001573 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1574 else
John McCallba135432009-11-21 08:51:07 +00001575 Conv = dyn_cast<CXXConversionDecl>(*I);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001576
1577 if (AllowExplicit || !Conv->isExplicit()) {
1578 if (ConvTemplate)
John McCall86820f52010-01-26 01:37:31 +00001579 AddTemplateConversionCandidate(ConvTemplate, I.getAccess(),
1580 ActingContext, From, ToType,
1581 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001582 else
John McCall86820f52010-01-26 01:37:31 +00001583 AddConversionCandidate(Conv, I.getAccess(), ActingContext,
1584 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001585 }
1586 }
1587 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001588 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001589
1590 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001591 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001592 case OR_Success:
1593 // Record the standard conversion we used and the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00001594 if (CXXConstructorDecl *Constructor
Douglas Gregor60d62c22008-10-31 16:23:19 +00001595 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1596 // C++ [over.ics.user]p1:
1597 // If the user-defined conversion is specified by a
1598 // constructor (12.3.1), the initial standard conversion
1599 // sequence converts the source type to the type required by
1600 // the argument of the constructor.
1601 //
Douglas Gregor60d62c22008-10-31 16:23:19 +00001602 QualType ThisType = Constructor->getThisType(Context);
John McCall1d318332010-01-12 00:44:57 +00001603 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001604 User.EllipsisConversion = true;
1605 else {
1606 User.Before = Best->Conversions[0].Standard;
1607 User.EllipsisConversion = false;
1608 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001609 User.ConversionFunction = Constructor;
1610 User.After.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +00001611 User.After.setFromType(
1612 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregorad323a82010-01-27 03:51:04 +00001613 User.After.setAllToTypes(ToType);
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001614 return OR_Success;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001615 } else if (CXXConversionDecl *Conversion
1616 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1617 // C++ [over.ics.user]p1:
1618 //
1619 // [...] If the user-defined conversion is specified by a
1620 // conversion function (12.3.2), the initial standard
1621 // conversion sequence converts the source type to the
1622 // implicit object parameter of the conversion function.
1623 User.Before = Best->Conversions[0].Standard;
1624 User.ConversionFunction = Conversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001625 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001626
1627 // C++ [over.ics.user]p2:
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001628 // The second standard conversion sequence converts the
1629 // result of the user-defined conversion to the target type
1630 // for the sequence. Since an implicit conversion sequence
1631 // is an initialization, the special rules for
1632 // initialization by user-defined conversion apply when
1633 // selecting the best user-defined conversion for a
1634 // user-defined conversion sequence (see 13.3.3 and
1635 // 13.3.3.1).
1636 User.After = Best->FinalConversion;
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001637 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001638 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001639 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001640 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001641 }
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Douglas Gregor60d62c22008-10-31 16:23:19 +00001643 case OR_No_Viable_Function:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001644 return OR_No_Viable_Function;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001645 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001646 // No conversion here! We're done.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001647 return OR_Deleted;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001648
1649 case OR_Ambiguous:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001650 return OR_Ambiguous;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001651 }
1652
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001653 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001654}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001655
1656bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001657Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001658 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00001659 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001660 OverloadingResult OvResult =
1661 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1662 CandidateSet, true, false, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001663 if (OvResult == OR_Ambiguous)
1664 Diag(From->getSourceRange().getBegin(),
1665 diag::err_typecheck_ambiguous_condition)
1666 << From->getType() << ToType << From->getSourceRange();
1667 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1668 Diag(From->getSourceRange().getBegin(),
1669 diag::err_typecheck_nonviable_condition)
1670 << From->getType() << ToType << From->getSourceRange();
1671 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001672 return false;
John McCallcbce6062010-01-12 07:18:19 +00001673 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001674 return true;
1675}
Douglas Gregor60d62c22008-10-31 16:23:19 +00001676
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001677/// CompareImplicitConversionSequences - Compare two implicit
1678/// conversion sequences to determine whether one is better than the
1679/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump1eb44332009-09-09 15:08:12 +00001680ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001681Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1682 const ImplicitConversionSequence& ICS2)
1683{
1684 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1685 // conversion sequences (as defined in 13.3.3.1)
1686 // -- a standard conversion sequence (13.3.3.1.1) is a better
1687 // conversion sequence than a user-defined conversion sequence or
1688 // an ellipsis conversion sequence, and
1689 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1690 // conversion sequence than an ellipsis conversion sequence
1691 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00001692 //
John McCall1d318332010-01-12 00:44:57 +00001693 // C++0x [over.best.ics]p10:
1694 // For the purpose of ranking implicit conversion sequences as
1695 // described in 13.3.3.2, the ambiguous conversion sequence is
1696 // treated as a user-defined sequence that is indistinguishable
1697 // from any other user-defined conversion sequence.
1698 if (ICS1.getKind() < ICS2.getKind()) {
1699 if (!(ICS1.isUserDefined() && ICS2.isAmbiguous()))
1700 return ImplicitConversionSequence::Better;
1701 } else if (ICS2.getKind() < ICS1.getKind()) {
1702 if (!(ICS2.isUserDefined() && ICS1.isAmbiguous()))
1703 return ImplicitConversionSequence::Worse;
1704 }
1705
1706 if (ICS1.isAmbiguous() || ICS2.isAmbiguous())
1707 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001708
1709 // Two implicit conversion sequences of the same form are
1710 // indistinguishable conversion sequences unless one of the
1711 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00001712 if (ICS1.isStandard())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001713 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00001714 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001715 // User-defined conversion sequence U1 is a better conversion
1716 // sequence than another user-defined conversion sequence U2 if
1717 // they contain the same user-defined conversion function or
1718 // constructor and if the second standard conversion sequence of
1719 // U1 is better than the second standard conversion sequence of
1720 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001721 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001722 ICS2.UserDefined.ConversionFunction)
1723 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1724 ICS2.UserDefined.After);
1725 }
1726
1727 return ImplicitConversionSequence::Indistinguishable;
1728}
1729
Douglas Gregorad323a82010-01-27 03:51:04 +00001730// Per 13.3.3.2p3, compare the given standard conversion sequences to
1731// determine if one is a proper subset of the other.
1732static ImplicitConversionSequence::CompareKind
1733compareStandardConversionSubsets(ASTContext &Context,
1734 const StandardConversionSequence& SCS1,
1735 const StandardConversionSequence& SCS2) {
1736 ImplicitConversionSequence::CompareKind Result
1737 = ImplicitConversionSequence::Indistinguishable;
1738
1739 if (SCS1.Second != SCS2.Second) {
1740 if (SCS1.Second == ICK_Identity)
1741 Result = ImplicitConversionSequence::Better;
1742 else if (SCS2.Second == ICK_Identity)
1743 Result = ImplicitConversionSequence::Worse;
1744 else
1745 return ImplicitConversionSequence::Indistinguishable;
1746 } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1)))
1747 return ImplicitConversionSequence::Indistinguishable;
1748
1749 if (SCS1.Third == SCS2.Third) {
1750 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
1751 : ImplicitConversionSequence::Indistinguishable;
1752 }
1753
1754 if (SCS1.Third == ICK_Identity)
1755 return Result == ImplicitConversionSequence::Worse
1756 ? ImplicitConversionSequence::Indistinguishable
1757 : ImplicitConversionSequence::Better;
1758
1759 if (SCS2.Third == ICK_Identity)
1760 return Result == ImplicitConversionSequence::Better
1761 ? ImplicitConversionSequence::Indistinguishable
1762 : ImplicitConversionSequence::Worse;
1763
1764 return ImplicitConversionSequence::Indistinguishable;
1765}
1766
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001767/// CompareStandardConversionSequences - Compare two standard
1768/// conversion sequences to determine whether one is better than the
1769/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001770ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001771Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1772 const StandardConversionSequence& SCS2)
1773{
1774 // Standard conversion sequence S1 is a better conversion sequence
1775 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1776
1777 // -- S1 is a proper subsequence of S2 (comparing the conversion
1778 // sequences in the canonical form defined by 13.3.3.1.1,
1779 // excluding any Lvalue Transformation; the identity conversion
1780 // sequence is considered to be a subsequence of any
1781 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00001782 if (ImplicitConversionSequence::CompareKind CK
1783 = compareStandardConversionSubsets(Context, SCS1, SCS2))
1784 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001785
1786 // -- the rank of S1 is better than the rank of S2 (by the rules
1787 // defined below), or, if not that,
1788 ImplicitConversionRank Rank1 = SCS1.getRank();
1789 ImplicitConversionRank Rank2 = SCS2.getRank();
1790 if (Rank1 < Rank2)
1791 return ImplicitConversionSequence::Better;
1792 else if (Rank2 < Rank1)
1793 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001794
Douglas Gregor57373262008-10-22 14:17:15 +00001795 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1796 // are indistinguishable unless one of the following rules
1797 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00001798
Douglas Gregor57373262008-10-22 14:17:15 +00001799 // A conversion that is not a conversion of a pointer, or
1800 // pointer to member, to bool is better than another conversion
1801 // that is such a conversion.
1802 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1803 return SCS2.isPointerConversionToBool()
1804 ? ImplicitConversionSequence::Better
1805 : ImplicitConversionSequence::Worse;
1806
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001807 // C++ [over.ics.rank]p4b2:
1808 //
1809 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001810 // conversion of B* to A* is better than conversion of B* to
1811 // void*, and conversion of A* to void* is better than conversion
1812 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00001813 bool SCS1ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001814 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001815 bool SCS2ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001816 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001817 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1818 // Exactly one of the conversion sequences is a conversion to
1819 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001820 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1821 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001822 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1823 // Neither conversion sequence converts to a void pointer; compare
1824 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001825 if (ImplicitConversionSequence::CompareKind DerivedCK
1826 = CompareDerivedToBaseConversions(SCS1, SCS2))
1827 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001828 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1829 // Both conversion sequences are conversions to void
1830 // pointers. Compare the source types to determine if there's an
1831 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00001832 QualType FromType1 = SCS1.getFromType();
1833 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001834
1835 // Adjust the types we're converting from via the array-to-pointer
1836 // conversion, if we need to.
1837 if (SCS1.First == ICK_Array_To_Pointer)
1838 FromType1 = Context.getArrayDecayedType(FromType1);
1839 if (SCS2.First == ICK_Array_To_Pointer)
1840 FromType2 = Context.getArrayDecayedType(FromType2);
1841
Douglas Gregor01919692009-12-13 21:37:05 +00001842 QualType FromPointee1
1843 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1844 QualType FromPointee2
1845 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001846
Douglas Gregor01919692009-12-13 21:37:05 +00001847 if (IsDerivedFrom(FromPointee2, FromPointee1))
1848 return ImplicitConversionSequence::Better;
1849 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1850 return ImplicitConversionSequence::Worse;
1851
1852 // Objective-C++: If one interface is more specific than the
1853 // other, it is the better one.
1854 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1855 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1856 if (FromIface1 && FromIface1) {
1857 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1858 return ImplicitConversionSequence::Better;
1859 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1860 return ImplicitConversionSequence::Worse;
1861 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001862 }
Douglas Gregor57373262008-10-22 14:17:15 +00001863
1864 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1865 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00001866 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001867 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001868 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001869
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001870 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001871 // C++0x [over.ics.rank]p3b4:
1872 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1873 // implicit object parameter of a non-static member function declared
1874 // without a ref-qualifier, and S1 binds an rvalue reference to an
1875 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00001876 // FIXME: We don't know if we're dealing with the implicit object parameter,
1877 // or if the member function in this case has a ref qualifier.
1878 // (Of course, we don't have ref qualifiers yet.)
1879 if (SCS1.RRefBinding != SCS2.RRefBinding)
1880 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1881 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001882
1883 // C++ [over.ics.rank]p3b4:
1884 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1885 // which the references refer are the same type except for
1886 // top-level cv-qualifiers, and the type to which the reference
1887 // initialized by S2 refers is more cv-qualified than the type
1888 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00001889 QualType T1 = SCS1.getToType(2);
1890 QualType T2 = SCS2.getToType(2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001891 T1 = Context.getCanonicalType(T1);
1892 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00001893 Qualifiers T1Quals, T2Quals;
1894 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1895 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1896 if (UnqualT1 == UnqualT2) {
1897 // If the type is an array type, promote the element qualifiers to the type
1898 // for comparison.
1899 if (isa<ArrayType>(T1) && T1Quals)
1900 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1901 if (isa<ArrayType>(T2) && T2Quals)
1902 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001903 if (T2.isMoreQualifiedThan(T1))
1904 return ImplicitConversionSequence::Better;
1905 else if (T1.isMoreQualifiedThan(T2))
1906 return ImplicitConversionSequence::Worse;
1907 }
1908 }
Douglas Gregor57373262008-10-22 14:17:15 +00001909
1910 return ImplicitConversionSequence::Indistinguishable;
1911}
1912
1913/// CompareQualificationConversions - Compares two standard conversion
1914/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00001915/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1916ImplicitConversionSequence::CompareKind
Douglas Gregor57373262008-10-22 14:17:15 +00001917Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump1eb44332009-09-09 15:08:12 +00001918 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00001919 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001920 // -- S1 and S2 differ only in their qualification conversion and
1921 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1922 // cv-qualification signature of type T1 is a proper subset of
1923 // the cv-qualification signature of type T2, and S1 is not the
1924 // deprecated string literal array-to-pointer conversion (4.2).
1925 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1926 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1927 return ImplicitConversionSequence::Indistinguishable;
1928
1929 // FIXME: the example in the standard doesn't use a qualification
1930 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00001931 QualType T1 = SCS1.getToType(2);
1932 QualType T2 = SCS2.getToType(2);
Douglas Gregor57373262008-10-22 14:17:15 +00001933 T1 = Context.getCanonicalType(T1);
1934 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00001935 Qualifiers T1Quals, T2Quals;
1936 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1937 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00001938
1939 // If the types are the same, we won't learn anything by unwrapped
1940 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00001941 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00001942 return ImplicitConversionSequence::Indistinguishable;
1943
Chandler Carruth28e318c2009-12-29 07:16:59 +00001944 // If the type is an array type, promote the element qualifiers to the type
1945 // for comparison.
1946 if (isa<ArrayType>(T1) && T1Quals)
1947 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1948 if (isa<ArrayType>(T2) && T2Quals)
1949 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
1950
Mike Stump1eb44332009-09-09 15:08:12 +00001951 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00001952 = ImplicitConversionSequence::Indistinguishable;
1953 while (UnwrapSimilarPointerTypes(T1, T2)) {
1954 // Within each iteration of the loop, we check the qualifiers to
1955 // determine if this still looks like a qualification
1956 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001957 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001958 // until there are no more pointers or pointers-to-members left
1959 // to unwrap. This essentially mimics what
1960 // IsQualificationConversion does, but here we're checking for a
1961 // strict subset of qualifiers.
1962 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1963 // The qualifiers are the same, so this doesn't tell us anything
1964 // about how the sequences rank.
1965 ;
1966 else if (T2.isMoreQualifiedThan(T1)) {
1967 // T1 has fewer qualifiers, so it could be the better sequence.
1968 if (Result == ImplicitConversionSequence::Worse)
1969 // Neither has qualifiers that are a subset of the other's
1970 // qualifiers.
1971 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001972
Douglas Gregor57373262008-10-22 14:17:15 +00001973 Result = ImplicitConversionSequence::Better;
1974 } else if (T1.isMoreQualifiedThan(T2)) {
1975 // T2 has fewer qualifiers, so it could be the better sequence.
1976 if (Result == ImplicitConversionSequence::Better)
1977 // Neither has qualifiers that are a subset of the other's
1978 // qualifiers.
1979 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001980
Douglas Gregor57373262008-10-22 14:17:15 +00001981 Result = ImplicitConversionSequence::Worse;
1982 } else {
1983 // Qualifiers are disjoint.
1984 return ImplicitConversionSequence::Indistinguishable;
1985 }
1986
1987 // If the types after this point are equivalent, we're done.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001988 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00001989 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001990 }
1991
Douglas Gregor57373262008-10-22 14:17:15 +00001992 // Check that the winning standard conversion sequence isn't using
1993 // the deprecated string literal array to pointer conversion.
1994 switch (Result) {
1995 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00001996 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00001997 Result = ImplicitConversionSequence::Indistinguishable;
1998 break;
1999
2000 case ImplicitConversionSequence::Indistinguishable:
2001 break;
2002
2003 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00002004 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002005 Result = ImplicitConversionSequence::Indistinguishable;
2006 break;
2007 }
2008
2009 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002010}
2011
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002012/// CompareDerivedToBaseConversions - Compares two standard conversion
2013/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00002014/// various kinds of derived-to-base conversions (C++
2015/// [over.ics.rank]p4b3). As part of these checks, we also look at
2016/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002017ImplicitConversionSequence::CompareKind
2018Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2019 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00002020 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002021 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00002022 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002023 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002024
2025 // Adjust the types we're converting from via the array-to-pointer
2026 // conversion, if we need to.
2027 if (SCS1.First == ICK_Array_To_Pointer)
2028 FromType1 = Context.getArrayDecayedType(FromType1);
2029 if (SCS2.First == ICK_Array_To_Pointer)
2030 FromType2 = Context.getArrayDecayedType(FromType2);
2031
2032 // Canonicalize all of the types.
2033 FromType1 = Context.getCanonicalType(FromType1);
2034 ToType1 = Context.getCanonicalType(ToType1);
2035 FromType2 = Context.getCanonicalType(FromType2);
2036 ToType2 = Context.getCanonicalType(ToType2);
2037
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002038 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002039 //
2040 // If class B is derived directly or indirectly from class A and
2041 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002042 //
2043 // For Objective-C, we let A, B, and C also be Objective-C
2044 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002045
2046 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00002047 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00002048 SCS2.Second == ICK_Pointer_Conversion &&
2049 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2050 FromType1->isPointerType() && FromType2->isPointerType() &&
2051 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002052 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002053 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002054 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002055 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002056 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002057 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002058 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002059 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002060
John McCall183700f2009-09-21 23:43:11 +00002061 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2062 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2063 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2064 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002065
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002066 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002067 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2068 if (IsDerivedFrom(ToPointee1, ToPointee2))
2069 return ImplicitConversionSequence::Better;
2070 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2071 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00002072
2073 if (ToIface1 && ToIface2) {
2074 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2075 return ImplicitConversionSequence::Better;
2076 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2077 return ImplicitConversionSequence::Worse;
2078 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002079 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002080
2081 // -- conversion of B* to A* is better than conversion of C* to A*,
2082 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2083 if (IsDerivedFrom(FromPointee2, FromPointee1))
2084 return ImplicitConversionSequence::Better;
2085 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2086 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Douglas Gregorcb7de522008-11-26 23:31:11 +00002088 if (FromIface1 && FromIface2) {
2089 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2090 return ImplicitConversionSequence::Better;
2091 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2092 return ImplicitConversionSequence::Worse;
2093 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002094 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002095 }
2096
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002097 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002098 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2099 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2100 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2101 const MemberPointerType * FromMemPointer1 =
2102 FromType1->getAs<MemberPointerType>();
2103 const MemberPointerType * ToMemPointer1 =
2104 ToType1->getAs<MemberPointerType>();
2105 const MemberPointerType * FromMemPointer2 =
2106 FromType2->getAs<MemberPointerType>();
2107 const MemberPointerType * ToMemPointer2 =
2108 ToType2->getAs<MemberPointerType>();
2109 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2110 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2111 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2112 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2113 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2114 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2115 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2116 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002117 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002118 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2119 if (IsDerivedFrom(ToPointee1, ToPointee2))
2120 return ImplicitConversionSequence::Worse;
2121 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2122 return ImplicitConversionSequence::Better;
2123 }
2124 // conversion of B::* to C::* is better than conversion of A::* to C::*
2125 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2126 if (IsDerivedFrom(FromPointee1, FromPointee2))
2127 return ImplicitConversionSequence::Better;
2128 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2129 return ImplicitConversionSequence::Worse;
2130 }
2131 }
2132
Douglas Gregor9e239322010-02-25 19:01:05 +00002133 if ((SCS1.ReferenceBinding || SCS1.CopyConstructor) &&
2134 (SCS2.ReferenceBinding || SCS2.CopyConstructor) &&
Douglas Gregor225c41e2008-11-03 19:09:14 +00002135 SCS1.Second == ICK_Derived_To_Base) {
2136 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00002137 // -- binding of an expression of type C to a reference of type
2138 // B& is better than binding an expression of type C to a
2139 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002140 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2141 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002142 if (IsDerivedFrom(ToType1, ToType2))
2143 return ImplicitConversionSequence::Better;
2144 else if (IsDerivedFrom(ToType2, ToType1))
2145 return ImplicitConversionSequence::Worse;
2146 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002147
Douglas Gregor225c41e2008-11-03 19:09:14 +00002148 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00002149 // -- binding of an expression of type B to a reference of type
2150 // A& is better than binding an expression of type C to a
2151 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002152 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2153 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002154 if (IsDerivedFrom(FromType2, FromType1))
2155 return ImplicitConversionSequence::Better;
2156 else if (IsDerivedFrom(FromType1, FromType2))
2157 return ImplicitConversionSequence::Worse;
2158 }
2159 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002160
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002161 return ImplicitConversionSequence::Indistinguishable;
2162}
2163
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002164/// TryCopyInitialization - Try to copy-initialize a value of type
2165/// ToType from the expression From. Return the implicit conversion
2166/// sequence required to pass this argument, which may be a bad
2167/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00002168/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redle2b68332009-04-12 17:16:29 +00002169/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2170/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump1eb44332009-09-09 15:08:12 +00002171ImplicitConversionSequence
2172Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002173 bool SuppressUserConversions, bool ForceRValue,
2174 bool InOverloadResolution) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00002175 if (ToType->isReferenceType()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002176 ImplicitConversionSequence ICS;
John McCallb1bdc622010-02-25 01:37:24 +00002177 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00002178 CheckReferenceInit(From, ToType,
Douglas Gregor739d8282009-09-23 23:04:10 +00002179 /*FIXME:*/From->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002180 SuppressUserConversions,
2181 /*AllowExplicit=*/false,
2182 ForceRValue,
2183 &ICS);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002184 return ICS;
2185 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002186 return TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002187 SuppressUserConversions,
2188 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002189 ForceRValue,
2190 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002191 }
2192}
2193
Sebastian Redle2b68332009-04-12 17:16:29 +00002194/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2195/// the expression @p From. Returns true (and emits a diagnostic) if there was
2196/// an error, returns false if the initialization succeeded. Elidable should
2197/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2198/// differently in C++0x for this case.
Mike Stump1eb44332009-09-09 15:08:12 +00002199bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00002200 AssignmentAction Action, bool Elidable) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002201 if (!getLangOptions().CPlusPlus) {
2202 // In C, argument passing is the same as performing an assignment.
2203 QualType FromType = From->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002204
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002205 AssignConvertType ConvTy =
2206 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00002207 if (ConvTy != Compatible &&
2208 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2209 ConvTy = Compatible;
Mike Stump1eb44332009-09-09 15:08:12 +00002210
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002211 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00002212 FromType, From, Action);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002213 }
Sebastian Redle2b68332009-04-12 17:16:29 +00002214
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002215 if (ToType->isReferenceType())
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002216 return CheckReferenceInit(From, ToType,
Douglas Gregor739d8282009-09-23 23:04:10 +00002217 /*FIXME:*/From->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002218 /*SuppressUserConversions=*/false,
2219 /*AllowExplicit=*/false,
2220 /*ForceRValue=*/false);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002221
Douglas Gregor68647482009-12-16 03:45:30 +00002222 if (!PerformImplicitConversion(From, ToType, Action,
Sebastian Redle2b68332009-04-12 17:16:29 +00002223 /*AllowExplicit=*/false, Elidable))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002224 return false;
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002225 if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
Fariborz Jahanian455acd92009-09-22 19:53:15 +00002226 return Diag(From->getSourceRange().getBegin(),
2227 diag::err_typecheck_convert_incompatible)
Douglas Gregor68647482009-12-16 03:45:30 +00002228 << ToType << From->getType() << Action << From->getSourceRange();
Fariborz Jahanian455acd92009-09-22 19:53:15 +00002229 return true;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002230}
2231
Douglas Gregor96176b32008-11-18 23:14:02 +00002232/// TryObjectArgumentInitialization - Try to initialize the object
2233/// parameter of the given member function (@c Method) from the
2234/// expression @p From.
2235ImplicitConversionSequence
John McCall651f3ee2010-01-14 03:28:57 +00002236Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall701c89e2009-12-03 04:06:58 +00002237 CXXMethodDecl *Method,
2238 CXXRecordDecl *ActingContext) {
2239 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002240 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2241 // const volatile object.
2242 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2243 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2244 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00002245
2246 // Set up the conversion sequence as a "bad" conversion, to allow us
2247 // to exit early.
2248 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00002249
2250 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00002251 QualType FromType = OrigFromType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002252 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00002253 FromType = PT->getPointeeType();
2254
2255 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002256
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002257 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00002258 // where X is the class of which the function is a member
2259 // (C++ [over.match.funcs]p4). However, when finding an implicit
2260 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00002261 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00002262 // (C++ [over.match.funcs]p5). We perform a simplified version of
2263 // reference binding here, that allows class rvalues to bind to
2264 // non-constant references.
2265
2266 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2267 // with the implicit object parameter (C++ [over.match.funcs]p5).
2268 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00002269 if (ImplicitParamType.getCVRQualifiers()
2270 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00002271 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00002272 ICS.setBad(BadConversionSequence::bad_qualifiers,
2273 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002274 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00002275 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002276
2277 // Check that we have either the same type or a derived type. It
2278 // affects the conversion rank.
2279 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00002280 ImplicitConversionKind SecondKind;
2281 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2282 SecondKind = ICK_Identity;
2283 } else if (IsDerivedFrom(FromType, ClassType))
2284 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00002285 else {
John McCallb1bdc622010-02-25 01:37:24 +00002286 ICS.setBad(BadConversionSequence::unrelated_class,
2287 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002288 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00002289 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002290
2291 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00002292 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00002293 ICS.Standard.setAsIdentityConversion();
2294 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00002295 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00002296 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002297 ICS.Standard.ReferenceBinding = true;
2298 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00002299 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002300 return ICS;
2301}
2302
2303/// PerformObjectArgumentInitialization - Perform initialization of
2304/// the implicit object parameter for the given Method with the given
2305/// expression.
2306bool
Douglas Gregora7cb22d2010-03-03 23:26:56 +00002307Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002308 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00002309 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00002310 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002311
Ted Kremenek6217b802009-07-29 21:53:49 +00002312 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002313 FromRecordType = PT->getPointeeType();
2314 DestType = Method->getThisType(Context);
2315 } else {
2316 FromRecordType = From->getType();
2317 DestType = ImplicitParamRecordType;
2318 }
2319
John McCall701c89e2009-12-03 04:06:58 +00002320 // Note that we always use the true parent context when performing
2321 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002322 ImplicitConversionSequence ICS
John McCall701c89e2009-12-03 04:06:58 +00002323 = TryObjectArgumentInitialization(From->getType(), Method,
2324 Method->getParent());
John McCall1d318332010-01-12 00:44:57 +00002325 if (ICS.isBad())
Douglas Gregor96176b32008-11-18 23:14:02 +00002326 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002327 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00002328 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002329
Douglas Gregora7cb22d2010-03-03 23:26:56 +00002330 if (ICS.Standard.Second == ICK_Derived_To_Base &&
2331 CheckDerivedToBaseConversion(FromRecordType,
2332 ImplicitParamRecordType,
2333 From->getSourceRange().getBegin(),
2334 From->getSourceRange()))
2335 return true;
Douglas Gregor96176b32008-11-18 23:14:02 +00002336
Douglas Gregora7cb22d2010-03-03 23:26:56 +00002337 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
2338 /*isLvalue=*/true);
Douglas Gregor96176b32008-11-18 23:14:02 +00002339 return false;
2340}
2341
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002342/// TryContextuallyConvertToBool - Attempt to contextually convert the
2343/// expression From to bool (C++0x [conv]p3).
2344ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump1eb44332009-09-09 15:08:12 +00002345 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002346 // FIXME: Are these flags correct?
2347 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00002348 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00002349 /*ForceRValue=*/false,
2350 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002351}
2352
2353/// PerformContextuallyConvertToBool - Perform a contextual conversion
2354/// of the expression From to bool (C++0x [conv]p3).
2355bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2356 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall1d318332010-01-12 00:44:57 +00002357 if (!ICS.isBad())
2358 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002359
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002360 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002361 return Diag(From->getSourceRange().getBegin(),
2362 diag::err_typecheck_bool_condition)
2363 << From->getType() << From->getSourceRange();
2364 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002365}
2366
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002367/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00002368/// candidate functions, using the given function call arguments. If
2369/// @p SuppressUserConversions, then don't allow user-defined
2370/// conversions via constructors or conversion operators.
Sebastian Redle2b68332009-04-12 17:16:29 +00002371/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2372/// hacky way to implement the overloading rules for elidable copy
2373/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002374///
2375/// \para PartialOverloading true if we are performing "partial" overloading
2376/// based on an incomplete set of function arguments. This feature is used by
2377/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00002378void
2379Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall86820f52010-01-26 01:37:31 +00002380 AccessSpecifier Access,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002381 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002382 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00002383 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002384 bool ForceRValue,
2385 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00002386 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002387 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002388 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00002389 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00002390 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00002391
Douglas Gregor88a35142008-12-22 05:46:06 +00002392 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002393 if (!isa<CXXConstructorDecl>(Method)) {
2394 // If we get here, it's because we're calling a member function
2395 // that is named without a member access expression (e.g.,
2396 // "this->f") that was either written explicitly or created
2397 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00002398 // function, e.g., X::f(). We use an empty type for the implied
2399 // object argument (C++ [over.call.func]p3), and the acting context
2400 // is irrelevant.
John McCall86820f52010-01-26 01:37:31 +00002401 AddMethodCandidate(Method, Access, Method->getParent(),
John McCall701c89e2009-12-03 04:06:58 +00002402 QualType(), Args, NumArgs, CandidateSet,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002403 SuppressUserConversions, ForceRValue);
2404 return;
2405 }
2406 // We treat a constructor like a non-member function, since its object
2407 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00002408 }
2409
Douglas Gregorfd476482009-11-13 23:59:09 +00002410 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00002411 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00002412
Douglas Gregor7edfb692009-11-23 12:27:39 +00002413 // Overload resolution is always an unevaluated context.
2414 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2415
Douglas Gregor66724ea2009-11-14 01:20:54 +00002416 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2417 // C++ [class.copy]p3:
2418 // A member function template is never instantiated to perform the copy
2419 // of a class object to an object of its class type.
2420 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2421 if (NumArgs == 1 &&
2422 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor12116062010-02-21 18:30:38 +00002423 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
2424 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00002425 return;
2426 }
2427
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002428 // Add this candidate
2429 CandidateSet.push_back(OverloadCandidate());
2430 OverloadCandidate& Candidate = CandidateSet.back();
2431 Candidate.Function = Function;
John McCall86820f52010-01-26 01:37:31 +00002432 Candidate.Access = Access;
Douglas Gregor88a35142008-12-22 05:46:06 +00002433 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002434 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002435 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002436
2437 unsigned NumArgsInProto = Proto->getNumArgs();
2438
2439 // (C++ 13.3.2p2): A candidate function having fewer than m
2440 // parameters is viable only if it has an ellipsis in its parameter
2441 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00002442 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2443 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002444 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002445 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002446 return;
2447 }
2448
2449 // (C++ 13.3.2p2): A candidate function having more than m parameters
2450 // is viable only if the (m+1)st parameter has a default argument
2451 // (8.3.6). For the purposes of overload resolution, the
2452 // parameter list is truncated on the right, so that there are
2453 // exactly m parameters.
2454 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002455 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002456 // Not enough arguments.
2457 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002458 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002459 return;
2460 }
2461
2462 // Determine the implicit conversion sequences for each of the
2463 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002464 Candidate.Conversions.resize(NumArgs);
2465 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2466 if (ArgIdx < NumArgsInProto) {
2467 // (C++ 13.3.2p3): for F to be a viable function, there shall
2468 // exist for each argument an implicit conversion sequence
2469 // (13.3.3.1) that converts that argument to the corresponding
2470 // parameter of F.
2471 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002472 Candidate.Conversions[ArgIdx]
2473 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002474 SuppressUserConversions, ForceRValue,
2475 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00002476 if (Candidate.Conversions[ArgIdx].isBad()) {
2477 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002478 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00002479 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00002480 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002481 } else {
2482 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2483 // argument for which there is no corresponding parameter is
2484 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00002485 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002486 }
2487 }
2488}
2489
Douglas Gregor063daf62009-03-13 18:40:31 +00002490/// \brief Add all of the function declarations in the given function set to
2491/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00002492void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00002493 Expr **Args, unsigned NumArgs,
2494 OverloadCandidateSet& CandidateSet,
2495 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00002496 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall701c89e2009-12-03 04:06:58 +00002497 // FIXME: using declarations
Douglas Gregor3f396022009-09-28 04:47:19 +00002498 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2499 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall6e266892010-01-26 03:27:55 +00002500 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getAccess(),
John McCall701c89e2009-12-03 04:06:58 +00002501 cast<CXXMethodDecl>(FD)->getParent(),
2502 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00002503 CandidateSet, SuppressUserConversions);
2504 else
John McCall86820f52010-01-26 01:37:31 +00002505 AddOverloadCandidate(FD, AS_none, Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00002506 SuppressUserConversions);
2507 } else {
2508 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2509 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2510 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall6e266892010-01-26 03:27:55 +00002511 AddMethodTemplateCandidate(FunTmpl, F.getAccess(),
John McCall701c89e2009-12-03 04:06:58 +00002512 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00002513 /*FIXME: explicit args */ 0,
John McCall701c89e2009-12-03 04:06:58 +00002514 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00002515 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00002516 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00002517 else
John McCall86820f52010-01-26 01:37:31 +00002518 AddTemplateOverloadCandidate(FunTmpl, AS_none,
John McCalld5532b62009-11-23 01:53:49 +00002519 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00002520 Args, NumArgs, CandidateSet,
2521 SuppressUserConversions);
2522 }
Douglas Gregor364e0212009-06-27 21:05:07 +00002523 }
Douglas Gregor063daf62009-03-13 18:40:31 +00002524}
2525
John McCall314be4e2009-11-17 07:50:12 +00002526/// AddMethodCandidate - Adds a named decl (which is some kind of
2527/// method) as a method candidate to the given overload set.
John McCall701c89e2009-12-03 04:06:58 +00002528void Sema::AddMethodCandidate(NamedDecl *Decl,
John McCall86820f52010-01-26 01:37:31 +00002529 AccessSpecifier Access,
John McCall701c89e2009-12-03 04:06:58 +00002530 QualType ObjectType,
John McCall314be4e2009-11-17 07:50:12 +00002531 Expr **Args, unsigned NumArgs,
2532 OverloadCandidateSet& CandidateSet,
2533 bool SuppressUserConversions, bool ForceRValue) {
John McCall701c89e2009-12-03 04:06:58 +00002534 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00002535
2536 if (isa<UsingShadowDecl>(Decl))
2537 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2538
2539 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2540 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2541 "Expected a member function template");
John McCall86820f52010-01-26 01:37:31 +00002542 AddMethodTemplateCandidate(TD, Access, ActingContext, /*ExplicitArgs*/ 0,
John McCall701c89e2009-12-03 04:06:58 +00002543 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00002544 CandidateSet,
2545 SuppressUserConversions,
2546 ForceRValue);
2547 } else {
John McCall86820f52010-01-26 01:37:31 +00002548 AddMethodCandidate(cast<CXXMethodDecl>(Decl), Access, ActingContext,
John McCall701c89e2009-12-03 04:06:58 +00002549 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00002550 CandidateSet, SuppressUserConversions, ForceRValue);
2551 }
2552}
2553
Douglas Gregor96176b32008-11-18 23:14:02 +00002554/// AddMethodCandidate - Adds the given C++ member function to the set
2555/// of candidate functions, using the given function call arguments
2556/// and the object argument (@c Object). For example, in a call
2557/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2558/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2559/// allow user-defined conversions via constructors or conversion
Sebastian Redle2b68332009-04-12 17:16:29 +00002560/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2561/// a slightly hacky way to implement the overloading rules for elidable copy
2562/// initialization in C++0x (C++0x 12.8p15).
Mike Stump1eb44332009-09-09 15:08:12 +00002563void
John McCall86820f52010-01-26 01:37:31 +00002564Sema::AddMethodCandidate(CXXMethodDecl *Method, AccessSpecifier Access,
2565 CXXRecordDecl *ActingContext, QualType ObjectType,
2566 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00002567 OverloadCandidateSet& CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00002568 bool SuppressUserConversions, bool ForceRValue) {
2569 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002570 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00002571 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002572 assert(!isa<CXXConstructorDecl>(Method) &&
2573 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00002574
Douglas Gregor3f396022009-09-28 04:47:19 +00002575 if (!CandidateSet.isNewCandidate(Method))
2576 return;
2577
Douglas Gregor7edfb692009-11-23 12:27:39 +00002578 // Overload resolution is always an unevaluated context.
2579 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2580
Douglas Gregor96176b32008-11-18 23:14:02 +00002581 // Add this candidate
2582 CandidateSet.push_back(OverloadCandidate());
2583 OverloadCandidate& Candidate = CandidateSet.back();
2584 Candidate.Function = Method;
John McCall86820f52010-01-26 01:37:31 +00002585 Candidate.Access = Access;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002586 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002587 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002588
2589 unsigned NumArgsInProto = Proto->getNumArgs();
2590
2591 // (C++ 13.3.2p2): A candidate function having fewer than m
2592 // parameters is viable only if it has an ellipsis in its parameter
2593 // list (8.3.5).
2594 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2595 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002596 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00002597 return;
2598 }
2599
2600 // (C++ 13.3.2p2): A candidate function having more than m parameters
2601 // is viable only if the (m+1)st parameter has a default argument
2602 // (8.3.6). For the purposes of overload resolution, the
2603 // parameter list is truncated on the right, so that there are
2604 // exactly m parameters.
2605 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2606 if (NumArgs < MinRequiredArgs) {
2607 // Not enough arguments.
2608 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002609 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00002610 return;
2611 }
2612
2613 Candidate.Viable = true;
2614 Candidate.Conversions.resize(NumArgs + 1);
2615
John McCall701c89e2009-12-03 04:06:58 +00002616 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00002617 // The implicit object argument is ignored.
2618 Candidate.IgnoreObjectArgument = true;
2619 else {
2620 // Determine the implicit conversion sequence for the object
2621 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00002622 Candidate.Conversions[0]
2623 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00002624 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002625 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002626 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00002627 return;
2628 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002629 }
2630
2631 // Determine the implicit conversion sequences for each of the
2632 // arguments.
2633 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2634 if (ArgIdx < NumArgsInProto) {
2635 // (C++ 13.3.2p3): for F to be a viable function, there shall
2636 // exist for each argument an implicit conversion sequence
2637 // (13.3.3.1) that converts that argument to the corresponding
2638 // parameter of F.
2639 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002640 Candidate.Conversions[ArgIdx + 1]
2641 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002642 SuppressUserConversions, ForceRValue,
Anders Carlsson08972922009-08-28 15:33:32 +00002643 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00002644 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002645 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002646 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00002647 break;
2648 }
2649 } else {
2650 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2651 // argument for which there is no corresponding parameter is
2652 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00002653 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00002654 }
2655 }
2656}
2657
Douglas Gregor6b906862009-08-21 00:16:32 +00002658/// \brief Add a C++ member function template as a candidate to the candidate
2659/// set, using template argument deduction to produce an appropriate member
2660/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002661void
Douglas Gregor6b906862009-08-21 00:16:32 +00002662Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall86820f52010-01-26 01:37:31 +00002663 AccessSpecifier Access,
John McCall701c89e2009-12-03 04:06:58 +00002664 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00002665 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00002666 QualType ObjectType,
2667 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002668 OverloadCandidateSet& CandidateSet,
2669 bool SuppressUserConversions,
2670 bool ForceRValue) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002671 if (!CandidateSet.isNewCandidate(MethodTmpl))
2672 return;
2673
Douglas Gregor6b906862009-08-21 00:16:32 +00002674 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002675 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00002676 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002677 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00002678 // candidate functions in the usual way.113) A given name can refer to one
2679 // or more function templates and also to a set of overloaded non-template
2680 // functions. In such a case, the candidate functions generated from each
2681 // function template are combined with the set of non-template candidate
2682 // functions.
John McCall5769d612010-02-08 23:07:23 +00002683 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00002684 FunctionDecl *Specialization = 0;
2685 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00002686 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002687 Args, NumArgs, Specialization, Info)) {
2688 // FIXME: Record what happened with template argument deduction, so
2689 // that we can give the user a beautiful diagnostic.
2690 (void)Result;
2691 return;
2692 }
Mike Stump1eb44332009-09-09 15:08:12 +00002693
Douglas Gregor6b906862009-08-21 00:16:32 +00002694 // Add the function template specialization produced by template argument
2695 // deduction as a candidate.
2696 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00002697 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00002698 "Specialization is not a member function?");
John McCall86820f52010-01-26 01:37:31 +00002699 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Access,
2700 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002701 CandidateSet, SuppressUserConversions, ForceRValue);
2702}
2703
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002704/// \brief Add a C++ function template specialization as a candidate
2705/// in the candidate set, using template argument deduction to produce
2706/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002707void
Douglas Gregore53060f2009-06-25 22:08:12 +00002708Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall86820f52010-01-26 01:37:31 +00002709 AccessSpecifier Access,
John McCalld5532b62009-11-23 01:53:49 +00002710 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002711 Expr **Args, unsigned NumArgs,
2712 OverloadCandidateSet& CandidateSet,
2713 bool SuppressUserConversions,
2714 bool ForceRValue) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002715 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2716 return;
2717
Douglas Gregore53060f2009-06-25 22:08:12 +00002718 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002719 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00002720 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002721 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00002722 // candidate functions in the usual way.113) A given name can refer to one
2723 // or more function templates and also to a set of overloaded non-template
2724 // functions. In such a case, the candidate functions generated from each
2725 // function template are combined with the set of non-template candidate
2726 // functions.
John McCall5769d612010-02-08 23:07:23 +00002727 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00002728 FunctionDecl *Specialization = 0;
2729 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00002730 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002731 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00002732 CandidateSet.push_back(OverloadCandidate());
2733 OverloadCandidate &Candidate = CandidateSet.back();
2734 Candidate.Function = FunctionTemplate->getTemplatedDecl();
John McCall86820f52010-01-26 01:37:31 +00002735 Candidate.Access = Access;
John McCall578b69b2009-12-16 08:11:27 +00002736 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002737 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00002738 Candidate.IsSurrogate = false;
2739 Candidate.IgnoreObjectArgument = false;
John McCall342fec42010-02-01 18:53:26 +00002740
2741 // TODO: record more information about failed template arguments
2742 Candidate.DeductionFailure.Result = Result;
2743 Candidate.DeductionFailure.TemplateParameter = Info.Param.getOpaqueValue();
Douglas Gregore53060f2009-06-25 22:08:12 +00002744 return;
2745 }
Mike Stump1eb44332009-09-09 15:08:12 +00002746
Douglas Gregore53060f2009-06-25 22:08:12 +00002747 // Add the function template specialization produced by template argument
2748 // deduction as a candidate.
2749 assert(Specialization && "Missing function template specialization?");
John McCall86820f52010-01-26 01:37:31 +00002750 AddOverloadCandidate(Specialization, Access, Args, NumArgs, CandidateSet,
Douglas Gregore53060f2009-06-25 22:08:12 +00002751 SuppressUserConversions, ForceRValue);
2752}
Mike Stump1eb44332009-09-09 15:08:12 +00002753
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002754/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00002755/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002756/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00002757/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002758/// (which may or may not be the same type as the type that the
2759/// conversion function produces).
2760void
2761Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall86820f52010-01-26 01:37:31 +00002762 AccessSpecifier Access,
John McCall701c89e2009-12-03 04:06:58 +00002763 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002764 Expr *From, QualType ToType,
2765 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002766 assert(!Conversion->getDescribedFunctionTemplate() &&
2767 "Conversion function templates use AddTemplateConversionCandidate");
2768
Douglas Gregor3f396022009-09-28 04:47:19 +00002769 if (!CandidateSet.isNewCandidate(Conversion))
2770 return;
2771
Douglas Gregor7edfb692009-11-23 12:27:39 +00002772 // Overload resolution is always an unevaluated context.
2773 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2774
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002775 // Add this candidate
2776 CandidateSet.push_back(OverloadCandidate());
2777 OverloadCandidate& Candidate = CandidateSet.back();
2778 Candidate.Function = Conversion;
John McCall86820f52010-01-26 01:37:31 +00002779 Candidate.Access = Access;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002780 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002781 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002782 Candidate.FinalConversion.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +00002783 Candidate.FinalConversion.setFromType(Conversion->getConversionType());
Douglas Gregorad323a82010-01-27 03:51:04 +00002784 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002785
Douglas Gregor96176b32008-11-18 23:14:02 +00002786 // Determine the implicit conversion sequence for the implicit
2787 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002788 Candidate.Viable = true;
2789 Candidate.Conversions.resize(1);
John McCall701c89e2009-12-03 04:06:58 +00002790 Candidate.Conversions[0]
2791 = TryObjectArgumentInitialization(From->getType(), Conversion,
2792 ActingContext);
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002793 // Conversion functions to a different type in the base class is visible in
2794 // the derived class. So, a derived to base conversion should not participate
2795 // in overload resolution.
2796 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2797 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall1d318332010-01-12 00:44:57 +00002798 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002799 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002800 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002801 return;
2802 }
Fariborz Jahanian3759a032009-10-19 19:18:20 +00002803
2804 // We won't go through a user-define type conversion function to convert a
2805 // derived to base as such conversions are given Conversion Rank. They only
2806 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2807 QualType FromCanon
2808 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2809 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2810 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2811 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00002812 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00002813 return;
2814 }
2815
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002816
2817 // To determine what the conversion from the result of calling the
2818 // conversion function to the type we're eventually trying to
2819 // convert to (ToType), we need to synthesize a call to the
2820 // conversion function and attempt copy initialization from it. This
2821 // makes sure that we get the right semantics with respect to
2822 // lvalues/rvalues and the type. Fortunately, we can allocate this
2823 // call on the stack and we don't need its arguments to be
2824 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00002825 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00002826 From->getLocStart());
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002827 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman73c39ab2009-10-20 08:27:19 +00002828 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002829 &ConversionRef, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002830
2831 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00002832 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2833 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00002834 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002835 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00002836 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00002837 ImplicitConversionSequence ICS =
2838 TryCopyInitialization(&Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002839 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002840 /*ForceRValue=*/false,
2841 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002842
John McCall1d318332010-01-12 00:44:57 +00002843 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002844 case ImplicitConversionSequence::StandardConversion:
2845 Candidate.FinalConversion = ICS.Standard;
2846 break;
2847
2848 case ImplicitConversionSequence::BadConversion:
2849 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00002850 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002851 break;
2852
2853 default:
Mike Stump1eb44332009-09-09 15:08:12 +00002854 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002855 "Can only end up with a standard conversion sequence or failure");
2856 }
2857}
2858
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002859/// \brief Adds a conversion function template specialization
2860/// candidate to the overload set, using template argument deduction
2861/// to deduce the template arguments of the conversion function
2862/// template from the type that we are converting to (C++
2863/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00002864void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002865Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall86820f52010-01-26 01:37:31 +00002866 AccessSpecifier Access,
John McCall701c89e2009-12-03 04:06:58 +00002867 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002868 Expr *From, QualType ToType,
2869 OverloadCandidateSet &CandidateSet) {
2870 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2871 "Only conversion function templates permitted here");
2872
Douglas Gregor3f396022009-09-28 04:47:19 +00002873 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2874 return;
2875
John McCall5769d612010-02-08 23:07:23 +00002876 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002877 CXXConversionDecl *Specialization = 0;
2878 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00002879 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002880 Specialization, Info)) {
2881 // FIXME: Record what happened with template argument deduction, so
2882 // that we can give the user a beautiful diagnostic.
2883 (void)Result;
2884 return;
2885 }
Mike Stump1eb44332009-09-09 15:08:12 +00002886
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002887 // Add the conversion function template specialization produced by
2888 // template argument deduction as a candidate.
2889 assert(Specialization && "Missing function template specialization?");
John McCall86820f52010-01-26 01:37:31 +00002890 AddConversionCandidate(Specialization, Access, ActingDC, From, ToType,
2891 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002892}
2893
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002894/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2895/// converts the given @c Object to a function pointer via the
2896/// conversion function @c Conversion, and then attempts to call it
2897/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2898/// the type of function that we'll eventually be calling.
2899void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall86820f52010-01-26 01:37:31 +00002900 AccessSpecifier Access,
John McCall701c89e2009-12-03 04:06:58 +00002901 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00002902 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00002903 QualType ObjectType,
2904 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002905 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002906 if (!CandidateSet.isNewCandidate(Conversion))
2907 return;
2908
Douglas Gregor7edfb692009-11-23 12:27:39 +00002909 // Overload resolution is always an unevaluated context.
2910 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2911
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002912 CandidateSet.push_back(OverloadCandidate());
2913 OverloadCandidate& Candidate = CandidateSet.back();
2914 Candidate.Function = 0;
John McCall86820f52010-01-26 01:37:31 +00002915 Candidate.Access = Access;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002916 Candidate.Surrogate = Conversion;
2917 Candidate.Viable = true;
2918 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002919 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002920 Candidate.Conversions.resize(NumArgs + 1);
2921
2922 // Determine the implicit conversion sequence for the implicit
2923 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00002924 ImplicitConversionSequence ObjectInit
John McCall701c89e2009-12-03 04:06:58 +00002925 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00002926 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002927 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002928 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00002929 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002930 return;
2931 }
2932
2933 // The first conversion is actually a user-defined conversion whose
2934 // first conversion is ObjectInit's standard conversion (which is
2935 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00002936 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002937 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002938 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002939 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00002940 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002941 = Candidate.Conversions[0].UserDefined.Before;
2942 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2943
Mike Stump1eb44332009-09-09 15:08:12 +00002944 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002945 unsigned NumArgsInProto = Proto->getNumArgs();
2946
2947 // (C++ 13.3.2p2): A candidate function having fewer than m
2948 // parameters is viable only if it has an ellipsis in its parameter
2949 // list (8.3.5).
2950 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2951 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002952 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002953 return;
2954 }
2955
2956 // Function types don't have any default arguments, so just check if
2957 // we have enough arguments.
2958 if (NumArgs < NumArgsInProto) {
2959 // Not enough arguments.
2960 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002961 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002962 return;
2963 }
2964
2965 // Determine the implicit conversion sequences for each of the
2966 // arguments.
2967 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2968 if (ArgIdx < NumArgsInProto) {
2969 // (C++ 13.3.2p3): for F to be a viable function, there shall
2970 // exist for each argument an implicit conversion sequence
2971 // (13.3.3.1) that converts that argument to the corresponding
2972 // parameter of F.
2973 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002974 Candidate.Conversions[ArgIdx + 1]
2975 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002976 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002977 /*ForceRValue=*/false,
2978 /*InOverloadResolution=*/false);
John McCall1d318332010-01-12 00:44:57 +00002979 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002980 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00002981 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002982 break;
2983 }
2984 } else {
2985 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2986 // argument for which there is no corresponding parameter is
2987 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00002988 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002989 }
2990 }
2991}
2992
Mike Stump390b4cc2009-05-16 07:39:55 +00002993// FIXME: This will eventually be removed, once we've migrated all of the
2994// operator overloading logic over to the scheme used by binary operators, which
2995// works for template instantiation.
Douglas Gregor063daf62009-03-13 18:40:31 +00002996void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002997 SourceLocation OpLoc,
Douglas Gregor96176b32008-11-18 23:14:02 +00002998 Expr **Args, unsigned NumArgs,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002999 OverloadCandidateSet& CandidateSet,
3000 SourceRange OpRange) {
John McCall6e266892010-01-26 03:27:55 +00003001 UnresolvedSet<16> Fns;
Douglas Gregor063daf62009-03-13 18:40:31 +00003002
3003 QualType T1 = Args[0]->getType();
3004 QualType T2;
3005 if (NumArgs > 1)
3006 T2 = Args[1]->getType();
3007
3008 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor3384c9c2009-05-19 00:01:19 +00003009 if (S)
John McCall6e266892010-01-26 03:27:55 +00003010 LookupOverloadedOperatorName(Op, S, T1, T2, Fns);
3011 AddFunctionCandidates(Fns, Args, NumArgs, CandidateSet, false);
3012 AddArgumentDependentLookupCandidates(OpName, false, Args, NumArgs, 0,
3013 CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00003014 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregor573d9c32009-10-21 23:19:44 +00003015 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00003016}
3017
3018/// \brief Add overload candidates for overloaded operators that are
3019/// member functions.
3020///
3021/// Add the overloaded operator candidates that are member functions
3022/// for the operator Op that was used in an operator expression such
3023/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3024/// CandidateSet will store the added overload candidates. (C++
3025/// [over.match.oper]).
3026void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3027 SourceLocation OpLoc,
3028 Expr **Args, unsigned NumArgs,
3029 OverloadCandidateSet& CandidateSet,
3030 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003031 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3032
3033 // C++ [over.match.oper]p3:
3034 // For a unary operator @ with an operand of a type whose
3035 // cv-unqualified version is T1, and for a binary operator @ with
3036 // a left operand of a type whose cv-unqualified version is T1 and
3037 // a right operand of a type whose cv-unqualified version is T2,
3038 // three sets of candidate functions, designated member
3039 // candidates, non-member candidates and built-in candidates, are
3040 // constructed as follows:
3041 QualType T1 = Args[0]->getType();
3042 QualType T2;
3043 if (NumArgs > 1)
3044 T2 = Args[1]->getType();
3045
3046 // -- If T1 is a class type, the set of member candidates is the
3047 // result of the qualified lookup of T1::operator@
3048 // (13.3.1.1.1); otherwise, the set of member candidates is
3049 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00003050 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003051 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003052 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003053 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003054
John McCalla24dc2e2009-11-17 02:14:36 +00003055 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3056 LookupQualifiedName(Operators, T1Rec->getDecl());
3057 Operators.suppressDiagnostics();
3058
Mike Stump1eb44332009-09-09 15:08:12 +00003059 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003060 OperEnd = Operators.end();
3061 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00003062 ++Oper)
John McCall86820f52010-01-26 01:37:31 +00003063 AddMethodCandidate(*Oper, Oper.getAccess(), Args[0]->getType(),
John McCall701c89e2009-12-03 04:06:58 +00003064 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00003065 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00003066 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003067}
3068
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003069/// AddBuiltinCandidate - Add a candidate for a built-in
3070/// operator. ResultTy and ParamTys are the result and parameter types
3071/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003072/// arguments being passed to the candidate. IsAssignmentOperator
3073/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003074/// operator. NumContextualBoolArguments is the number of arguments
3075/// (at the beginning of the argument list) that will be contextually
3076/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00003077void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003078 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003079 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003080 bool IsAssignmentOperator,
3081 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00003082 // Overload resolution is always an unevaluated context.
3083 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3084
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003085 // Add this candidate
3086 CandidateSet.push_back(OverloadCandidate());
3087 OverloadCandidate& Candidate = CandidateSet.back();
3088 Candidate.Function = 0;
John McCall86820f52010-01-26 01:37:31 +00003089 Candidate.Access = AS_none;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003090 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003091 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003092 Candidate.BuiltinTypes.ResultTy = ResultTy;
3093 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3094 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3095
3096 // Determine the implicit conversion sequences for each of the
3097 // arguments.
3098 Candidate.Viable = true;
3099 Candidate.Conversions.resize(NumArgs);
3100 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003101 // C++ [over.match.oper]p4:
3102 // For the built-in assignment operators, conversions of the
3103 // left operand are restricted as follows:
3104 // -- no temporaries are introduced to hold the left operand, and
3105 // -- no user-defined conversions are applied to the left
3106 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00003107 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003108 //
3109 // We block these conversions by turning off user-defined
3110 // conversions, since that is the only way that initialization of
3111 // a reference to a non-class type can occur from something that
3112 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003113 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00003114 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003115 "Contextual conversion to bool requires bool type");
3116 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3117 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003118 Candidate.Conversions[ArgIdx]
3119 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00003120 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003121 /*ForceRValue=*/false,
3122 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003123 }
John McCall1d318332010-01-12 00:44:57 +00003124 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003125 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003126 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003127 break;
3128 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003129 }
3130}
3131
3132/// BuiltinCandidateTypeSet - A set of types that will be used for the
3133/// candidate operator functions for built-in operators (C++
3134/// [over.built]). The types are separated into pointer types and
3135/// enumeration types.
3136class BuiltinCandidateTypeSet {
3137 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003138 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003139
3140 /// PointerTypes - The set of pointer types that will be used in the
3141 /// built-in candidates.
3142 TypeSet PointerTypes;
3143
Sebastian Redl78eb8742009-04-19 21:53:20 +00003144 /// MemberPointerTypes - The set of member pointer types that will be
3145 /// used in the built-in candidates.
3146 TypeSet MemberPointerTypes;
3147
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003148 /// EnumerationTypes - The set of enumeration types that will be
3149 /// used in the built-in candidates.
3150 TypeSet EnumerationTypes;
3151
Douglas Gregor5842ba92009-08-24 15:23:48 +00003152 /// Sema - The semantic analysis instance where we are building the
3153 /// candidate type set.
3154 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00003155
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003156 /// Context - The AST context in which we will build the type sets.
3157 ASTContext &Context;
3158
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003159 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3160 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00003161 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003162
3163public:
3164 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003165 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003166
Mike Stump1eb44332009-09-09 15:08:12 +00003167 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00003168 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003169
Douglas Gregor573d9c32009-10-21 23:19:44 +00003170 void AddTypesConvertedFrom(QualType Ty,
3171 SourceLocation Loc,
3172 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003173 bool AllowExplicitConversions,
3174 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003175
3176 /// pointer_begin - First pointer type found;
3177 iterator pointer_begin() { return PointerTypes.begin(); }
3178
Sebastian Redl78eb8742009-04-19 21:53:20 +00003179 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003180 iterator pointer_end() { return PointerTypes.end(); }
3181
Sebastian Redl78eb8742009-04-19 21:53:20 +00003182 /// member_pointer_begin - First member pointer type found;
3183 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3184
3185 /// member_pointer_end - Past the last member pointer type found;
3186 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3187
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003188 /// enumeration_begin - First enumeration type found;
3189 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3190
Sebastian Redl78eb8742009-04-19 21:53:20 +00003191 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003192 iterator enumeration_end() { return EnumerationTypes.end(); }
3193};
3194
Sebastian Redl78eb8742009-04-19 21:53:20 +00003195/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003196/// the set of pointer types along with any more-qualified variants of
3197/// that type. For example, if @p Ty is "int const *", this routine
3198/// will add "int const *", "int const volatile *", "int const
3199/// restrict *", and "int const volatile restrict *" to the set of
3200/// pointer types. Returns true if the add of @p Ty itself succeeded,
3201/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003202///
3203/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003204bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00003205BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3206 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00003207
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003208 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003209 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003210 return false;
3211
John McCall0953e762009-09-24 19:53:00 +00003212 const PointerType *PointerTy = Ty->getAs<PointerType>();
3213 assert(PointerTy && "type was not a pointer type!");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003214
John McCall0953e762009-09-24 19:53:00 +00003215 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003216 // Don't add qualified variants of arrays. For one, they're not allowed
3217 // (the qualifier would sink to the element type), and for another, the
3218 // only overload situation where it matters is subscript or pointer +- int,
3219 // and those shouldn't have qualifier variants anyway.
3220 if (PointeeTy->isArrayType())
3221 return true;
John McCall0953e762009-09-24 19:53:00 +00003222 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00003223 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00003224 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003225 bool hasVolatile = VisibleQuals.hasVolatile();
3226 bool hasRestrict = VisibleQuals.hasRestrict();
3227
John McCall0953e762009-09-24 19:53:00 +00003228 // Iterate through all strict supersets of BaseCVR.
3229 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3230 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003231 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3232 // in the types.
3233 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3234 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00003235 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3236 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003237 }
3238
3239 return true;
3240}
3241
Sebastian Redl78eb8742009-04-19 21:53:20 +00003242/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3243/// to the set of pointer types along with any more-qualified variants of
3244/// that type. For example, if @p Ty is "int const *", this routine
3245/// will add "int const *", "int const volatile *", "int const
3246/// restrict *", and "int const volatile restrict *" to the set of
3247/// pointer types. Returns true if the add of @p Ty itself succeeded,
3248/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003249///
3250/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003251bool
3252BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3253 QualType Ty) {
3254 // Insert this type.
3255 if (!MemberPointerTypes.insert(Ty))
3256 return false;
3257
John McCall0953e762009-09-24 19:53:00 +00003258 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3259 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00003260
John McCall0953e762009-09-24 19:53:00 +00003261 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003262 // Don't add qualified variants of arrays. For one, they're not allowed
3263 // (the qualifier would sink to the element type), and for another, the
3264 // only overload situation where it matters is subscript or pointer +- int,
3265 // and those shouldn't have qualifier variants anyway.
3266 if (PointeeTy->isArrayType())
3267 return true;
John McCall0953e762009-09-24 19:53:00 +00003268 const Type *ClassTy = PointerTy->getClass();
3269
3270 // Iterate through all strict supersets of the pointee type's CVR
3271 // qualifiers.
3272 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3273 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3274 if ((CVR | BaseCVR) != CVR) continue;
3275
3276 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3277 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00003278 }
3279
3280 return true;
3281}
3282
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003283/// AddTypesConvertedFrom - Add each of the types to which the type @p
3284/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00003285/// primarily interested in pointer types and enumeration types. We also
3286/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003287/// AllowUserConversions is true if we should look at the conversion
3288/// functions of a class type, and AllowExplicitConversions if we
3289/// should also include the explicit conversion functions of a class
3290/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003291void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003292BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003293 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003294 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003295 bool AllowExplicitConversions,
3296 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003297 // Only deal with canonical types.
3298 Ty = Context.getCanonicalType(Ty);
3299
3300 // Look through reference types; they aren't part of the type of an
3301 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00003302 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003303 Ty = RefTy->getPointeeType();
3304
3305 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003306 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003307
Sebastian Redla65b5512009-11-05 16:36:20 +00003308 // If we're dealing with an array type, decay to the pointer.
3309 if (Ty->isArrayType())
3310 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3311
Ted Kremenek6217b802009-07-29 21:53:49 +00003312 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003313 QualType PointeeTy = PointerTy->getPointeeType();
3314
3315 // Insert our type, and its more-qualified variants, into the set
3316 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003317 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003318 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00003319 } else if (Ty->isMemberPointerType()) {
3320 // Member pointers are far easier, since the pointee can't be converted.
3321 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3322 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003323 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00003324 EnumerationTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003325 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003326 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003327 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003328 // No conversion functions in incomplete types.
3329 return;
3330 }
Mike Stump1eb44332009-09-09 15:08:12 +00003331
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003332 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00003333 const UnresolvedSetImpl *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00003334 = ClassDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003335 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00003336 E = Conversions->end(); I != E; ++I) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003337
Mike Stump1eb44332009-09-09 15:08:12 +00003338 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003339 // about which builtin types we can convert to.
John McCallba135432009-11-21 08:51:07 +00003340 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003341 continue;
3342
John McCallba135432009-11-21 08:51:07 +00003343 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003344 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003345 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003346 VisibleQuals);
3347 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003348 }
3349 }
3350 }
3351}
3352
Douglas Gregor19b7b152009-08-24 13:43:27 +00003353/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3354/// the volatile- and non-volatile-qualified assignment operators for the
3355/// given type to the candidate set.
3356static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3357 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00003358 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003359 unsigned NumArgs,
3360 OverloadCandidateSet &CandidateSet) {
3361 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00003362
Douglas Gregor19b7b152009-08-24 13:43:27 +00003363 // T& operator=(T&, T)
3364 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3365 ParamTypes[1] = T;
3366 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3367 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003368
Douglas Gregor19b7b152009-08-24 13:43:27 +00003369 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3370 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00003371 ParamTypes[0]
3372 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00003373 ParamTypes[1] = T;
3374 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00003375 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003376 }
3377}
Mike Stump1eb44332009-09-09 15:08:12 +00003378
Sebastian Redl9994a342009-10-25 17:03:50 +00003379/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3380/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003381static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3382 Qualifiers VRQuals;
3383 const RecordType *TyRec;
3384 if (const MemberPointerType *RHSMPType =
3385 ArgExpr->getType()->getAs<MemberPointerType>())
3386 TyRec = cast<RecordType>(RHSMPType->getClass());
3387 else
3388 TyRec = ArgExpr->getType()->getAs<RecordType>();
3389 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003390 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003391 VRQuals.addVolatile();
3392 VRQuals.addRestrict();
3393 return VRQuals;
3394 }
3395
3396 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00003397 if (!ClassDecl->hasDefinition())
3398 return VRQuals;
3399
John McCalleec51cf2010-01-20 00:46:10 +00003400 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00003401 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003402
John McCalleec51cf2010-01-20 00:46:10 +00003403 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00003404 E = Conversions->end(); I != E; ++I) {
3405 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003406 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3407 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3408 CanTy = ResTypeRef->getPointeeType();
3409 // Need to go down the pointer/mempointer chain and add qualifiers
3410 // as see them.
3411 bool done = false;
3412 while (!done) {
3413 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3414 CanTy = ResTypePtr->getPointeeType();
3415 else if (const MemberPointerType *ResTypeMPtr =
3416 CanTy->getAs<MemberPointerType>())
3417 CanTy = ResTypeMPtr->getPointeeType();
3418 else
3419 done = true;
3420 if (CanTy.isVolatileQualified())
3421 VRQuals.addVolatile();
3422 if (CanTy.isRestrictQualified())
3423 VRQuals.addRestrict();
3424 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3425 return VRQuals;
3426 }
3427 }
3428 }
3429 return VRQuals;
3430}
3431
Douglas Gregor74253732008-11-19 15:42:04 +00003432/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3433/// operator overloads to the candidate set (C++ [over.built]), based
3434/// on the operator @p Op and the arguments given. For example, if the
3435/// operator is a binary '+', this routine might add "int
3436/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003437void
Mike Stump1eb44332009-09-09 15:08:12 +00003438Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003439 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00003440 Expr **Args, unsigned NumArgs,
3441 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003442 // The set of "promoted arithmetic types", which are the arithmetic
3443 // types are that preserved by promotion (C++ [over.built]p2). Note
3444 // that the first few of these types are the promoted integral
3445 // types; these types need to be first.
3446 // FIXME: What about complex?
3447 const unsigned FirstIntegralType = 0;
3448 const unsigned LastIntegralType = 13;
Mike Stump1eb44332009-09-09 15:08:12 +00003449 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003450 LastPromotedIntegralType = 13;
3451 const unsigned FirstPromotedArithmeticType = 7,
3452 LastPromotedArithmeticType = 16;
3453 const unsigned NumArithmeticTypes = 16;
3454 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00003455 Context.BoolTy, Context.CharTy, Context.WCharTy,
3456// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003457 Context.SignedCharTy, Context.ShortTy,
3458 Context.UnsignedCharTy, Context.UnsignedShortTy,
3459 Context.IntTy, Context.LongTy, Context.LongLongTy,
3460 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3461 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3462 };
Douglas Gregor652371a2009-10-21 22:01:30 +00003463 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3464 "Invalid first promoted integral type");
3465 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3466 == Context.UnsignedLongLongTy &&
3467 "Invalid last promoted integral type");
3468 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3469 "Invalid first promoted arithmetic type");
3470 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3471 == Context.LongDoubleTy &&
3472 "Invalid last promoted arithmetic type");
3473
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003474 // Find all of the types that the arguments can convert to, but only
3475 // if the operator we're looking at has built-in operator candidates
3476 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003477 Qualifiers VisibleTypeConversionsQuals;
3478 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003479 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3480 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3481
Douglas Gregor5842ba92009-08-24 15:23:48 +00003482 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003483 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3484 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00003485 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003486 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00003487 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003488 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor74253732008-11-19 15:42:04 +00003489 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003490 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregor573d9c32009-10-21 23:19:44 +00003491 OpLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003492 true,
3493 (Op == OO_Exclaim ||
3494 Op == OO_AmpAmp ||
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003495 Op == OO_PipePipe),
3496 VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003497 }
3498
3499 bool isComparison = false;
3500 switch (Op) {
3501 case OO_None:
3502 case NUM_OVERLOADED_OPERATORS:
3503 assert(false && "Expected an overloaded operator");
3504 break;
3505
Douglas Gregor74253732008-11-19 15:42:04 +00003506 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00003507 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00003508 goto UnaryStar;
3509 else
3510 goto BinaryStar;
3511 break;
3512
3513 case OO_Plus: // '+' is either unary or binary
3514 if (NumArgs == 1)
3515 goto UnaryPlus;
3516 else
3517 goto BinaryPlus;
3518 break;
3519
3520 case OO_Minus: // '-' is either unary or binary
3521 if (NumArgs == 1)
3522 goto UnaryMinus;
3523 else
3524 goto BinaryMinus;
3525 break;
3526
3527 case OO_Amp: // '&' is either unary or binary
3528 if (NumArgs == 1)
3529 goto UnaryAmp;
3530 else
3531 goto BinaryAmp;
3532
3533 case OO_PlusPlus:
3534 case OO_MinusMinus:
3535 // C++ [over.built]p3:
3536 //
3537 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3538 // is either volatile or empty, there exist candidate operator
3539 // functions of the form
3540 //
3541 // VQ T& operator++(VQ T&);
3542 // T operator++(VQ T&, int);
3543 //
3544 // C++ [over.built]p4:
3545 //
3546 // For every pair (T, VQ), where T is an arithmetic type other
3547 // than bool, and VQ is either volatile or empty, there exist
3548 // candidate operator functions of the form
3549 //
3550 // VQ T& operator--(VQ T&);
3551 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00003552 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00003553 Arith < NumArithmeticTypes; ++Arith) {
3554 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00003555 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003556 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00003557
3558 // Non-volatile version.
3559 if (NumArgs == 1)
3560 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3561 else
3562 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003563 // heuristic to reduce number of builtin candidates in the set.
3564 // Add volatile version only if there are conversions to a volatile type.
3565 if (VisibleTypeConversionsQuals.hasVolatile()) {
3566 // Volatile version
3567 ParamTypes[0]
3568 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3569 if (NumArgs == 1)
3570 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3571 else
3572 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3573 }
Douglas Gregor74253732008-11-19 15:42:04 +00003574 }
3575
3576 // C++ [over.built]p5:
3577 //
3578 // For every pair (T, VQ), where T is a cv-qualified or
3579 // cv-unqualified object type, and VQ is either volatile or
3580 // empty, there exist candidate operator functions of the form
3581 //
3582 // T*VQ& operator++(T*VQ&);
3583 // T*VQ& operator--(T*VQ&);
3584 // T* operator++(T*VQ&, int);
3585 // T* operator--(T*VQ&, int);
3586 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3587 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3588 // Skip pointer types that aren't pointers to object types.
Ted Kremenek6217b802009-07-29 21:53:49 +00003589 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00003590 continue;
3591
Mike Stump1eb44332009-09-09 15:08:12 +00003592 QualType ParamTypes[2] = {
3593 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00003594 };
Mike Stump1eb44332009-09-09 15:08:12 +00003595
Douglas Gregor74253732008-11-19 15:42:04 +00003596 // Without volatile
3597 if (NumArgs == 1)
3598 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3599 else
3600 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3601
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003602 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3603 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00003604 // With volatile
John McCall0953e762009-09-24 19:53:00 +00003605 ParamTypes[0]
3606 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00003607 if (NumArgs == 1)
3608 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3609 else
3610 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3611 }
3612 }
3613 break;
3614
3615 UnaryStar:
3616 // C++ [over.built]p6:
3617 // For every cv-qualified or cv-unqualified object type T, there
3618 // exist candidate operator functions of the form
3619 //
3620 // T& operator*(T*);
3621 //
3622 // C++ [over.built]p7:
3623 // For every function type T, there exist candidate operator
3624 // functions of the form
3625 // T& operator*(T*);
3626 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3627 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3628 QualType ParamTy = *Ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00003629 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003630 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00003631 &ParamTy, Args, 1, CandidateSet);
3632 }
3633 break;
3634
3635 UnaryPlus:
3636 // C++ [over.built]p8:
3637 // For every type T, there exist candidate operator functions of
3638 // the form
3639 //
3640 // T* operator+(T*);
3641 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3642 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3643 QualType ParamTy = *Ptr;
3644 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3645 }
Mike Stump1eb44332009-09-09 15:08:12 +00003646
Douglas Gregor74253732008-11-19 15:42:04 +00003647 // Fall through
3648
3649 UnaryMinus:
3650 // C++ [over.built]p9:
3651 // For every promoted arithmetic type T, there exist candidate
3652 // operator functions of the form
3653 //
3654 // T operator+(T);
3655 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003656 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00003657 Arith < LastPromotedArithmeticType; ++Arith) {
3658 QualType ArithTy = ArithmeticTypes[Arith];
3659 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3660 }
3661 break;
3662
3663 case OO_Tilde:
3664 // C++ [over.built]p10:
3665 // For every promoted integral type T, there exist candidate
3666 // operator functions of the form
3667 //
3668 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003669 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00003670 Int < LastPromotedIntegralType; ++Int) {
3671 QualType IntTy = ArithmeticTypes[Int];
3672 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3673 }
3674 break;
3675
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003676 case OO_New:
3677 case OO_Delete:
3678 case OO_Array_New:
3679 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003680 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00003681 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003682 break;
3683
3684 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00003685 UnaryAmp:
3686 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003687 // C++ [over.match.oper]p3:
3688 // -- For the operator ',', the unary operator '&', or the
3689 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003690 break;
3691
Douglas Gregor19b7b152009-08-24 13:43:27 +00003692 case OO_EqualEqual:
3693 case OO_ExclaimEqual:
3694 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00003695 // For every pointer to member type T, there exist candidate operator
3696 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00003697 //
3698 // bool operator==(T,T);
3699 // bool operator!=(T,T);
Mike Stump1eb44332009-09-09 15:08:12 +00003700 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor19b7b152009-08-24 13:43:27 +00003701 MemPtr = CandidateTypes.member_pointer_begin(),
3702 MemPtrEnd = CandidateTypes.member_pointer_end();
3703 MemPtr != MemPtrEnd;
3704 ++MemPtr) {
3705 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3706 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3707 }
Mike Stump1eb44332009-09-09 15:08:12 +00003708
Douglas Gregor19b7b152009-08-24 13:43:27 +00003709 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00003710
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003711 case OO_Less:
3712 case OO_Greater:
3713 case OO_LessEqual:
3714 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003715 // C++ [over.built]p15:
3716 //
3717 // For every pointer or enumeration type T, there exist
3718 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003719 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003720 // bool operator<(T, T);
3721 // bool operator>(T, T);
3722 // bool operator<=(T, T);
3723 // bool operator>=(T, T);
3724 // bool operator==(T, T);
3725 // bool operator!=(T, T);
3726 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3727 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3728 QualType ParamTypes[2] = { *Ptr, *Ptr };
3729 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3730 }
Mike Stump1eb44332009-09-09 15:08:12 +00003731 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003732 = CandidateTypes.enumeration_begin();
3733 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3734 QualType ParamTypes[2] = { *Enum, *Enum };
3735 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3736 }
3737
3738 // Fall through.
3739 isComparison = true;
3740
Douglas Gregor74253732008-11-19 15:42:04 +00003741 BinaryPlus:
3742 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003743 if (!isComparison) {
3744 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3745
3746 // C++ [over.built]p13:
3747 //
3748 // For every cv-qualified or cv-unqualified object type T
3749 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003750 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003751 // T* operator+(T*, ptrdiff_t);
3752 // T& operator[](T*, ptrdiff_t); [BELOW]
3753 // T* operator-(T*, ptrdiff_t);
3754 // T* operator+(ptrdiff_t, T*);
3755 // T& operator[](ptrdiff_t, T*); [BELOW]
3756 //
3757 // C++ [over.built]p14:
3758 //
3759 // For every T, where T is a pointer to object type, there
3760 // exist candidate operator functions of the form
3761 //
3762 // ptrdiff_t operator-(T, T);
Mike Stump1eb44332009-09-09 15:08:12 +00003763 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003764 = CandidateTypes.pointer_begin();
3765 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3766 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3767
3768 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3769 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3770
3771 if (Op == OO_Plus) {
3772 // T* operator+(ptrdiff_t, T*);
3773 ParamTypes[0] = ParamTypes[1];
3774 ParamTypes[1] = *Ptr;
3775 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3776 } else {
3777 // ptrdiff_t operator-(T, T);
3778 ParamTypes[1] = *Ptr;
3779 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3780 Args, 2, CandidateSet);
3781 }
3782 }
3783 }
3784 // Fall through
3785
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003786 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00003787 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003788 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003789 // C++ [over.built]p12:
3790 //
3791 // For every pair of promoted arithmetic types L and R, there
3792 // exist candidate operator functions of the form
3793 //
3794 // LR operator*(L, R);
3795 // LR operator/(L, R);
3796 // LR operator+(L, R);
3797 // LR operator-(L, R);
3798 // bool operator<(L, R);
3799 // bool operator>(L, R);
3800 // bool operator<=(L, R);
3801 // bool operator>=(L, R);
3802 // bool operator==(L, R);
3803 // bool operator!=(L, R);
3804 //
3805 // where LR is the result of the usual arithmetic conversions
3806 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003807 //
3808 // C++ [over.built]p24:
3809 //
3810 // For every pair of promoted arithmetic types L and R, there exist
3811 // candidate operator functions of the form
3812 //
3813 // LR operator?(bool, L, R);
3814 //
3815 // where LR is the result of the usual arithmetic conversions
3816 // between types L and R.
3817 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003818 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003819 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003820 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003821 Right < LastPromotedArithmeticType; ++Right) {
3822 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00003823 QualType Result
3824 = isComparison
3825 ? Context.BoolTy
3826 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003827 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3828 }
3829 }
3830 break;
3831
3832 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00003833 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003834 case OO_Caret:
3835 case OO_Pipe:
3836 case OO_LessLess:
3837 case OO_GreaterGreater:
3838 // C++ [over.built]p17:
3839 //
3840 // For every pair of promoted integral types L and R, there
3841 // exist candidate operator functions of the form
3842 //
3843 // LR operator%(L, R);
3844 // LR operator&(L, R);
3845 // LR operator^(L, R);
3846 // LR operator|(L, R);
3847 // L operator<<(L, R);
3848 // L operator>>(L, R);
3849 //
3850 // where LR is the result of the usual arithmetic conversions
3851 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00003852 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003853 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003854 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003855 Right < LastPromotedIntegralType; ++Right) {
3856 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3857 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3858 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00003859 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003860 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3861 }
3862 }
3863 break;
3864
3865 case OO_Equal:
3866 // C++ [over.built]p20:
3867 //
3868 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00003869 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003870 // empty, there exist candidate operator functions of the form
3871 //
3872 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003873 for (BuiltinCandidateTypeSet::iterator
3874 Enum = CandidateTypes.enumeration_begin(),
3875 EnumEnd = CandidateTypes.enumeration_end();
3876 Enum != EnumEnd; ++Enum)
Mike Stump1eb44332009-09-09 15:08:12 +00003877 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003878 CandidateSet);
3879 for (BuiltinCandidateTypeSet::iterator
3880 MemPtr = CandidateTypes.member_pointer_begin(),
3881 MemPtrEnd = CandidateTypes.member_pointer_end();
3882 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump1eb44332009-09-09 15:08:12 +00003883 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003884 CandidateSet);
3885 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003886
3887 case OO_PlusEqual:
3888 case OO_MinusEqual:
3889 // C++ [over.built]p19:
3890 //
3891 // For every pair (T, VQ), where T is any type and VQ is either
3892 // volatile or empty, there exist candidate operator functions
3893 // of the form
3894 //
3895 // T*VQ& operator=(T*VQ&, T*);
3896 //
3897 // C++ [over.built]p21:
3898 //
3899 // For every pair (T, VQ), where T is a cv-qualified or
3900 // cv-unqualified object type and VQ is either volatile or
3901 // empty, there exist candidate operator functions of the form
3902 //
3903 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3904 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3905 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3906 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3907 QualType ParamTypes[2];
3908 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3909
3910 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003911 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003912 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3913 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003914
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003915 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3916 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00003917 // volatile version
John McCall0953e762009-09-24 19:53:00 +00003918 ParamTypes[0]
3919 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003920 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3921 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00003922 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003923 }
3924 // Fall through.
3925
3926 case OO_StarEqual:
3927 case OO_SlashEqual:
3928 // C++ [over.built]p18:
3929 //
3930 // For every triple (L, VQ, R), where L is an arithmetic type,
3931 // VQ is either volatile or empty, and R is a promoted
3932 // arithmetic type, there exist candidate operator functions of
3933 // the form
3934 //
3935 // VQ L& operator=(VQ L&, R);
3936 // VQ L& operator*=(VQ L&, R);
3937 // VQ L& operator/=(VQ L&, R);
3938 // VQ L& operator+=(VQ L&, R);
3939 // VQ L& operator-=(VQ L&, R);
3940 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003941 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003942 Right < LastPromotedArithmeticType; ++Right) {
3943 QualType ParamTypes[2];
3944 ParamTypes[1] = ArithmeticTypes[Right];
3945
3946 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003947 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003948 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3949 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003950
3951 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003952 if (VisibleTypeConversionsQuals.hasVolatile()) {
3953 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3954 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3955 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3956 /*IsAssigmentOperator=*/Op == OO_Equal);
3957 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003958 }
3959 }
3960 break;
3961
3962 case OO_PercentEqual:
3963 case OO_LessLessEqual:
3964 case OO_GreaterGreaterEqual:
3965 case OO_AmpEqual:
3966 case OO_CaretEqual:
3967 case OO_PipeEqual:
3968 // C++ [over.built]p22:
3969 //
3970 // For every triple (L, VQ, R), where L is an integral type, VQ
3971 // is either volatile or empty, and R is a promoted integral
3972 // type, there exist candidate operator functions of the form
3973 //
3974 // VQ L& operator%=(VQ L&, R);
3975 // VQ L& operator<<=(VQ L&, R);
3976 // VQ L& operator>>=(VQ L&, R);
3977 // VQ L& operator&=(VQ L&, R);
3978 // VQ L& operator^=(VQ L&, R);
3979 // VQ L& operator|=(VQ L&, R);
3980 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003981 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003982 Right < LastPromotedIntegralType; ++Right) {
3983 QualType ParamTypes[2];
3984 ParamTypes[1] = ArithmeticTypes[Right];
3985
3986 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003987 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003988 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00003989 if (VisibleTypeConversionsQuals.hasVolatile()) {
3990 // Add this built-in operator as a candidate (VQ is 'volatile').
3991 ParamTypes[0] = ArithmeticTypes[Left];
3992 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3993 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3994 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3995 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003996 }
3997 }
3998 break;
3999
Douglas Gregor74253732008-11-19 15:42:04 +00004000 case OO_Exclaim: {
4001 // C++ [over.operator]p23:
4002 //
4003 // There also exist candidate operator functions of the form
4004 //
Mike Stump1eb44332009-09-09 15:08:12 +00004005 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00004006 // bool operator&&(bool, bool); [BELOW]
4007 // bool operator||(bool, bool); [BELOW]
4008 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004009 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4010 /*IsAssignmentOperator=*/false,
4011 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00004012 break;
4013 }
4014
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004015 case OO_AmpAmp:
4016 case OO_PipePipe: {
4017 // C++ [over.operator]p23:
4018 //
4019 // There also exist candidate operator functions of the form
4020 //
Douglas Gregor74253732008-11-19 15:42:04 +00004021 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004022 // bool operator&&(bool, bool);
4023 // bool operator||(bool, bool);
4024 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004025 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4026 /*IsAssignmentOperator=*/false,
4027 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004028 break;
4029 }
4030
4031 case OO_Subscript:
4032 // C++ [over.built]p13:
4033 //
4034 // For every cv-qualified or cv-unqualified object type T there
4035 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004036 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004037 // T* operator+(T*, ptrdiff_t); [ABOVE]
4038 // T& operator[](T*, ptrdiff_t);
4039 // T* operator-(T*, ptrdiff_t); [ABOVE]
4040 // T* operator+(ptrdiff_t, T*); [ABOVE]
4041 // T& operator[](ptrdiff_t, T*);
4042 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4043 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4044 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenek6217b802009-07-29 21:53:49 +00004045 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004046 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004047
4048 // T& operator[](T*, ptrdiff_t)
4049 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4050
4051 // T& operator[](ptrdiff_t, T*);
4052 ParamTypes[0] = ParamTypes[1];
4053 ParamTypes[1] = *Ptr;
4054 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4055 }
4056 break;
4057
4058 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004059 // C++ [over.built]p11:
4060 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4061 // C1 is the same type as C2 or is a derived class of C2, T is an object
4062 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4063 // there exist candidate operator functions of the form
4064 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4065 // where CV12 is the union of CV1 and CV2.
4066 {
4067 for (BuiltinCandidateTypeSet::iterator Ptr =
4068 CandidateTypes.pointer_begin();
4069 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4070 QualType C1Ty = (*Ptr);
4071 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004072 QualifierCollector Q1;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004073 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004074 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004075 if (!isa<RecordType>(C1))
4076 continue;
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004077 // heuristic to reduce number of builtin candidates in the set.
4078 // Add volatile/restrict version only if there are conversions to a
4079 // volatile/restrict type.
4080 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4081 continue;
4082 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4083 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004084 }
4085 for (BuiltinCandidateTypeSet::iterator
4086 MemPtr = CandidateTypes.member_pointer_begin(),
4087 MemPtrEnd = CandidateTypes.member_pointer_end();
4088 MemPtr != MemPtrEnd; ++MemPtr) {
4089 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4090 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00004091 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004092 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4093 break;
4094 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4095 // build CV12 T&
4096 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004097 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4098 T.isVolatileQualified())
4099 continue;
4100 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4101 T.isRestrictQualified())
4102 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004103 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004104 QualType ResultTy = Context.getLValueReferenceType(T);
4105 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4106 }
4107 }
4108 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004109 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004110
4111 case OO_Conditional:
4112 // Note that we don't consider the first argument, since it has been
4113 // contextually converted to bool long ago. The candidates below are
4114 // therefore added as binary.
4115 //
4116 // C++ [over.built]p24:
4117 // For every type T, where T is a pointer or pointer-to-member type,
4118 // there exist candidate operator functions of the form
4119 //
4120 // T operator?(bool, T, T);
4121 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004122 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4123 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4124 QualType ParamTypes[2] = { *Ptr, *Ptr };
4125 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4126 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00004127 for (BuiltinCandidateTypeSet::iterator Ptr =
4128 CandidateTypes.member_pointer_begin(),
4129 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4130 QualType ParamTypes[2] = { *Ptr, *Ptr };
4131 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4132 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004133 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004134 }
4135}
4136
Douglas Gregorfa047642009-02-04 00:32:51 +00004137/// \brief Add function candidates found via argument-dependent lookup
4138/// to the set of overloading candidates.
4139///
4140/// This routine performs argument-dependent name lookup based on the
4141/// given function name (which may also be an operator name) and adds
4142/// all of the overload candidates found by ADL to the overload
4143/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00004144void
Douglas Gregorfa047642009-02-04 00:32:51 +00004145Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00004146 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00004147 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00004148 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004149 OverloadCandidateSet& CandidateSet,
4150 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00004151 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00004152
John McCalla113e722010-01-26 06:04:06 +00004153 // FIXME: This approach for uniquing ADL results (and removing
4154 // redundant candidates from the set) relies on pointer-equality,
4155 // which means we need to key off the canonical decl. However,
4156 // always going back to the canonical decl might not get us the
4157 // right set of default arguments. What default arguments are
4158 // we supposed to consider on ADL candidates, anyway?
4159
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004160 // FIXME: Pass in the explicit template arguments?
John McCall7edb5fd2010-01-26 07:16:45 +00004161 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00004162
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004163 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004164 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4165 CandEnd = CandidateSet.end();
4166 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00004167 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00004168 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00004169 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00004170 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00004171 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004172
4173 // For each of the ADL candidates we found, add it to the overload
4174 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00004175 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall6e266892010-01-26 03:27:55 +00004176 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00004177 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004178 continue;
4179
John McCall86820f52010-01-26 01:37:31 +00004180 AddOverloadCandidate(FD, AS_none, Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004181 false, false, PartialOverloading);
4182 } else
John McCall6e266892010-01-26 03:27:55 +00004183 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall86820f52010-01-26 01:37:31 +00004184 AS_none, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004185 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00004186 }
Douglas Gregorfa047642009-02-04 00:32:51 +00004187}
4188
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004189/// isBetterOverloadCandidate - Determines whether the first overload
4190/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00004191bool
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004192Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCall5769d612010-02-08 23:07:23 +00004193 const OverloadCandidate& Cand2,
4194 SourceLocation Loc) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004195 // Define viable functions to be better candidates than non-viable
4196 // functions.
4197 if (!Cand2.Viable)
4198 return Cand1.Viable;
4199 else if (!Cand1.Viable)
4200 return false;
4201
Douglas Gregor88a35142008-12-22 05:46:06 +00004202 // C++ [over.match.best]p1:
4203 //
4204 // -- if F is a static member function, ICS1(F) is defined such
4205 // that ICS1(F) is neither better nor worse than ICS1(G) for
4206 // any function G, and, symmetrically, ICS1(G) is neither
4207 // better nor worse than ICS1(F).
4208 unsigned StartArg = 0;
4209 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4210 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004211
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004212 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00004213 // A viable function F1 is defined to be a better function than another
4214 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004215 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004216 unsigned NumArgs = Cand1.Conversions.size();
4217 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4218 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004219 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004220 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4221 Cand2.Conversions[ArgIdx])) {
4222 case ImplicitConversionSequence::Better:
4223 // Cand1 has a better conversion sequence.
4224 HasBetterConversion = true;
4225 break;
4226
4227 case ImplicitConversionSequence::Worse:
4228 // Cand1 can't be better than Cand2.
4229 return false;
4230
4231 case ImplicitConversionSequence::Indistinguishable:
4232 // Do nothing.
4233 break;
4234 }
4235 }
4236
Mike Stump1eb44332009-09-09 15:08:12 +00004237 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004238 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004239 if (HasBetterConversion)
4240 return true;
4241
Mike Stump1eb44332009-09-09 15:08:12 +00004242 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004243 // specialization, or, if not that,
4244 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4245 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4246 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004247
4248 // -- F1 and F2 are function template specializations, and the function
4249 // template for F1 is more specialized than the template for F2
4250 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004251 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00004252 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4253 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004254 if (FunctionTemplateDecl *BetterTemplate
4255 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4256 Cand2.Function->getPrimaryTemplate(),
John McCall5769d612010-02-08 23:07:23 +00004257 Loc,
Douglas Gregor5d7d3752009-09-14 23:02:14 +00004258 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4259 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004260 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004261
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004262 // -- the context is an initialization by user-defined conversion
4263 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4264 // from the return type of F1 to the destination type (i.e.,
4265 // the type of the entity being initialized) is a better
4266 // conversion sequence than the standard conversion sequence
4267 // from the return type of F2 to the destination type.
Mike Stump1eb44332009-09-09 15:08:12 +00004268 if (Cand1.Function && Cand2.Function &&
4269 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004270 isa<CXXConversionDecl>(Cand2.Function)) {
4271 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4272 Cand2.FinalConversion)) {
4273 case ImplicitConversionSequence::Better:
4274 // Cand1 has a better conversion sequence.
4275 return true;
4276
4277 case ImplicitConversionSequence::Worse:
4278 // Cand1 can't be better than Cand2.
4279 return false;
4280
4281 case ImplicitConversionSequence::Indistinguishable:
4282 // Do nothing
4283 break;
4284 }
4285 }
4286
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004287 return false;
4288}
4289
Mike Stump1eb44332009-09-09 15:08:12 +00004290/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00004291/// within an overload candidate set.
4292///
4293/// \param CandidateSet the set of candidate functions.
4294///
4295/// \param Loc the location of the function name (or operator symbol) for
4296/// which overload resolution occurs.
4297///
Mike Stump1eb44332009-09-09 15:08:12 +00004298/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00004299/// function, Best points to the candidate function found.
4300///
4301/// \returns The result of overload resolution.
Douglas Gregor20093b42009-12-09 23:02:17 +00004302OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4303 SourceLocation Loc,
4304 OverloadCandidateSet::iterator& Best) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004305 // Find the best viable function.
4306 Best = CandidateSet.end();
4307 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4308 Cand != CandidateSet.end(); ++Cand) {
4309 if (Cand->Viable) {
John McCall5769d612010-02-08 23:07:23 +00004310 if (Best == CandidateSet.end() ||
4311 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004312 Best = Cand;
4313 }
4314 }
4315
4316 // If we didn't find any viable functions, abort.
4317 if (Best == CandidateSet.end())
4318 return OR_No_Viable_Function;
4319
4320 // Make sure that this function is better than every other viable
4321 // function. If not, we have an ambiguity.
4322 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4323 Cand != CandidateSet.end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00004324 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004325 Cand != Best &&
John McCall5769d612010-02-08 23:07:23 +00004326 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004327 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004328 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004329 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004330 }
Mike Stump1eb44332009-09-09 15:08:12 +00004331
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004332 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004333 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00004334 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004335 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004336 return OR_Deleted;
4337
Douglas Gregore0762c92009-06-19 23:52:42 +00004338 // C++ [basic.def.odr]p2:
4339 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00004340 // when referred to from a potentially-evaluated expression. [Note: this
4341 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00004342 // (clause 13), user-defined conversions (12.3.2), allocation function for
4343 // placement new (5.3.4), as well as non-default initialization (8.5).
4344 if (Best->Function)
4345 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004346 return OR_Success;
4347}
4348
John McCall3c80f572010-01-12 02:15:36 +00004349namespace {
4350
4351enum OverloadCandidateKind {
4352 oc_function,
4353 oc_method,
4354 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00004355 oc_function_template,
4356 oc_method_template,
4357 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00004358 oc_implicit_default_constructor,
4359 oc_implicit_copy_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00004360 oc_implicit_copy_assignment
John McCall3c80f572010-01-12 02:15:36 +00004361};
4362
John McCall220ccbf2010-01-13 00:25:19 +00004363OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4364 FunctionDecl *Fn,
4365 std::string &Description) {
4366 bool isTemplate = false;
4367
4368 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4369 isTemplate = true;
4370 Description = S.getTemplateArgumentBindingsText(
4371 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4372 }
John McCallb1622a12010-01-06 09:43:14 +00004373
4374 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00004375 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00004376 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00004377
John McCall3c80f572010-01-12 02:15:36 +00004378 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4379 : oc_implicit_default_constructor;
John McCallb1622a12010-01-06 09:43:14 +00004380 }
4381
4382 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4383 // This actually gets spelled 'candidate function' for now, but
4384 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00004385 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00004386 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00004387
4388 assert(Meth->isCopyAssignment()
4389 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00004390 return oc_implicit_copy_assignment;
4391 }
4392
John McCall220ccbf2010-01-13 00:25:19 +00004393 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00004394}
4395
4396} // end anonymous namespace
4397
4398// Notes the location of an overload candidate.
4399void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00004400 std::string FnDesc;
4401 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4402 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4403 << (unsigned) K << FnDesc;
John McCallb1622a12010-01-06 09:43:14 +00004404}
4405
John McCall1d318332010-01-12 00:44:57 +00004406/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4407/// "lead" diagnostic; it will be given two arguments, the source and
4408/// target types of the conversion.
4409void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4410 SourceLocation CaretLoc,
4411 const PartialDiagnostic &PDiag) {
4412 Diag(CaretLoc, PDiag)
4413 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4414 for (AmbiguousConversionSequence::const_iterator
4415 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4416 NoteOverloadCandidate(*I);
4417 }
John McCall81201622010-01-08 04:41:39 +00004418}
4419
John McCall1d318332010-01-12 00:44:57 +00004420namespace {
4421
John McCalladbb8f82010-01-13 09:16:55 +00004422void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4423 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4424 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00004425 assert(Cand->Function && "for now, candidate must be a function");
4426 FunctionDecl *Fn = Cand->Function;
4427
4428 // There's a conversion slot for the object argument if this is a
4429 // non-constructor method. Note that 'I' corresponds the
4430 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00004431 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00004432 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00004433 if (I == 0)
4434 isObjectArgument = true;
4435 else
4436 I--;
John McCall220ccbf2010-01-13 00:25:19 +00004437 }
4438
John McCall220ccbf2010-01-13 00:25:19 +00004439 std::string FnDesc;
4440 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4441
John McCalladbb8f82010-01-13 09:16:55 +00004442 Expr *FromExpr = Conv.Bad.FromExpr;
4443 QualType FromTy = Conv.Bad.getFromType();
4444 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00004445
John McCall5920dbb2010-02-02 02:42:52 +00004446 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00004447 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00004448 Expr *E = FromExpr->IgnoreParens();
4449 if (isa<UnaryOperator>(E))
4450 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00004451 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00004452
4453 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
4454 << (unsigned) FnKind << FnDesc
4455 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4456 << ToTy << Name << I+1;
4457 return;
4458 }
4459
John McCall258b2032010-01-23 08:10:49 +00004460 // Do some hand-waving analysis to see if the non-viability is due
4461 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00004462 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4463 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4464 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4465 CToTy = RT->getPointeeType();
4466 else {
4467 // TODO: detect and diagnose the full richness of const mismatches.
4468 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4469 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4470 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4471 }
4472
4473 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4474 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4475 // It is dumb that we have to do this here.
4476 while (isa<ArrayType>(CFromTy))
4477 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4478 while (isa<ArrayType>(CToTy))
4479 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4480
4481 Qualifiers FromQs = CFromTy.getQualifiers();
4482 Qualifiers ToQs = CToTy.getQualifiers();
4483
4484 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
4485 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
4486 << (unsigned) FnKind << FnDesc
4487 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4488 << FromTy
4489 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
4490 << (unsigned) isObjectArgument << I+1;
4491 return;
4492 }
4493
4494 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4495 assert(CVR && "unexpected qualifiers mismatch");
4496
4497 if (isObjectArgument) {
4498 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
4499 << (unsigned) FnKind << FnDesc
4500 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4501 << FromTy << (CVR - 1);
4502 } else {
4503 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
4504 << (unsigned) FnKind << FnDesc
4505 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4506 << FromTy << (CVR - 1) << I+1;
4507 }
4508 return;
4509 }
4510
John McCall258b2032010-01-23 08:10:49 +00004511 // Diagnose references or pointers to incomplete types differently,
4512 // since it's far from impossible that the incompleteness triggered
4513 // the failure.
4514 QualType TempFromTy = FromTy.getNonReferenceType();
4515 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
4516 TempFromTy = PTy->getPointeeType();
4517 if (TempFromTy->isIncompleteType()) {
4518 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
4519 << (unsigned) FnKind << FnDesc
4520 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4521 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
4522 return;
4523 }
4524
John McCall651f3ee2010-01-14 03:28:57 +00004525 // TODO: specialize more based on the kind of mismatch
John McCall220ccbf2010-01-13 00:25:19 +00004526 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
4527 << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00004528 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalle81e15e2010-01-14 00:56:20 +00004529 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCalladbb8f82010-01-13 09:16:55 +00004530}
4531
4532void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
4533 unsigned NumFormalArgs) {
4534 // TODO: treat calls to a missing default constructor as a special case
4535
4536 FunctionDecl *Fn = Cand->Function;
4537 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
4538
4539 unsigned MinParams = Fn->getMinRequiredArguments();
4540
4541 // at least / at most / exactly
4542 unsigned mode, modeCount;
4543 if (NumFormalArgs < MinParams) {
4544 assert(Cand->FailureKind == ovl_fail_too_few_arguments);
4545 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
4546 mode = 0; // "at least"
4547 else
4548 mode = 2; // "exactly"
4549 modeCount = MinParams;
4550 } else {
4551 assert(Cand->FailureKind == ovl_fail_too_many_arguments);
4552 if (MinParams != FnTy->getNumArgs())
4553 mode = 1; // "at most"
4554 else
4555 mode = 2; // "exactly"
4556 modeCount = FnTy->getNumArgs();
4557 }
4558
4559 std::string Description;
4560 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
4561
4562 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
4563 << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs;
John McCall220ccbf2010-01-13 00:25:19 +00004564}
4565
John McCall342fec42010-02-01 18:53:26 +00004566/// Diagnose a failed template-argument deduction.
4567void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
4568 Expr **Args, unsigned NumArgs) {
4569 FunctionDecl *Fn = Cand->Function; // pattern
4570
4571 TemplateParameter Param = TemplateParameter::getFromOpaqueValue(
4572 Cand->DeductionFailure.TemplateParameter);
4573
4574 switch (Cand->DeductionFailure.Result) {
4575 case Sema::TDK_Success:
4576 llvm_unreachable("TDK_success while diagnosing bad deduction");
4577
4578 case Sema::TDK_Incomplete: {
4579 NamedDecl *ParamD;
4580 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
4581 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
4582 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
4583 assert(ParamD && "no parameter found for incomplete deduction result");
4584 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
4585 << ParamD->getDeclName();
4586 return;
4587 }
4588
4589 // TODO: diagnose these individually, then kill off
4590 // note_ovl_candidate_bad_deduction, which is uselessly vague.
4591 case Sema::TDK_InstantiationDepth:
4592 case Sema::TDK_Inconsistent:
4593 case Sema::TDK_InconsistentQuals:
4594 case Sema::TDK_SubstitutionFailure:
4595 case Sema::TDK_NonDeducedMismatch:
4596 case Sema::TDK_TooManyArguments:
4597 case Sema::TDK_TooFewArguments:
4598 case Sema::TDK_InvalidExplicitArguments:
4599 case Sema::TDK_FailedOverloadResolution:
4600 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
4601 return;
4602 }
4603}
4604
4605/// Generates a 'note' diagnostic for an overload candidate. We've
4606/// already generated a primary error at the call site.
4607///
4608/// It really does need to be a single diagnostic with its caret
4609/// pointed at the candidate declaration. Yes, this creates some
4610/// major challenges of technical writing. Yes, this makes pointing
4611/// out problems with specific arguments quite awkward. It's still
4612/// better than generating twenty screens of text for every failed
4613/// overload.
4614///
4615/// It would be great to be able to express per-candidate problems
4616/// more richly for those diagnostic clients that cared, but we'd
4617/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00004618void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
4619 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00004620 FunctionDecl *Fn = Cand->Function;
4621
John McCall81201622010-01-08 04:41:39 +00004622 // Note deleted candidates, but only if they're viable.
John McCall3c80f572010-01-12 02:15:36 +00004623 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCall220ccbf2010-01-13 00:25:19 +00004624 std::string FnDesc;
4625 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00004626
4627 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00004628 << FnKind << FnDesc << Fn->isDeleted();
John McCalla1d7d622010-01-08 00:58:21 +00004629 return;
John McCall81201622010-01-08 04:41:39 +00004630 }
4631
John McCall220ccbf2010-01-13 00:25:19 +00004632 // We don't really have anything else to say about viable candidates.
4633 if (Cand->Viable) {
4634 S.NoteOverloadCandidate(Fn);
4635 return;
4636 }
John McCall1d318332010-01-12 00:44:57 +00004637
John McCalladbb8f82010-01-13 09:16:55 +00004638 switch (Cand->FailureKind) {
4639 case ovl_fail_too_many_arguments:
4640 case ovl_fail_too_few_arguments:
4641 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00004642
John McCalladbb8f82010-01-13 09:16:55 +00004643 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00004644 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
4645
John McCall717e8912010-01-23 05:17:32 +00004646 case ovl_fail_trivial_conversion:
4647 case ovl_fail_bad_final_conversion:
John McCalladbb8f82010-01-13 09:16:55 +00004648 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00004649
John McCallb1bdc622010-02-25 01:37:24 +00004650 case ovl_fail_bad_conversion: {
4651 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
4652 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00004653 if (Cand->Conversions[I].isBad())
4654 return DiagnoseBadConversion(S, Cand, I);
4655
4656 // FIXME: this currently happens when we're called from SemaInit
4657 // when user-conversion overload fails. Figure out how to handle
4658 // those conditions and diagnose them well.
4659 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00004660 }
John McCallb1bdc622010-02-25 01:37:24 +00004661 }
John McCalla1d7d622010-01-08 00:58:21 +00004662}
4663
4664void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
4665 // Desugar the type of the surrogate down to a function type,
4666 // retaining as many typedefs as possible while still showing
4667 // the function type (and, therefore, its parameter types).
4668 QualType FnType = Cand->Surrogate->getConversionType();
4669 bool isLValueReference = false;
4670 bool isRValueReference = false;
4671 bool isPointer = false;
4672 if (const LValueReferenceType *FnTypeRef =
4673 FnType->getAs<LValueReferenceType>()) {
4674 FnType = FnTypeRef->getPointeeType();
4675 isLValueReference = true;
4676 } else if (const RValueReferenceType *FnTypeRef =
4677 FnType->getAs<RValueReferenceType>()) {
4678 FnType = FnTypeRef->getPointeeType();
4679 isRValueReference = true;
4680 }
4681 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4682 FnType = FnTypePtr->getPointeeType();
4683 isPointer = true;
4684 }
4685 // Desugar down to a function type.
4686 FnType = QualType(FnType->getAs<FunctionType>(), 0);
4687 // Reconstruct the pointer/reference as appropriate.
4688 if (isPointer) FnType = S.Context.getPointerType(FnType);
4689 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
4690 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
4691
4692 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
4693 << FnType;
4694}
4695
4696void NoteBuiltinOperatorCandidate(Sema &S,
4697 const char *Opc,
4698 SourceLocation OpLoc,
4699 OverloadCandidate *Cand) {
4700 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
4701 std::string TypeStr("operator");
4702 TypeStr += Opc;
4703 TypeStr += "(";
4704 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4705 if (Cand->Conversions.size() == 1) {
4706 TypeStr += ")";
4707 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
4708 } else {
4709 TypeStr += ", ";
4710 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4711 TypeStr += ")";
4712 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
4713 }
4714}
4715
4716void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
4717 OverloadCandidate *Cand) {
4718 unsigned NoOperands = Cand->Conversions.size();
4719 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
4720 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00004721 if (ICS.isBad()) break; // all meaningless after first invalid
4722 if (!ICS.isAmbiguous()) continue;
4723
4724 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
4725 PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00004726 }
4727}
4728
John McCall1b77e732010-01-15 23:32:50 +00004729SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
4730 if (Cand->Function)
4731 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00004732 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00004733 return Cand->Surrogate->getLocation();
4734 return SourceLocation();
4735}
4736
John McCallbf65c0b2010-01-12 00:48:53 +00004737struct CompareOverloadCandidatesForDisplay {
4738 Sema &S;
4739 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00004740
4741 bool operator()(const OverloadCandidate *L,
4742 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00004743 // Fast-path this check.
4744 if (L == R) return false;
4745
John McCall81201622010-01-08 04:41:39 +00004746 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00004747 if (L->Viable) {
4748 if (!R->Viable) return true;
4749
4750 // TODO: introduce a tri-valued comparison for overload
4751 // candidates. Would be more worthwhile if we had a sort
4752 // that could exploit it.
John McCall5769d612010-02-08 23:07:23 +00004753 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
4754 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00004755 } else if (R->Viable)
4756 return false;
John McCall81201622010-01-08 04:41:39 +00004757
John McCall1b77e732010-01-15 23:32:50 +00004758 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00004759
John McCall1b77e732010-01-15 23:32:50 +00004760 // Criteria by which we can sort non-viable candidates:
4761 if (!L->Viable) {
4762 // 1. Arity mismatches come after other candidates.
4763 if (L->FailureKind == ovl_fail_too_many_arguments ||
4764 L->FailureKind == ovl_fail_too_few_arguments)
4765 return false;
4766 if (R->FailureKind == ovl_fail_too_many_arguments ||
4767 R->FailureKind == ovl_fail_too_few_arguments)
4768 return true;
John McCall81201622010-01-08 04:41:39 +00004769
John McCall717e8912010-01-23 05:17:32 +00004770 // 2. Bad conversions come first and are ordered by the number
4771 // of bad conversions and quality of good conversions.
4772 if (L->FailureKind == ovl_fail_bad_conversion) {
4773 if (R->FailureKind != ovl_fail_bad_conversion)
4774 return true;
4775
4776 // If there's any ordering between the defined conversions...
4777 // FIXME: this might not be transitive.
4778 assert(L->Conversions.size() == R->Conversions.size());
4779
4780 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00004781 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
4782 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall717e8912010-01-23 05:17:32 +00004783 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
4784 R->Conversions[I])) {
4785 case ImplicitConversionSequence::Better:
4786 leftBetter++;
4787 break;
4788
4789 case ImplicitConversionSequence::Worse:
4790 leftBetter--;
4791 break;
4792
4793 case ImplicitConversionSequence::Indistinguishable:
4794 break;
4795 }
4796 }
4797 if (leftBetter > 0) return true;
4798 if (leftBetter < 0) return false;
4799
4800 } else if (R->FailureKind == ovl_fail_bad_conversion)
4801 return false;
4802
John McCall1b77e732010-01-15 23:32:50 +00004803 // TODO: others?
4804 }
4805
4806 // Sort everything else by location.
4807 SourceLocation LLoc = GetLocationForCandidate(L);
4808 SourceLocation RLoc = GetLocationForCandidate(R);
4809
4810 // Put candidates without locations (e.g. builtins) at the end.
4811 if (LLoc.isInvalid()) return false;
4812 if (RLoc.isInvalid()) return true;
4813
4814 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00004815 }
4816};
4817
John McCall717e8912010-01-23 05:17:32 +00004818/// CompleteNonViableCandidate - Normally, overload resolution only
4819/// computes up to the first
4820void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
4821 Expr **Args, unsigned NumArgs) {
4822 assert(!Cand->Viable);
4823
4824 // Don't do anything on failures other than bad conversion.
4825 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
4826
4827 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00004828 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00004829 unsigned ConvCount = Cand->Conversions.size();
4830 while (true) {
4831 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
4832 ConvIdx++;
4833 if (Cand->Conversions[ConvIdx - 1].isBad())
4834 break;
4835 }
4836
4837 if (ConvIdx == ConvCount)
4838 return;
4839
John McCallb1bdc622010-02-25 01:37:24 +00004840 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
4841 "remaining conversion is initialized?");
4842
John McCall717e8912010-01-23 05:17:32 +00004843 // FIXME: these should probably be preserved from the overload
4844 // operation somehow.
4845 bool SuppressUserConversions = false;
4846 bool ForceRValue = false;
4847
4848 const FunctionProtoType* Proto;
4849 unsigned ArgIdx = ConvIdx;
4850
4851 if (Cand->IsSurrogate) {
4852 QualType ConvType
4853 = Cand->Surrogate->getConversionType().getNonReferenceType();
4854 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4855 ConvType = ConvPtrType->getPointeeType();
4856 Proto = ConvType->getAs<FunctionProtoType>();
4857 ArgIdx--;
4858 } else if (Cand->Function) {
4859 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
4860 if (isa<CXXMethodDecl>(Cand->Function) &&
4861 !isa<CXXConstructorDecl>(Cand->Function))
4862 ArgIdx--;
4863 } else {
4864 // Builtin binary operator with a bad first conversion.
4865 assert(ConvCount <= 3);
4866 for (; ConvIdx != ConvCount; ++ConvIdx)
4867 Cand->Conversions[ConvIdx]
4868 = S.TryCopyInitialization(Args[ConvIdx],
4869 Cand->BuiltinTypes.ParamTypes[ConvIdx],
4870 SuppressUserConversions, ForceRValue,
4871 /*InOverloadResolution*/ true);
4872 return;
4873 }
4874
4875 // Fill in the rest of the conversions.
4876 unsigned NumArgsInProto = Proto->getNumArgs();
4877 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
4878 if (ArgIdx < NumArgsInProto)
4879 Cand->Conversions[ConvIdx]
4880 = S.TryCopyInitialization(Args[ArgIdx], Proto->getArgType(ArgIdx),
4881 SuppressUserConversions, ForceRValue,
4882 /*InOverloadResolution=*/true);
4883 else
4884 Cand->Conversions[ConvIdx].setEllipsis();
4885 }
4886}
4887
John McCalla1d7d622010-01-08 00:58:21 +00004888} // end anonymous namespace
4889
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004890/// PrintOverloadCandidates - When overload resolution fails, prints
4891/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00004892/// set.
Mike Stump1eb44332009-09-09 15:08:12 +00004893void
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004894Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall81201622010-01-08 04:41:39 +00004895 OverloadCandidateDisplayKind OCD,
John McCallcbce6062010-01-12 07:18:19 +00004896 Expr **Args, unsigned NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004897 const char *Opc,
Fariborz Jahanian16a5eac2009-10-09 00:13:15 +00004898 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00004899 // Sort the candidates by viability and position. Sorting directly would
4900 // be prohibitive, so we make a set of pointers and sort those.
4901 llvm::SmallVector<OverloadCandidate*, 32> Cands;
4902 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
4903 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4904 LastCand = CandidateSet.end();
John McCall717e8912010-01-23 05:17:32 +00004905 Cand != LastCand; ++Cand) {
4906 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00004907 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00004908 else if (OCD == OCD_AllCandidates) {
4909 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
4910 Cands.push_back(Cand);
4911 }
4912 }
4913
John McCallbf65c0b2010-01-12 00:48:53 +00004914 std::sort(Cands.begin(), Cands.end(),
4915 CompareOverloadCandidatesForDisplay(*this));
John McCall81201622010-01-08 04:41:39 +00004916
John McCall1d318332010-01-12 00:44:57 +00004917 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00004918
John McCall81201622010-01-08 04:41:39 +00004919 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
4920 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
4921 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00004922
John McCalla1d7d622010-01-08 00:58:21 +00004923 if (Cand->Function)
John McCall220ccbf2010-01-13 00:25:19 +00004924 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00004925 else if (Cand->IsSurrogate)
4926 NoteSurrogateCandidate(*this, Cand);
4927
4928 // This a builtin candidate. We do not, in general, want to list
4929 // every possible builtin candidate.
John McCall1d318332010-01-12 00:44:57 +00004930 else if (Cand->Viable) {
4931 // Generally we only see ambiguities including viable builtin
4932 // operators if overload resolution got screwed up by an
4933 // ambiguous user-defined conversion.
4934 //
4935 // FIXME: It's quite possible for different conversions to see
4936 // different ambiguities, though.
4937 if (!ReportedAmbiguousConversions) {
4938 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
4939 ReportedAmbiguousConversions = true;
4940 }
John McCalla1d7d622010-01-08 00:58:21 +00004941
John McCall1d318332010-01-12 00:44:57 +00004942 // If this is a viable builtin, print it.
John McCalla1d7d622010-01-08 00:58:21 +00004943 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004944 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004945 }
4946}
4947
John McCall7bb12da2010-02-02 06:20:04 +00004948static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, NamedDecl *D,
John McCallc373d482010-01-27 01:50:18 +00004949 AccessSpecifier AS) {
4950 if (isa<UnresolvedLookupExpr>(E))
4951 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D, AS);
4952
4953 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D, AS);
4954}
4955
Douglas Gregor904eed32008-11-10 20:40:00 +00004956/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4957/// an overloaded function (C++ [over.over]), where @p From is an
4958/// expression with overloaded function type and @p ToType is the type
4959/// we're trying to resolve to. For example:
4960///
4961/// @code
4962/// int f(double);
4963/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00004964///
Douglas Gregor904eed32008-11-10 20:40:00 +00004965/// int (*pfd)(double) = f; // selects f(double)
4966/// @endcode
4967///
4968/// This routine returns the resulting FunctionDecl if it could be
4969/// resolved, and NULL otherwise. When @p Complain is true, this
4970/// routine will emit diagnostics if there is an error.
4971FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00004972Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor904eed32008-11-10 20:40:00 +00004973 bool Complain) {
4974 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00004975 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00004976 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00004977 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004978 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00004979 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00004980 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00004981 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00004982 FunctionType = MemTypePtr->getPointeeType();
4983 IsMember = true;
4984 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004985
4986 // We only look at pointers or references to functions.
Douglas Gregor72e771f2009-07-09 17:16:51 +00004987 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor83314aa2009-07-08 20:55:45 +00004988 if (!FunctionType->isFunctionType())
Douglas Gregor904eed32008-11-10 20:40:00 +00004989 return 0;
4990
4991 // Find the actual overloaded function declaration.
John McCall7bb12da2010-02-02 06:20:04 +00004992 if (From->getType() != Context.OverloadTy)
4993 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004994
Douglas Gregor904eed32008-11-10 20:40:00 +00004995 // C++ [over.over]p1:
4996 // [...] [Note: any redundant set of parentheses surrounding the
4997 // overloaded function name is ignored (5.1). ]
Douglas Gregor904eed32008-11-10 20:40:00 +00004998 // C++ [over.over]p1:
4999 // [...] The overloaded function name can be preceded by the &
5000 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00005001 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5002 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5003 if (OvlExpr->hasExplicitTemplateArgs()) {
5004 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5005 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregor904eed32008-11-10 20:40:00 +00005006 }
5007
Douglas Gregor904eed32008-11-10 20:40:00 +00005008 // Look through all of the overloaded functions, searching for one
5009 // whose type matches exactly.
John McCallc373d482010-01-27 01:50:18 +00005010 UnresolvedSet<4> Matches; // contains only FunctionDecls
Douglas Gregor00aeb522009-07-08 23:33:52 +00005011 bool FoundNonTemplateFunction = false;
John McCall7bb12da2010-02-02 06:20:04 +00005012 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5013 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00005014 // Look through any using declarations to find the underlying function.
5015 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5016
Douglas Gregor904eed32008-11-10 20:40:00 +00005017 // C++ [over.over]p3:
5018 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00005019 // targets of type "pointer-to-function" or "reference-to-function."
5020 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00005021 // type "pointer-to-member-function."
5022 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00005023
Mike Stump1eb44332009-09-09 15:08:12 +00005024 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthbd647292009-12-29 06:17:27 +00005025 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump1eb44332009-09-09 15:08:12 +00005026 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00005027 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00005028 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00005029 // static when converting to member pointer.
5030 if (Method->isStatic() == IsMember)
5031 continue;
5032 } else if (IsMember)
5033 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00005034
Douglas Gregor00aeb522009-07-08 23:33:52 +00005035 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00005036 // If the name is a function template, template argument deduction is
5037 // done (14.8.2.2), and if the argument deduction succeeds, the
5038 // resulting template argument list is used to generate a single
5039 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00005040 // overloaded functions considered.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005041 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor83314aa2009-07-08 20:55:45 +00005042 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00005043 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor83314aa2009-07-08 20:55:45 +00005044 if (TemplateDeductionResult Result
John McCall7bb12da2010-02-02 06:20:04 +00005045 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00005046 FunctionType, Specialization, Info)) {
5047 // FIXME: make a note of the failed deduction for diagnostics.
5048 (void)Result;
5049 } else {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005050 // FIXME: If the match isn't exact, shouldn't we just drop this as
5051 // a candidate? Find a testcase before changing the code.
Mike Stump1eb44332009-09-09 15:08:12 +00005052 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00005053 == Context.getCanonicalType(Specialization->getType()));
John McCallc373d482010-01-27 01:50:18 +00005054 Matches.addDecl(cast<FunctionDecl>(Specialization->getCanonicalDecl()),
5055 I.getAccess());
Douglas Gregor83314aa2009-07-08 20:55:45 +00005056 }
John McCallba135432009-11-21 08:51:07 +00005057
5058 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00005059 }
Mike Stump1eb44332009-09-09 15:08:12 +00005060
Chandler Carruthbd647292009-12-29 06:17:27 +00005061 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00005062 // Skip non-static functions when converting to pointer, and static
5063 // when converting to member pointer.
5064 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00005065 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005066
5067 // If we have explicit template arguments, skip non-templates.
John McCall7bb12da2010-02-02 06:20:04 +00005068 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005069 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00005070 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00005071 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00005072
Chandler Carruthbd647292009-12-29 06:17:27 +00005073 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00005074 QualType ResultTy;
5075 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5076 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5077 ResultTy)) {
John McCallc373d482010-01-27 01:50:18 +00005078 Matches.addDecl(cast<FunctionDecl>(FunDecl->getCanonicalDecl()),
5079 I.getAccess());
Douglas Gregor00aeb522009-07-08 23:33:52 +00005080 FoundNonTemplateFunction = true;
5081 }
Mike Stump1eb44332009-09-09 15:08:12 +00005082 }
Douglas Gregor904eed32008-11-10 20:40:00 +00005083 }
5084
Douglas Gregor00aeb522009-07-08 23:33:52 +00005085 // If there were 0 or 1 matches, we're done.
5086 if (Matches.empty())
5087 return 0;
Sebastian Redl07ab2022009-10-17 21:12:09 +00005088 else if (Matches.size() == 1) {
John McCallc373d482010-01-27 01:50:18 +00005089 FunctionDecl *Result = cast<FunctionDecl>(*Matches.begin());
Sebastian Redl07ab2022009-10-17 21:12:09 +00005090 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCallc373d482010-01-27 01:50:18 +00005091 if (Complain)
5092 CheckUnresolvedAccess(*this, OvlExpr, Result, Matches.begin().getAccess());
Sebastian Redl07ab2022009-10-17 21:12:09 +00005093 return Result;
5094 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00005095
5096 // C++ [over.over]p4:
5097 // If more than one function is selected, [...]
Douglas Gregor312a2022009-09-26 03:56:17 +00005098 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005099 // [...] and any given function template specialization F1 is
5100 // eliminated if the set contains a second function template
5101 // specialization whose function template is more specialized
5102 // than the function template of F1 according to the partial
5103 // ordering rules of 14.5.5.2.
5104
5105 // The algorithm specified above is quadratic. We instead use a
5106 // two-pass algorithm (similar to the one used to identify the
5107 // best viable function in an overload set) that identifies the
5108 // best function template (if it exists).
John McCallc373d482010-01-27 01:50:18 +00005109
5110 UnresolvedSetIterator Result =
5111 getMostSpecialized(Matches.begin(), Matches.end(),
Sebastian Redl07ab2022009-10-17 21:12:09 +00005112 TPOC_Other, From->getLocStart(),
5113 PDiag(),
5114 PDiag(diag::err_addr_ovl_ambiguous)
John McCallc373d482010-01-27 01:50:18 +00005115 << Matches[0]->getDeclName(),
John McCall220ccbf2010-01-13 00:25:19 +00005116 PDiag(diag::note_ovl_candidate)
5117 << (unsigned) oc_function_template);
John McCallc373d482010-01-27 01:50:18 +00005118 assert(Result != Matches.end() && "no most-specialized template");
5119 MarkDeclarationReferenced(From->getLocStart(), *Result);
5120 if (Complain)
5121 CheckUnresolvedAccess(*this, OvlExpr, *Result, Result.getAccess());
5122 return cast<FunctionDecl>(*Result);
Douglas Gregor00aeb522009-07-08 23:33:52 +00005123 }
Mike Stump1eb44332009-09-09 15:08:12 +00005124
Douglas Gregor312a2022009-09-26 03:56:17 +00005125 // [...] any function template specializations in the set are
5126 // eliminated if the set also contains a non-template function, [...]
John McCallc373d482010-01-27 01:50:18 +00005127 for (unsigned I = 0, N = Matches.size(); I != N; ) {
5128 if (cast<FunctionDecl>(Matches[I].getDecl())->getPrimaryTemplate() == 0)
5129 ++I;
5130 else {
5131 Matches.erase(I);
5132 --N;
5133 }
5134 }
Douglas Gregor312a2022009-09-26 03:56:17 +00005135
Mike Stump1eb44332009-09-09 15:08:12 +00005136 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00005137 // selected function.
John McCallc373d482010-01-27 01:50:18 +00005138 if (Matches.size() == 1) {
5139 UnresolvedSetIterator Match = Matches.begin();
5140 MarkDeclarationReferenced(From->getLocStart(), *Match);
5141 if (Complain)
5142 CheckUnresolvedAccess(*this, OvlExpr, *Match, Match.getAccess());
5143 return cast<FunctionDecl>(*Match);
Sebastian Redl07ab2022009-10-17 21:12:09 +00005144 }
Mike Stump1eb44332009-09-09 15:08:12 +00005145
Douglas Gregor00aeb522009-07-08 23:33:52 +00005146 // FIXME: We should probably return the same thing that BestViableFunction
5147 // returns (even if we issue the diagnostics here).
5148 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCallc373d482010-01-27 01:50:18 +00005149 << Matches[0]->getDeclName();
5150 for (UnresolvedSetIterator I = Matches.begin(),
5151 E = Matches.end(); I != E; ++I)
5152 NoteOverloadCandidate(cast<FunctionDecl>(*I));
Douglas Gregor904eed32008-11-10 20:40:00 +00005153 return 0;
5154}
5155
Douglas Gregor4b52e252009-12-21 23:17:24 +00005156/// \brief Given an expression that refers to an overloaded function, try to
5157/// resolve that overloaded function expression down to a single function.
5158///
5159/// This routine can only resolve template-ids that refer to a single function
5160/// template, where that template-id refers to a single template whose template
5161/// arguments are either provided by the template-id or have defaults,
5162/// as described in C++0x [temp.arg.explicit]p3.
5163FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5164 // C++ [over.over]p1:
5165 // [...] [Note: any redundant set of parentheses surrounding the
5166 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00005167 // C++ [over.over]p1:
5168 // [...] The overloaded function name can be preceded by the &
5169 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00005170
5171 if (From->getType() != Context.OverloadTy)
5172 return 0;
5173
5174 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor4b52e252009-12-21 23:17:24 +00005175
5176 // If we didn't actually find any template-ids, we're done.
John McCall7bb12da2010-02-02 06:20:04 +00005177 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00005178 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00005179
5180 TemplateArgumentListInfo ExplicitTemplateArgs;
5181 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor4b52e252009-12-21 23:17:24 +00005182
5183 // Look through all of the overloaded functions, searching for one
5184 // whose type matches exactly.
5185 FunctionDecl *Matched = 0;
John McCall7bb12da2010-02-02 06:20:04 +00005186 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5187 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00005188 // C++0x [temp.arg.explicit]p3:
5189 // [...] In contexts where deduction is done and fails, or in contexts
5190 // where deduction is not done, if a template argument list is
5191 // specified and it, along with any default template arguments,
5192 // identifies a single function template specialization, then the
5193 // template-id is an lvalue for the function template specialization.
5194 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5195
5196 // C++ [over.over]p2:
5197 // If the name is a function template, template argument deduction is
5198 // done (14.8.2.2), and if the argument deduction succeeds, the
5199 // resulting template argument list is used to generate a single
5200 // function template specialization, which is added to the set of
5201 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00005202 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00005203 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00005204 if (TemplateDeductionResult Result
5205 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5206 Specialization, Info)) {
5207 // FIXME: make a note of the failed deduction for diagnostics.
5208 (void)Result;
5209 continue;
5210 }
5211
5212 // Multiple matches; we can't resolve to a single declaration.
5213 if (Matched)
5214 return 0;
5215
5216 Matched = Specialization;
5217 }
5218
5219 return Matched;
5220}
5221
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005222/// \brief Add a single candidate to the overload set.
5223static void AddOverloadedCallCandidate(Sema &S,
John McCallba135432009-11-21 08:51:07 +00005224 NamedDecl *Callee,
John McCall86820f52010-01-26 01:37:31 +00005225 AccessSpecifier Access,
John McCalld5532b62009-11-23 01:53:49 +00005226 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005227 Expr **Args, unsigned NumArgs,
5228 OverloadCandidateSet &CandidateSet,
5229 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00005230 if (isa<UsingShadowDecl>(Callee))
5231 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5232
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005233 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00005234 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCall86820f52010-01-26 01:37:31 +00005235 S.AddOverloadCandidate(Func, Access, Args, NumArgs, CandidateSet,
5236 false, false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005237 return;
John McCallba135432009-11-21 08:51:07 +00005238 }
5239
5240 if (FunctionTemplateDecl *FuncTemplate
5241 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall86820f52010-01-26 01:37:31 +00005242 S.AddTemplateOverloadCandidate(FuncTemplate, Access, ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00005243 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00005244 return;
5245 }
5246
5247 assert(false && "unhandled case in overloaded call candidate");
5248
5249 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005250}
5251
5252/// \brief Add the overload candidates named by callee and/or found by argument
5253/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00005254void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005255 Expr **Args, unsigned NumArgs,
5256 OverloadCandidateSet &CandidateSet,
5257 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00005258
5259#ifndef NDEBUG
5260 // Verify that ArgumentDependentLookup is consistent with the rules
5261 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005262 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005263 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5264 // and let Y be the lookup set produced by argument dependent
5265 // lookup (defined as follows). If X contains
5266 //
5267 // -- a declaration of a class member, or
5268 //
5269 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00005270 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005271 //
5272 // -- a declaration that is neither a function or a function
5273 // template
5274 //
5275 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00005276
John McCall3b4294e2009-12-16 12:17:52 +00005277 if (ULE->requiresADL()) {
5278 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5279 E = ULE->decls_end(); I != E; ++I) {
5280 assert(!(*I)->getDeclContext()->isRecord());
5281 assert(isa<UsingShadowDecl>(*I) ||
5282 !(*I)->getDeclContext()->isFunctionOrMethod());
5283 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00005284 }
5285 }
5286#endif
5287
John McCall3b4294e2009-12-16 12:17:52 +00005288 // It would be nice to avoid this copy.
5289 TemplateArgumentListInfo TABuffer;
5290 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5291 if (ULE->hasExplicitTemplateArgs()) {
5292 ULE->copyTemplateArgumentsInto(TABuffer);
5293 ExplicitTemplateArgs = &TABuffer;
5294 }
5295
5296 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5297 E = ULE->decls_end(); I != E; ++I)
John McCall86820f52010-01-26 01:37:31 +00005298 AddOverloadedCallCandidate(*this, *I, I.getAccess(), ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00005299 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005300 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00005301
John McCall3b4294e2009-12-16 12:17:52 +00005302 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00005303 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
5304 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005305 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005306 CandidateSet,
5307 PartialOverloading);
5308}
John McCall578b69b2009-12-16 08:11:27 +00005309
John McCall3b4294e2009-12-16 12:17:52 +00005310static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5311 Expr **Args, unsigned NumArgs) {
5312 Fn->Destroy(SemaRef.Context);
5313 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5314 Args[Arg]->Destroy(SemaRef.Context);
5315 return SemaRef.ExprError();
5316}
5317
John McCall578b69b2009-12-16 08:11:27 +00005318/// Attempts to recover from a call where no functions were found.
5319///
5320/// Returns true if new candidates were found.
John McCall3b4294e2009-12-16 12:17:52 +00005321static Sema::OwningExprResult
5322BuildRecoveryCallExpr(Sema &SemaRef, Expr *Fn,
5323 UnresolvedLookupExpr *ULE,
5324 SourceLocation LParenLoc,
5325 Expr **Args, unsigned NumArgs,
5326 SourceLocation *CommaLocs,
5327 SourceLocation RParenLoc) {
John McCall578b69b2009-12-16 08:11:27 +00005328
5329 CXXScopeSpec SS;
5330 if (ULE->getQualifier()) {
5331 SS.setScopeRep(ULE->getQualifier());
5332 SS.setRange(ULE->getQualifierRange());
5333 }
5334
John McCall3b4294e2009-12-16 12:17:52 +00005335 TemplateArgumentListInfo TABuffer;
5336 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5337 if (ULE->hasExplicitTemplateArgs()) {
5338 ULE->copyTemplateArgumentsInto(TABuffer);
5339 ExplicitTemplateArgs = &TABuffer;
5340 }
5341
John McCall578b69b2009-12-16 08:11:27 +00005342 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5343 Sema::LookupOrdinaryName);
Douglas Gregorbb092ba2009-12-31 05:20:13 +00005344 if (SemaRef.DiagnoseEmptyLookup(/*Scope=*/0, SS, R))
John McCall3b4294e2009-12-16 12:17:52 +00005345 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCall578b69b2009-12-16 08:11:27 +00005346
John McCall3b4294e2009-12-16 12:17:52 +00005347 assert(!R.empty() && "lookup results empty despite recovery");
5348
5349 // Build an implicit member call if appropriate. Just drop the
5350 // casts and such from the call, we don't really care.
5351 Sema::OwningExprResult NewFn = SemaRef.ExprError();
5352 if ((*R.begin())->isCXXClassMember())
5353 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5354 else if (ExplicitTemplateArgs)
5355 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5356 else
5357 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5358
5359 if (NewFn.isInvalid())
5360 return Destroy(SemaRef, Fn, Args, NumArgs);
5361
5362 Fn->Destroy(SemaRef.Context);
5363
5364 // This shouldn't cause an infinite loop because we're giving it
5365 // an expression with non-empty lookup results, which should never
5366 // end up here.
5367 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5368 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5369 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00005370}
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005371
Douglas Gregorf6b89692008-11-26 05:54:23 +00005372/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00005373/// (which eventually refers to the declaration Func) and the call
5374/// arguments Args/NumArgs, attempt to resolve the function call down
5375/// to a specific function. If overload resolution succeeds, returns
5376/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00005377/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00005378/// arguments and Fn, and returns NULL.
John McCall3b4294e2009-12-16 12:17:52 +00005379Sema::OwningExprResult
5380Sema::BuildOverloadedCallExpr(Expr *Fn, UnresolvedLookupExpr *ULE,
5381 SourceLocation LParenLoc,
5382 Expr **Args, unsigned NumArgs,
5383 SourceLocation *CommaLocs,
5384 SourceLocation RParenLoc) {
5385#ifndef NDEBUG
5386 if (ULE->requiresADL()) {
5387 // To do ADL, we must have found an unqualified name.
5388 assert(!ULE->getQualifier() && "qualified name with ADL");
5389
5390 // We don't perform ADL for implicit declarations of builtins.
5391 // Verify that this was correctly set up.
5392 FunctionDecl *F;
5393 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5394 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5395 F->getBuiltinID() && F->isImplicit())
5396 assert(0 && "performing ADL for builtin");
5397
5398 // We don't perform ADL in C.
5399 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5400 }
5401#endif
5402
John McCall5769d612010-02-08 23:07:23 +00005403 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00005404
John McCall3b4294e2009-12-16 12:17:52 +00005405 // Add the functions denoted by the callee to the set of candidate
5406 // functions, including those from argument-dependent lookup.
5407 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00005408
5409 // If we found nothing, try to recover.
5410 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5411 // bailout out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00005412 if (CandidateSet.empty())
5413 return BuildRecoveryCallExpr(*this, Fn, ULE, LParenLoc, Args, NumArgs,
5414 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00005415
Douglas Gregorf6b89692008-11-26 05:54:23 +00005416 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005417 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00005418 case OR_Success: {
5419 FunctionDecl *FDecl = Best->Function;
John McCallc373d482010-01-27 01:50:18 +00005420 CheckUnresolvedLookupAccess(ULE, FDecl, Best->getAccess());
John McCall3b4294e2009-12-16 12:17:52 +00005421 Fn = FixOverloadedFunctionReference(Fn, FDecl);
5422 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5423 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00005424
5425 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00005426 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00005427 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00005428 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005429 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00005430 break;
5431
5432 case OR_Ambiguous:
5433 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00005434 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005435 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00005436 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005437
5438 case OR_Deleted:
5439 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5440 << Best->Function->isDeleted()
John McCall3b4294e2009-12-16 12:17:52 +00005441 << ULE->getName()
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005442 << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005443 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005444 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00005445 }
5446
5447 // Overload resolution failed. Destroy all of the subexpressions and
5448 // return NULL.
5449 Fn->Destroy(Context);
5450 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5451 Args[Arg]->Destroy(Context);
John McCall3b4294e2009-12-16 12:17:52 +00005452 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00005453}
5454
John McCall6e266892010-01-26 03:27:55 +00005455static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00005456 return Functions.size() > 1 ||
5457 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5458}
5459
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005460/// \brief Create a unary operation that may resolve to an overloaded
5461/// operator.
5462///
5463/// \param OpLoc The location of the operator itself (e.g., '*').
5464///
5465/// \param OpcIn The UnaryOperator::Opcode that describes this
5466/// operator.
5467///
5468/// \param Functions The set of non-member functions that will be
5469/// considered by overload resolution. The caller needs to build this
5470/// set based on the context using, e.g.,
5471/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5472/// set should not contain any member functions; those will be added
5473/// by CreateOverloadedUnaryOp().
5474///
5475/// \param input The input argument.
John McCall6e266892010-01-26 03:27:55 +00005476Sema::OwningExprResult
5477Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
5478 const UnresolvedSetImpl &Fns,
5479 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005480 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5481 Expr *Input = (Expr *)input.get();
5482
5483 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5484 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5485 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5486
5487 Expr *Args[2] = { Input, 0 };
5488 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00005489
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005490 // For post-increment and post-decrement, add the implicit '0' as
5491 // the second argument, so that we know this is a post-increment or
5492 // post-decrement.
5493 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5494 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump1eb44332009-09-09 15:08:12 +00005495 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005496 SourceLocation());
5497 NumArgs = 2;
5498 }
5499
5500 if (Input->isTypeDependent()) {
John McCallc373d482010-01-27 01:50:18 +00005501 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00005502 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00005503 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00005504 0, SourceRange(), OpName, OpLoc,
John McCall6e266892010-01-26 03:27:55 +00005505 /*ADL*/ true, IsOverloaded(Fns));
5506 Fn->addDecls(Fns.begin(), Fns.end());
Mike Stump1eb44332009-09-09 15:08:12 +00005507
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005508 input.release();
5509 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5510 &Args[0], NumArgs,
5511 Context.DependentTy,
5512 OpLoc));
5513 }
5514
5515 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00005516 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005517
5518 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00005519 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005520
5521 // Add operator candidates that are member functions.
5522 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5523
John McCall6e266892010-01-26 03:27:55 +00005524 // Add candidates from ADL.
5525 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00005526 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00005527 /*ExplicitTemplateArgs*/ 0,
5528 CandidateSet);
5529
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005530 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00005531 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005532
5533 // Perform overload resolution.
5534 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005535 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005536 case OR_Success: {
5537 // We found a built-in operator or an overloaded operator.
5538 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00005539
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005540 if (FnDecl) {
5541 // We matched an overloaded operator. Build a call to that
5542 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00005543
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005544 // Convert the arguments.
5545 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00005546 CheckMemberOperatorAccess(OpLoc, Args[0], Method, Best->getAccess());
5547
Douglas Gregora7cb22d2010-03-03 23:26:56 +00005548 if (PerformObjectArgumentInitialization(Input, Method))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005549 return ExprError();
5550 } else {
5551 // Convert the arguments.
Douglas Gregore1a5c172009-12-23 17:40:29 +00005552 OwningExprResult InputInit
5553 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregorbaecfed2009-12-23 00:02:00 +00005554 FnDecl->getParamDecl(0)),
Douglas Gregore1a5c172009-12-23 17:40:29 +00005555 SourceLocation(),
5556 move(input));
5557 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005558 return ExprError();
Douglas Gregorbaecfed2009-12-23 00:02:00 +00005559
Douglas Gregore1a5c172009-12-23 17:40:29 +00005560 input = move(InputInit);
Douglas Gregorbaecfed2009-12-23 00:02:00 +00005561 Input = (Expr *)input.get();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005562 }
5563
5564 // Determine the result type
Anders Carlsson26a2a072009-10-13 21:19:37 +00005565 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00005566
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005567 // Build the actual expression node.
5568 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5569 SourceLocation());
5570 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00005571
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005572 input.release();
Eli Friedman4c3b8962009-11-18 03:58:17 +00005573 Args[0] = Input;
Anders Carlsson26a2a072009-10-13 21:19:37 +00005574 ExprOwningPtr<CallExpr> TheCall(this,
5575 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman4c3b8962009-11-18 03:58:17 +00005576 Args, NumArgs, ResultTy, OpLoc));
Anders Carlsson26a2a072009-10-13 21:19:37 +00005577
5578 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5579 FnDecl))
5580 return ExprError();
5581
5582 return MaybeBindToTemporary(TheCall.release());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005583 } else {
5584 // We matched a built-in operator. Convert the arguments, then
5585 // break out so that we will build the appropriate built-in
5586 // operator node.
5587 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00005588 Best->Conversions[0], AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005589 return ExprError();
5590
5591 break;
5592 }
5593 }
5594
5595 case OR_No_Viable_Function:
5596 // No viable function; fall through to handling this as a
5597 // built-in operator, which will produce an error message for us.
5598 break;
5599
5600 case OR_Ambiguous:
5601 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5602 << UnaryOperator::getOpcodeStr(Opc)
5603 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005604 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005605 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005606 return ExprError();
5607
5608 case OR_Deleted:
5609 Diag(OpLoc, diag::err_ovl_deleted_oper)
5610 << Best->Function->isDeleted()
5611 << UnaryOperator::getOpcodeStr(Opc)
5612 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005613 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005614 return ExprError();
5615 }
5616
5617 // Either we found no viable overloaded operator or we matched a
5618 // built-in operator. In either case, fall through to trying to
5619 // build a built-in operation.
5620 input.release();
5621 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5622}
5623
Douglas Gregor063daf62009-03-13 18:40:31 +00005624/// \brief Create a binary operation that may resolve to an overloaded
5625/// operator.
5626///
5627/// \param OpLoc The location of the operator itself (e.g., '+').
5628///
5629/// \param OpcIn The BinaryOperator::Opcode that describes this
5630/// operator.
5631///
5632/// \param Functions The set of non-member functions that will be
5633/// considered by overload resolution. The caller needs to build this
5634/// set based on the context using, e.g.,
5635/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5636/// set should not contain any member functions; those will be added
5637/// by CreateOverloadedBinOp().
5638///
5639/// \param LHS Left-hand argument.
5640/// \param RHS Right-hand argument.
Mike Stump1eb44332009-09-09 15:08:12 +00005641Sema::OwningExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00005642Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005643 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00005644 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00005645 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00005646 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005647 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00005648
5649 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5650 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5651 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5652
5653 // If either side is type-dependent, create an appropriate dependent
5654 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005655 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00005656 if (Fns.empty()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005657 // If there are no functions to store, just build a dependent
5658 // BinaryOperator or CompoundAssignment.
5659 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
5660 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
5661 Context.DependentTy, OpLoc));
5662
5663 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
5664 Context.DependentTy,
5665 Context.DependentTy,
5666 Context.DependentTy,
5667 OpLoc));
5668 }
John McCall6e266892010-01-26 03:27:55 +00005669
5670 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00005671 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00005672 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00005673 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00005674 0, SourceRange(), OpName, OpLoc,
John McCall6e266892010-01-26 03:27:55 +00005675 /*ADL*/ true, IsOverloaded(Fns));
Mike Stump1eb44332009-09-09 15:08:12 +00005676
John McCall6e266892010-01-26 03:27:55 +00005677 Fn->addDecls(Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00005678 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00005679 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00005680 Context.DependentTy,
5681 OpLoc));
5682 }
5683
5684 // If this is the .* operator, which is not overloadable, just
5685 // create a built-in binary operator.
5686 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005687 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00005688
Sebastian Redl275c2b42009-11-18 23:10:33 +00005689 // If this is the assignment operator, we only perform overload resolution
5690 // if the left-hand side is a class or enumeration type. This is actually
5691 // a hack. The standard requires that we do overload resolution between the
5692 // various built-in candidates, but as DR507 points out, this can lead to
5693 // problems. So we do it this way, which pretty much follows what GCC does.
5694 // Note that we go the traditional code path for compound assignment forms.
5695 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005696 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00005697
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005698 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00005699 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00005700
5701 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00005702 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00005703
5704 // Add operator candidates that are member functions.
5705 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
5706
John McCall6e266892010-01-26 03:27:55 +00005707 // Add candidates from ADL.
5708 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
5709 Args, 2,
5710 /*ExplicitTemplateArgs*/ 0,
5711 CandidateSet);
5712
Douglas Gregor063daf62009-03-13 18:40:31 +00005713 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00005714 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00005715
5716 // Perform overload resolution.
5717 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005718 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005719 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00005720 // We found a built-in operator or an overloaded operator.
5721 FunctionDecl *FnDecl = Best->Function;
5722
5723 if (FnDecl) {
5724 // We matched an overloaded operator. Build a call to that
5725 // operator.
5726
5727 // Convert the arguments.
5728 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00005729 // Best->Access is only meaningful for class members.
5730 CheckMemberOperatorAccess(OpLoc, Args[0], Method, Best->getAccess());
5731
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005732 OwningExprResult Arg1
5733 = PerformCopyInitialization(
5734 InitializedEntity::InitializeParameter(
5735 FnDecl->getParamDecl(0)),
5736 SourceLocation(),
5737 Owned(Args[1]));
5738 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00005739 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005740
Douglas Gregora7cb22d2010-03-03 23:26:56 +00005741 if (PerformObjectArgumentInitialization(Args[0], Method))
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005742 return ExprError();
5743
5744 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00005745 } else {
5746 // Convert the arguments.
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005747 OwningExprResult Arg0
5748 = PerformCopyInitialization(
5749 InitializedEntity::InitializeParameter(
5750 FnDecl->getParamDecl(0)),
5751 SourceLocation(),
5752 Owned(Args[0]));
5753 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00005754 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00005755
5756 OwningExprResult Arg1
5757 = PerformCopyInitialization(
5758 InitializedEntity::InitializeParameter(
5759 FnDecl->getParamDecl(1)),
5760 SourceLocation(),
5761 Owned(Args[1]));
5762 if (Arg1.isInvalid())
5763 return ExprError();
5764 Args[0] = LHS = Arg0.takeAs<Expr>();
5765 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00005766 }
5767
5768 // Determine the result type
5769 QualType ResultTy
John McCall183700f2009-09-21 23:43:11 +00005770 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor063daf62009-03-13 18:40:31 +00005771 ResultTy = ResultTy.getNonReferenceType();
5772
5773 // Build the actual expression node.
5774 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00005775 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00005776 UsualUnaryConversions(FnExpr);
5777
Anders Carlsson15ea3782009-10-13 22:43:21 +00005778 ExprOwningPtr<CXXOperatorCallExpr>
5779 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
5780 Args, 2, ResultTy,
5781 OpLoc));
5782
5783 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5784 FnDecl))
5785 return ExprError();
5786
5787 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor063daf62009-03-13 18:40:31 +00005788 } else {
5789 // We matched a built-in operator. Convert the arguments, then
5790 // break out so that we will build the appropriate built-in
5791 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005792 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00005793 Best->Conversions[0], AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005794 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00005795 Best->Conversions[1], AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00005796 return ExprError();
5797
5798 break;
5799 }
5800 }
5801
Douglas Gregor33074752009-09-30 21:46:01 +00005802 case OR_No_Viable_Function: {
5803 // C++ [over.match.oper]p9:
5804 // If the operator is the operator , [...] and there are no
5805 // viable functions, then the operator is assumed to be the
5806 // built-in operator and interpreted according to clause 5.
5807 if (Opc == BinaryOperator::Comma)
5808 break;
5809
Sebastian Redl8593c782009-05-21 11:50:50 +00005810 // For class as left operand for assignment or compound assigment operator
5811 // do not fall through to handling in built-in, but report that no overloaded
5812 // assignment operator found
Douglas Gregor33074752009-09-30 21:46:01 +00005813 OwningExprResult Result = ExprError();
5814 if (Args[0]->getType()->isRecordType() &&
5815 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00005816 Diag(OpLoc, diag::err_ovl_no_viable_oper)
5817 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005818 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00005819 } else {
5820 // No viable function; try to create a built-in operation, which will
5821 // produce an error. Then, show the non-viable candidates.
5822 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00005823 }
Douglas Gregor33074752009-09-30 21:46:01 +00005824 assert(Result.isInvalid() &&
5825 "C++ binary operator overloading is missing candidates!");
5826 if (Result.isInvalid())
John McCallcbce6062010-01-12 07:18:19 +00005827 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005828 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00005829 return move(Result);
5830 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005831
5832 case OR_Ambiguous:
5833 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5834 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005835 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005836 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005837 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00005838 return ExprError();
5839
5840 case OR_Deleted:
5841 Diag(OpLoc, diag::err_ovl_deleted_oper)
5842 << Best->Function->isDeleted()
5843 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005844 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005845 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor063daf62009-03-13 18:40:31 +00005846 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00005847 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005848
Douglas Gregor33074752009-09-30 21:46:01 +00005849 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005850 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00005851}
5852
Sebastian Redlf322ed62009-10-29 20:17:01 +00005853Action::OwningExprResult
5854Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5855 SourceLocation RLoc,
5856 ExprArg Base, ExprArg Idx) {
5857 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5858 static_cast<Expr*>(Idx.get()) };
5859 DeclarationName OpName =
5860 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5861
5862 // If either side is type-dependent, create an appropriate dependent
5863 // expression.
5864 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5865
John McCallc373d482010-01-27 01:50:18 +00005866 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00005867 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00005868 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00005869 0, SourceRange(), OpName, LLoc,
John McCall7453ed42009-11-22 00:44:51 +00005870 /*ADL*/ true, /*Overloaded*/ false);
John McCallf7a1a742009-11-24 19:00:30 +00005871 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00005872
5873 Base.release();
5874 Idx.release();
5875 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5876 Args, 2,
5877 Context.DependentTy,
5878 RLoc));
5879 }
5880
5881 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00005882 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00005883
5884 // Subscript can only be overloaded as a member function.
5885
5886 // Add operator candidates that are member functions.
5887 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5888
5889 // Add builtin operator candidates.
5890 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5891
5892 // Perform overload resolution.
5893 OverloadCandidateSet::iterator Best;
5894 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5895 case OR_Success: {
5896 // We found a built-in operator or an overloaded operator.
5897 FunctionDecl *FnDecl = Best->Function;
5898
5899 if (FnDecl) {
5900 // We matched an overloaded operator. Build a call to that
5901 // operator.
5902
John McCall5357b612010-01-28 01:42:12 +00005903 CheckMemberOperatorAccess(LLoc, Args[0], FnDecl, Best->getAccess());
John McCallc373d482010-01-27 01:50:18 +00005904
Sebastian Redlf322ed62009-10-29 20:17:01 +00005905 // Convert the arguments.
5906 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregora7cb22d2010-03-03 23:26:56 +00005907 if (PerformObjectArgumentInitialization(Args[0], Method))
Sebastian Redlf322ed62009-10-29 20:17:01 +00005908 return ExprError();
5909
Anders Carlsson38f88ab2010-01-29 18:37:50 +00005910 // Convert the arguments.
5911 OwningExprResult InputInit
5912 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
5913 FnDecl->getParamDecl(0)),
5914 SourceLocation(),
5915 Owned(Args[1]));
5916 if (InputInit.isInvalid())
5917 return ExprError();
5918
5919 Args[1] = InputInit.takeAs<Expr>();
5920
Sebastian Redlf322ed62009-10-29 20:17:01 +00005921 // Determine the result type
5922 QualType ResultTy
5923 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5924 ResultTy = ResultTy.getNonReferenceType();
5925
5926 // Build the actual expression node.
5927 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5928 LLoc);
5929 UsualUnaryConversions(FnExpr);
5930
5931 Base.release();
5932 Idx.release();
5933 ExprOwningPtr<CXXOperatorCallExpr>
5934 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5935 FnExpr, Args, 2,
5936 ResultTy, RLoc));
5937
5938 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5939 FnDecl))
5940 return ExprError();
5941
5942 return MaybeBindToTemporary(TheCall.release());
5943 } else {
5944 // We matched a built-in operator. Convert the arguments, then
5945 // break out so that we will build the appropriate built-in
5946 // operator node.
5947 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00005948 Best->Conversions[0], AA_Passing) ||
Sebastian Redlf322ed62009-10-29 20:17:01 +00005949 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00005950 Best->Conversions[1], AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00005951 return ExprError();
5952
5953 break;
5954 }
5955 }
5956
5957 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00005958 if (CandidateSet.empty())
5959 Diag(LLoc, diag::err_ovl_no_oper)
5960 << Args[0]->getType() << /*subscript*/ 0
5961 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5962 else
5963 Diag(LLoc, diag::err_ovl_no_viable_subscript)
5964 << Args[0]->getType()
5965 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005966 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall1eb3e102010-01-07 02:04:15 +00005967 "[]", LLoc);
5968 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00005969 }
5970
5971 case OR_Ambiguous:
5972 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5973 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005974 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redlf322ed62009-10-29 20:17:01 +00005975 "[]", LLoc);
5976 return ExprError();
5977
5978 case OR_Deleted:
5979 Diag(LLoc, diag::err_ovl_deleted_oper)
5980 << Best->Function->isDeleted() << "[]"
5981 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00005982 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall81201622010-01-08 04:41:39 +00005983 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00005984 return ExprError();
5985 }
5986
5987 // We matched a built-in operator; build it.
5988 Base.release();
5989 Idx.release();
5990 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5991 Owned(Args[1]), RLoc);
5992}
5993
Douglas Gregor88a35142008-12-22 05:46:06 +00005994/// BuildCallToMemberFunction - Build a call to a member
5995/// function. MemExpr is the expression that refers to the member
5996/// function (and includes the object parameter), Args/NumArgs are the
5997/// arguments to the function call (not including the object
5998/// parameter). The caller needs to validate that the member
5999/// expression refers to a member function or an overloaded member
6000/// function.
John McCallaa81e162009-12-01 22:10:20 +00006001Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00006002Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6003 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor88a35142008-12-22 05:46:06 +00006004 unsigned NumArgs, SourceLocation *CommaLocs,
6005 SourceLocation RParenLoc) {
6006 // Dig out the member expression. This holds both the object
6007 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00006008 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6009
John McCall129e2df2009-11-30 22:42:35 +00006010 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00006011 CXXMethodDecl *Method = 0;
John McCall129e2df2009-11-30 22:42:35 +00006012 if (isa<MemberExpr>(NakedMemExpr)) {
6013 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00006014 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
6015 } else {
6016 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregora7cb22d2010-03-03 23:26:56 +00006017
John McCall701c89e2009-12-03 04:06:58 +00006018 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00006019
Douglas Gregor88a35142008-12-22 05:46:06 +00006020 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00006021 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00006022
John McCallaa81e162009-12-01 22:10:20 +00006023 // FIXME: avoid copy.
6024 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6025 if (UnresExpr->hasExplicitTemplateArgs()) {
6026 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6027 TemplateArgs = &TemplateArgsBuffer;
6028 }
6029
John McCall129e2df2009-11-30 22:42:35 +00006030 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6031 E = UnresExpr->decls_end(); I != E; ++I) {
6032
John McCall701c89e2009-12-03 04:06:58 +00006033 NamedDecl *Func = *I;
6034 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6035 if (isa<UsingShadowDecl>(Func))
6036 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6037
John McCall129e2df2009-11-30 22:42:35 +00006038 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006039 // If explicit template arguments were provided, we can't call a
6040 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00006041 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006042 continue;
6043
John McCall86820f52010-01-26 01:37:31 +00006044 AddMethodCandidate(Method, I.getAccess(), ActingDC, ObjectType,
6045 Args, NumArgs,
John McCall701c89e2009-12-03 04:06:58 +00006046 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00006047 } else {
John McCall129e2df2009-11-30 22:42:35 +00006048 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall86820f52010-01-26 01:37:31 +00006049 I.getAccess(), ActingDC, TemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00006050 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00006051 CandidateSet,
6052 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00006053 }
Douglas Gregordec06662009-08-21 18:42:58 +00006054 }
Mike Stump1eb44332009-09-09 15:08:12 +00006055
John McCall129e2df2009-11-30 22:42:35 +00006056 DeclarationName DeclName = UnresExpr->getMemberName();
6057
Douglas Gregor88a35142008-12-22 05:46:06 +00006058 OverloadCandidateSet::iterator Best;
John McCall129e2df2009-11-30 22:42:35 +00006059 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00006060 case OR_Success:
6061 Method = cast<CXXMethodDecl>(Best->Function);
John McCallc373d482010-01-27 01:50:18 +00006062 CheckUnresolvedMemberAccess(UnresExpr, Method, Best->getAccess());
Douglas Gregor88a35142008-12-22 05:46:06 +00006063 break;
6064
6065 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00006066 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00006067 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00006068 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006069 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00006070 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006071 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006072
6073 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00006074 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00006075 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006076 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00006077 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006078 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006079
6080 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00006081 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006082 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00006083 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006084 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006085 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006086 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006087 }
6088
Douglas Gregor699ee522009-11-20 19:42:02 +00006089 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
John McCallaa81e162009-12-01 22:10:20 +00006090
John McCallaa81e162009-12-01 22:10:20 +00006091 // If overload resolution picked a static member, build a
6092 // non-member call based on that function.
6093 if (Method->isStatic()) {
6094 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6095 Args, NumArgs, RParenLoc);
6096 }
6097
John McCall129e2df2009-11-30 22:42:35 +00006098 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00006099 }
6100
6101 assert(Method && "Member call to something that isn't a method?");
Mike Stump1eb44332009-09-09 15:08:12 +00006102 ExprOwningPtr<CXXMemberCallExpr>
John McCallaa81e162009-12-01 22:10:20 +00006103 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump1eb44332009-09-09 15:08:12 +00006104 NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00006105 Method->getResultType().getNonReferenceType(),
6106 RParenLoc));
6107
Anders Carlssoneed3e692009-10-10 00:06:20 +00006108 // Check for a valid return type.
6109 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6110 TheCall.get(), Method))
John McCallaa81e162009-12-01 22:10:20 +00006111 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00006112
Douglas Gregor88a35142008-12-22 05:46:06 +00006113 // Convert the object argument (for a non-static member function call).
John McCallaa81e162009-12-01 22:10:20 +00006114 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00006115 if (!Method->isStatic() &&
Douglas Gregora7cb22d2010-03-03 23:26:56 +00006116 PerformObjectArgumentInitialization(ObjectArg, Method))
John McCallaa81e162009-12-01 22:10:20 +00006117 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006118 MemExpr->setBase(ObjectArg);
6119
6120 // Convert the rest of the arguments
Douglas Gregor72564e72009-02-26 23:50:07 +00006121 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00006122 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00006123 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00006124 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006125
Anders Carlssond406bf02009-08-16 01:56:34 +00006126 if (CheckFunctionCall(Method, TheCall.get()))
John McCallaa81e162009-12-01 22:10:20 +00006127 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00006128
John McCallaa81e162009-12-01 22:10:20 +00006129 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor88a35142008-12-22 05:46:06 +00006130}
6131
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006132/// BuildCallToObjectOfClassType - Build a call to an object of class
6133/// type (C++ [over.call.object]), which can end up invoking an
6134/// overloaded function call operator (@c operator()) or performing a
6135/// user-defined conversion on the object argument.
Mike Stump1eb44332009-09-09 15:08:12 +00006136Sema::ExprResult
6137Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00006138 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006139 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00006140 SourceLocation *CommaLocs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006141 SourceLocation RParenLoc) {
6142 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00006143 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006144
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006145 // C++ [over.call.object]p1:
6146 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00006147 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006148 // candidate functions includes at least the function call
6149 // operators of T. The function call operators of T are obtained by
6150 // ordinary lookup of the name operator() in the context of
6151 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00006152 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00006153 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00006154
6155 if (RequireCompleteType(LParenLoc, Object->getType(),
6156 PartialDiagnostic(diag::err_incomplete_object_call)
6157 << Object->getSourceRange()))
6158 return true;
6159
John McCalla24dc2e2009-11-17 02:14:36 +00006160 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6161 LookupQualifiedName(R, Record->getDecl());
6162 R.suppressDiagnostics();
6163
Douglas Gregor593564b2009-11-15 07:48:03 +00006164 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00006165 Oper != OperEnd; ++Oper) {
John McCall86820f52010-01-26 01:37:31 +00006166 AddMethodCandidate(*Oper, Oper.getAccess(), Object->getType(),
6167 Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00006168 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00006169 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00006170
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006171 // C++ [over.call.object]p2:
6172 // In addition, for each conversion function declared in T of the
6173 // form
6174 //
6175 // operator conversion-type-id () cv-qualifier;
6176 //
6177 // where cv-qualifier is the same cv-qualification as, or a
6178 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00006179 // denotes the type "pointer to function of (P1,...,Pn) returning
6180 // R", or the type "reference to pointer to function of
6181 // (P1,...,Pn) returning R", or the type "reference to function
6182 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006183 // is also considered as a candidate function. Similarly,
6184 // surrogate call functions are added to the set of candidate
6185 // functions for each conversion function declared in an
6186 // accessible base class provided the function is not hidden
6187 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00006188 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00006189 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00006190 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00006191 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00006192 NamedDecl *D = *I;
6193 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6194 if (isa<UsingShadowDecl>(D))
6195 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6196
Douglas Gregor4a27d702009-10-21 06:18:39 +00006197 // Skip over templated conversion functions; they aren't
6198 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00006199 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00006200 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006201
John McCall701c89e2009-12-03 04:06:58 +00006202 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00006203
Douglas Gregor4a27d702009-10-21 06:18:39 +00006204 // Strip the reference type (if any) and then the pointer type (if
6205 // any) to get down to what might be a function type.
6206 QualType ConvType = Conv->getConversionType().getNonReferenceType();
6207 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6208 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006209
Douglas Gregor4a27d702009-10-21 06:18:39 +00006210 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall86820f52010-01-26 01:37:31 +00006211 AddSurrogateCandidate(Conv, I.getAccess(), ActingContext, Proto,
John McCall701c89e2009-12-03 04:06:58 +00006212 Object->getType(), Args, NumArgs,
6213 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006214 }
Mike Stump1eb44332009-09-09 15:08:12 +00006215
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006216 // Perform overload resolution.
6217 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006218 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006219 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006220 // Overload resolution succeeded; we'll build the appropriate call
6221 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006222 break;
6223
6224 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00006225 if (CandidateSet.empty())
6226 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
6227 << Object->getType() << /*call*/ 1
6228 << Object->getSourceRange();
6229 else
6230 Diag(Object->getSourceRange().getBegin(),
6231 diag::err_ovl_no_viable_object_call)
6232 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006233 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006234 break;
6235
6236 case OR_Ambiguous:
6237 Diag(Object->getSourceRange().getBegin(),
6238 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00006239 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006240 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006241 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006242
6243 case OR_Deleted:
6244 Diag(Object->getSourceRange().getBegin(),
6245 diag::err_ovl_deleted_object_call)
6246 << Best->Function->isDeleted()
6247 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006248 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006249 break;
Mike Stump1eb44332009-09-09 15:08:12 +00006250 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006251
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006252 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006253 // We had an error; delete all of the subexpressions and return
6254 // the error.
Ted Kremenek8189cde2009-02-07 01:47:29 +00006255 Object->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006256 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek8189cde2009-02-07 01:47:29 +00006257 Args[ArgIdx]->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006258 return true;
6259 }
6260
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006261 if (Best->Function == 0) {
6262 // Since there is no function declaration, this is one of the
6263 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00006264 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006265 = cast<CXXConversionDecl>(
6266 Best->Conversions[0].UserDefined.ConversionFunction);
6267
John McCall233a6412010-01-28 07:38:46 +00006268 CheckMemberOperatorAccess(LParenLoc, Object, Conv, Best->getAccess());
John McCall41d89032010-01-28 01:54:34 +00006269
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006270 // We selected one of the surrogate functions that converts the
6271 // object parameter to a function pointer. Perform the conversion
6272 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00006273
6274 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00006275 // and then call it.
Eli Friedmanc8c771e2009-12-09 04:52:43 +00006276 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00006277
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00006278 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00006279 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
6280 CommaLocs, RParenLoc).release();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006281 }
6282
John McCall233a6412010-01-28 07:38:46 +00006283 CheckMemberOperatorAccess(LParenLoc, Object,
6284 Best->Function, Best->getAccess());
John McCall41d89032010-01-28 01:54:34 +00006285
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006286 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6287 // that calls this method, using Object for the implicit object
6288 // parameter and passing along the remaining arguments.
6289 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00006290 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006291
6292 unsigned NumArgsInProto = Proto->getNumArgs();
6293 unsigned NumArgsToCheck = NumArgs;
6294
6295 // Build the full argument list for the method call (the
6296 // implicit object parameter is placed at the beginning of the
6297 // list).
6298 Expr **MethodArgs;
6299 if (NumArgs < NumArgsInProto) {
6300 NumArgsToCheck = NumArgsInProto;
6301 MethodArgs = new Expr*[NumArgsInProto + 1];
6302 } else {
6303 MethodArgs = new Expr*[NumArgs + 1];
6304 }
6305 MethodArgs[0] = Object;
6306 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6307 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00006308
6309 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00006310 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006311 UsualUnaryConversions(NewFn);
6312
6313 // Once we've built TheCall, all of the expressions are properly
6314 // owned.
6315 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00006316 ExprOwningPtr<CXXOperatorCallExpr>
6317 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor063daf62009-03-13 18:40:31 +00006318 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00006319 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006320 delete [] MethodArgs;
6321
Anders Carlsson07d68f12009-10-13 21:49:31 +00006322 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6323 Method))
6324 return true;
6325
Douglas Gregor518fda12009-01-13 05:10:00 +00006326 // We may have default arguments. If so, we need to allocate more
6327 // slots in the call for them.
6328 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00006329 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00006330 else if (NumArgs > NumArgsInProto)
6331 NumArgsToCheck = NumArgsInProto;
6332
Chris Lattner312531a2009-04-12 08:11:20 +00006333 bool IsError = false;
6334
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006335 // Initialize the implicit object parameter.
Douglas Gregora7cb22d2010-03-03 23:26:56 +00006336 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006337 TheCall->setArg(0, Object);
6338
Chris Lattner312531a2009-04-12 08:11:20 +00006339
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006340 // Check the argument types.
6341 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006342 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00006343 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006344 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00006345
Douglas Gregor518fda12009-01-13 05:10:00 +00006346 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +00006347
6348 OwningExprResult InputInit
6349 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6350 Method->getParamDecl(i)),
6351 SourceLocation(), Owned(Arg));
6352
6353 IsError |= InputInit.isInvalid();
6354 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00006355 } else {
Douglas Gregord47c47d2009-11-09 19:27:57 +00006356 OwningExprResult DefArg
6357 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6358 if (DefArg.isInvalid()) {
6359 IsError = true;
6360 break;
6361 }
6362
6363 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00006364 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006365
6366 TheCall->setArg(i + 1, Arg);
6367 }
6368
6369 // If this is a variadic call, handle args passed through "...".
6370 if (Proto->isVariadic()) {
6371 // Promote the arguments (C99 6.5.2.2p7).
6372 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6373 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00006374 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006375 TheCall->setArg(i + 1, Arg);
6376 }
6377 }
6378
Chris Lattner312531a2009-04-12 08:11:20 +00006379 if (IsError) return true;
6380
Anders Carlssond406bf02009-08-16 01:56:34 +00006381 if (CheckFunctionCall(Method, TheCall.get()))
6382 return true;
6383
Anders Carlssona303f9e2009-08-16 03:53:54 +00006384 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006385}
6386
Douglas Gregor8ba10742008-11-20 16:27:02 +00006387/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00006388/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00006389/// @c Member is the name of the member we're trying to find.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006390Sema::OwningExprResult
6391Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6392 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor8ba10742008-11-20 16:27:02 +00006393 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00006394
John McCall5769d612010-02-08 23:07:23 +00006395 SourceLocation Loc = Base->getExprLoc();
6396
Douglas Gregor8ba10742008-11-20 16:27:02 +00006397 // C++ [over.ref]p1:
6398 //
6399 // [...] An expression x->m is interpreted as (x.operator->())->m
6400 // for a class object x of type T if T::operator->() exists and if
6401 // the operator is selected as the best match function by the
6402 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00006403 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +00006404 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +00006405 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006406
John McCall5769d612010-02-08 23:07:23 +00006407 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +00006408 PDiag(diag::err_typecheck_incomplete_tag)
6409 << Base->getSourceRange()))
6410 return ExprError();
6411
John McCalla24dc2e2009-11-17 02:14:36 +00006412 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
6413 LookupQualifiedName(R, BaseRecord->getDecl());
6414 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00006415
6416 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00006417 Oper != OperEnd; ++Oper) {
6418 NamedDecl *D = *Oper;
6419 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6420 if (isa<UsingShadowDecl>(D))
6421 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6422
John McCall86820f52010-01-26 01:37:31 +00006423 AddMethodCandidate(cast<CXXMethodDecl>(D), Oper.getAccess(), ActingContext,
John McCall701c89e2009-12-03 04:06:58 +00006424 Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00006425 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00006426 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00006427
6428 // Perform overload resolution.
6429 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006430 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00006431 case OR_Success:
6432 // Overload resolution succeeded; we'll build the call below.
6433 break;
6434
6435 case OR_No_Viable_Function:
6436 if (CandidateSet.empty())
6437 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006438 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006439 else
6440 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006441 << "operator->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006442 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006443 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006444
6445 case OR_Ambiguous:
6446 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00006447 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006448 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006449 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006450
6451 case OR_Deleted:
6452 Diag(OpLoc, diag::err_ovl_deleted_oper)
6453 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00006454 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006455 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006456 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006457 }
6458
6459 // Convert the object parameter.
6460 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregora7cb22d2010-03-03 23:26:56 +00006461 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006462 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00006463
6464 // No concerns about early exits now.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00006465 BaseIn.release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00006466
6467 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00006468 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6469 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00006470 UsualUnaryConversions(FnExpr);
Anders Carlsson15ea3782009-10-13 22:43:21 +00006471
6472 QualType ResultTy = Method->getResultType().getNonReferenceType();
6473 ExprOwningPtr<CXXOperatorCallExpr>
6474 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6475 &Base, 1, ResultTy, OpLoc));
6476
6477 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6478 Method))
6479 return ExprError();
6480 return move(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00006481}
6482
Douglas Gregor904eed32008-11-10 20:40:00 +00006483/// FixOverloadedFunctionReference - E is an expression that refers to
6484/// a C++ overloaded function (possibly with some parentheses and
6485/// perhaps a '&' around it). We have resolved the overloaded function
6486/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00006487/// refer (possibly indirectly) to Fn. Returns the new expr.
6488Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00006489 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor699ee522009-11-20 19:42:02 +00006490 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
6491 if (SubExpr == PE->getSubExpr())
6492 return PE->Retain();
6493
6494 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6495 }
6496
6497 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6498 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00006499 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00006500 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00006501 "Implicit cast type cannot be determined from overload");
Douglas Gregor699ee522009-11-20 19:42:02 +00006502 if (SubExpr == ICE->getSubExpr())
6503 return ICE->Retain();
6504
6505 return new (Context) ImplicitCastExpr(ICE->getType(),
6506 ICE->getCastKind(),
6507 SubExpr,
6508 ICE->isLvalueCast());
6509 }
6510
6511 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006512 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00006513 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00006514 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6515 if (Method->isStatic()) {
6516 // Do nothing: static member functions aren't any different
6517 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00006518 } else {
John McCallf7a1a742009-11-24 19:00:30 +00006519 // Fix the sub expression, which really has to be an
6520 // UnresolvedLookupExpr holding an overloaded member function
6521 // or template.
John McCallba135432009-11-21 08:51:07 +00006522 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6523 if (SubExpr == UnOp->getSubExpr())
6524 return UnOp->Retain();
Douglas Gregor699ee522009-11-20 19:42:02 +00006525
John McCallba135432009-11-21 08:51:07 +00006526 assert(isa<DeclRefExpr>(SubExpr)
6527 && "fixed to something other than a decl ref");
6528 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6529 && "fixed to a member ref with no nested name qualifier");
6530
6531 // We have taken the address of a pointer to member
6532 // function. Perform the computation here so that we get the
6533 // appropriate pointer to member type.
6534 QualType ClassType
6535 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6536 QualType MemPtrType
6537 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6538
6539 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6540 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00006541 }
6542 }
Douglas Gregor699ee522009-11-20 19:42:02 +00006543 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
6544 if (SubExpr == UnOp->getSubExpr())
6545 return UnOp->Retain();
Anders Carlsson96ad5332009-10-21 17:16:23 +00006546
Douglas Gregor699ee522009-11-20 19:42:02 +00006547 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6548 Context.getPointerType(SubExpr->getType()),
6549 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00006550 }
John McCallba135432009-11-21 08:51:07 +00006551
6552 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00006553 // FIXME: avoid copy.
6554 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00006555 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00006556 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6557 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00006558 }
6559
John McCallba135432009-11-21 08:51:07 +00006560 return DeclRefExpr::Create(Context,
6561 ULE->getQualifier(),
6562 ULE->getQualifierRange(),
6563 Fn,
6564 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00006565 Fn->getType(),
6566 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00006567 }
6568
John McCall129e2df2009-11-30 22:42:35 +00006569 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00006570 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00006571 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6572 if (MemExpr->hasExplicitTemplateArgs()) {
6573 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6574 TemplateArgs = &TemplateArgsBuffer;
6575 }
John McCalld5532b62009-11-23 01:53:49 +00006576
John McCallaa81e162009-12-01 22:10:20 +00006577 Expr *Base;
6578
6579 // If we're filling in
6580 if (MemExpr->isImplicitAccess()) {
6581 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6582 return DeclRefExpr::Create(Context,
6583 MemExpr->getQualifier(),
6584 MemExpr->getQualifierRange(),
6585 Fn,
6586 MemExpr->getMemberLoc(),
6587 Fn->getType(),
6588 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00006589 } else {
6590 SourceLocation Loc = MemExpr->getMemberLoc();
6591 if (MemExpr->getQualifier())
6592 Loc = MemExpr->getQualifierRange().getBegin();
6593 Base = new (Context) CXXThisExpr(Loc,
6594 MemExpr->getBaseType(),
6595 /*isImplicit=*/true);
6596 }
John McCallaa81e162009-12-01 22:10:20 +00006597 } else
6598 Base = MemExpr->getBase()->Retain();
6599
6600 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00006601 MemExpr->isArrow(),
6602 MemExpr->getQualifier(),
6603 MemExpr->getQualifierRange(),
6604 Fn,
John McCalld5532b62009-11-23 01:53:49 +00006605 MemExpr->getMemberLoc(),
John McCallaa81e162009-12-01 22:10:20 +00006606 TemplateArgs,
Douglas Gregor699ee522009-11-20 19:42:02 +00006607 Fn->getType());
6608 }
6609
Douglas Gregor699ee522009-11-20 19:42:02 +00006610 assert(false && "Invalid reference to overloaded function");
6611 return E->Retain();
Douglas Gregor904eed32008-11-10 20:40:00 +00006612}
6613
Douglas Gregor20093b42009-12-09 23:02:17 +00006614Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
6615 FunctionDecl *Fn) {
6616 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Fn));
6617}
6618
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006619} // end namespace clang