blob: 3d9ec8d6cb5141e3c875972bfcf2e7bd1b195e12 [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"
Douglas Gregor94b1dd22008-10-24 04:54:22 +000015#include "SemaInherit.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000020#include "clang/AST/ExprCXX.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000022#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000023#include "llvm/Support/Compiler.h"
24#include <algorithm>
25
26namespace clang {
27
28/// GetConversionCategory - Retrieve the implicit conversion
29/// category corresponding to the given implicit conversion kind.
30ImplicitConversionCategory
31GetConversionCategory(ImplicitConversionKind Kind) {
32 static const ImplicitConversionCategory
33 Category[(int)ICK_Num_Conversion_Kinds] = {
34 ICC_Identity,
35 ICC_Lvalue_Transformation,
36 ICC_Lvalue_Transformation,
37 ICC_Lvalue_Transformation,
38 ICC_Qualification_Adjustment,
39 ICC_Promotion,
40 ICC_Promotion,
41 ICC_Conversion,
42 ICC_Conversion,
43 ICC_Conversion,
44 ICC_Conversion,
45 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000046 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000047 ICC_Conversion
48 };
49 return Category[(int)Kind];
50}
51
52/// GetConversionRank - Retrieve the implicit conversion rank
53/// corresponding to the given implicit conversion kind.
54ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
55 static const ImplicitConversionRank
56 Rank[(int)ICK_Num_Conversion_Kinds] = {
57 ICR_Exact_Match,
58 ICR_Exact_Match,
59 ICR_Exact_Match,
60 ICR_Exact_Match,
61 ICR_Exact_Match,
62 ICR_Promotion,
63 ICR_Promotion,
64 ICR_Conversion,
65 ICR_Conversion,
66 ICR_Conversion,
67 ICR_Conversion,
68 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000069 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000070 ICR_Conversion
71 };
72 return Rank[(int)Kind];
73}
74
75/// GetImplicitConversionName - Return the name of this kind of
76/// implicit conversion.
77const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
78 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
79 "No conversion",
80 "Lvalue-to-rvalue",
81 "Array-to-pointer",
82 "Function-to-pointer",
83 "Qualification",
84 "Integral promotion",
85 "Floating point promotion",
86 "Integral conversion",
87 "Floating conversion",
88 "Floating-integral conversion",
89 "Pointer conversion",
90 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +000091 "Boolean conversion",
92 "Derived-to-base conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000093 };
94 return Name[Kind];
95}
96
Douglas Gregor60d62c22008-10-31 16:23:19 +000097/// StandardConversionSequence - Set the standard conversion
98/// sequence to the identity conversion.
99void StandardConversionSequence::setAsIdentityConversion() {
100 First = ICK_Identity;
101 Second = ICK_Identity;
102 Third = ICK_Identity;
103 Deprecated = false;
104 ReferenceBinding = false;
105 DirectBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000106 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000107}
108
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000109/// getRank - Retrieve the rank of this standard conversion sequence
110/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
111/// implicit conversions.
112ImplicitConversionRank StandardConversionSequence::getRank() const {
113 ImplicitConversionRank Rank = ICR_Exact_Match;
114 if (GetConversionRank(First) > Rank)
115 Rank = GetConversionRank(First);
116 if (GetConversionRank(Second) > Rank)
117 Rank = GetConversionRank(Second);
118 if (GetConversionRank(Third) > Rank)
119 Rank = GetConversionRank(Third);
120 return Rank;
121}
122
123/// isPointerConversionToBool - Determines whether this conversion is
124/// a conversion of a pointer or pointer-to-member to bool. This is
125/// used as part of the ranking of standard conversion sequences
126/// (C++ 13.3.3.2p4).
127bool StandardConversionSequence::isPointerConversionToBool() const
128{
129 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
130 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
131
132 // Note that FromType has not necessarily been transformed by the
133 // array-to-pointer or function-to-pointer implicit conversions, so
134 // check for their presence as well as checking whether FromType is
135 // a pointer.
136 if (ToType->isBooleanType() &&
137 (FromType->isPointerType() ||
138 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
139 return true;
140
141 return false;
142}
143
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000144/// isPointerConversionToVoidPointer - Determines whether this
145/// conversion is a conversion of a pointer to a void pointer. This is
146/// used as part of the ranking of standard conversion sequences (C++
147/// 13.3.3.2p4).
148bool
149StandardConversionSequence::
150isPointerConversionToVoidPointer(ASTContext& Context) const
151{
152 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
153 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
154
155 // Note that FromType has not necessarily been transformed by the
156 // array-to-pointer implicit conversion, so check for its presence
157 // and redo the conversion to get a pointer.
158 if (First == ICK_Array_To_Pointer)
159 FromType = Context.getArrayDecayedType(FromType);
160
161 if (Second == ICK_Pointer_Conversion)
162 if (const PointerType* ToPtrType = ToType->getAsPointerType())
163 return ToPtrType->getPointeeType()->isVoidType();
164
165 return false;
166}
167
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000168/// DebugPrint - Print this standard conversion sequence to standard
169/// error. Useful for debugging overloading issues.
170void StandardConversionSequence::DebugPrint() const {
171 bool PrintedSomething = false;
172 if (First != ICK_Identity) {
173 fprintf(stderr, "%s", GetImplicitConversionName(First));
174 PrintedSomething = true;
175 }
176
177 if (Second != ICK_Identity) {
178 if (PrintedSomething) {
179 fprintf(stderr, " -> ");
180 }
181 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregor225c41e2008-11-03 19:09:14 +0000182
183 if (CopyConstructor) {
184 fprintf(stderr, " (by copy constructor)");
185 } else if (DirectBinding) {
186 fprintf(stderr, " (direct reference binding)");
187 } else if (ReferenceBinding) {
188 fprintf(stderr, " (reference binding)");
189 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000190 PrintedSomething = true;
191 }
192
193 if (Third != ICK_Identity) {
194 if (PrintedSomething) {
195 fprintf(stderr, " -> ");
196 }
197 fprintf(stderr, "%s", GetImplicitConversionName(Third));
198 PrintedSomething = true;
199 }
200
201 if (!PrintedSomething) {
202 fprintf(stderr, "No conversions required");
203 }
204}
205
206/// DebugPrint - Print this user-defined conversion sequence to standard
207/// error. Useful for debugging overloading issues.
208void UserDefinedConversionSequence::DebugPrint() const {
209 if (Before.First || Before.Second || Before.Third) {
210 Before.DebugPrint();
211 fprintf(stderr, " -> ");
212 }
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000213 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000214 if (After.First || After.Second || After.Third) {
215 fprintf(stderr, " -> ");
216 After.DebugPrint();
217 }
218}
219
220/// DebugPrint - Print this implicit conversion sequence to standard
221/// error. Useful for debugging overloading issues.
222void ImplicitConversionSequence::DebugPrint() const {
223 switch (ConversionKind) {
224 case StandardConversion:
225 fprintf(stderr, "Standard conversion: ");
226 Standard.DebugPrint();
227 break;
228 case UserDefinedConversion:
229 fprintf(stderr, "User-defined conversion: ");
230 UserDefined.DebugPrint();
231 break;
232 case EllipsisConversion:
233 fprintf(stderr, "Ellipsis conversion");
234 break;
235 case BadConversion:
236 fprintf(stderr, "Bad conversion");
237 break;
238 }
239
240 fprintf(stderr, "\n");
241}
242
243// IsOverload - Determine whether the given New declaration is an
244// overload of the Old declaration. This routine returns false if New
245// and Old cannot be overloaded, e.g., if they are functions with the
246// same signature (C++ 1.3.10) or if the Old declaration isn't a
247// function (or overload set). When it does return false and Old is an
248// OverloadedFunctionDecl, MatchedDecl will be set to point to the
249// FunctionDecl that New cannot be overloaded with.
250//
251// Example: Given the following input:
252//
253// void f(int, float); // #1
254// void f(int, int); // #2
255// int f(int, int); // #3
256//
257// When we process #1, there is no previous declaration of "f",
258// so IsOverload will not be used.
259//
260// When we process #2, Old is a FunctionDecl for #1. By comparing the
261// parameter types, we see that #1 and #2 are overloaded (since they
262// have different signatures), so this routine returns false;
263// MatchedDecl is unchanged.
264//
265// When we process #3, Old is an OverloadedFunctionDecl containing #1
266// and #2. We compare the signatures of #3 to #1 (they're overloaded,
267// so we do nothing) and then #3 to #2. Since the signatures of #3 and
268// #2 are identical (return types of functions are not part of the
269// signature), IsOverload returns false and MatchedDecl will be set to
270// point to the FunctionDecl for #2.
271bool
272Sema::IsOverload(FunctionDecl *New, Decl* OldD,
273 OverloadedFunctionDecl::function_iterator& MatchedDecl)
274{
275 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
276 // Is this new function an overload of every function in the
277 // overload set?
278 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
279 FuncEnd = Ovl->function_end();
280 for (; Func != FuncEnd; ++Func) {
281 if (!IsOverload(New, *Func, MatchedDecl)) {
282 MatchedDecl = Func;
283 return false;
284 }
285 }
286
287 // This function overloads every function in the overload set.
288 return true;
289 } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
290 // Is the function New an overload of the function Old?
291 QualType OldQType = Context.getCanonicalType(Old->getType());
292 QualType NewQType = Context.getCanonicalType(New->getType());
293
294 // Compare the signatures (C++ 1.3.10) of the two functions to
295 // determine whether they are overloads. If we find any mismatch
296 // in the signature, they are overloads.
297
298 // If either of these functions is a K&R-style function (no
299 // prototype), then we consider them to have matching signatures.
300 if (isa<FunctionTypeNoProto>(OldQType.getTypePtr()) ||
301 isa<FunctionTypeNoProto>(NewQType.getTypePtr()))
302 return false;
303
304 FunctionTypeProto* OldType = cast<FunctionTypeProto>(OldQType.getTypePtr());
305 FunctionTypeProto* NewType = cast<FunctionTypeProto>(NewQType.getTypePtr());
306
307 // The signature of a function includes the types of its
308 // parameters (C++ 1.3.10), which includes the presence or absence
309 // of the ellipsis; see C++ DR 357).
310 if (OldQType != NewQType &&
311 (OldType->getNumArgs() != NewType->getNumArgs() ||
312 OldType->isVariadic() != NewType->isVariadic() ||
313 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
314 NewType->arg_type_begin())))
315 return true;
316
317 // If the function is a class member, its signature includes the
318 // cv-qualifiers (if any) on the function itself.
319 //
320 // As part of this, also check whether one of the member functions
321 // is static, in which case they are not overloads (C++
322 // 13.1p2). While not part of the definition of the signature,
323 // this check is important to determine whether these functions
324 // can be overloaded.
325 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
326 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
327 if (OldMethod && NewMethod &&
328 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor1ca50c32008-11-21 15:36:28 +0000329 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000330 return true;
331
332 // The signatures match; this is not an overload.
333 return false;
334 } else {
335 // (C++ 13p1):
336 // Only function declarations can be overloaded; object and type
337 // declarations cannot be overloaded.
338 return false;
339 }
340}
341
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000342/// TryImplicitConversion - Attempt to perform an implicit conversion
343/// from the given expression (Expr) to the given type (ToType). This
344/// function returns an implicit conversion sequence that can be used
345/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000346///
347/// void f(float f);
348/// void g(int i) { f(i); }
349///
350/// this routine would produce an implicit conversion sequence to
351/// describe the initialization of f from i, which will be a standard
352/// conversion sequence containing an lvalue-to-rvalue conversion (C++
353/// 4.1) followed by a floating-integral conversion (C++ 4.9).
354//
355/// Note that this routine only determines how the conversion can be
356/// performed; it does not actually perform the conversion. As such,
357/// it will not produce any diagnostics if no conversion is available,
358/// but will instead return an implicit conversion sequence of kind
359/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000360///
361/// If @p SuppressUserConversions, then user-defined conversions are
362/// not permitted.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000363ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +0000364Sema::TryImplicitConversion(Expr* From, QualType ToType,
365 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000366{
367 ImplicitConversionSequence ICS;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000368 if (IsStandardConversion(From, ToType, ICS.Standard))
369 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000370 else if (!SuppressUserConversions &&
371 IsUserDefinedConversion(From, ToType, ICS.UserDefined)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000372 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000373 // C++ [over.ics.user]p4:
374 // A conversion of an expression of class type to the same class
375 // type is given Exact Match rank, and a conversion of an
376 // expression of class type to a base class of that type is
377 // given Conversion rank, in spite of the fact that a copy
378 // constructor (i.e., a user-defined conversion function) is
379 // called for those cases.
380 if (CXXConstructorDecl *Constructor
381 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
382 if (Constructor->isCopyConstructor(Context)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000383 // Turn this into a "standard" conversion sequence, so that it
384 // gets ranked with standard conversion sequences.
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000385 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
386 ICS.Standard.setAsIdentityConversion();
387 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
388 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000389 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000390 if (IsDerivedFrom(From->getType().getUnqualifiedType(),
391 ToType.getUnqualifiedType()))
392 ICS.Standard.Second = ICK_Derived_To_Base;
393 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000394 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000395 } else
Douglas Gregor60d62c22008-10-31 16:23:19 +0000396 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000397
398 return ICS;
399}
400
401/// IsStandardConversion - Determines whether there is a standard
402/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
403/// expression From to the type ToType. Standard conversion sequences
404/// only consider non-class types; for conversions that involve class
405/// types, use TryImplicitConversion. If a conversion exists, SCS will
406/// contain the standard conversion sequence required to perform this
407/// conversion and this routine will return true. Otherwise, this
408/// routine will return false and the value of SCS is unspecified.
409bool
410Sema::IsStandardConversion(Expr* From, QualType ToType,
411 StandardConversionSequence &SCS)
412{
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000413 QualType FromType = From->getType();
414
Douglas Gregor60d62c22008-10-31 16:23:19 +0000415 // There are no standard conversions for class types, so abort early.
416 if (FromType->isRecordType() || ToType->isRecordType())
417 return false;
418
419 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000420 SCS.setAsIdentityConversion();
Douglas Gregor60d62c22008-10-31 16:23:19 +0000421 SCS.Deprecated = false;
422 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000423 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000424
425 // The first conversion can be an lvalue-to-rvalue conversion,
426 // array-to-pointer conversion, or function-to-pointer conversion
427 // (C++ 4p1).
428
429 // Lvalue-to-rvalue conversion (C++ 4.1):
430 // An lvalue (3.10) of a non-function, non-array type T can be
431 // converted to an rvalue.
432 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
433 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000434 !FromType->isFunctionType() && !FromType->isArrayType() &&
435 !FromType->isOverloadType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000436 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000437
438 // If T is a non-class type, the type of the rvalue is the
439 // cv-unqualified version of T. Otherwise, the type of the rvalue
440 // is T (C++ 4.1p1).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000441 FromType = FromType.getUnqualifiedType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000442 }
443 // Array-to-pointer conversion (C++ 4.2)
444 else if (FromType->isArrayType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000445 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000446
447 // An lvalue or rvalue of type "array of N T" or "array of unknown
448 // bound of T" can be converted to an rvalue of type "pointer to
449 // T" (C++ 4.2p1).
450 FromType = Context.getArrayDecayedType(FromType);
451
452 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
453 // This conversion is deprecated. (C++ D.4).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000454 SCS.Deprecated = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000455
456 // For the purpose of ranking in overload resolution
457 // (13.3.3.1.1), this conversion is considered an
458 // array-to-pointer conversion followed by a qualification
459 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000460 SCS.Second = ICK_Identity;
461 SCS.Third = ICK_Qualification;
462 SCS.ToTypePtr = ToType.getAsOpaquePtr();
463 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000464 }
465 }
466 // Function-to-pointer conversion (C++ 4.3).
467 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000468 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000469
470 // An lvalue of function type T can be converted to an rvalue of
471 // type "pointer to T." The result is a pointer to the
472 // function. (C++ 4.3p1).
473 FromType = Context.getPointerType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000474 }
Douglas Gregor904eed32008-11-10 20:40:00 +0000475 // Address of overloaded function (C++ [over.over]).
476 else if (FunctionDecl *Fn
477 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
478 SCS.First = ICK_Function_To_Pointer;
479
480 // We were able to resolve the address of the overloaded function,
481 // so we can convert to the type of that function.
482 FromType = Fn->getType();
483 if (ToType->isReferenceType())
484 FromType = Context.getReferenceType(FromType);
485 else
486 FromType = Context.getPointerType(FromType);
487 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000488 // We don't require any conversions for the first step.
489 else {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000490 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000491 }
492
493 // The second conversion can be an integral promotion, floating
494 // point promotion, integral conversion, floating point conversion,
495 // floating-integral conversion, pointer conversion,
496 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
497 if (Context.getCanonicalType(FromType).getUnqualifiedType() ==
498 Context.getCanonicalType(ToType).getUnqualifiedType()) {
499 // The unqualified versions of the types are the same: there's no
500 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000501 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000502 }
503 // Integral promotion (C++ 4.5).
504 else if (IsIntegralPromotion(From, FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000505 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000506 FromType = ToType.getUnqualifiedType();
507 }
508 // Floating point promotion (C++ 4.6).
509 else if (IsFloatingPointPromotion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000510 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000511 FromType = ToType.getUnqualifiedType();
512 }
513 // Integral conversions (C++ 4.7).
Sebastian Redl07779722008-10-31 14:43:28 +0000514 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000515 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000516 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000517 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000518 FromType = ToType.getUnqualifiedType();
519 }
520 // Floating point conversions (C++ 4.8).
521 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000522 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000523 FromType = ToType.getUnqualifiedType();
524 }
525 // Floating-integral conversions (C++ 4.9).
Sebastian Redl07779722008-10-31 14:43:28 +0000526 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000527 else if ((FromType->isFloatingType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000528 ToType->isIntegralType() && !ToType->isBooleanType() &&
529 !ToType->isEnumeralType()) ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000530 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
531 ToType->isFloatingType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000532 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000533 FromType = ToType.getUnqualifiedType();
534 }
535 // Pointer conversions (C++ 4.10).
Sebastian Redl07779722008-10-31 14:43:28 +0000536 else if (IsPointerConversion(From, FromType, ToType, FromType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000537 SCS.Second = ICK_Pointer_Conversion;
Sebastian Redl07779722008-10-31 14:43:28 +0000538 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000539 // FIXME: Pointer to member conversions (4.11).
540 // Boolean conversions (C++ 4.12).
541 // FIXME: pointer-to-member type
542 else if (ToType->isBooleanType() &&
543 (FromType->isArithmeticType() ||
544 FromType->isEnumeralType() ||
545 FromType->isPointerType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000546 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000547 FromType = Context.BoolTy;
548 } else {
549 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000550 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000551 }
552
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000553 QualType CanonFrom;
554 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000555 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000556 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000557 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000558 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000559 CanonFrom = Context.getCanonicalType(FromType);
560 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000561 } else {
562 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000563 SCS.Third = ICK_Identity;
564
565 // C++ [over.best.ics]p6:
566 // [...] Any difference in top-level cv-qualification is
567 // subsumed by the initialization itself and does not constitute
568 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000569 CanonFrom = Context.getCanonicalType(FromType);
570 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000571 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000572 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
573 FromType = ToType;
574 CanonFrom = CanonTo;
575 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000576 }
577
578 // If we have not converted the argument type to the parameter type,
579 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000580 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000581 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000582
Douglas Gregor60d62c22008-10-31 16:23:19 +0000583 SCS.ToTypePtr = FromType.getAsOpaquePtr();
584 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000585}
586
587/// IsIntegralPromotion - Determines whether the conversion from the
588/// expression From (whose potentially-adjusted type is FromType) to
589/// ToType is an integral promotion (C++ 4.5). If so, returns true and
590/// sets PromotedType to the promoted type.
591bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
592{
593 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000594 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000595 if (!To) {
596 return false;
597 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000598
599 // An rvalue of type char, signed char, unsigned char, short int, or
600 // unsigned short int can be converted to an rvalue of type int if
601 // int can represent all the values of the source type; otherwise,
602 // the source rvalue can be converted to an rvalue of type unsigned
603 // int (C++ 4.5p1).
Sebastian Redl07779722008-10-31 14:43:28 +0000604 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000605 if (// We can promote any signed, promotable integer type to an int
606 (FromType->isSignedIntegerType() ||
607 // We can promote any unsigned integer type whose size is
608 // less than int to an int.
609 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000610 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000611 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000612 }
613
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000614 return To->getKind() == BuiltinType::UInt;
615 }
616
617 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
618 // can be converted to an rvalue of the first of the following types
619 // that can represent all the values of its underlying type: int,
620 // unsigned int, long, or unsigned long (C++ 4.5p2).
621 if ((FromType->isEnumeralType() || FromType->isWideCharType())
622 && ToType->isIntegerType()) {
623 // Determine whether the type we're converting from is signed or
624 // unsigned.
625 bool FromIsSigned;
626 uint64_t FromSize = Context.getTypeSize(FromType);
627 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
628 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
629 FromIsSigned = UnderlyingType->isSignedIntegerType();
630 } else {
631 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
632 FromIsSigned = true;
633 }
634
635 // The types we'll try to promote to, in the appropriate
636 // order. Try each of these types.
637 QualType PromoteTypes[4] = {
638 Context.IntTy, Context.UnsignedIntTy,
639 Context.LongTy, Context.UnsignedLongTy
640 };
Douglas Gregor447b69e2008-11-19 03:25:36 +0000641 for (int Idx = 0; Idx < 4; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000642 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
643 if (FromSize < ToSize ||
644 (FromSize == ToSize &&
645 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
646 // We found the type that we can promote to. If this is the
647 // type we wanted, we have a promotion. Otherwise, no
648 // promotion.
Sebastian Redl07779722008-10-31 14:43:28 +0000649 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000650 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
651 }
652 }
653 }
654
655 // An rvalue for an integral bit-field (9.6) can be converted to an
656 // rvalue of type int if int can represent all the values of the
657 // bit-field; otherwise, it can be converted to unsigned int if
658 // unsigned int can represent all the values of the bit-field. If
659 // the bit-field is larger yet, no integral promotion applies to
660 // it. If the bit-field has an enumerated type, it is treated as any
661 // other value of that type for promotion purposes (C++ 4.5p3).
662 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) {
663 using llvm::APSInt;
664 FieldDecl *MemberDecl = MemRef->getMemberDecl();
665 APSInt BitWidth;
666 if (MemberDecl->isBitField() &&
667 FromType->isIntegralType() && !FromType->isEnumeralType() &&
668 From->isIntegerConstantExpr(BitWidth, Context)) {
669 APSInt ToSize(Context.getTypeSize(ToType));
670
671 // Are we promoting to an int from a bitfield that fits in an int?
672 if (BitWidth < ToSize ||
Sebastian Redl07779722008-10-31 14:43:28 +0000673 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000674 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000675 }
676
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000677 // Are we promoting to an unsigned int from an unsigned bitfield
678 // that fits into an unsigned int?
Sebastian Redl07779722008-10-31 14:43:28 +0000679 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000680 return To->getKind() == BuiltinType::UInt;
Sebastian Redl07779722008-10-31 14:43:28 +0000681 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000682
683 return false;
684 }
685 }
686
687 // An rvalue of type bool can be converted to an rvalue of type int,
688 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000689 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000690 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000691 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000692
693 return false;
694}
695
696/// IsFloatingPointPromotion - Determines whether the conversion from
697/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
698/// returns true and sets PromotedType to the promoted type.
699bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
700{
701 /// An rvalue of type float can be converted to an rvalue of type
702 /// double. (C++ 4.6p1).
703 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
704 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType())
705 if (FromBuiltin->getKind() == BuiltinType::Float &&
706 ToBuiltin->getKind() == BuiltinType::Double)
707 return true;
708
709 return false;
710}
711
Douglas Gregorcb7de522008-11-26 23:31:11 +0000712/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
713/// the pointer type FromPtr to a pointer to type ToPointee, with the
714/// same type qualifiers as FromPtr has on its pointee type. ToType,
715/// if non-empty, will be a pointer to ToType that may or may not have
716/// the right set of qualifiers on its pointee.
717static QualType
718BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
719 QualType ToPointee, QualType ToType,
720 ASTContext &Context) {
721 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
722 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
723 unsigned Quals = CanonFromPointee.getCVRQualifiers();
724
725 // Exact qualifier match -> return the pointer type we're converting to.
726 if (CanonToPointee.getCVRQualifiers() == Quals) {
727 // ToType is exactly what we need. Return it.
728 if (ToType.getTypePtr())
729 return ToType;
730
731 // Build a pointer to ToPointee. It has the right qualifiers
732 // already.
733 return Context.getPointerType(ToPointee);
734 }
735
736 // Just build a canonical type that has the right qualifiers.
737 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
738}
739
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000740/// IsPointerConversion - Determines whether the conversion of the
741/// expression From, which has the (possibly adjusted) type FromType,
742/// can be converted to the type ToType via a pointer conversion (C++
743/// 4.10). If so, returns true and places the converted type (that
744/// might differ from ToType in its cv-qualifiers at some level) into
745/// ConvertedType.
746bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
747 QualType& ConvertedType)
748{
749 const PointerType* ToTypePtr = ToType->getAsPointerType();
750 if (!ToTypePtr)
751 return false;
752
753 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
754 if (From->isNullPointerConstant(Context)) {
755 ConvertedType = ToType;
756 return true;
757 }
Sebastian Redl07779722008-10-31 14:43:28 +0000758
Douglas Gregorcb7de522008-11-26 23:31:11 +0000759 // Beyond this point, both types need to be pointers.
760 const PointerType *FromTypePtr = FromType->getAsPointerType();
761 if (!FromTypePtr)
762 return false;
763
764 QualType FromPointeeType = FromTypePtr->getPointeeType();
765 QualType ToPointeeType = ToTypePtr->getPointeeType();
766
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000767 // An rvalue of type "pointer to cv T," where T is an object type,
768 // can be converted to an rvalue of type "pointer to cv void" (C++
769 // 4.10p2).
Douglas Gregorcb7de522008-11-26 23:31:11 +0000770 if (FromPointeeType->isIncompleteOrObjectType() && ToPointeeType->isVoidType()) {
771 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, ToPointeeType,
772 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000773 return true;
774 }
775
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000776 // C++ [conv.ptr]p3:
777 //
778 // An rvalue of type "pointer to cv D," where D is a class type,
779 // can be converted to an rvalue of type "pointer to cv B," where
780 // B is a base class (clause 10) of D. If B is an inaccessible
781 // (clause 11) or ambiguous (10.2) base class of D, a program that
782 // necessitates this conversion is ill-formed. The result of the
783 // conversion is a pointer to the base class sub-object of the
784 // derived class object. The null pointer value is converted to
785 // the null pointer value of the destination type.
786 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000787 // Note that we do not check for ambiguity or inaccessibility
788 // here. That is handled by CheckPointerConversion.
Douglas Gregorcb7de522008-11-26 23:31:11 +0000789 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
790 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
791 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, ToPointeeType,
792 ToType, Context);
793 return true;
794 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000795
Douglas Gregorcb7de522008-11-26 23:31:11 +0000796 // Objective C++: We're able to convert from a pointer to an
797 // interface to a pointer to a different interface.
798 const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType();
799 const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType();
800 if (FromIface && ToIface &&
801 Context.canAssignObjCInterfaces(ToIface, FromIface)) {
802 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, ToPointeeType,
803 ToType, Context);
804 return true;
805 }
806
807 // Objective C++: We're able to convert between "id" and a pointer
808 // to any interface (in both directions).
809 if ((FromIface && Context.isObjCIdType(ToPointeeType))
810 || (ToIface && Context.isObjCIdType(FromPointeeType))) {
811 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, ToPointeeType,
812 ToType, Context);
813 return true;
814 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000815
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000816 return false;
817}
818
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000819/// CheckPointerConversion - Check the pointer conversion from the
820/// expression From to the type ToType. This routine checks for
821/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
822/// conversions for which IsPointerConversion has already returned
823/// true. It returns true and produces a diagnostic if there was an
824/// error, or returns false otherwise.
825bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
826 QualType FromType = From->getType();
827
828 if (const PointerType *FromPtrType = FromType->getAsPointerType())
829 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
Sebastian Redl07779722008-10-31 14:43:28 +0000830 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
831 /*DetectVirtual=*/false);
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000832 QualType FromPointeeType = FromPtrType->getPointeeType(),
833 ToPointeeType = ToPtrType->getPointeeType();
834 if (FromPointeeType->isRecordType() &&
835 ToPointeeType->isRecordType()) {
836 // We must have a derived-to-base conversion. Check an
837 // ambiguous or inaccessible conversion.
Douglas Gregor0575d4a2008-10-24 16:17:19 +0000838 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
839 From->getExprLoc(),
840 From->getSourceRange());
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000841 }
842 }
843
844 return false;
845}
846
Douglas Gregor98cd5992008-10-21 23:43:52 +0000847/// IsQualificationConversion - Determines whether the conversion from
848/// an rvalue of type FromType to ToType is a qualification conversion
849/// (C++ 4.4).
850bool
851Sema::IsQualificationConversion(QualType FromType, QualType ToType)
852{
853 FromType = Context.getCanonicalType(FromType);
854 ToType = Context.getCanonicalType(ToType);
855
856 // If FromType and ToType are the same type, this is not a
857 // qualification conversion.
858 if (FromType == ToType)
859 return false;
860
861 // (C++ 4.4p4):
862 // A conversion can add cv-qualifiers at levels other than the first
863 // in multi-level pointers, subject to the following rules: [...]
864 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +0000865 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +0000866 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +0000867 // Within each iteration of the loop, we check the qualifiers to
868 // determine if this still looks like a qualification
869 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000870 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +0000871 // until there are no more pointers or pointers-to-members left to
872 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +0000873 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +0000874
875 // -- for every j > 0, if const is in cv 1,j then const is in cv
876 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +0000877 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +0000878 return false;
Douglas Gregor57373262008-10-22 14:17:15 +0000879
Douglas Gregor98cd5992008-10-21 23:43:52 +0000880 // -- if the cv 1,j and cv 2,j are different, then const is in
881 // every cv for 0 < k < j.
882 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +0000883 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +0000884 return false;
Douglas Gregor57373262008-10-22 14:17:15 +0000885
Douglas Gregor98cd5992008-10-21 23:43:52 +0000886 // Keep track of whether all prior cv-qualifiers in the "to" type
887 // include const.
888 PreviousToQualsIncludeConst
889 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +0000890 }
Douglas Gregor98cd5992008-10-21 23:43:52 +0000891
892 // We are left with FromType and ToType being the pointee types
893 // after unwrapping the original FromType and ToType the same number
894 // of types. If we unwrapped any pointers, and if FromType and
895 // ToType have the same unqualified type (since we checked
896 // qualifiers above), then this is a qualification conversion.
897 return UnwrappedAnyPointer &&
898 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
899}
900
Douglas Gregor60d62c22008-10-31 16:23:19 +0000901/// IsUserDefinedConversion - Determines whether there is a
902/// user-defined conversion sequence (C++ [over.ics.user]) that
903/// converts expression From to the type ToType. If such a conversion
904/// exists, User will contain the user-defined conversion sequence
905/// that performs such a conversion and this routine will return
906/// true. Otherwise, this routine returns false and User is
907/// unspecified.
908bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
909 UserDefinedConversionSequence& User)
910{
911 OverloadCandidateSet CandidateSet;
912 if (const CXXRecordType *ToRecordType
913 = dyn_cast_or_null<CXXRecordType>(ToType->getAsRecordType())) {
914 // C++ [over.match.ctor]p1:
915 // When objects of class type are direct-initialized (8.5), or
916 // copy-initialized from an expression of the same or a
917 // derived class type (8.5), overload resolution selects the
918 // constructor. [...] For copy-initialization, the candidate
919 // functions are all the converting constructors (12.3.1) of
920 // that class. The argument list is the expression-list within
921 // the parentheses of the initializer.
922 CXXRecordDecl *ToRecordDecl = ToRecordType->getDecl();
923 const OverloadedFunctionDecl *Constructors = ToRecordDecl->getConstructors();
924 for (OverloadedFunctionDecl::function_const_iterator func
925 = Constructors->function_begin();
926 func != Constructors->function_end(); ++func) {
927 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*func);
928 if (Constructor->isConvertingConstructor())
Douglas Gregor225c41e2008-11-03 19:09:14 +0000929 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
930 /*SuppressUserConversions=*/true);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000931 }
932 }
933
Douglas Gregorf1991ea2008-11-07 22:36:19 +0000934 if (const CXXRecordType *FromRecordType
935 = dyn_cast_or_null<CXXRecordType>(From->getType()->getAsRecordType())) {
936 // Add all of the conversion functions as candidates.
937 // FIXME: Look for conversions in base classes!
938 CXXRecordDecl *FromRecordDecl = FromRecordType->getDecl();
939 OverloadedFunctionDecl *Conversions
940 = FromRecordDecl->getConversionFunctions();
941 for (OverloadedFunctionDecl::function_iterator Func
942 = Conversions->function_begin();
943 Func != Conversions->function_end(); ++Func) {
944 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
945 AddConversionCandidate(Conv, From, ToType, CandidateSet);
946 }
947 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000948
949 OverloadCandidateSet::iterator Best;
950 switch (BestViableFunction(CandidateSet, Best)) {
951 case OR_Success:
952 // Record the standard conversion we used and the conversion function.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000953 if (CXXConstructorDecl *Constructor
954 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
955 // C++ [over.ics.user]p1:
956 // If the user-defined conversion is specified by a
957 // constructor (12.3.1), the initial standard conversion
958 // sequence converts the source type to the type required by
959 // the argument of the constructor.
960 //
961 // FIXME: What about ellipsis conversions?
962 QualType ThisType = Constructor->getThisType(Context);
963 User.Before = Best->Conversions[0].Standard;
964 User.ConversionFunction = Constructor;
965 User.After.setAsIdentityConversion();
966 User.After.FromTypePtr
967 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
968 User.After.ToTypePtr = ToType.getAsOpaquePtr();
969 return true;
Douglas Gregorf1991ea2008-11-07 22:36:19 +0000970 } else if (CXXConversionDecl *Conversion
971 = dyn_cast<CXXConversionDecl>(Best->Function)) {
972 // C++ [over.ics.user]p1:
973 //
974 // [...] If the user-defined conversion is specified by a
975 // conversion function (12.3.2), the initial standard
976 // conversion sequence converts the source type to the
977 // implicit object parameter of the conversion function.
978 User.Before = Best->Conversions[0].Standard;
979 User.ConversionFunction = Conversion;
980
981 // C++ [over.ics.user]p2:
982 // The second standard conversion sequence converts the
983 // result of the user-defined conversion to the target type
984 // for the sequence. Since an implicit conversion sequence
985 // is an initialization, the special rules for
986 // initialization by user-defined conversion apply when
987 // selecting the best user-defined conversion for a
988 // user-defined conversion sequence (see 13.3.3 and
989 // 13.3.3.1).
990 User.After = Best->FinalConversion;
991 return true;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000992 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +0000993 assert(false && "Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000994 return false;
995 }
996
997 case OR_No_Viable_Function:
998 // No conversion here! We're done.
999 return false;
1000
1001 case OR_Ambiguous:
1002 // FIXME: See C++ [over.best.ics]p10 for the handling of
1003 // ambiguous conversion sequences.
1004 return false;
1005 }
1006
1007 return false;
1008}
1009
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001010/// CompareImplicitConversionSequences - Compare two implicit
1011/// conversion sequences to determine whether one is better than the
1012/// other or if they are indistinguishable (C++ 13.3.3.2).
1013ImplicitConversionSequence::CompareKind
1014Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1015 const ImplicitConversionSequence& ICS2)
1016{
1017 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1018 // conversion sequences (as defined in 13.3.3.1)
1019 // -- a standard conversion sequence (13.3.3.1.1) is a better
1020 // conversion sequence than a user-defined conversion sequence or
1021 // an ellipsis conversion sequence, and
1022 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1023 // conversion sequence than an ellipsis conversion sequence
1024 // (13.3.3.1.3).
1025 //
1026 if (ICS1.ConversionKind < ICS2.ConversionKind)
1027 return ImplicitConversionSequence::Better;
1028 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1029 return ImplicitConversionSequence::Worse;
1030
1031 // Two implicit conversion sequences of the same form are
1032 // indistinguishable conversion sequences unless one of the
1033 // following rules apply: (C++ 13.3.3.2p3):
1034 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1035 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1036 else if (ICS1.ConversionKind ==
1037 ImplicitConversionSequence::UserDefinedConversion) {
1038 // User-defined conversion sequence U1 is a better conversion
1039 // sequence than another user-defined conversion sequence U2 if
1040 // they contain the same user-defined conversion function or
1041 // constructor and if the second standard conversion sequence of
1042 // U1 is better than the second standard conversion sequence of
1043 // U2 (C++ 13.3.3.2p3).
1044 if (ICS1.UserDefined.ConversionFunction ==
1045 ICS2.UserDefined.ConversionFunction)
1046 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1047 ICS2.UserDefined.After);
1048 }
1049
1050 return ImplicitConversionSequence::Indistinguishable;
1051}
1052
1053/// CompareStandardConversionSequences - Compare two standard
1054/// conversion sequences to determine whether one is better than the
1055/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1056ImplicitConversionSequence::CompareKind
1057Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1058 const StandardConversionSequence& SCS2)
1059{
1060 // Standard conversion sequence S1 is a better conversion sequence
1061 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1062
1063 // -- S1 is a proper subsequence of S2 (comparing the conversion
1064 // sequences in the canonical form defined by 13.3.3.1.1,
1065 // excluding any Lvalue Transformation; the identity conversion
1066 // sequence is considered to be a subsequence of any
1067 // non-identity conversion sequence) or, if not that,
1068 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1069 // Neither is a proper subsequence of the other. Do nothing.
1070 ;
1071 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1072 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1073 (SCS1.Second == ICK_Identity &&
1074 SCS1.Third == ICK_Identity))
1075 // SCS1 is a proper subsequence of SCS2.
1076 return ImplicitConversionSequence::Better;
1077 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1078 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1079 (SCS2.Second == ICK_Identity &&
1080 SCS2.Third == ICK_Identity))
1081 // SCS2 is a proper subsequence of SCS1.
1082 return ImplicitConversionSequence::Worse;
1083
1084 // -- the rank of S1 is better than the rank of S2 (by the rules
1085 // defined below), or, if not that,
1086 ImplicitConversionRank Rank1 = SCS1.getRank();
1087 ImplicitConversionRank Rank2 = SCS2.getRank();
1088 if (Rank1 < Rank2)
1089 return ImplicitConversionSequence::Better;
1090 else if (Rank2 < Rank1)
1091 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001092
Douglas Gregor57373262008-10-22 14:17:15 +00001093 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1094 // are indistinguishable unless one of the following rules
1095 // applies:
1096
1097 // A conversion that is not a conversion of a pointer, or
1098 // pointer to member, to bool is better than another conversion
1099 // that is such a conversion.
1100 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1101 return SCS2.isPointerConversionToBool()
1102 ? ImplicitConversionSequence::Better
1103 : ImplicitConversionSequence::Worse;
1104
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001105 // C++ [over.ics.rank]p4b2:
1106 //
1107 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001108 // conversion of B* to A* is better than conversion of B* to
1109 // void*, and conversion of A* to void* is better than conversion
1110 // of B* to void*.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001111 bool SCS1ConvertsToVoid
1112 = SCS1.isPointerConversionToVoidPointer(Context);
1113 bool SCS2ConvertsToVoid
1114 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001115 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1116 // Exactly one of the conversion sequences is a conversion to
1117 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001118 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1119 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001120 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1121 // Neither conversion sequence converts to a void pointer; compare
1122 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001123 if (ImplicitConversionSequence::CompareKind DerivedCK
1124 = CompareDerivedToBaseConversions(SCS1, SCS2))
1125 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001126 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1127 // Both conversion sequences are conversions to void
1128 // pointers. Compare the source types to determine if there's an
1129 // inheritance relationship in their sources.
1130 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1131 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1132
1133 // Adjust the types we're converting from via the array-to-pointer
1134 // conversion, if we need to.
1135 if (SCS1.First == ICK_Array_To_Pointer)
1136 FromType1 = Context.getArrayDecayedType(FromType1);
1137 if (SCS2.First == ICK_Array_To_Pointer)
1138 FromType2 = Context.getArrayDecayedType(FromType2);
1139
1140 QualType FromPointee1
1141 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1142 QualType FromPointee2
1143 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1144
1145 if (IsDerivedFrom(FromPointee2, FromPointee1))
1146 return ImplicitConversionSequence::Better;
1147 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1148 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001149
1150 // Objective-C++: If one interface is more specific than the
1151 // other, it is the better one.
1152 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1153 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1154 if (FromIface1 && FromIface1) {
1155 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1156 return ImplicitConversionSequence::Better;
1157 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1158 return ImplicitConversionSequence::Worse;
1159 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001160 }
Douglas Gregor57373262008-10-22 14:17:15 +00001161
1162 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1163 // bullet 3).
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001164 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001165 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001166 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001167
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001168 // C++ [over.ics.rank]p3b4:
1169 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1170 // which the references refer are the same type except for
1171 // top-level cv-qualifiers, and the type to which the reference
1172 // initialized by S2 refers is more cv-qualified than the type
1173 // to which the reference initialized by S1 refers.
1174 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1175 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1176 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1177 T1 = Context.getCanonicalType(T1);
1178 T2 = Context.getCanonicalType(T2);
1179 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1180 if (T2.isMoreQualifiedThan(T1))
1181 return ImplicitConversionSequence::Better;
1182 else if (T1.isMoreQualifiedThan(T2))
1183 return ImplicitConversionSequence::Worse;
1184 }
1185 }
Douglas Gregor57373262008-10-22 14:17:15 +00001186
1187 return ImplicitConversionSequence::Indistinguishable;
1188}
1189
1190/// CompareQualificationConversions - Compares two standard conversion
1191/// sequences to determine whether they can be ranked based on their
1192/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1193ImplicitConversionSequence::CompareKind
1194Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1195 const StandardConversionSequence& SCS2)
1196{
Douglas Gregorba7e2102008-10-22 15:04:37 +00001197 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001198 // -- S1 and S2 differ only in their qualification conversion and
1199 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1200 // cv-qualification signature of type T1 is a proper subset of
1201 // the cv-qualification signature of type T2, and S1 is not the
1202 // deprecated string literal array-to-pointer conversion (4.2).
1203 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1204 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1205 return ImplicitConversionSequence::Indistinguishable;
1206
1207 // FIXME: the example in the standard doesn't use a qualification
1208 // conversion (!)
1209 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1210 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1211 T1 = Context.getCanonicalType(T1);
1212 T2 = Context.getCanonicalType(T2);
1213
1214 // If the types are the same, we won't learn anything by unwrapped
1215 // them.
1216 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1217 return ImplicitConversionSequence::Indistinguishable;
1218
1219 ImplicitConversionSequence::CompareKind Result
1220 = ImplicitConversionSequence::Indistinguishable;
1221 while (UnwrapSimilarPointerTypes(T1, T2)) {
1222 // Within each iteration of the loop, we check the qualifiers to
1223 // determine if this still looks like a qualification
1224 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001225 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001226 // until there are no more pointers or pointers-to-members left
1227 // to unwrap. This essentially mimics what
1228 // IsQualificationConversion does, but here we're checking for a
1229 // strict subset of qualifiers.
1230 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1231 // The qualifiers are the same, so this doesn't tell us anything
1232 // about how the sequences rank.
1233 ;
1234 else if (T2.isMoreQualifiedThan(T1)) {
1235 // T1 has fewer qualifiers, so it could be the better sequence.
1236 if (Result == ImplicitConversionSequence::Worse)
1237 // Neither has qualifiers that are a subset of the other's
1238 // qualifiers.
1239 return ImplicitConversionSequence::Indistinguishable;
1240
1241 Result = ImplicitConversionSequence::Better;
1242 } else if (T1.isMoreQualifiedThan(T2)) {
1243 // T2 has fewer qualifiers, so it could be the better sequence.
1244 if (Result == ImplicitConversionSequence::Better)
1245 // Neither has qualifiers that are a subset of the other's
1246 // qualifiers.
1247 return ImplicitConversionSequence::Indistinguishable;
1248
1249 Result = ImplicitConversionSequence::Worse;
1250 } else {
1251 // Qualifiers are disjoint.
1252 return ImplicitConversionSequence::Indistinguishable;
1253 }
1254
1255 // If the types after this point are equivalent, we're done.
1256 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1257 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001258 }
1259
Douglas Gregor57373262008-10-22 14:17:15 +00001260 // Check that the winning standard conversion sequence isn't using
1261 // the deprecated string literal array to pointer conversion.
1262 switch (Result) {
1263 case ImplicitConversionSequence::Better:
1264 if (SCS1.Deprecated)
1265 Result = ImplicitConversionSequence::Indistinguishable;
1266 break;
1267
1268 case ImplicitConversionSequence::Indistinguishable:
1269 break;
1270
1271 case ImplicitConversionSequence::Worse:
1272 if (SCS2.Deprecated)
1273 Result = ImplicitConversionSequence::Indistinguishable;
1274 break;
1275 }
1276
1277 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001278}
1279
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001280/// CompareDerivedToBaseConversions - Compares two standard conversion
1281/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00001282/// various kinds of derived-to-base conversions (C++
1283/// [over.ics.rank]p4b3). As part of these checks, we also look at
1284/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001285ImplicitConversionSequence::CompareKind
1286Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1287 const StandardConversionSequence& SCS2) {
1288 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1289 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1290 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1291 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1292
1293 // Adjust the types we're converting from via the array-to-pointer
1294 // conversion, if we need to.
1295 if (SCS1.First == ICK_Array_To_Pointer)
1296 FromType1 = Context.getArrayDecayedType(FromType1);
1297 if (SCS2.First == ICK_Array_To_Pointer)
1298 FromType2 = Context.getArrayDecayedType(FromType2);
1299
1300 // Canonicalize all of the types.
1301 FromType1 = Context.getCanonicalType(FromType1);
1302 ToType1 = Context.getCanonicalType(ToType1);
1303 FromType2 = Context.getCanonicalType(FromType2);
1304 ToType2 = Context.getCanonicalType(ToType2);
1305
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001306 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001307 //
1308 // If class B is derived directly or indirectly from class A and
1309 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001310 //
1311 // For Objective-C, we let A, B, and C also be Objective-C
1312 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001313
1314 // Compare based on pointer conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001315 if (SCS1.Second == ICK_Pointer_Conversion &&
1316 SCS2.Second == ICK_Pointer_Conversion) {
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001317 QualType FromPointee1
1318 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1319 QualType ToPointee1
1320 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1321 QualType FromPointee2
1322 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1323 QualType ToPointee2
1324 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001325
1326 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1327 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1328 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1329 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1330
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001331 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001332 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1333 if (IsDerivedFrom(ToPointee1, ToPointee2))
1334 return ImplicitConversionSequence::Better;
1335 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1336 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001337
1338 if (ToIface1 && ToIface2) {
1339 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1340 return ImplicitConversionSequence::Better;
1341 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1342 return ImplicitConversionSequence::Worse;
1343 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001344 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001345
1346 // -- conversion of B* to A* is better than conversion of C* to A*,
1347 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1348 if (IsDerivedFrom(FromPointee2, FromPointee1))
1349 return ImplicitConversionSequence::Better;
1350 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1351 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001352
1353 if (FromIface1 && FromIface2) {
1354 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1355 return ImplicitConversionSequence::Better;
1356 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1357 return ImplicitConversionSequence::Worse;
1358 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001359 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001360 }
1361
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001362 // Compare based on reference bindings.
1363 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1364 SCS1.Second == ICK_Derived_To_Base) {
1365 // -- binding of an expression of type C to a reference of type
1366 // B& is better than binding an expression of type C to a
1367 // reference of type A&,
1368 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1369 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1370 if (IsDerivedFrom(ToType1, ToType2))
1371 return ImplicitConversionSequence::Better;
1372 else if (IsDerivedFrom(ToType2, ToType1))
1373 return ImplicitConversionSequence::Worse;
1374 }
1375
Douglas Gregor225c41e2008-11-03 19:09:14 +00001376 // -- binding of an expression of type B to a reference of type
1377 // A& is better than binding an expression of type C to a
1378 // reference of type A&,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001379 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1380 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1381 if (IsDerivedFrom(FromType2, FromType1))
1382 return ImplicitConversionSequence::Better;
1383 else if (IsDerivedFrom(FromType1, FromType2))
1384 return ImplicitConversionSequence::Worse;
1385 }
1386 }
1387
1388
1389 // FIXME: conversion of A::* to B::* is better than conversion of
1390 // A::* to C::*,
1391
1392 // FIXME: conversion of B::* to C::* is better than conversion of
1393 // A::* to C::*, and
1394
Douglas Gregor225c41e2008-11-03 19:09:14 +00001395 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1396 SCS1.Second == ICK_Derived_To_Base) {
1397 // -- conversion of C to B is better than conversion of C to A,
1398 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1399 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1400 if (IsDerivedFrom(ToType1, ToType2))
1401 return ImplicitConversionSequence::Better;
1402 else if (IsDerivedFrom(ToType2, ToType1))
1403 return ImplicitConversionSequence::Worse;
1404 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001405
Douglas Gregor225c41e2008-11-03 19:09:14 +00001406 // -- conversion of B to A is better than conversion of C to A.
1407 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1408 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1409 if (IsDerivedFrom(FromType2, FromType1))
1410 return ImplicitConversionSequence::Better;
1411 else if (IsDerivedFrom(FromType1, FromType2))
1412 return ImplicitConversionSequence::Worse;
1413 }
1414 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001415
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001416 return ImplicitConversionSequence::Indistinguishable;
1417}
1418
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001419/// TryCopyInitialization - Try to copy-initialize a value of type
1420/// ToType from the expression From. Return the implicit conversion
1421/// sequence required to pass this argument, which may be a bad
1422/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00001423/// a parameter of this type). If @p SuppressUserConversions, then we
1424/// do not permit any user-defined conversion sequences.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001425ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +00001426Sema::TryCopyInitialization(Expr *From, QualType ToType,
1427 bool SuppressUserConversions) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001428 if (!getLangOptions().CPlusPlus) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001429 // In C, copy initialization is the same as performing an assignment.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001430 AssignConvertType ConvTy =
1431 CheckSingleAssignmentConstraints(ToType, From);
1432 ImplicitConversionSequence ICS;
1433 if (getLangOptions().NoExtensions? ConvTy != Compatible
1434 : ConvTy == Incompatible)
1435 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1436 else
1437 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1438 return ICS;
1439 } else if (ToType->isReferenceType()) {
1440 ImplicitConversionSequence ICS;
Douglas Gregor225c41e2008-11-03 19:09:14 +00001441 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001442 return ICS;
1443 } else {
Douglas Gregor225c41e2008-11-03 19:09:14 +00001444 return TryImplicitConversion(From, ToType, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001445 }
1446}
1447
1448/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1449/// type ToType. Returns true (and emits a diagnostic) if there was
1450/// an error, returns false if the initialization succeeded.
1451bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1452 const char* Flavor) {
1453 if (!getLangOptions().CPlusPlus) {
1454 // In C, argument passing is the same as performing an assignment.
1455 QualType FromType = From->getType();
1456 AssignConvertType ConvTy =
1457 CheckSingleAssignmentConstraints(ToType, From);
1458
1459 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1460 FromType, From, Flavor);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001461 }
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001462
1463 if (ToType->isReferenceType())
1464 return CheckReferenceInit(From, ToType);
1465
1466 if (!PerformImplicitConversion(From, ToType))
1467 return false;
1468
1469 return Diag(From->getSourceRange().getBegin(),
1470 diag::err_typecheck_convert_incompatible)
1471 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001472}
1473
Douglas Gregor96176b32008-11-18 23:14:02 +00001474/// TryObjectArgumentInitialization - Try to initialize the object
1475/// parameter of the given member function (@c Method) from the
1476/// expression @p From.
1477ImplicitConversionSequence
1478Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1479 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1480 unsigned MethodQuals = Method->getTypeQualifiers();
1481 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1482
1483 // Set up the conversion sequence as a "bad" conversion, to allow us
1484 // to exit early.
1485 ImplicitConversionSequence ICS;
1486 ICS.Standard.setAsIdentityConversion();
1487 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1488
1489 // We need to have an object of class type.
1490 QualType FromType = From->getType();
1491 if (!FromType->isRecordType())
1492 return ICS;
1493
1494 // The implicit object parmeter is has the type "reference to cv X",
1495 // where X is the class of which the function is a member
1496 // (C++ [over.match.funcs]p4). However, when finding an implicit
1497 // conversion sequence for the argument, we are not allowed to
1498 // create temporaries or perform user-defined conversions
1499 // (C++ [over.match.funcs]p5). We perform a simplified version of
1500 // reference binding here, that allows class rvalues to bind to
1501 // non-constant references.
1502
1503 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1504 // with the implicit object parameter (C++ [over.match.funcs]p5).
1505 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1506 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1507 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1508 return ICS;
1509
1510 // Check that we have either the same type or a derived type. It
1511 // affects the conversion rank.
1512 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1513 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1514 ICS.Standard.Second = ICK_Identity;
1515 else if (IsDerivedFrom(FromType, ClassType))
1516 ICS.Standard.Second = ICK_Derived_To_Base;
1517 else
1518 return ICS;
1519
1520 // Success. Mark this as a reference binding.
1521 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1522 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1523 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1524 ICS.Standard.ReferenceBinding = true;
1525 ICS.Standard.DirectBinding = true;
1526 return ICS;
1527}
1528
1529/// PerformObjectArgumentInitialization - Perform initialization of
1530/// the implicit object parameter for the given Method with the given
1531/// expression.
1532bool
1533Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
1534 QualType ImplicitParamType
1535 = Method->getThisType(Context)->getAsPointerType()->getPointeeType();
1536 ImplicitConversionSequence ICS
1537 = TryObjectArgumentInitialization(From, Method);
1538 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
1539 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001540 diag::err_implicit_object_parameter_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00001541 << ImplicitParamType << From->getType() << From->getSourceRange();
Douglas Gregor96176b32008-11-18 23:14:02 +00001542
1543 if (ICS.Standard.Second == ICK_Derived_To_Base &&
1544 CheckDerivedToBaseConversion(From->getType(), ImplicitParamType,
1545 From->getSourceRange().getBegin(),
1546 From->getSourceRange()))
1547 return true;
1548
1549 ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true);
1550 return false;
1551}
1552
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001553/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00001554/// candidate functions, using the given function call arguments. If
1555/// @p SuppressUserConversions, then don't allow user-defined
1556/// conversions via constructors or conversion operators.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001557void
1558Sema::AddOverloadCandidate(FunctionDecl *Function,
1559 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00001560 OverloadCandidateSet& CandidateSet,
1561 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001562{
1563 const FunctionTypeProto* Proto
1564 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType());
1565 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001566 assert(!isa<CXXConversionDecl>(Function) &&
1567 "Use AddConversionCandidate for conversion functions");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001568
1569 // Add this candidate
1570 CandidateSet.push_back(OverloadCandidate());
1571 OverloadCandidate& Candidate = CandidateSet.back();
1572 Candidate.Function = Function;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001573 Candidate.IsSurrogate = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001574
1575 unsigned NumArgsInProto = Proto->getNumArgs();
1576
1577 // (C++ 13.3.2p2): A candidate function having fewer than m
1578 // parameters is viable only if it has an ellipsis in its parameter
1579 // list (8.3.5).
1580 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1581 Candidate.Viable = false;
1582 return;
1583 }
1584
1585 // (C++ 13.3.2p2): A candidate function having more than m parameters
1586 // is viable only if the (m+1)st parameter has a default argument
1587 // (8.3.6). For the purposes of overload resolution, the
1588 // parameter list is truncated on the right, so that there are
1589 // exactly m parameters.
1590 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
1591 if (NumArgs < MinRequiredArgs) {
1592 // Not enough arguments.
1593 Candidate.Viable = false;
1594 return;
1595 }
1596
1597 // Determine the implicit conversion sequences for each of the
1598 // arguments.
1599 Candidate.Viable = true;
1600 Candidate.Conversions.resize(NumArgs);
1601 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1602 if (ArgIdx < NumArgsInProto) {
1603 // (C++ 13.3.2p3): for F to be a viable function, there shall
1604 // exist for each argument an implicit conversion sequence
1605 // (13.3.3.1) that converts that argument to the corresponding
1606 // parameter of F.
1607 QualType ParamType = Proto->getArgType(ArgIdx);
1608 Candidate.Conversions[ArgIdx]
Douglas Gregor225c41e2008-11-03 19:09:14 +00001609 = TryCopyInitialization(Args[ArgIdx], ParamType,
1610 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001611 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00001612 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001613 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001614 break;
1615 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001616 } else {
1617 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1618 // argument for which there is no corresponding parameter is
1619 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1620 Candidate.Conversions[ArgIdx].ConversionKind
1621 = ImplicitConversionSequence::EllipsisConversion;
1622 }
1623 }
1624}
1625
Douglas Gregor96176b32008-11-18 23:14:02 +00001626/// AddMethodCandidate - Adds the given C++ member function to the set
1627/// of candidate functions, using the given function call arguments
1628/// and the object argument (@c Object). For example, in a call
1629/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
1630/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
1631/// allow user-defined conversions via constructors or conversion
1632/// operators.
1633void
1634Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
1635 Expr **Args, unsigned NumArgs,
1636 OverloadCandidateSet& CandidateSet,
1637 bool SuppressUserConversions)
1638{
1639 const FunctionTypeProto* Proto
1640 = dyn_cast<FunctionTypeProto>(Method->getType()->getAsFunctionType());
1641 assert(Proto && "Methods without a prototype cannot be overloaded");
1642 assert(!isa<CXXConversionDecl>(Method) &&
1643 "Use AddConversionCandidate for conversion functions");
1644
1645 // Add this candidate
1646 CandidateSet.push_back(OverloadCandidate());
1647 OverloadCandidate& Candidate = CandidateSet.back();
1648 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001649 Candidate.IsSurrogate = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001650
1651 unsigned NumArgsInProto = Proto->getNumArgs();
1652
1653 // (C++ 13.3.2p2): A candidate function having fewer than m
1654 // parameters is viable only if it has an ellipsis in its parameter
1655 // list (8.3.5).
1656 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1657 Candidate.Viable = false;
1658 return;
1659 }
1660
1661 // (C++ 13.3.2p2): A candidate function having more than m parameters
1662 // is viable only if the (m+1)st parameter has a default argument
1663 // (8.3.6). For the purposes of overload resolution, the
1664 // parameter list is truncated on the right, so that there are
1665 // exactly m parameters.
1666 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
1667 if (NumArgs < MinRequiredArgs) {
1668 // Not enough arguments.
1669 Candidate.Viable = false;
1670 return;
1671 }
1672
1673 Candidate.Viable = true;
1674 Candidate.Conversions.resize(NumArgs + 1);
1675
1676 // Determine the implicit conversion sequence for the object
1677 // parameter.
1678 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
1679 if (Candidate.Conversions[0].ConversionKind
1680 == ImplicitConversionSequence::BadConversion) {
1681 Candidate.Viable = false;
1682 return;
1683 }
1684
1685 // Determine the implicit conversion sequences for each of the
1686 // arguments.
1687 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1688 if (ArgIdx < NumArgsInProto) {
1689 // (C++ 13.3.2p3): for F to be a viable function, there shall
1690 // exist for each argument an implicit conversion sequence
1691 // (13.3.3.1) that converts that argument to the corresponding
1692 // parameter of F.
1693 QualType ParamType = Proto->getArgType(ArgIdx);
1694 Candidate.Conversions[ArgIdx + 1]
1695 = TryCopyInitialization(Args[ArgIdx], ParamType,
1696 SuppressUserConversions);
1697 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
1698 == ImplicitConversionSequence::BadConversion) {
1699 Candidate.Viable = false;
1700 break;
1701 }
1702 } else {
1703 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1704 // argument for which there is no corresponding parameter is
1705 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1706 Candidate.Conversions[ArgIdx + 1].ConversionKind
1707 = ImplicitConversionSequence::EllipsisConversion;
1708 }
1709 }
1710}
1711
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001712/// AddConversionCandidate - Add a C++ conversion function as a
1713/// candidate in the candidate set (C++ [over.match.conv],
1714/// C++ [over.match.copy]). From is the expression we're converting from,
1715/// and ToType is the type that we're eventually trying to convert to
1716/// (which may or may not be the same type as the type that the
1717/// conversion function produces).
1718void
1719Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
1720 Expr *From, QualType ToType,
1721 OverloadCandidateSet& CandidateSet) {
1722 // Add this candidate
1723 CandidateSet.push_back(OverloadCandidate());
1724 OverloadCandidate& Candidate = CandidateSet.back();
1725 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001726 Candidate.IsSurrogate = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001727 Candidate.FinalConversion.setAsIdentityConversion();
1728 Candidate.FinalConversion.FromTypePtr
1729 = Conversion->getConversionType().getAsOpaquePtr();
1730 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
1731
Douglas Gregor96176b32008-11-18 23:14:02 +00001732 // Determine the implicit conversion sequence for the implicit
1733 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001734 Candidate.Viable = true;
1735 Candidate.Conversions.resize(1);
Douglas Gregor96176b32008-11-18 23:14:02 +00001736 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001737
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001738 if (Candidate.Conversions[0].ConversionKind
1739 == ImplicitConversionSequence::BadConversion) {
1740 Candidate.Viable = false;
1741 return;
1742 }
1743
1744 // To determine what the conversion from the result of calling the
1745 // conversion function to the type we're eventually trying to
1746 // convert to (ToType), we need to synthesize a call to the
1747 // conversion function and attempt copy initialization from it. This
1748 // makes sure that we get the right semantics with respect to
1749 // lvalues/rvalues and the type. Fortunately, we can allocate this
1750 // call on the stack and we don't need its arguments to be
1751 // well-formed.
1752 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
1753 SourceLocation());
1754 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001755 &ConversionRef, false);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001756 CallExpr Call(&ConversionFn, 0, 0,
1757 Conversion->getConversionType().getNonReferenceType(),
1758 SourceLocation());
1759 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
1760 switch (ICS.ConversionKind) {
1761 case ImplicitConversionSequence::StandardConversion:
1762 Candidate.FinalConversion = ICS.Standard;
1763 break;
1764
1765 case ImplicitConversionSequence::BadConversion:
1766 Candidate.Viable = false;
1767 break;
1768
1769 default:
1770 assert(false &&
1771 "Can only end up with a standard conversion sequence or failure");
1772 }
1773}
1774
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001775/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
1776/// converts the given @c Object to a function pointer via the
1777/// conversion function @c Conversion, and then attempts to call it
1778/// with the given arguments (C++ [over.call.object]p2-4). Proto is
1779/// the type of function that we'll eventually be calling.
1780void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
1781 const FunctionTypeProto *Proto,
1782 Expr *Object, Expr **Args, unsigned NumArgs,
1783 OverloadCandidateSet& CandidateSet) {
1784 CandidateSet.push_back(OverloadCandidate());
1785 OverloadCandidate& Candidate = CandidateSet.back();
1786 Candidate.Function = 0;
1787 Candidate.Surrogate = Conversion;
1788 Candidate.Viable = true;
1789 Candidate.IsSurrogate = true;
1790 Candidate.Conversions.resize(NumArgs + 1);
1791
1792 // Determine the implicit conversion sequence for the implicit
1793 // object parameter.
1794 ImplicitConversionSequence ObjectInit
1795 = TryObjectArgumentInitialization(Object, Conversion);
1796 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
1797 Candidate.Viable = false;
1798 return;
1799 }
1800
1801 // The first conversion is actually a user-defined conversion whose
1802 // first conversion is ObjectInit's standard conversion (which is
1803 // effectively a reference binding). Record it as such.
1804 Candidate.Conversions[0].ConversionKind
1805 = ImplicitConversionSequence::UserDefinedConversion;
1806 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
1807 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
1808 Candidate.Conversions[0].UserDefined.After
1809 = Candidate.Conversions[0].UserDefined.Before;
1810 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
1811
1812 // Find the
1813 unsigned NumArgsInProto = Proto->getNumArgs();
1814
1815 // (C++ 13.3.2p2): A candidate function having fewer than m
1816 // parameters is viable only if it has an ellipsis in its parameter
1817 // list (8.3.5).
1818 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1819 Candidate.Viable = false;
1820 return;
1821 }
1822
1823 // Function types don't have any default arguments, so just check if
1824 // we have enough arguments.
1825 if (NumArgs < NumArgsInProto) {
1826 // Not enough arguments.
1827 Candidate.Viable = false;
1828 return;
1829 }
1830
1831 // Determine the implicit conversion sequences for each of the
1832 // arguments.
1833 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1834 if (ArgIdx < NumArgsInProto) {
1835 // (C++ 13.3.2p3): for F to be a viable function, there shall
1836 // exist for each argument an implicit conversion sequence
1837 // (13.3.3.1) that converts that argument to the corresponding
1838 // parameter of F.
1839 QualType ParamType = Proto->getArgType(ArgIdx);
1840 Candidate.Conversions[ArgIdx + 1]
1841 = TryCopyInitialization(Args[ArgIdx], ParamType,
1842 /*SuppressUserConversions=*/false);
1843 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
1844 == ImplicitConversionSequence::BadConversion) {
1845 Candidate.Viable = false;
1846 break;
1847 }
1848 } else {
1849 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1850 // argument for which there is no corresponding parameter is
1851 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1852 Candidate.Conversions[ArgIdx + 1].ConversionKind
1853 = ImplicitConversionSequence::EllipsisConversion;
1854 }
1855 }
1856}
1857
Douglas Gregor447b69e2008-11-19 03:25:36 +00001858/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1859/// an acceptable non-member overloaded operator for a call whose
1860/// arguments have types T1 (and, if non-empty, T2). This routine
1861/// implements the check in C++ [over.match.oper]p3b2 concerning
1862/// enumeration types.
1863static bool
1864IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1865 QualType T1, QualType T2,
1866 ASTContext &Context) {
1867 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1868 return true;
1869
1870 const FunctionTypeProto *Proto = Fn->getType()->getAsFunctionTypeProto();
1871 if (Proto->getNumArgs() < 1)
1872 return false;
1873
1874 if (T1->isEnumeralType()) {
1875 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
1876 if (Context.getCanonicalType(T1).getUnqualifiedType()
1877 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1878 return true;
1879 }
1880
1881 if (Proto->getNumArgs() < 2)
1882 return false;
1883
1884 if (!T2.isNull() && T2->isEnumeralType()) {
1885 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
1886 if (Context.getCanonicalType(T2).getUnqualifiedType()
1887 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1888 return true;
1889 }
1890
1891 return false;
1892}
1893
Douglas Gregor96176b32008-11-18 23:14:02 +00001894/// AddOperatorCandidates - Add the overloaded operator candidates for
1895/// the operator Op that was used in an operator expression such as "x
1896/// Op y". S is the scope in which the expression occurred (used for
1897/// name lookup of the operator), Args/NumArgs provides the operator
1898/// arguments, and CandidateSet will store the added overload
1899/// candidates. (C++ [over.match.oper]).
1900void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
1901 Expr **Args, unsigned NumArgs,
1902 OverloadCandidateSet& CandidateSet) {
1903 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
1904
1905 // C++ [over.match.oper]p3:
1906 // For a unary operator @ with an operand of a type whose
1907 // cv-unqualified version is T1, and for a binary operator @ with
1908 // a left operand of a type whose cv-unqualified version is T1 and
1909 // a right operand of a type whose cv-unqualified version is T2,
1910 // three sets of candidate functions, designated member
1911 // candidates, non-member candidates and built-in candidates, are
1912 // constructed as follows:
1913 QualType T1 = Args[0]->getType();
1914 QualType T2;
1915 if (NumArgs > 1)
1916 T2 = Args[1]->getType();
1917
1918 // -- If T1 is a class type, the set of member candidates is the
1919 // result of the qualified lookup of T1::operator@
1920 // (13.3.1.1.1); otherwise, the set of member candidates is
1921 // empty.
1922 if (const RecordType *T1Rec = T1->getAsRecordType()) {
1923 IdentifierResolver::iterator I
1924 = IdResolver.begin(OpName, cast<CXXRecordType>(T1Rec)->getDecl(),
1925 /*LookInParentCtx=*/false);
1926 NamedDecl *MemberOps = (I == IdResolver.end())? 0 : *I;
1927 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps))
1928 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet,
1929 /*SuppressUserConversions=*/false);
1930 else if (OverloadedFunctionDecl *Ovl
1931 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) {
1932 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
1933 FEnd = Ovl->function_end();
1934 F != FEnd; ++F) {
1935 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F))
1936 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet,
1937 /*SuppressUserConversions=*/false);
1938 }
1939 }
1940 }
1941
1942 // -- The set of non-member candidates is the result of the
1943 // unqualified lookup of operator@ in the context of the
1944 // expression according to the usual rules for name lookup in
1945 // unqualified function calls (3.4.2) except that all member
1946 // functions are ignored. However, if no operand has a class
1947 // type, only those non-member functions in the lookup set
1948 // that have a first parameter of type T1 or “reference to
1949 // (possibly cv-qualified) T1”, when T1 is an enumeration
1950 // type, or (if there is a right operand) a second parameter
1951 // of type T2 or “reference to (possibly cv-qualified) T2”,
1952 // when T2 is an enumeration type, are candidate functions.
1953 {
1954 NamedDecl *NonMemberOps = 0;
1955 for (IdentifierResolver::iterator I
1956 = IdResolver.begin(OpName, CurContext, true/*LookInParentCtx*/);
1957 I != IdResolver.end(); ++I) {
1958 // We don't need to check the identifier namespace, because
1959 // operator names can only be ordinary identifiers.
1960
1961 // Ignore member functions.
1962 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(*I)) {
1963 if (SD->getDeclContext()->isCXXRecord())
1964 continue;
1965 }
1966
1967 // We found something with this name. We're done.
1968 NonMemberOps = *I;
1969 break;
1970 }
1971
Douglas Gregor447b69e2008-11-19 03:25:36 +00001972 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NonMemberOps)) {
1973 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1974 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
1975 /*SuppressUserConversions=*/false);
1976 } else if (OverloadedFunctionDecl *Ovl
1977 = dyn_cast_or_null<OverloadedFunctionDecl>(NonMemberOps)) {
Douglas Gregor96176b32008-11-18 23:14:02 +00001978 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
1979 FEnd = Ovl->function_end();
Douglas Gregor447b69e2008-11-19 03:25:36 +00001980 F != FEnd; ++F) {
1981 if (IsAcceptableNonMemberOperatorCandidate(*F, T1, T2, Context))
1982 AddOverloadCandidate(*F, Args, NumArgs, CandidateSet,
1983 /*SuppressUserConversions=*/false);
1984 }
Douglas Gregor96176b32008-11-18 23:14:02 +00001985 }
1986 }
1987
1988 // Add builtin overload candidates (C++ [over.built]).
Douglas Gregor74253732008-11-19 15:42:04 +00001989 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
Douglas Gregor96176b32008-11-18 23:14:02 +00001990}
1991
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001992/// AddBuiltinCandidate - Add a candidate for a built-in
1993/// operator. ResultTy and ParamTys are the result and parameter types
1994/// of the built-in candidate, respectively. Args and NumArgs are the
1995/// arguments being passed to the candidate.
1996void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
1997 Expr **Args, unsigned NumArgs,
1998 OverloadCandidateSet& CandidateSet) {
1999 // Add this candidate
2000 CandidateSet.push_back(OverloadCandidate());
2001 OverloadCandidate& Candidate = CandidateSet.back();
2002 Candidate.Function = 0;
2003 Candidate.BuiltinTypes.ResultTy = ResultTy;
2004 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2005 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2006
2007 // Determine the implicit conversion sequences for each of the
2008 // arguments.
2009 Candidate.Viable = true;
2010 Candidate.Conversions.resize(NumArgs);
2011 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2012 Candidate.Conversions[ArgIdx]
2013 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx], false);
2014 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002015 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002016 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002017 break;
2018 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002019 }
2020}
2021
2022/// BuiltinCandidateTypeSet - A set of types that will be used for the
2023/// candidate operator functions for built-in operators (C++
2024/// [over.built]). The types are separated into pointer types and
2025/// enumeration types.
2026class BuiltinCandidateTypeSet {
2027 /// TypeSet - A set of types.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002028 typedef llvm::SmallPtrSet<void*, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002029
2030 /// PointerTypes - The set of pointer types that will be used in the
2031 /// built-in candidates.
2032 TypeSet PointerTypes;
2033
2034 /// EnumerationTypes - The set of enumeration types that will be
2035 /// used in the built-in candidates.
2036 TypeSet EnumerationTypes;
2037
2038 /// Context - The AST context in which we will build the type sets.
2039 ASTContext &Context;
2040
2041 bool AddWithMoreQualifiedTypeVariants(QualType Ty);
2042
2043public:
2044 /// iterator - Iterates through the types that are part of the set.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002045 class iterator {
2046 TypeSet::iterator Base;
2047
2048 public:
2049 typedef QualType value_type;
2050 typedef QualType reference;
2051 typedef QualType pointer;
2052 typedef std::ptrdiff_t difference_type;
2053 typedef std::input_iterator_tag iterator_category;
2054
2055 iterator(TypeSet::iterator B) : Base(B) { }
2056
2057 iterator& operator++() {
2058 ++Base;
2059 return *this;
2060 }
2061
2062 iterator operator++(int) {
2063 iterator tmp(*this);
2064 ++(*this);
2065 return tmp;
2066 }
2067
2068 reference operator*() const {
2069 return QualType::getFromOpaquePtr(*Base);
2070 }
2071
2072 pointer operator->() const {
2073 return **this;
2074 }
2075
2076 friend bool operator==(iterator LHS, iterator RHS) {
2077 return LHS.Base == RHS.Base;
2078 }
2079
2080 friend bool operator!=(iterator LHS, iterator RHS) {
2081 return LHS.Base != RHS.Base;
2082 }
2083 };
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002084
2085 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2086
2087 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions = true);
2088
2089 /// pointer_begin - First pointer type found;
2090 iterator pointer_begin() { return PointerTypes.begin(); }
2091
2092 /// pointer_end - Last pointer type found;
2093 iterator pointer_end() { return PointerTypes.end(); }
2094
2095 /// enumeration_begin - First enumeration type found;
2096 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2097
2098 /// enumeration_end - Last enumeration type found;
2099 iterator enumeration_end() { return EnumerationTypes.end(); }
2100};
2101
2102/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2103/// the set of pointer types along with any more-qualified variants of
2104/// that type. For example, if @p Ty is "int const *", this routine
2105/// will add "int const *", "int const volatile *", "int const
2106/// restrict *", and "int const volatile restrict *" to the set of
2107/// pointer types. Returns true if the add of @p Ty itself succeeded,
2108/// false otherwise.
2109bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) {
2110 // Insert this type.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002111 if (!PointerTypes.insert(Ty.getAsOpaquePtr()))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002112 return false;
2113
2114 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2115 QualType PointeeTy = PointerTy->getPointeeType();
2116 // FIXME: Optimize this so that we don't keep trying to add the same types.
2117
2118 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
2119 // with all pointer conversions that don't cast away constness?
2120 if (!PointeeTy.isConstQualified())
2121 AddWithMoreQualifiedTypeVariants
2122 (Context.getPointerType(PointeeTy.withConst()));
2123 if (!PointeeTy.isVolatileQualified())
2124 AddWithMoreQualifiedTypeVariants
2125 (Context.getPointerType(PointeeTy.withVolatile()));
2126 if (!PointeeTy.isRestrictQualified())
2127 AddWithMoreQualifiedTypeVariants
2128 (Context.getPointerType(PointeeTy.withRestrict()));
2129 }
2130
2131 return true;
2132}
2133
2134/// AddTypesConvertedFrom - Add each of the types to which the type @p
2135/// Ty can be implicit converted to the given set of @p Types. We're
2136/// primarily interested in pointer types, enumeration types,
2137void BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2138 bool AllowUserConversions) {
2139 // Only deal with canonical types.
2140 Ty = Context.getCanonicalType(Ty);
2141
2142 // Look through reference types; they aren't part of the type of an
2143 // expression for the purposes of conversions.
2144 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2145 Ty = RefTy->getPointeeType();
2146
2147 // We don't care about qualifiers on the type.
2148 Ty = Ty.getUnqualifiedType();
2149
2150 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2151 QualType PointeeTy = PointerTy->getPointeeType();
2152
2153 // Insert our type, and its more-qualified variants, into the set
2154 // of types.
2155 if (!AddWithMoreQualifiedTypeVariants(Ty))
2156 return;
2157
2158 // Add 'cv void*' to our set of types.
2159 if (!Ty->isVoidType()) {
2160 QualType QualVoid
2161 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2162 AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2163 }
2164
2165 // If this is a pointer to a class type, add pointers to its bases
2166 // (with the same level of cv-qualification as the original
2167 // derived class, of course).
2168 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2169 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2170 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2171 Base != ClassDecl->bases_end(); ++Base) {
2172 QualType BaseTy = Context.getCanonicalType(Base->getType());
2173 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2174
2175 // Add the pointer type, recursively, so that we get all of
2176 // the indirect base classes, too.
2177 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false);
2178 }
2179 }
2180 } else if (Ty->isEnumeralType()) {
Douglas Gregorbf3af052008-11-13 20:12:29 +00002181 EnumerationTypes.insert(Ty.getAsOpaquePtr());
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002182 } else if (AllowUserConversions) {
2183 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2184 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2185 // FIXME: Visit conversion functions in the base classes, too.
2186 OverloadedFunctionDecl *Conversions
2187 = ClassDecl->getConversionFunctions();
2188 for (OverloadedFunctionDecl::function_iterator Func
2189 = Conversions->function_begin();
2190 Func != Conversions->function_end(); ++Func) {
2191 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
2192 AddTypesConvertedFrom(Conv->getConversionType(), false);
2193 }
2194 }
2195 }
2196}
2197
Douglas Gregor74253732008-11-19 15:42:04 +00002198/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2199/// operator overloads to the candidate set (C++ [over.built]), based
2200/// on the operator @p Op and the arguments given. For example, if the
2201/// operator is a binary '+', this routine might add "int
2202/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002203void
Douglas Gregor74253732008-11-19 15:42:04 +00002204Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2205 Expr **Args, unsigned NumArgs,
2206 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002207 // The set of "promoted arithmetic types", which are the arithmetic
2208 // types are that preserved by promotion (C++ [over.built]p2). Note
2209 // that the first few of these types are the promoted integral
2210 // types; these types need to be first.
2211 // FIXME: What about complex?
2212 const unsigned FirstIntegralType = 0;
2213 const unsigned LastIntegralType = 13;
2214 const unsigned FirstPromotedIntegralType = 7,
2215 LastPromotedIntegralType = 13;
2216 const unsigned FirstPromotedArithmeticType = 7,
2217 LastPromotedArithmeticType = 16;
2218 const unsigned NumArithmeticTypes = 16;
2219 QualType ArithmeticTypes[NumArithmeticTypes] = {
2220 Context.BoolTy, Context.CharTy, Context.WCharTy,
2221 Context.SignedCharTy, Context.ShortTy,
2222 Context.UnsignedCharTy, Context.UnsignedShortTy,
2223 Context.IntTy, Context.LongTy, Context.LongLongTy,
2224 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2225 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2226 };
2227
2228 // Find all of the types that the arguments can convert to, but only
2229 // if the operator we're looking at has built-in operator candidates
2230 // that make use of these types.
2231 BuiltinCandidateTypeSet CandidateTypes(Context);
2232 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2233 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00002234 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002235 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00002236 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
2237 (Op == OO_Star && NumArgs == 1)) {
2238 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002239 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType());
2240 }
2241
2242 bool isComparison = false;
2243 switch (Op) {
2244 case OO_None:
2245 case NUM_OVERLOADED_OPERATORS:
2246 assert(false && "Expected an overloaded operator");
2247 break;
2248
Douglas Gregor74253732008-11-19 15:42:04 +00002249 case OO_Star: // '*' is either unary or binary
2250 if (NumArgs == 1)
2251 goto UnaryStar;
2252 else
2253 goto BinaryStar;
2254 break;
2255
2256 case OO_Plus: // '+' is either unary or binary
2257 if (NumArgs == 1)
2258 goto UnaryPlus;
2259 else
2260 goto BinaryPlus;
2261 break;
2262
2263 case OO_Minus: // '-' is either unary or binary
2264 if (NumArgs == 1)
2265 goto UnaryMinus;
2266 else
2267 goto BinaryMinus;
2268 break;
2269
2270 case OO_Amp: // '&' is either unary or binary
2271 if (NumArgs == 1)
2272 goto UnaryAmp;
2273 else
2274 goto BinaryAmp;
2275
2276 case OO_PlusPlus:
2277 case OO_MinusMinus:
2278 // C++ [over.built]p3:
2279 //
2280 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2281 // is either volatile or empty, there exist candidate operator
2282 // functions of the form
2283 //
2284 // VQ T& operator++(VQ T&);
2285 // T operator++(VQ T&, int);
2286 //
2287 // C++ [over.built]p4:
2288 //
2289 // For every pair (T, VQ), where T is an arithmetic type other
2290 // than bool, and VQ is either volatile or empty, there exist
2291 // candidate operator functions of the form
2292 //
2293 // VQ T& operator--(VQ T&);
2294 // T operator--(VQ T&, int);
2295 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2296 Arith < NumArithmeticTypes; ++Arith) {
2297 QualType ArithTy = ArithmeticTypes[Arith];
2298 QualType ParamTypes[2]
2299 = { Context.getReferenceType(ArithTy), Context.IntTy };
2300
2301 // Non-volatile version.
2302 if (NumArgs == 1)
2303 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2304 else
2305 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2306
2307 // Volatile version
2308 ParamTypes[0] = Context.getReferenceType(ArithTy.withVolatile());
2309 if (NumArgs == 1)
2310 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2311 else
2312 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2313 }
2314
2315 // C++ [over.built]p5:
2316 //
2317 // For every pair (T, VQ), where T is a cv-qualified or
2318 // cv-unqualified object type, and VQ is either volatile or
2319 // empty, there exist candidate operator functions of the form
2320 //
2321 // T*VQ& operator++(T*VQ&);
2322 // T*VQ& operator--(T*VQ&);
2323 // T* operator++(T*VQ&, int);
2324 // T* operator--(T*VQ&, int);
2325 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2326 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2327 // Skip pointer types that aren't pointers to object types.
Douglas Gregorcb7de522008-11-26 23:31:11 +00002328 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00002329 continue;
2330
2331 QualType ParamTypes[2] = {
2332 Context.getReferenceType(*Ptr), Context.IntTy
2333 };
2334
2335 // Without volatile
2336 if (NumArgs == 1)
2337 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2338 else
2339 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2340
2341 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2342 // With volatile
2343 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2344 if (NumArgs == 1)
2345 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2346 else
2347 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2348 }
2349 }
2350 break;
2351
2352 UnaryStar:
2353 // C++ [over.built]p6:
2354 // For every cv-qualified or cv-unqualified object type T, there
2355 // exist candidate operator functions of the form
2356 //
2357 // T& operator*(T*);
2358 //
2359 // C++ [over.built]p7:
2360 // For every function type T, there exist candidate operator
2361 // functions of the form
2362 // T& operator*(T*);
2363 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2364 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2365 QualType ParamTy = *Ptr;
2366 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
2367 AddBuiltinCandidate(Context.getReferenceType(PointeeTy),
2368 &ParamTy, Args, 1, CandidateSet);
2369 }
2370 break;
2371
2372 UnaryPlus:
2373 // C++ [over.built]p8:
2374 // For every type T, there exist candidate operator functions of
2375 // the form
2376 //
2377 // T* operator+(T*);
2378 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2379 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2380 QualType ParamTy = *Ptr;
2381 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2382 }
2383
2384 // Fall through
2385
2386 UnaryMinus:
2387 // C++ [over.built]p9:
2388 // For every promoted arithmetic type T, there exist candidate
2389 // operator functions of the form
2390 //
2391 // T operator+(T);
2392 // T operator-(T);
2393 for (unsigned Arith = FirstPromotedArithmeticType;
2394 Arith < LastPromotedArithmeticType; ++Arith) {
2395 QualType ArithTy = ArithmeticTypes[Arith];
2396 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2397 }
2398 break;
2399
2400 case OO_Tilde:
2401 // C++ [over.built]p10:
2402 // For every promoted integral type T, there exist candidate
2403 // operator functions of the form
2404 //
2405 // T operator~(T);
2406 for (unsigned Int = FirstPromotedIntegralType;
2407 Int < LastPromotedIntegralType; ++Int) {
2408 QualType IntTy = ArithmeticTypes[Int];
2409 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2410 }
2411 break;
2412
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002413 case OO_New:
2414 case OO_Delete:
2415 case OO_Array_New:
2416 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002417 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00002418 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002419 break;
2420
2421 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00002422 UnaryAmp:
2423 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002424 // C++ [over.match.oper]p3:
2425 // -- For the operator ',', the unary operator '&', or the
2426 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002427 break;
2428
2429 case OO_Less:
2430 case OO_Greater:
2431 case OO_LessEqual:
2432 case OO_GreaterEqual:
2433 case OO_EqualEqual:
2434 case OO_ExclaimEqual:
2435 // C++ [over.built]p15:
2436 //
2437 // For every pointer or enumeration type T, there exist
2438 // candidate operator functions of the form
2439 //
2440 // bool operator<(T, T);
2441 // bool operator>(T, T);
2442 // bool operator<=(T, T);
2443 // bool operator>=(T, T);
2444 // bool operator==(T, T);
2445 // bool operator!=(T, T);
2446 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2447 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2448 QualType ParamTypes[2] = { *Ptr, *Ptr };
2449 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2450 }
2451 for (BuiltinCandidateTypeSet::iterator Enum
2452 = CandidateTypes.enumeration_begin();
2453 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2454 QualType ParamTypes[2] = { *Enum, *Enum };
2455 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2456 }
2457
2458 // Fall through.
2459 isComparison = true;
2460
Douglas Gregor74253732008-11-19 15:42:04 +00002461 BinaryPlus:
2462 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002463 if (!isComparison) {
2464 // We didn't fall through, so we must have OO_Plus or OO_Minus.
2465
2466 // C++ [over.built]p13:
2467 //
2468 // For every cv-qualified or cv-unqualified object type T
2469 // there exist candidate operator functions of the form
2470 //
2471 // T* operator+(T*, ptrdiff_t);
2472 // T& operator[](T*, ptrdiff_t); [BELOW]
2473 // T* operator-(T*, ptrdiff_t);
2474 // T* operator+(ptrdiff_t, T*);
2475 // T& operator[](ptrdiff_t, T*); [BELOW]
2476 //
2477 // C++ [over.built]p14:
2478 //
2479 // For every T, where T is a pointer to object type, there
2480 // exist candidate operator functions of the form
2481 //
2482 // ptrdiff_t operator-(T, T);
2483 for (BuiltinCandidateTypeSet::iterator Ptr
2484 = CandidateTypes.pointer_begin();
2485 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2486 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2487
2488 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
2489 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2490
2491 if (Op == OO_Plus) {
2492 // T* operator+(ptrdiff_t, T*);
2493 ParamTypes[0] = ParamTypes[1];
2494 ParamTypes[1] = *Ptr;
2495 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2496 } else {
2497 // ptrdiff_t operator-(T, T);
2498 ParamTypes[1] = *Ptr;
2499 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
2500 Args, 2, CandidateSet);
2501 }
2502 }
2503 }
2504 // Fall through
2505
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002506 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00002507 BinaryStar:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002508 // C++ [over.built]p12:
2509 //
2510 // For every pair of promoted arithmetic types L and R, there
2511 // exist candidate operator functions of the form
2512 //
2513 // LR operator*(L, R);
2514 // LR operator/(L, R);
2515 // LR operator+(L, R);
2516 // LR operator-(L, R);
2517 // bool operator<(L, R);
2518 // bool operator>(L, R);
2519 // bool operator<=(L, R);
2520 // bool operator>=(L, R);
2521 // bool operator==(L, R);
2522 // bool operator!=(L, R);
2523 //
2524 // where LR is the result of the usual arithmetic conversions
2525 // between types L and R.
2526 for (unsigned Left = FirstPromotedArithmeticType;
2527 Left < LastPromotedArithmeticType; ++Left) {
2528 for (unsigned Right = FirstPromotedArithmeticType;
2529 Right < LastPromotedArithmeticType; ++Right) {
2530 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2531 QualType Result
2532 = isComparison? Context.BoolTy
2533 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2534 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2535 }
2536 }
2537 break;
2538
2539 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00002540 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002541 case OO_Caret:
2542 case OO_Pipe:
2543 case OO_LessLess:
2544 case OO_GreaterGreater:
2545 // C++ [over.built]p17:
2546 //
2547 // For every pair of promoted integral types L and R, there
2548 // exist candidate operator functions of the form
2549 //
2550 // LR operator%(L, R);
2551 // LR operator&(L, R);
2552 // LR operator^(L, R);
2553 // LR operator|(L, R);
2554 // L operator<<(L, R);
2555 // L operator>>(L, R);
2556 //
2557 // where LR is the result of the usual arithmetic conversions
2558 // between types L and R.
2559 for (unsigned Left = FirstPromotedIntegralType;
2560 Left < LastPromotedIntegralType; ++Left) {
2561 for (unsigned Right = FirstPromotedIntegralType;
2562 Right < LastPromotedIntegralType; ++Right) {
2563 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2564 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
2565 ? LandR[0]
2566 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2567 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2568 }
2569 }
2570 break;
2571
2572 case OO_Equal:
2573 // C++ [over.built]p20:
2574 //
2575 // For every pair (T, VQ), where T is an enumeration or
2576 // (FIXME:) pointer to member type and VQ is either volatile or
2577 // empty, there exist candidate operator functions of the form
2578 //
2579 // VQ T& operator=(VQ T&, T);
2580 for (BuiltinCandidateTypeSet::iterator Enum
2581 = CandidateTypes.enumeration_begin();
2582 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2583 QualType ParamTypes[2];
2584
2585 // T& operator=(T&, T)
2586 ParamTypes[0] = Context.getReferenceType(*Enum);
2587 ParamTypes[1] = *Enum;
2588 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2589
Douglas Gregor74253732008-11-19 15:42:04 +00002590 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
2591 // volatile T& operator=(volatile T&, T)
2592 ParamTypes[0] = Context.getReferenceType((*Enum).withVolatile());
2593 ParamTypes[1] = *Enum;
2594 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2595 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002596 }
2597 // Fall through.
2598
2599 case OO_PlusEqual:
2600 case OO_MinusEqual:
2601 // C++ [over.built]p19:
2602 //
2603 // For every pair (T, VQ), where T is any type and VQ is either
2604 // volatile or empty, there exist candidate operator functions
2605 // of the form
2606 //
2607 // T*VQ& operator=(T*VQ&, T*);
2608 //
2609 // C++ [over.built]p21:
2610 //
2611 // For every pair (T, VQ), where T is a cv-qualified or
2612 // cv-unqualified object type and VQ is either volatile or
2613 // empty, there exist candidate operator functions of the form
2614 //
2615 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
2616 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
2617 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2618 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2619 QualType ParamTypes[2];
2620 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
2621
2622 // non-volatile version
2623 ParamTypes[0] = Context.getReferenceType(*Ptr);
2624 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2625
Douglas Gregor74253732008-11-19 15:42:04 +00002626 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2627 // volatile version
2628 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2629 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2630 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002631 }
2632 // Fall through.
2633
2634 case OO_StarEqual:
2635 case OO_SlashEqual:
2636 // C++ [over.built]p18:
2637 //
2638 // For every triple (L, VQ, R), where L is an arithmetic type,
2639 // VQ is either volatile or empty, and R is a promoted
2640 // arithmetic type, there exist candidate operator functions of
2641 // the form
2642 //
2643 // VQ L& operator=(VQ L&, R);
2644 // VQ L& operator*=(VQ L&, R);
2645 // VQ L& operator/=(VQ L&, R);
2646 // VQ L& operator+=(VQ L&, R);
2647 // VQ L& operator-=(VQ L&, R);
2648 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
2649 for (unsigned Right = FirstPromotedArithmeticType;
2650 Right < LastPromotedArithmeticType; ++Right) {
2651 QualType ParamTypes[2];
2652 ParamTypes[1] = ArithmeticTypes[Right];
2653
2654 // Add this built-in operator as a candidate (VQ is empty).
2655 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
2656 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2657
2658 // Add this built-in operator as a candidate (VQ is 'volatile').
2659 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
2660 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
2661 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2662 }
2663 }
2664 break;
2665
2666 case OO_PercentEqual:
2667 case OO_LessLessEqual:
2668 case OO_GreaterGreaterEqual:
2669 case OO_AmpEqual:
2670 case OO_CaretEqual:
2671 case OO_PipeEqual:
2672 // C++ [over.built]p22:
2673 //
2674 // For every triple (L, VQ, R), where L is an integral type, VQ
2675 // is either volatile or empty, and R is a promoted integral
2676 // type, there exist candidate operator functions of the form
2677 //
2678 // VQ L& operator%=(VQ L&, R);
2679 // VQ L& operator<<=(VQ L&, R);
2680 // VQ L& operator>>=(VQ L&, R);
2681 // VQ L& operator&=(VQ L&, R);
2682 // VQ L& operator^=(VQ L&, R);
2683 // VQ L& operator|=(VQ L&, R);
2684 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
2685 for (unsigned Right = FirstPromotedIntegralType;
2686 Right < LastPromotedIntegralType; ++Right) {
2687 QualType ParamTypes[2];
2688 ParamTypes[1] = ArithmeticTypes[Right];
2689
2690 // Add this built-in operator as a candidate (VQ is empty).
2691 // FIXME: We should be caching these declarations somewhere,
2692 // rather than re-building them every time.
2693 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
2694 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2695
2696 // Add this built-in operator as a candidate (VQ is 'volatile').
2697 ParamTypes[0] = ArithmeticTypes[Left];
2698 ParamTypes[0].addVolatile();
2699 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
2700 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2701 }
2702 }
2703 break;
2704
Douglas Gregor74253732008-11-19 15:42:04 +00002705 case OO_Exclaim: {
2706 // C++ [over.operator]p23:
2707 //
2708 // There also exist candidate operator functions of the form
2709 //
2710 // bool operator!(bool);
2711 // bool operator&&(bool, bool); [BELOW]
2712 // bool operator||(bool, bool); [BELOW]
2713 QualType ParamTy = Context.BoolTy;
2714 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2715 break;
2716 }
2717
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002718 case OO_AmpAmp:
2719 case OO_PipePipe: {
2720 // C++ [over.operator]p23:
2721 //
2722 // There also exist candidate operator functions of the form
2723 //
Douglas Gregor74253732008-11-19 15:42:04 +00002724 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002725 // bool operator&&(bool, bool);
2726 // bool operator||(bool, bool);
2727 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
2728 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2729 break;
2730 }
2731
2732 case OO_Subscript:
2733 // C++ [over.built]p13:
2734 //
2735 // For every cv-qualified or cv-unqualified object type T there
2736 // exist candidate operator functions of the form
2737 //
2738 // T* operator+(T*, ptrdiff_t); [ABOVE]
2739 // T& operator[](T*, ptrdiff_t);
2740 // T* operator-(T*, ptrdiff_t); [ABOVE]
2741 // T* operator+(ptrdiff_t, T*); [ABOVE]
2742 // T& operator[](ptrdiff_t, T*);
2743 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2744 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2745 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2746 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
2747 QualType ResultTy = Context.getReferenceType(PointeeType);
2748
2749 // T& operator[](T*, ptrdiff_t)
2750 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
2751
2752 // T& operator[](ptrdiff_t, T*);
2753 ParamTypes[0] = ParamTypes[1];
2754 ParamTypes[1] = *Ptr;
2755 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
2756 }
2757 break;
2758
2759 case OO_ArrowStar:
2760 // FIXME: No support for pointer-to-members yet.
2761 break;
2762 }
2763}
2764
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002765/// AddOverloadCandidates - Add all of the function overloads in Ovl
2766/// to the candidate set.
2767void
Douglas Gregor18fe5682008-11-03 20:45:27 +00002768Sema::AddOverloadCandidates(const OverloadedFunctionDecl *Ovl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002769 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002770 OverloadCandidateSet& CandidateSet,
2771 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002772{
Douglas Gregor18fe5682008-11-03 20:45:27 +00002773 for (OverloadedFunctionDecl::function_const_iterator Func
2774 = Ovl->function_begin();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002775 Func != Ovl->function_end(); ++Func)
Douglas Gregor225c41e2008-11-03 19:09:14 +00002776 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet,
2777 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002778}
2779
2780/// isBetterOverloadCandidate - Determines whether the first overload
2781/// candidate is a better candidate than the second (C++ 13.3.3p1).
2782bool
2783Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
2784 const OverloadCandidate& Cand2)
2785{
2786 // Define viable functions to be better candidates than non-viable
2787 // functions.
2788 if (!Cand2.Viable)
2789 return Cand1.Viable;
2790 else if (!Cand1.Viable)
2791 return false;
2792
2793 // FIXME: Deal with the implicit object parameter for static member
2794 // functions. (C++ 13.3.3p1).
2795
2796 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
2797 // function than another viable function F2 if for all arguments i,
2798 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
2799 // then...
2800 unsigned NumArgs = Cand1.Conversions.size();
2801 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
2802 bool HasBetterConversion = false;
2803 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2804 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
2805 Cand2.Conversions[ArgIdx])) {
2806 case ImplicitConversionSequence::Better:
2807 // Cand1 has a better conversion sequence.
2808 HasBetterConversion = true;
2809 break;
2810
2811 case ImplicitConversionSequence::Worse:
2812 // Cand1 can't be better than Cand2.
2813 return false;
2814
2815 case ImplicitConversionSequence::Indistinguishable:
2816 // Do nothing.
2817 break;
2818 }
2819 }
2820
2821 if (HasBetterConversion)
2822 return true;
2823
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002824 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
2825 // implemented, but they require template support.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002826
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002827 // C++ [over.match.best]p1b4:
2828 //
2829 // -- the context is an initialization by user-defined conversion
2830 // (see 8.5, 13.3.1.5) and the standard conversion sequence
2831 // from the return type of F1 to the destination type (i.e.,
2832 // the type of the entity being initialized) is a better
2833 // conversion sequence than the standard conversion sequence
2834 // from the return type of F2 to the destination type.
Douglas Gregor447b69e2008-11-19 03:25:36 +00002835 if (Cand1.Function && Cand2.Function &&
2836 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002837 isa<CXXConversionDecl>(Cand2.Function)) {
2838 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
2839 Cand2.FinalConversion)) {
2840 case ImplicitConversionSequence::Better:
2841 // Cand1 has a better conversion sequence.
2842 return true;
2843
2844 case ImplicitConversionSequence::Worse:
2845 // Cand1 can't be better than Cand2.
2846 return false;
2847
2848 case ImplicitConversionSequence::Indistinguishable:
2849 // Do nothing
2850 break;
2851 }
2852 }
2853
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002854 return false;
2855}
2856
2857/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
2858/// within an overload candidate set. If overloading is successful,
2859/// the result will be OR_Success and Best will be set to point to the
2860/// best viable function within the candidate set. Otherwise, one of
2861/// several kinds of errors will be returned; see
2862/// Sema::OverloadingResult.
2863Sema::OverloadingResult
2864Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
2865 OverloadCandidateSet::iterator& Best)
2866{
2867 // Find the best viable function.
2868 Best = CandidateSet.end();
2869 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2870 Cand != CandidateSet.end(); ++Cand) {
2871 if (Cand->Viable) {
2872 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
2873 Best = Cand;
2874 }
2875 }
2876
2877 // If we didn't find any viable functions, abort.
2878 if (Best == CandidateSet.end())
2879 return OR_No_Viable_Function;
2880
2881 // Make sure that this function is better than every other viable
2882 // function. If not, we have an ambiguity.
2883 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2884 Cand != CandidateSet.end(); ++Cand) {
2885 if (Cand->Viable &&
2886 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002887 !isBetterOverloadCandidate(*Best, *Cand)) {
2888 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002889 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002890 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002891 }
2892
2893 // Best is the best viable function.
2894 return OR_Success;
2895}
2896
2897/// PrintOverloadCandidates - When overload resolution fails, prints
2898/// diagnostic messages containing the candidates in the candidate
2899/// set. If OnlyViable is true, only viable candidates will be printed.
2900void
2901Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
2902 bool OnlyViable)
2903{
2904 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
2905 LastCand = CandidateSet.end();
2906 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002907 if (Cand->Viable || !OnlyViable) {
2908 if (Cand->Function) {
2909 // Normal function
2910 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002911 } else if (Cand->IsSurrogate) {
Douglas Gregor621b3932008-11-21 02:54:28 +00002912 // Desugar the type of the surrogate down to a function type,
2913 // retaining as many typedefs as possible while still showing
2914 // the function type (and, therefore, its parameter types).
2915 QualType FnType = Cand->Surrogate->getConversionType();
2916 bool isReference = false;
2917 bool isPointer = false;
2918 if (const ReferenceType *FnTypeRef = FnType->getAsReferenceType()) {
2919 FnType = FnTypeRef->getPointeeType();
2920 isReference = true;
2921 }
2922 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
2923 FnType = FnTypePtr->getPointeeType();
2924 isPointer = true;
2925 }
2926 // Desugar down to a function type.
2927 FnType = QualType(FnType->getAsFunctionType(), 0);
2928 // Reconstruct the pointer/reference as appropriate.
2929 if (isPointer) FnType = Context.getPointerType(FnType);
2930 if (isReference) FnType = Context.getReferenceType(FnType);
2931
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002932 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattnerd1625842008-11-24 06:25:27 +00002933 << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002934 } else {
2935 // FIXME: We need to get the identifier in here
2936 // FIXME: Do we want the error message to point at the
2937 // operator? (built-ins won't have a location)
2938 QualType FnType
2939 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
2940 Cand->BuiltinTypes.ParamTypes,
2941 Cand->Conversions.size(),
2942 false, 0);
2943
Chris Lattnerd1625842008-11-24 06:25:27 +00002944 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002945 }
2946 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002947 }
2948}
2949
Douglas Gregor904eed32008-11-10 20:40:00 +00002950/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
2951/// an overloaded function (C++ [over.over]), where @p From is an
2952/// expression with overloaded function type and @p ToType is the type
2953/// we're trying to resolve to. For example:
2954///
2955/// @code
2956/// int f(double);
2957/// int f(int);
2958///
2959/// int (*pfd)(double) = f; // selects f(double)
2960/// @endcode
2961///
2962/// This routine returns the resulting FunctionDecl if it could be
2963/// resolved, and NULL otherwise. When @p Complain is true, this
2964/// routine will emit diagnostics if there is an error.
2965FunctionDecl *
2966Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
2967 bool Complain) {
2968 QualType FunctionType = ToType;
2969 if (const PointerLikeType *ToTypePtr = ToType->getAsPointerLikeType())
2970 FunctionType = ToTypePtr->getPointeeType();
2971
2972 // We only look at pointers or references to functions.
2973 if (!FunctionType->isFunctionType())
2974 return 0;
2975
2976 // Find the actual overloaded function declaration.
2977 OverloadedFunctionDecl *Ovl = 0;
2978
2979 // C++ [over.over]p1:
2980 // [...] [Note: any redundant set of parentheses surrounding the
2981 // overloaded function name is ignored (5.1). ]
2982 Expr *OvlExpr = From->IgnoreParens();
2983
2984 // C++ [over.over]p1:
2985 // [...] The overloaded function name can be preceded by the &
2986 // operator.
2987 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
2988 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2989 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
2990 }
2991
2992 // Try to dig out the overloaded function.
2993 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
2994 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
2995
2996 // If there's no overloaded function declaration, we're done.
2997 if (!Ovl)
2998 return 0;
2999
3000 // Look through all of the overloaded functions, searching for one
3001 // whose type matches exactly.
3002 // FIXME: When templates or using declarations come along, we'll actually
3003 // have to deal with duplicates, partial ordering, etc. For now, we
3004 // can just do a simple search.
3005 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
3006 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
3007 Fun != Ovl->function_end(); ++Fun) {
3008 // C++ [over.over]p3:
3009 // Non-member functions and static member functions match
3010 // targets of type “pointer-to-function”or
3011 // “reference-to-function.”
3012 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun))
3013 if (!Method->isStatic())
3014 continue;
3015
3016 if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
3017 return *Fun;
3018 }
3019
3020 return 0;
3021}
3022
Douglas Gregorf6b89692008-11-26 05:54:23 +00003023/// ResolveOverloadedCallFn - Given the call expression that calls Fn
3024/// (which eventually refers to the set of overloaded functions in
3025/// Ovl) and the call arguments Args/NumArgs, attempt to resolve the
3026/// function call down to a specific function. If overload resolution
Douglas Gregor0a396682008-11-26 06:01:48 +00003027/// succeeds, returns the function declaration produced by overload
3028/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00003029/// arguments and Fn, and returns NULL.
Douglas Gregor0a396682008-11-26 06:01:48 +00003030FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, OverloadedFunctionDecl *Ovl,
3031 SourceLocation LParenLoc,
3032 Expr **Args, unsigned NumArgs,
3033 SourceLocation *CommaLocs,
3034 SourceLocation RParenLoc) {
Douglas Gregorf6b89692008-11-26 05:54:23 +00003035 OverloadCandidateSet CandidateSet;
3036 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet);
3037 OverloadCandidateSet::iterator Best;
3038 switch (BestViableFunction(CandidateSet, Best)) {
Douglas Gregor0a396682008-11-26 06:01:48 +00003039 case OR_Success:
3040 return Best->Function;
Douglas Gregorf6b89692008-11-26 05:54:23 +00003041
3042 case OR_No_Viable_Function:
3043 Diag(Fn->getSourceRange().getBegin(),
3044 diag::err_ovl_no_viable_function_in_call)
3045 << Ovl->getDeclName() << (unsigned)CandidateSet.size()
3046 << Fn->getSourceRange();
3047 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3048 break;
3049
3050 case OR_Ambiguous:
3051 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
3052 << Ovl->getDeclName() << Fn->getSourceRange();
3053 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3054 break;
3055 }
3056
3057 // Overload resolution failed. Destroy all of the subexpressions and
3058 // return NULL.
3059 Fn->Destroy(Context);
3060 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3061 Args[Arg]->Destroy(Context);
3062 return 0;
3063}
3064
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003065/// BuildCallToObjectOfClassType - Build a call to an object of class
3066/// type (C++ [over.call.object]), which can end up invoking an
3067/// overloaded function call operator (@c operator()) or performing a
3068/// user-defined conversion on the object argument.
3069Action::ExprResult
3070Sema::BuildCallToObjectOfClassType(Expr *Object, SourceLocation LParenLoc,
3071 Expr **Args, unsigned NumArgs,
3072 SourceLocation *CommaLocs,
3073 SourceLocation RParenLoc) {
3074 assert(Object->getType()->isRecordType() && "Requires object type argument");
3075 const RecordType *Record = Object->getType()->getAsRecordType();
3076
3077 // C++ [over.call.object]p1:
3078 // If the primary-expression E in the function call syntax
3079 // evaluates to a class object of type “cv T”, then the set of
3080 // candidate functions includes at least the function call
3081 // operators of T. The function call operators of T are obtained by
3082 // ordinary lookup of the name operator() in the context of
3083 // (E).operator().
3084 OverloadCandidateSet CandidateSet;
3085 IdentifierResolver::iterator I
3086 = IdResolver.begin(Context.DeclarationNames.getCXXOperatorName(OO_Call),
3087 cast<CXXRecordType>(Record)->getDecl(),
3088 /*LookInParentCtx=*/false);
3089 NamedDecl *MemberOps = (I == IdResolver.end())? 0 : *I;
3090 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps))
3091 AddMethodCandidate(Method, Object, Args, NumArgs, CandidateSet,
3092 /*SuppressUserConversions=*/false);
3093 else if (OverloadedFunctionDecl *Ovl
3094 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) {
3095 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
3096 FEnd = Ovl->function_end();
3097 F != FEnd; ++F) {
3098 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F))
3099 AddMethodCandidate(Method, Object, Args, NumArgs, CandidateSet,
3100 /*SuppressUserConversions=*/false);
3101 }
3102 }
3103
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003104 // C++ [over.call.object]p2:
3105 // In addition, for each conversion function declared in T of the
3106 // form
3107 //
3108 // operator conversion-type-id () cv-qualifier;
3109 //
3110 // where cv-qualifier is the same cv-qualification as, or a
3111 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00003112 // denotes the type "pointer to function of (P1,...,Pn) returning
3113 // R", or the type "reference to pointer to function of
3114 // (P1,...,Pn) returning R", or the type "reference to function
3115 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003116 // is also considered as a candidate function. Similarly,
3117 // surrogate call functions are added to the set of candidate
3118 // functions for each conversion function declared in an
3119 // accessible base class provided the function is not hidden
3120 // within T by another intervening declaration.
3121 //
3122 // FIXME: Look in base classes for more conversion operators!
3123 OverloadedFunctionDecl *Conversions
3124 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor621b3932008-11-21 02:54:28 +00003125 for (OverloadedFunctionDecl::function_iterator
3126 Func = Conversions->function_begin(),
3127 FuncEnd = Conversions->function_end();
3128 Func != FuncEnd; ++Func) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003129 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
3130
3131 // Strip the reference type (if any) and then the pointer type (if
3132 // any) to get down to what might be a function type.
3133 QualType ConvType = Conv->getConversionType().getNonReferenceType();
3134 if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
3135 ConvType = ConvPtrType->getPointeeType();
3136
3137 if (const FunctionTypeProto *Proto = ConvType->getAsFunctionTypeProto())
3138 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
3139 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003140
3141 // Perform overload resolution.
3142 OverloadCandidateSet::iterator Best;
3143 switch (BestViableFunction(CandidateSet, Best)) {
3144 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003145 // Overload resolution succeeded; we'll build the appropriate call
3146 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003147 break;
3148
3149 case OR_No_Viable_Function:
Sebastian Redle4c452c2008-11-22 13:44:36 +00003150 Diag(Object->getSourceRange().getBegin(),
3151 diag::err_ovl_no_viable_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00003152 << Object->getType() << (unsigned)CandidateSet.size()
Sebastian Redle4c452c2008-11-22 13:44:36 +00003153 << Object->getSourceRange();
3154 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003155 break;
3156
3157 case OR_Ambiguous:
3158 Diag(Object->getSourceRange().getBegin(),
3159 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00003160 << Object->getType() << Object->getSourceRange();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003161 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3162 break;
3163 }
3164
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003165 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003166 // We had an error; delete all of the subexpressions and return
3167 // the error.
3168 delete Object;
3169 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3170 delete Args[ArgIdx];
3171 return true;
3172 }
3173
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003174 if (Best->Function == 0) {
3175 // Since there is no function declaration, this is one of the
3176 // surrogate candidates. Dig out the conversion function.
3177 CXXConversionDecl *Conv
3178 = cast<CXXConversionDecl>(
3179 Best->Conversions[0].UserDefined.ConversionFunction);
3180
3181 // We selected one of the surrogate functions that converts the
3182 // object parameter to a function pointer. Perform the conversion
3183 // on the object argument, then let ActOnCallExpr finish the job.
3184 // FIXME: Represent the user-defined conversion in the AST!
3185 ImpCastExprToType(Object,
3186 Conv->getConversionType().getNonReferenceType(),
3187 Conv->getConversionType()->isReferenceType());
3188 return ActOnCallExpr((ExprTy*)Object, LParenLoc, (ExprTy**)Args, NumArgs,
3189 CommaLocs, RParenLoc);
3190 }
3191
3192 // We found an overloaded operator(). Build a CXXOperatorCallExpr
3193 // that calls this method, using Object for the implicit object
3194 // parameter and passing along the remaining arguments.
3195 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003196 const FunctionTypeProto *Proto = Method->getType()->getAsFunctionTypeProto();
3197
3198 unsigned NumArgsInProto = Proto->getNumArgs();
3199 unsigned NumArgsToCheck = NumArgs;
3200
3201 // Build the full argument list for the method call (the
3202 // implicit object parameter is placed at the beginning of the
3203 // list).
3204 Expr **MethodArgs;
3205 if (NumArgs < NumArgsInProto) {
3206 NumArgsToCheck = NumArgsInProto;
3207 MethodArgs = new Expr*[NumArgsInProto + 1];
3208 } else {
3209 MethodArgs = new Expr*[NumArgs + 1];
3210 }
3211 MethodArgs[0] = Object;
3212 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3213 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
3214
3215 Expr *NewFn = new DeclRefExpr(Method, Method->getType(),
3216 SourceLocation());
3217 UsualUnaryConversions(NewFn);
3218
3219 // Once we've built TheCall, all of the expressions are properly
3220 // owned.
3221 QualType ResultTy = Method->getResultType().getNonReferenceType();
3222 llvm::OwningPtr<CXXOperatorCallExpr>
3223 TheCall(new CXXOperatorCallExpr(NewFn, MethodArgs, NumArgs + 1,
3224 ResultTy, RParenLoc));
3225 delete [] MethodArgs;
3226
3227 // Initialize the implicit object parameter.
3228 if (!PerformObjectArgumentInitialization(Object, Method))
3229 return true;
3230 TheCall->setArg(0, Object);
3231
3232 // Check the argument types.
3233 for (unsigned i = 0; i != NumArgsToCheck; i++) {
3234 QualType ProtoArgType = Proto->getArgType(i);
3235
3236 Expr *Arg;
3237 if (i < NumArgs)
3238 Arg = Args[i];
3239 else
3240 Arg = new CXXDefaultArgExpr(Method->getParamDecl(i));
3241 QualType ArgType = Arg->getType();
3242
3243 // Pass the argument.
3244 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3245 return true;
3246
3247 TheCall->setArg(i + 1, Arg);
3248 }
3249
3250 // If this is a variadic call, handle args passed through "...".
3251 if (Proto->isVariadic()) {
3252 // Promote the arguments (C99 6.5.2.2p7).
3253 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3254 Expr *Arg = Args[i];
3255 DefaultArgumentPromotion(Arg);
3256 TheCall->setArg(i + 1, Arg);
3257 }
3258 }
3259
3260 return CheckFunctionCall(Method, TheCall.take());
3261}
3262
Douglas Gregor8ba10742008-11-20 16:27:02 +00003263/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
3264/// (if one exists), where @c Base is an expression of class type and
3265/// @c Member is the name of the member we're trying to find.
3266Action::ExprResult
3267Sema::BuildOverloadedArrowExpr(Expr *Base, SourceLocation OpLoc,
3268 SourceLocation MemberLoc,
3269 IdentifierInfo &Member) {
3270 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
3271
3272 // C++ [over.ref]p1:
3273 //
3274 // [...] An expression x->m is interpreted as (x.operator->())->m
3275 // for a class object x of type T if T::operator->() exists and if
3276 // the operator is selected as the best match function by the
3277 // overload resolution mechanism (13.3).
3278 // FIXME: look in base classes.
3279 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
3280 OverloadCandidateSet CandidateSet;
3281 const RecordType *BaseRecord = Base->getType()->getAsRecordType();
3282 IdentifierResolver::iterator I
3283 = IdResolver.begin(OpName, cast<CXXRecordType>(BaseRecord)->getDecl(),
3284 /*LookInParentCtx=*/false);
3285 NamedDecl *MemberOps = (I == IdResolver.end())? 0 : *I;
3286 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps))
3287 AddMethodCandidate(Method, Base, 0, 0, CandidateSet,
3288 /*SuppressUserConversions=*/false);
3289 else if (OverloadedFunctionDecl *Ovl
3290 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) {
3291 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
3292 FEnd = Ovl->function_end();
3293 F != FEnd; ++F) {
3294 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F))
3295 AddMethodCandidate(Method, Base, 0, 0, CandidateSet,
3296 /*SuppressUserConversions=*/false);
3297 }
3298 }
3299
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003300 llvm::OwningPtr<Expr> BasePtr(Base);
3301
Douglas Gregor8ba10742008-11-20 16:27:02 +00003302 // Perform overload resolution.
3303 OverloadCandidateSet::iterator Best;
3304 switch (BestViableFunction(CandidateSet, Best)) {
3305 case OR_Success:
3306 // Overload resolution succeeded; we'll build the call below.
3307 break;
3308
3309 case OR_No_Viable_Function:
3310 if (CandidateSet.empty())
3311 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattnerd1625842008-11-24 06:25:27 +00003312 << BasePtr->getType() << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003313 else
3314 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Sebastian Redle4c452c2008-11-22 13:44:36 +00003315 << "operator->" << (unsigned)CandidateSet.size()
3316 << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003317 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003318 return true;
3319
3320 case OR_Ambiguous:
3321 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Chris Lattnerd1625842008-11-24 06:25:27 +00003322 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003323 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003324 return true;
3325 }
3326
3327 // Convert the object parameter.
3328 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003329 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregor8ba10742008-11-20 16:27:02 +00003330 return true;
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003331
3332 // No concerns about early exits now.
3333 BasePtr.take();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003334
3335 // Build the operator call.
3336 Expr *FnExpr = new DeclRefExpr(Method, Method->getType(), SourceLocation());
3337 UsualUnaryConversions(FnExpr);
3338 Base = new CXXOperatorCallExpr(FnExpr, &Base, 1,
3339 Method->getResultType().getNonReferenceType(),
3340 OpLoc);
3341 return ActOnMemberReferenceExpr(Base, OpLoc, tok::arrow, MemberLoc, Member);
3342}
3343
Douglas Gregor904eed32008-11-10 20:40:00 +00003344/// FixOverloadedFunctionReference - E is an expression that refers to
3345/// a C++ overloaded function (possibly with some parentheses and
3346/// perhaps a '&' around it). We have resolved the overloaded function
3347/// to the function declaration Fn, so patch up the expression E to
3348/// refer (possibly indirectly) to Fn.
3349void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
3350 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
3351 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
3352 E->setType(PE->getSubExpr()->getType());
3353 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
3354 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
3355 "Can only take the address of an overloaded function");
3356 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
3357 E->setType(Context.getPointerType(E->getType()));
3358 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
3359 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
3360 "Expected overloaded function");
3361 DR->setDecl(Fn);
3362 E->setType(Fn->getType());
3363 } else {
3364 assert(false && "Invalid reference to overloaded function");
3365 }
3366}
3367
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003368} // end namespace clang