blob: 3321ef19b25467577ebfd97417e803cd1db0d76f [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
712/// IsPointerConversion - Determines whether the conversion of the
713/// expression From, which has the (possibly adjusted) type FromType,
714/// can be converted to the type ToType via a pointer conversion (C++
715/// 4.10). If so, returns true and places the converted type (that
716/// might differ from ToType in its cv-qualifiers at some level) into
717/// ConvertedType.
718bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
719 QualType& ConvertedType)
720{
721 const PointerType* ToTypePtr = ToType->getAsPointerType();
722 if (!ToTypePtr)
723 return false;
724
725 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
726 if (From->isNullPointerConstant(Context)) {
727 ConvertedType = ToType;
728 return true;
729 }
Sebastian Redl07779722008-10-31 14:43:28 +0000730
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000731 // An rvalue of type "pointer to cv T," where T is an object type,
732 // can be converted to an rvalue of type "pointer to cv void" (C++
733 // 4.10p2).
734 if (FromType->isPointerType() &&
735 FromType->getAsPointerType()->getPointeeType()->isObjectType() &&
736 ToTypePtr->getPointeeType()->isVoidType()) {
737 // We need to produce a pointer to cv void, where cv is the same
738 // set of cv-qualifiers as we had on the incoming pointee type.
739 QualType toPointee = ToTypePtr->getPointeeType();
740 unsigned Quals = Context.getCanonicalType(FromType)->getAsPointerType()
741 ->getPointeeType().getCVRQualifiers();
742
743 if (Context.getCanonicalType(ToTypePtr->getPointeeType()).getCVRQualifiers()
744 == Quals) {
745 // ToType is exactly the type we want. Use it.
746 ConvertedType = ToType;
747 } else {
748 // Build a new type with the right qualifiers.
749 ConvertedType
750 = Context.getPointerType(Context.VoidTy.getQualifiedType(Quals));
751 }
752 return true;
753 }
754
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000755 // C++ [conv.ptr]p3:
756 //
757 // An rvalue of type "pointer to cv D," where D is a class type,
758 // can be converted to an rvalue of type "pointer to cv B," where
759 // B is a base class (clause 10) of D. If B is an inaccessible
760 // (clause 11) or ambiguous (10.2) base class of D, a program that
761 // necessitates this conversion is ill-formed. The result of the
762 // conversion is a pointer to the base class sub-object of the
763 // derived class object. The null pointer value is converted to
764 // the null pointer value of the destination type.
765 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000766 // Note that we do not check for ambiguity or inaccessibility
767 // here. That is handled by CheckPointerConversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000768 if (const PointerType *FromPtrType = FromType->getAsPointerType())
769 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
770 if (FromPtrType->getPointeeType()->isRecordType() &&
771 ToPtrType->getPointeeType()->isRecordType() &&
772 IsDerivedFrom(FromPtrType->getPointeeType(),
773 ToPtrType->getPointeeType())) {
774 // The conversion is okay. Now, we need to produce the type
775 // that results from this conversion, which will have the same
776 // qualifiers as the incoming type.
777 QualType CanonFromPointee
778 = Context.getCanonicalType(FromPtrType->getPointeeType());
779 QualType ToPointee = ToPtrType->getPointeeType();
780 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
781 unsigned Quals = CanonFromPointee.getCVRQualifiers();
782
783 if (CanonToPointee.getCVRQualifiers() == Quals) {
784 // ToType is exactly the type we want. Use it.
785 ConvertedType = ToType;
786 } else {
787 // Build a new type with the right qualifiers.
788 ConvertedType
789 = Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
790 }
791 return true;
792 }
793 }
794
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000795 return false;
796}
797
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000798/// CheckPointerConversion - Check the pointer conversion from the
799/// expression From to the type ToType. This routine checks for
800/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
801/// conversions for which IsPointerConversion has already returned
802/// true. It returns true and produces a diagnostic if there was an
803/// error, or returns false otherwise.
804bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
805 QualType FromType = From->getType();
806
807 if (const PointerType *FromPtrType = FromType->getAsPointerType())
808 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
Sebastian Redl07779722008-10-31 14:43:28 +0000809 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
810 /*DetectVirtual=*/false);
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000811 QualType FromPointeeType = FromPtrType->getPointeeType(),
812 ToPointeeType = ToPtrType->getPointeeType();
813 if (FromPointeeType->isRecordType() &&
814 ToPointeeType->isRecordType()) {
815 // We must have a derived-to-base conversion. Check an
816 // ambiguous or inaccessible conversion.
Douglas Gregor0575d4a2008-10-24 16:17:19 +0000817 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
818 From->getExprLoc(),
819 From->getSourceRange());
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000820 }
821 }
822
823 return false;
824}
825
Douglas Gregor98cd5992008-10-21 23:43:52 +0000826/// IsQualificationConversion - Determines whether the conversion from
827/// an rvalue of type FromType to ToType is a qualification conversion
828/// (C++ 4.4).
829bool
830Sema::IsQualificationConversion(QualType FromType, QualType ToType)
831{
832 FromType = Context.getCanonicalType(FromType);
833 ToType = Context.getCanonicalType(ToType);
834
835 // If FromType and ToType are the same type, this is not a
836 // qualification conversion.
837 if (FromType == ToType)
838 return false;
839
840 // (C++ 4.4p4):
841 // A conversion can add cv-qualifiers at levels other than the first
842 // in multi-level pointers, subject to the following rules: [...]
843 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +0000844 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +0000845 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +0000846 // Within each iteration of the loop, we check the qualifiers to
847 // determine if this still looks like a qualification
848 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000849 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +0000850 // until there are no more pointers or pointers-to-members left to
851 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +0000852 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +0000853
854 // -- for every j > 0, if const is in cv 1,j then const is in cv
855 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +0000856 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +0000857 return false;
Douglas Gregor57373262008-10-22 14:17:15 +0000858
Douglas Gregor98cd5992008-10-21 23:43:52 +0000859 // -- if the cv 1,j and cv 2,j are different, then const is in
860 // every cv for 0 < k < j.
861 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +0000862 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +0000863 return false;
Douglas Gregor57373262008-10-22 14:17:15 +0000864
Douglas Gregor98cd5992008-10-21 23:43:52 +0000865 // Keep track of whether all prior cv-qualifiers in the "to" type
866 // include const.
867 PreviousToQualsIncludeConst
868 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +0000869 }
Douglas Gregor98cd5992008-10-21 23:43:52 +0000870
871 // We are left with FromType and ToType being the pointee types
872 // after unwrapping the original FromType and ToType the same number
873 // of types. If we unwrapped any pointers, and if FromType and
874 // ToType have the same unqualified type (since we checked
875 // qualifiers above), then this is a qualification conversion.
876 return UnwrappedAnyPointer &&
877 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
878}
879
Douglas Gregor60d62c22008-10-31 16:23:19 +0000880/// IsUserDefinedConversion - Determines whether there is a
881/// user-defined conversion sequence (C++ [over.ics.user]) that
882/// converts expression From to the type ToType. If such a conversion
883/// exists, User will contain the user-defined conversion sequence
884/// that performs such a conversion and this routine will return
885/// true. Otherwise, this routine returns false and User is
886/// unspecified.
887bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
888 UserDefinedConversionSequence& User)
889{
890 OverloadCandidateSet CandidateSet;
891 if (const CXXRecordType *ToRecordType
892 = dyn_cast_or_null<CXXRecordType>(ToType->getAsRecordType())) {
893 // C++ [over.match.ctor]p1:
894 // When objects of class type are direct-initialized (8.5), or
895 // copy-initialized from an expression of the same or a
896 // derived class type (8.5), overload resolution selects the
897 // constructor. [...] For copy-initialization, the candidate
898 // functions are all the converting constructors (12.3.1) of
899 // that class. The argument list is the expression-list within
900 // the parentheses of the initializer.
901 CXXRecordDecl *ToRecordDecl = ToRecordType->getDecl();
902 const OverloadedFunctionDecl *Constructors = ToRecordDecl->getConstructors();
903 for (OverloadedFunctionDecl::function_const_iterator func
904 = Constructors->function_begin();
905 func != Constructors->function_end(); ++func) {
906 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*func);
907 if (Constructor->isConvertingConstructor())
Douglas Gregor225c41e2008-11-03 19:09:14 +0000908 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
909 /*SuppressUserConversions=*/true);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000910 }
911 }
912
Douglas Gregorf1991ea2008-11-07 22:36:19 +0000913 if (const CXXRecordType *FromRecordType
914 = dyn_cast_or_null<CXXRecordType>(From->getType()->getAsRecordType())) {
915 // Add all of the conversion functions as candidates.
916 // FIXME: Look for conversions in base classes!
917 CXXRecordDecl *FromRecordDecl = FromRecordType->getDecl();
918 OverloadedFunctionDecl *Conversions
919 = FromRecordDecl->getConversionFunctions();
920 for (OverloadedFunctionDecl::function_iterator Func
921 = Conversions->function_begin();
922 Func != Conversions->function_end(); ++Func) {
923 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
924 AddConversionCandidate(Conv, From, ToType, CandidateSet);
925 }
926 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000927
928 OverloadCandidateSet::iterator Best;
929 switch (BestViableFunction(CandidateSet, Best)) {
930 case OR_Success:
931 // Record the standard conversion we used and the conversion function.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000932 if (CXXConstructorDecl *Constructor
933 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
934 // C++ [over.ics.user]p1:
935 // If the user-defined conversion is specified by a
936 // constructor (12.3.1), the initial standard conversion
937 // sequence converts the source type to the type required by
938 // the argument of the constructor.
939 //
940 // FIXME: What about ellipsis conversions?
941 QualType ThisType = Constructor->getThisType(Context);
942 User.Before = Best->Conversions[0].Standard;
943 User.ConversionFunction = Constructor;
944 User.After.setAsIdentityConversion();
945 User.After.FromTypePtr
946 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
947 User.After.ToTypePtr = ToType.getAsOpaquePtr();
948 return true;
Douglas Gregorf1991ea2008-11-07 22:36:19 +0000949 } else if (CXXConversionDecl *Conversion
950 = dyn_cast<CXXConversionDecl>(Best->Function)) {
951 // C++ [over.ics.user]p1:
952 //
953 // [...] If the user-defined conversion is specified by a
954 // conversion function (12.3.2), the initial standard
955 // conversion sequence converts the source type to the
956 // implicit object parameter of the conversion function.
957 User.Before = Best->Conversions[0].Standard;
958 User.ConversionFunction = Conversion;
959
960 // C++ [over.ics.user]p2:
961 // The second standard conversion sequence converts the
962 // result of the user-defined conversion to the target type
963 // for the sequence. Since an implicit conversion sequence
964 // is an initialization, the special rules for
965 // initialization by user-defined conversion apply when
966 // selecting the best user-defined conversion for a
967 // user-defined conversion sequence (see 13.3.3 and
968 // 13.3.3.1).
969 User.After = Best->FinalConversion;
970 return true;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000971 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +0000972 assert(false && "Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000973 return false;
974 }
975
976 case OR_No_Viable_Function:
977 // No conversion here! We're done.
978 return false;
979
980 case OR_Ambiguous:
981 // FIXME: See C++ [over.best.ics]p10 for the handling of
982 // ambiguous conversion sequences.
983 return false;
984 }
985
986 return false;
987}
988
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000989/// CompareImplicitConversionSequences - Compare two implicit
990/// conversion sequences to determine whether one is better than the
991/// other or if they are indistinguishable (C++ 13.3.3.2).
992ImplicitConversionSequence::CompareKind
993Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
994 const ImplicitConversionSequence& ICS2)
995{
996 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
997 // conversion sequences (as defined in 13.3.3.1)
998 // -- a standard conversion sequence (13.3.3.1.1) is a better
999 // conversion sequence than a user-defined conversion sequence or
1000 // an ellipsis conversion sequence, and
1001 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1002 // conversion sequence than an ellipsis conversion sequence
1003 // (13.3.3.1.3).
1004 //
1005 if (ICS1.ConversionKind < ICS2.ConversionKind)
1006 return ImplicitConversionSequence::Better;
1007 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1008 return ImplicitConversionSequence::Worse;
1009
1010 // Two implicit conversion sequences of the same form are
1011 // indistinguishable conversion sequences unless one of the
1012 // following rules apply: (C++ 13.3.3.2p3):
1013 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1014 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1015 else if (ICS1.ConversionKind ==
1016 ImplicitConversionSequence::UserDefinedConversion) {
1017 // User-defined conversion sequence U1 is a better conversion
1018 // sequence than another user-defined conversion sequence U2 if
1019 // they contain the same user-defined conversion function or
1020 // constructor and if the second standard conversion sequence of
1021 // U1 is better than the second standard conversion sequence of
1022 // U2 (C++ 13.3.3.2p3).
1023 if (ICS1.UserDefined.ConversionFunction ==
1024 ICS2.UserDefined.ConversionFunction)
1025 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1026 ICS2.UserDefined.After);
1027 }
1028
1029 return ImplicitConversionSequence::Indistinguishable;
1030}
1031
1032/// CompareStandardConversionSequences - Compare two standard
1033/// conversion sequences to determine whether one is better than the
1034/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1035ImplicitConversionSequence::CompareKind
1036Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1037 const StandardConversionSequence& SCS2)
1038{
1039 // Standard conversion sequence S1 is a better conversion sequence
1040 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1041
1042 // -- S1 is a proper subsequence of S2 (comparing the conversion
1043 // sequences in the canonical form defined by 13.3.3.1.1,
1044 // excluding any Lvalue Transformation; the identity conversion
1045 // sequence is considered to be a subsequence of any
1046 // non-identity conversion sequence) or, if not that,
1047 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1048 // Neither is a proper subsequence of the other. Do nothing.
1049 ;
1050 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1051 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1052 (SCS1.Second == ICK_Identity &&
1053 SCS1.Third == ICK_Identity))
1054 // SCS1 is a proper subsequence of SCS2.
1055 return ImplicitConversionSequence::Better;
1056 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1057 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1058 (SCS2.Second == ICK_Identity &&
1059 SCS2.Third == ICK_Identity))
1060 // SCS2 is a proper subsequence of SCS1.
1061 return ImplicitConversionSequence::Worse;
1062
1063 // -- the rank of S1 is better than the rank of S2 (by the rules
1064 // defined below), or, if not that,
1065 ImplicitConversionRank Rank1 = SCS1.getRank();
1066 ImplicitConversionRank Rank2 = SCS2.getRank();
1067 if (Rank1 < Rank2)
1068 return ImplicitConversionSequence::Better;
1069 else if (Rank2 < Rank1)
1070 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001071
Douglas Gregor57373262008-10-22 14:17:15 +00001072 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1073 // are indistinguishable unless one of the following rules
1074 // applies:
1075
1076 // A conversion that is not a conversion of a pointer, or
1077 // pointer to member, to bool is better than another conversion
1078 // that is such a conversion.
1079 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1080 return SCS2.isPointerConversionToBool()
1081 ? ImplicitConversionSequence::Better
1082 : ImplicitConversionSequence::Worse;
1083
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001084 // C++ [over.ics.rank]p4b2:
1085 //
1086 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001087 // conversion of B* to A* is better than conversion of B* to
1088 // void*, and conversion of A* to void* is better than conversion
1089 // of B* to void*.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001090 bool SCS1ConvertsToVoid
1091 = SCS1.isPointerConversionToVoidPointer(Context);
1092 bool SCS2ConvertsToVoid
1093 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001094 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1095 // Exactly one of the conversion sequences is a conversion to
1096 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001097 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1098 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001099 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1100 // Neither conversion sequence converts to a void pointer; compare
1101 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001102 if (ImplicitConversionSequence::CompareKind DerivedCK
1103 = CompareDerivedToBaseConversions(SCS1, SCS2))
1104 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001105 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1106 // Both conversion sequences are conversions to void
1107 // pointers. Compare the source types to determine if there's an
1108 // inheritance relationship in their sources.
1109 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1110 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1111
1112 // Adjust the types we're converting from via the array-to-pointer
1113 // conversion, if we need to.
1114 if (SCS1.First == ICK_Array_To_Pointer)
1115 FromType1 = Context.getArrayDecayedType(FromType1);
1116 if (SCS2.First == ICK_Array_To_Pointer)
1117 FromType2 = Context.getArrayDecayedType(FromType2);
1118
1119 QualType FromPointee1
1120 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1121 QualType FromPointee2
1122 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1123
1124 if (IsDerivedFrom(FromPointee2, FromPointee1))
1125 return ImplicitConversionSequence::Better;
1126 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1127 return ImplicitConversionSequence::Worse;
1128 }
Douglas Gregor57373262008-10-22 14:17:15 +00001129
1130 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1131 // bullet 3).
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001132 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001133 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001134 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001135
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001136 // C++ [over.ics.rank]p3b4:
1137 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1138 // which the references refer are the same type except for
1139 // top-level cv-qualifiers, and the type to which the reference
1140 // initialized by S2 refers is more cv-qualified than the type
1141 // to which the reference initialized by S1 refers.
1142 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1143 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1144 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1145 T1 = Context.getCanonicalType(T1);
1146 T2 = Context.getCanonicalType(T2);
1147 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1148 if (T2.isMoreQualifiedThan(T1))
1149 return ImplicitConversionSequence::Better;
1150 else if (T1.isMoreQualifiedThan(T2))
1151 return ImplicitConversionSequence::Worse;
1152 }
1153 }
Douglas Gregor57373262008-10-22 14:17:15 +00001154
1155 return ImplicitConversionSequence::Indistinguishable;
1156}
1157
1158/// CompareQualificationConversions - Compares two standard conversion
1159/// sequences to determine whether they can be ranked based on their
1160/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1161ImplicitConversionSequence::CompareKind
1162Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1163 const StandardConversionSequence& SCS2)
1164{
Douglas Gregorba7e2102008-10-22 15:04:37 +00001165 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001166 // -- S1 and S2 differ only in their qualification conversion and
1167 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1168 // cv-qualification signature of type T1 is a proper subset of
1169 // the cv-qualification signature of type T2, and S1 is not the
1170 // deprecated string literal array-to-pointer conversion (4.2).
1171 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1172 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1173 return ImplicitConversionSequence::Indistinguishable;
1174
1175 // FIXME: the example in the standard doesn't use a qualification
1176 // conversion (!)
1177 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1178 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1179 T1 = Context.getCanonicalType(T1);
1180 T2 = Context.getCanonicalType(T2);
1181
1182 // If the types are the same, we won't learn anything by unwrapped
1183 // them.
1184 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1185 return ImplicitConversionSequence::Indistinguishable;
1186
1187 ImplicitConversionSequence::CompareKind Result
1188 = ImplicitConversionSequence::Indistinguishable;
1189 while (UnwrapSimilarPointerTypes(T1, T2)) {
1190 // Within each iteration of the loop, we check the qualifiers to
1191 // determine if this still looks like a qualification
1192 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001193 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001194 // until there are no more pointers or pointers-to-members left
1195 // to unwrap. This essentially mimics what
1196 // IsQualificationConversion does, but here we're checking for a
1197 // strict subset of qualifiers.
1198 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1199 // The qualifiers are the same, so this doesn't tell us anything
1200 // about how the sequences rank.
1201 ;
1202 else if (T2.isMoreQualifiedThan(T1)) {
1203 // T1 has fewer qualifiers, so it could be the better sequence.
1204 if (Result == ImplicitConversionSequence::Worse)
1205 // Neither has qualifiers that are a subset of the other's
1206 // qualifiers.
1207 return ImplicitConversionSequence::Indistinguishable;
1208
1209 Result = ImplicitConversionSequence::Better;
1210 } else if (T1.isMoreQualifiedThan(T2)) {
1211 // T2 has fewer qualifiers, so it could be the better sequence.
1212 if (Result == ImplicitConversionSequence::Better)
1213 // Neither has qualifiers that are a subset of the other's
1214 // qualifiers.
1215 return ImplicitConversionSequence::Indistinguishable;
1216
1217 Result = ImplicitConversionSequence::Worse;
1218 } else {
1219 // Qualifiers are disjoint.
1220 return ImplicitConversionSequence::Indistinguishable;
1221 }
1222
1223 // If the types after this point are equivalent, we're done.
1224 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1225 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001226 }
1227
Douglas Gregor57373262008-10-22 14:17:15 +00001228 // Check that the winning standard conversion sequence isn't using
1229 // the deprecated string literal array to pointer conversion.
1230 switch (Result) {
1231 case ImplicitConversionSequence::Better:
1232 if (SCS1.Deprecated)
1233 Result = ImplicitConversionSequence::Indistinguishable;
1234 break;
1235
1236 case ImplicitConversionSequence::Indistinguishable:
1237 break;
1238
1239 case ImplicitConversionSequence::Worse:
1240 if (SCS2.Deprecated)
1241 Result = ImplicitConversionSequence::Indistinguishable;
1242 break;
1243 }
1244
1245 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001246}
1247
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001248/// CompareDerivedToBaseConversions - Compares two standard conversion
1249/// sequences to determine whether they can be ranked based on their
1250/// various kinds of derived-to-base conversions (C++ [over.ics.rank]p4b3).
1251ImplicitConversionSequence::CompareKind
1252Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1253 const StandardConversionSequence& SCS2) {
1254 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1255 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1256 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1257 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1258
1259 // Adjust the types we're converting from via the array-to-pointer
1260 // conversion, if we need to.
1261 if (SCS1.First == ICK_Array_To_Pointer)
1262 FromType1 = Context.getArrayDecayedType(FromType1);
1263 if (SCS2.First == ICK_Array_To_Pointer)
1264 FromType2 = Context.getArrayDecayedType(FromType2);
1265
1266 // Canonicalize all of the types.
1267 FromType1 = Context.getCanonicalType(FromType1);
1268 ToType1 = Context.getCanonicalType(ToType1);
1269 FromType2 = Context.getCanonicalType(FromType2);
1270 ToType2 = Context.getCanonicalType(ToType2);
1271
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001272 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001273 //
1274 // If class B is derived directly or indirectly from class A and
1275 // class C is derived directly or indirectly from B,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001276
1277 // Compare based on pointer conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001278 if (SCS1.Second == ICK_Pointer_Conversion &&
1279 SCS2.Second == ICK_Pointer_Conversion) {
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001280 QualType FromPointee1
1281 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1282 QualType ToPointee1
1283 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1284 QualType FromPointee2
1285 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1286 QualType ToPointee2
1287 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001288 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001289 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1290 if (IsDerivedFrom(ToPointee1, ToPointee2))
1291 return ImplicitConversionSequence::Better;
1292 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1293 return ImplicitConversionSequence::Worse;
1294 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001295
1296 // -- conversion of B* to A* is better than conversion of C* to A*,
1297 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1298 if (IsDerivedFrom(FromPointee2, FromPointee1))
1299 return ImplicitConversionSequence::Better;
1300 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1301 return ImplicitConversionSequence::Worse;
1302 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001303 }
1304
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001305 // Compare based on reference bindings.
1306 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1307 SCS1.Second == ICK_Derived_To_Base) {
1308 // -- binding of an expression of type C to a reference of type
1309 // B& is better than binding an expression of type C to a
1310 // reference of type A&,
1311 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1312 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1313 if (IsDerivedFrom(ToType1, ToType2))
1314 return ImplicitConversionSequence::Better;
1315 else if (IsDerivedFrom(ToType2, ToType1))
1316 return ImplicitConversionSequence::Worse;
1317 }
1318
Douglas Gregor225c41e2008-11-03 19:09:14 +00001319 // -- binding of an expression of type B to a reference of type
1320 // A& is better than binding an expression of type C to a
1321 // reference of type A&,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001322 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1323 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1324 if (IsDerivedFrom(FromType2, FromType1))
1325 return ImplicitConversionSequence::Better;
1326 else if (IsDerivedFrom(FromType1, FromType2))
1327 return ImplicitConversionSequence::Worse;
1328 }
1329 }
1330
1331
1332 // FIXME: conversion of A::* to B::* is better than conversion of
1333 // A::* to C::*,
1334
1335 // FIXME: conversion of B::* to C::* is better than conversion of
1336 // A::* to C::*, and
1337
Douglas Gregor225c41e2008-11-03 19:09:14 +00001338 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1339 SCS1.Second == ICK_Derived_To_Base) {
1340 // -- conversion of C to B is better than conversion of C to A,
1341 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1342 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1343 if (IsDerivedFrom(ToType1, ToType2))
1344 return ImplicitConversionSequence::Better;
1345 else if (IsDerivedFrom(ToType2, ToType1))
1346 return ImplicitConversionSequence::Worse;
1347 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001348
Douglas Gregor225c41e2008-11-03 19:09:14 +00001349 // -- conversion of B to A is better than conversion of C to A.
1350 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1351 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1352 if (IsDerivedFrom(FromType2, FromType1))
1353 return ImplicitConversionSequence::Better;
1354 else if (IsDerivedFrom(FromType1, FromType2))
1355 return ImplicitConversionSequence::Worse;
1356 }
1357 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001358
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001359 return ImplicitConversionSequence::Indistinguishable;
1360}
1361
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001362/// TryCopyInitialization - Try to copy-initialize a value of type
1363/// ToType from the expression From. Return the implicit conversion
1364/// sequence required to pass this argument, which may be a bad
1365/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00001366/// a parameter of this type). If @p SuppressUserConversions, then we
1367/// do not permit any user-defined conversion sequences.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001368ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +00001369Sema::TryCopyInitialization(Expr *From, QualType ToType,
1370 bool SuppressUserConversions) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001371 if (!getLangOptions().CPlusPlus) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001372 // In C, copy initialization is the same as performing an assignment.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001373 AssignConvertType ConvTy =
1374 CheckSingleAssignmentConstraints(ToType, From);
1375 ImplicitConversionSequence ICS;
1376 if (getLangOptions().NoExtensions? ConvTy != Compatible
1377 : ConvTy == Incompatible)
1378 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1379 else
1380 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1381 return ICS;
1382 } else if (ToType->isReferenceType()) {
1383 ImplicitConversionSequence ICS;
Douglas Gregor225c41e2008-11-03 19:09:14 +00001384 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001385 return ICS;
1386 } else {
Douglas Gregor225c41e2008-11-03 19:09:14 +00001387 return TryImplicitConversion(From, ToType, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001388 }
1389}
1390
1391/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1392/// type ToType. Returns true (and emits a diagnostic) if there was
1393/// an error, returns false if the initialization succeeded.
1394bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1395 const char* Flavor) {
1396 if (!getLangOptions().CPlusPlus) {
1397 // In C, argument passing is the same as performing an assignment.
1398 QualType FromType = From->getType();
1399 AssignConvertType ConvTy =
1400 CheckSingleAssignmentConstraints(ToType, From);
1401
1402 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1403 FromType, From, Flavor);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001404 }
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001405
1406 if (ToType->isReferenceType())
1407 return CheckReferenceInit(From, ToType);
1408
1409 if (!PerformImplicitConversion(From, ToType))
1410 return false;
1411
1412 return Diag(From->getSourceRange().getBegin(),
1413 diag::err_typecheck_convert_incompatible)
1414 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001415}
1416
Douglas Gregor96176b32008-11-18 23:14:02 +00001417/// TryObjectArgumentInitialization - Try to initialize the object
1418/// parameter of the given member function (@c Method) from the
1419/// expression @p From.
1420ImplicitConversionSequence
1421Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1422 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1423 unsigned MethodQuals = Method->getTypeQualifiers();
1424 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1425
1426 // Set up the conversion sequence as a "bad" conversion, to allow us
1427 // to exit early.
1428 ImplicitConversionSequence ICS;
1429 ICS.Standard.setAsIdentityConversion();
1430 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1431
1432 // We need to have an object of class type.
1433 QualType FromType = From->getType();
1434 if (!FromType->isRecordType())
1435 return ICS;
1436
1437 // The implicit object parmeter is has the type "reference to cv X",
1438 // where X is the class of which the function is a member
1439 // (C++ [over.match.funcs]p4). However, when finding an implicit
1440 // conversion sequence for the argument, we are not allowed to
1441 // create temporaries or perform user-defined conversions
1442 // (C++ [over.match.funcs]p5). We perform a simplified version of
1443 // reference binding here, that allows class rvalues to bind to
1444 // non-constant references.
1445
1446 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1447 // with the implicit object parameter (C++ [over.match.funcs]p5).
1448 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1449 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1450 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1451 return ICS;
1452
1453 // Check that we have either the same type or a derived type. It
1454 // affects the conversion rank.
1455 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1456 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1457 ICS.Standard.Second = ICK_Identity;
1458 else if (IsDerivedFrom(FromType, ClassType))
1459 ICS.Standard.Second = ICK_Derived_To_Base;
1460 else
1461 return ICS;
1462
1463 // Success. Mark this as a reference binding.
1464 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1465 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1466 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1467 ICS.Standard.ReferenceBinding = true;
1468 ICS.Standard.DirectBinding = true;
1469 return ICS;
1470}
1471
1472/// PerformObjectArgumentInitialization - Perform initialization of
1473/// the implicit object parameter for the given Method with the given
1474/// expression.
1475bool
1476Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
1477 QualType ImplicitParamType
1478 = Method->getThisType(Context)->getAsPointerType()->getPointeeType();
1479 ImplicitConversionSequence ICS
1480 = TryObjectArgumentInitialization(From, Method);
1481 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
1482 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001483 diag::err_implicit_object_parameter_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00001484 << ImplicitParamType << From->getType() << From->getSourceRange();
Douglas Gregor96176b32008-11-18 23:14:02 +00001485
1486 if (ICS.Standard.Second == ICK_Derived_To_Base &&
1487 CheckDerivedToBaseConversion(From->getType(), ImplicitParamType,
1488 From->getSourceRange().getBegin(),
1489 From->getSourceRange()))
1490 return true;
1491
1492 ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true);
1493 return false;
1494}
1495
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001496/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00001497/// candidate functions, using the given function call arguments. If
1498/// @p SuppressUserConversions, then don't allow user-defined
1499/// conversions via constructors or conversion operators.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001500void
1501Sema::AddOverloadCandidate(FunctionDecl *Function,
1502 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00001503 OverloadCandidateSet& CandidateSet,
1504 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001505{
1506 const FunctionTypeProto* Proto
1507 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType());
1508 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001509 assert(!isa<CXXConversionDecl>(Function) &&
1510 "Use AddConversionCandidate for conversion functions");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001511
1512 // Add this candidate
1513 CandidateSet.push_back(OverloadCandidate());
1514 OverloadCandidate& Candidate = CandidateSet.back();
1515 Candidate.Function = Function;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001516 Candidate.IsSurrogate = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001517
1518 unsigned NumArgsInProto = Proto->getNumArgs();
1519
1520 // (C++ 13.3.2p2): A candidate function having fewer than m
1521 // parameters is viable only if it has an ellipsis in its parameter
1522 // list (8.3.5).
1523 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1524 Candidate.Viable = false;
1525 return;
1526 }
1527
1528 // (C++ 13.3.2p2): A candidate function having more than m parameters
1529 // is viable only if the (m+1)st parameter has a default argument
1530 // (8.3.6). For the purposes of overload resolution, the
1531 // parameter list is truncated on the right, so that there are
1532 // exactly m parameters.
1533 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
1534 if (NumArgs < MinRequiredArgs) {
1535 // Not enough arguments.
1536 Candidate.Viable = false;
1537 return;
1538 }
1539
1540 // Determine the implicit conversion sequences for each of the
1541 // arguments.
1542 Candidate.Viable = true;
1543 Candidate.Conversions.resize(NumArgs);
1544 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1545 if (ArgIdx < NumArgsInProto) {
1546 // (C++ 13.3.2p3): for F to be a viable function, there shall
1547 // exist for each argument an implicit conversion sequence
1548 // (13.3.3.1) that converts that argument to the corresponding
1549 // parameter of F.
1550 QualType ParamType = Proto->getArgType(ArgIdx);
1551 Candidate.Conversions[ArgIdx]
Douglas Gregor225c41e2008-11-03 19:09:14 +00001552 = TryCopyInitialization(Args[ArgIdx], ParamType,
1553 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001554 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00001555 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001556 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001557 break;
1558 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001559 } else {
1560 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1561 // argument for which there is no corresponding parameter is
1562 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1563 Candidate.Conversions[ArgIdx].ConversionKind
1564 = ImplicitConversionSequence::EllipsisConversion;
1565 }
1566 }
1567}
1568
Douglas Gregor96176b32008-11-18 23:14:02 +00001569/// AddMethodCandidate - Adds the given C++ member function to the set
1570/// of candidate functions, using the given function call arguments
1571/// and the object argument (@c Object). For example, in a call
1572/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
1573/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
1574/// allow user-defined conversions via constructors or conversion
1575/// operators.
1576void
1577Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
1578 Expr **Args, unsigned NumArgs,
1579 OverloadCandidateSet& CandidateSet,
1580 bool SuppressUserConversions)
1581{
1582 const FunctionTypeProto* Proto
1583 = dyn_cast<FunctionTypeProto>(Method->getType()->getAsFunctionType());
1584 assert(Proto && "Methods without a prototype cannot be overloaded");
1585 assert(!isa<CXXConversionDecl>(Method) &&
1586 "Use AddConversionCandidate for conversion functions");
1587
1588 // Add this candidate
1589 CandidateSet.push_back(OverloadCandidate());
1590 OverloadCandidate& Candidate = CandidateSet.back();
1591 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001592 Candidate.IsSurrogate = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001593
1594 unsigned NumArgsInProto = Proto->getNumArgs();
1595
1596 // (C++ 13.3.2p2): A candidate function having fewer than m
1597 // parameters is viable only if it has an ellipsis in its parameter
1598 // list (8.3.5).
1599 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1600 Candidate.Viable = false;
1601 return;
1602 }
1603
1604 // (C++ 13.3.2p2): A candidate function having more than m parameters
1605 // is viable only if the (m+1)st parameter has a default argument
1606 // (8.3.6). For the purposes of overload resolution, the
1607 // parameter list is truncated on the right, so that there are
1608 // exactly m parameters.
1609 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
1610 if (NumArgs < MinRequiredArgs) {
1611 // Not enough arguments.
1612 Candidate.Viable = false;
1613 return;
1614 }
1615
1616 Candidate.Viable = true;
1617 Candidate.Conversions.resize(NumArgs + 1);
1618
1619 // Determine the implicit conversion sequence for the object
1620 // parameter.
1621 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
1622 if (Candidate.Conversions[0].ConversionKind
1623 == ImplicitConversionSequence::BadConversion) {
1624 Candidate.Viable = false;
1625 return;
1626 }
1627
1628 // Determine the implicit conversion sequences for each of the
1629 // arguments.
1630 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1631 if (ArgIdx < NumArgsInProto) {
1632 // (C++ 13.3.2p3): for F to be a viable function, there shall
1633 // exist for each argument an implicit conversion sequence
1634 // (13.3.3.1) that converts that argument to the corresponding
1635 // parameter of F.
1636 QualType ParamType = Proto->getArgType(ArgIdx);
1637 Candidate.Conversions[ArgIdx + 1]
1638 = TryCopyInitialization(Args[ArgIdx], ParamType,
1639 SuppressUserConversions);
1640 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
1641 == ImplicitConversionSequence::BadConversion) {
1642 Candidate.Viable = false;
1643 break;
1644 }
1645 } else {
1646 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1647 // argument for which there is no corresponding parameter is
1648 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1649 Candidate.Conversions[ArgIdx + 1].ConversionKind
1650 = ImplicitConversionSequence::EllipsisConversion;
1651 }
1652 }
1653}
1654
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001655/// AddConversionCandidate - Add a C++ conversion function as a
1656/// candidate in the candidate set (C++ [over.match.conv],
1657/// C++ [over.match.copy]). From is the expression we're converting from,
1658/// and ToType is the type that we're eventually trying to convert to
1659/// (which may or may not be the same type as the type that the
1660/// conversion function produces).
1661void
1662Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
1663 Expr *From, QualType ToType,
1664 OverloadCandidateSet& CandidateSet) {
1665 // Add this candidate
1666 CandidateSet.push_back(OverloadCandidate());
1667 OverloadCandidate& Candidate = CandidateSet.back();
1668 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001669 Candidate.IsSurrogate = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001670 Candidate.FinalConversion.setAsIdentityConversion();
1671 Candidate.FinalConversion.FromTypePtr
1672 = Conversion->getConversionType().getAsOpaquePtr();
1673 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
1674
Douglas Gregor96176b32008-11-18 23:14:02 +00001675 // Determine the implicit conversion sequence for the implicit
1676 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001677 Candidate.Viable = true;
1678 Candidate.Conversions.resize(1);
Douglas Gregor96176b32008-11-18 23:14:02 +00001679 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001680
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001681 if (Candidate.Conversions[0].ConversionKind
1682 == ImplicitConversionSequence::BadConversion) {
1683 Candidate.Viable = false;
1684 return;
1685 }
1686
1687 // To determine what the conversion from the result of calling the
1688 // conversion function to the type we're eventually trying to
1689 // convert to (ToType), we need to synthesize a call to the
1690 // conversion function and attempt copy initialization from it. This
1691 // makes sure that we get the right semantics with respect to
1692 // lvalues/rvalues and the type. Fortunately, we can allocate this
1693 // call on the stack and we don't need its arguments to be
1694 // well-formed.
1695 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
1696 SourceLocation());
1697 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001698 &ConversionRef, false);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001699 CallExpr Call(&ConversionFn, 0, 0,
1700 Conversion->getConversionType().getNonReferenceType(),
1701 SourceLocation());
1702 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
1703 switch (ICS.ConversionKind) {
1704 case ImplicitConversionSequence::StandardConversion:
1705 Candidate.FinalConversion = ICS.Standard;
1706 break;
1707
1708 case ImplicitConversionSequence::BadConversion:
1709 Candidate.Viable = false;
1710 break;
1711
1712 default:
1713 assert(false &&
1714 "Can only end up with a standard conversion sequence or failure");
1715 }
1716}
1717
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001718/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
1719/// converts the given @c Object to a function pointer via the
1720/// conversion function @c Conversion, and then attempts to call it
1721/// with the given arguments (C++ [over.call.object]p2-4). Proto is
1722/// the type of function that we'll eventually be calling.
1723void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
1724 const FunctionTypeProto *Proto,
1725 Expr *Object, Expr **Args, unsigned NumArgs,
1726 OverloadCandidateSet& CandidateSet) {
1727 CandidateSet.push_back(OverloadCandidate());
1728 OverloadCandidate& Candidate = CandidateSet.back();
1729 Candidate.Function = 0;
1730 Candidate.Surrogate = Conversion;
1731 Candidate.Viable = true;
1732 Candidate.IsSurrogate = true;
1733 Candidate.Conversions.resize(NumArgs + 1);
1734
1735 // Determine the implicit conversion sequence for the implicit
1736 // object parameter.
1737 ImplicitConversionSequence ObjectInit
1738 = TryObjectArgumentInitialization(Object, Conversion);
1739 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
1740 Candidate.Viable = false;
1741 return;
1742 }
1743
1744 // The first conversion is actually a user-defined conversion whose
1745 // first conversion is ObjectInit's standard conversion (which is
1746 // effectively a reference binding). Record it as such.
1747 Candidate.Conversions[0].ConversionKind
1748 = ImplicitConversionSequence::UserDefinedConversion;
1749 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
1750 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
1751 Candidate.Conversions[0].UserDefined.After
1752 = Candidate.Conversions[0].UserDefined.Before;
1753 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
1754
1755 // Find the
1756 unsigned NumArgsInProto = Proto->getNumArgs();
1757
1758 // (C++ 13.3.2p2): A candidate function having fewer than m
1759 // parameters is viable only if it has an ellipsis in its parameter
1760 // list (8.3.5).
1761 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1762 Candidate.Viable = false;
1763 return;
1764 }
1765
1766 // Function types don't have any default arguments, so just check if
1767 // we have enough arguments.
1768 if (NumArgs < NumArgsInProto) {
1769 // Not enough arguments.
1770 Candidate.Viable = false;
1771 return;
1772 }
1773
1774 // Determine the implicit conversion sequences for each of the
1775 // arguments.
1776 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1777 if (ArgIdx < NumArgsInProto) {
1778 // (C++ 13.3.2p3): for F to be a viable function, there shall
1779 // exist for each argument an implicit conversion sequence
1780 // (13.3.3.1) that converts that argument to the corresponding
1781 // parameter of F.
1782 QualType ParamType = Proto->getArgType(ArgIdx);
1783 Candidate.Conversions[ArgIdx + 1]
1784 = TryCopyInitialization(Args[ArgIdx], ParamType,
1785 /*SuppressUserConversions=*/false);
1786 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
1787 == ImplicitConversionSequence::BadConversion) {
1788 Candidate.Viable = false;
1789 break;
1790 }
1791 } else {
1792 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1793 // argument for which there is no corresponding parameter is
1794 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1795 Candidate.Conversions[ArgIdx + 1].ConversionKind
1796 = ImplicitConversionSequence::EllipsisConversion;
1797 }
1798 }
1799}
1800
Douglas Gregor447b69e2008-11-19 03:25:36 +00001801/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1802/// an acceptable non-member overloaded operator for a call whose
1803/// arguments have types T1 (and, if non-empty, T2). This routine
1804/// implements the check in C++ [over.match.oper]p3b2 concerning
1805/// enumeration types.
1806static bool
1807IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1808 QualType T1, QualType T2,
1809 ASTContext &Context) {
1810 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1811 return true;
1812
1813 const FunctionTypeProto *Proto = Fn->getType()->getAsFunctionTypeProto();
1814 if (Proto->getNumArgs() < 1)
1815 return false;
1816
1817 if (T1->isEnumeralType()) {
1818 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
1819 if (Context.getCanonicalType(T1).getUnqualifiedType()
1820 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1821 return true;
1822 }
1823
1824 if (Proto->getNumArgs() < 2)
1825 return false;
1826
1827 if (!T2.isNull() && T2->isEnumeralType()) {
1828 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
1829 if (Context.getCanonicalType(T2).getUnqualifiedType()
1830 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1831 return true;
1832 }
1833
1834 return false;
1835}
1836
Douglas Gregor96176b32008-11-18 23:14:02 +00001837/// AddOperatorCandidates - Add the overloaded operator candidates for
1838/// the operator Op that was used in an operator expression such as "x
1839/// Op y". S is the scope in which the expression occurred (used for
1840/// name lookup of the operator), Args/NumArgs provides the operator
1841/// arguments, and CandidateSet will store the added overload
1842/// candidates. (C++ [over.match.oper]).
1843void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
1844 Expr **Args, unsigned NumArgs,
1845 OverloadCandidateSet& CandidateSet) {
1846 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
1847
1848 // C++ [over.match.oper]p3:
1849 // For a unary operator @ with an operand of a type whose
1850 // cv-unqualified version is T1, and for a binary operator @ with
1851 // a left operand of a type whose cv-unqualified version is T1 and
1852 // a right operand of a type whose cv-unqualified version is T2,
1853 // three sets of candidate functions, designated member
1854 // candidates, non-member candidates and built-in candidates, are
1855 // constructed as follows:
1856 QualType T1 = Args[0]->getType();
1857 QualType T2;
1858 if (NumArgs > 1)
1859 T2 = Args[1]->getType();
1860
1861 // -- If T1 is a class type, the set of member candidates is the
1862 // result of the qualified lookup of T1::operator@
1863 // (13.3.1.1.1); otherwise, the set of member candidates is
1864 // empty.
1865 if (const RecordType *T1Rec = T1->getAsRecordType()) {
1866 IdentifierResolver::iterator I
1867 = IdResolver.begin(OpName, cast<CXXRecordType>(T1Rec)->getDecl(),
1868 /*LookInParentCtx=*/false);
1869 NamedDecl *MemberOps = (I == IdResolver.end())? 0 : *I;
1870 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps))
1871 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet,
1872 /*SuppressUserConversions=*/false);
1873 else if (OverloadedFunctionDecl *Ovl
1874 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) {
1875 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
1876 FEnd = Ovl->function_end();
1877 F != FEnd; ++F) {
1878 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F))
1879 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet,
1880 /*SuppressUserConversions=*/false);
1881 }
1882 }
1883 }
1884
1885 // -- The set of non-member candidates is the result of the
1886 // unqualified lookup of operator@ in the context of the
1887 // expression according to the usual rules for name lookup in
1888 // unqualified function calls (3.4.2) except that all member
1889 // functions are ignored. However, if no operand has a class
1890 // type, only those non-member functions in the lookup set
1891 // that have a first parameter of type T1 or “reference to
1892 // (possibly cv-qualified) T1”, when T1 is an enumeration
1893 // type, or (if there is a right operand) a second parameter
1894 // of type T2 or “reference to (possibly cv-qualified) T2”,
1895 // when T2 is an enumeration type, are candidate functions.
1896 {
1897 NamedDecl *NonMemberOps = 0;
1898 for (IdentifierResolver::iterator I
1899 = IdResolver.begin(OpName, CurContext, true/*LookInParentCtx*/);
1900 I != IdResolver.end(); ++I) {
1901 // We don't need to check the identifier namespace, because
1902 // operator names can only be ordinary identifiers.
1903
1904 // Ignore member functions.
1905 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(*I)) {
1906 if (SD->getDeclContext()->isCXXRecord())
1907 continue;
1908 }
1909
1910 // We found something with this name. We're done.
1911 NonMemberOps = *I;
1912 break;
1913 }
1914
Douglas Gregor447b69e2008-11-19 03:25:36 +00001915 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NonMemberOps)) {
1916 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1917 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
1918 /*SuppressUserConversions=*/false);
1919 } else if (OverloadedFunctionDecl *Ovl
1920 = dyn_cast_or_null<OverloadedFunctionDecl>(NonMemberOps)) {
Douglas Gregor96176b32008-11-18 23:14:02 +00001921 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
1922 FEnd = Ovl->function_end();
Douglas Gregor447b69e2008-11-19 03:25:36 +00001923 F != FEnd; ++F) {
1924 if (IsAcceptableNonMemberOperatorCandidate(*F, T1, T2, Context))
1925 AddOverloadCandidate(*F, Args, NumArgs, CandidateSet,
1926 /*SuppressUserConversions=*/false);
1927 }
Douglas Gregor96176b32008-11-18 23:14:02 +00001928 }
1929 }
1930
1931 // Add builtin overload candidates (C++ [over.built]).
Douglas Gregor74253732008-11-19 15:42:04 +00001932 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
Douglas Gregor96176b32008-11-18 23:14:02 +00001933}
1934
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001935/// AddBuiltinCandidate - Add a candidate for a built-in
1936/// operator. ResultTy and ParamTys are the result and parameter types
1937/// of the built-in candidate, respectively. Args and NumArgs are the
1938/// arguments being passed to the candidate.
1939void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
1940 Expr **Args, unsigned NumArgs,
1941 OverloadCandidateSet& CandidateSet) {
1942 // Add this candidate
1943 CandidateSet.push_back(OverloadCandidate());
1944 OverloadCandidate& Candidate = CandidateSet.back();
1945 Candidate.Function = 0;
1946 Candidate.BuiltinTypes.ResultTy = ResultTy;
1947 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
1948 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
1949
1950 // Determine the implicit conversion sequences for each of the
1951 // arguments.
1952 Candidate.Viable = true;
1953 Candidate.Conversions.resize(NumArgs);
1954 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1955 Candidate.Conversions[ArgIdx]
1956 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx], false);
1957 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00001958 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001959 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001960 break;
1961 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001962 }
1963}
1964
1965/// BuiltinCandidateTypeSet - A set of types that will be used for the
1966/// candidate operator functions for built-in operators (C++
1967/// [over.built]). The types are separated into pointer types and
1968/// enumeration types.
1969class BuiltinCandidateTypeSet {
1970 /// TypeSet - A set of types.
Douglas Gregorbf3af052008-11-13 20:12:29 +00001971 typedef llvm::SmallPtrSet<void*, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001972
1973 /// PointerTypes - The set of pointer types that will be used in the
1974 /// built-in candidates.
1975 TypeSet PointerTypes;
1976
1977 /// EnumerationTypes - The set of enumeration types that will be
1978 /// used in the built-in candidates.
1979 TypeSet EnumerationTypes;
1980
1981 /// Context - The AST context in which we will build the type sets.
1982 ASTContext &Context;
1983
1984 bool AddWithMoreQualifiedTypeVariants(QualType Ty);
1985
1986public:
1987 /// iterator - Iterates through the types that are part of the set.
Douglas Gregorbf3af052008-11-13 20:12:29 +00001988 class iterator {
1989 TypeSet::iterator Base;
1990
1991 public:
1992 typedef QualType value_type;
1993 typedef QualType reference;
1994 typedef QualType pointer;
1995 typedef std::ptrdiff_t difference_type;
1996 typedef std::input_iterator_tag iterator_category;
1997
1998 iterator(TypeSet::iterator B) : Base(B) { }
1999
2000 iterator& operator++() {
2001 ++Base;
2002 return *this;
2003 }
2004
2005 iterator operator++(int) {
2006 iterator tmp(*this);
2007 ++(*this);
2008 return tmp;
2009 }
2010
2011 reference operator*() const {
2012 return QualType::getFromOpaquePtr(*Base);
2013 }
2014
2015 pointer operator->() const {
2016 return **this;
2017 }
2018
2019 friend bool operator==(iterator LHS, iterator RHS) {
2020 return LHS.Base == RHS.Base;
2021 }
2022
2023 friend bool operator!=(iterator LHS, iterator RHS) {
2024 return LHS.Base != RHS.Base;
2025 }
2026 };
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002027
2028 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2029
2030 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions = true);
2031
2032 /// pointer_begin - First pointer type found;
2033 iterator pointer_begin() { return PointerTypes.begin(); }
2034
2035 /// pointer_end - Last pointer type found;
2036 iterator pointer_end() { return PointerTypes.end(); }
2037
2038 /// enumeration_begin - First enumeration type found;
2039 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2040
2041 /// enumeration_end - Last enumeration type found;
2042 iterator enumeration_end() { return EnumerationTypes.end(); }
2043};
2044
2045/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2046/// the set of pointer types along with any more-qualified variants of
2047/// that type. For example, if @p Ty is "int const *", this routine
2048/// will add "int const *", "int const volatile *", "int const
2049/// restrict *", and "int const volatile restrict *" to the set of
2050/// pointer types. Returns true if the add of @p Ty itself succeeded,
2051/// false otherwise.
2052bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) {
2053 // Insert this type.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002054 if (!PointerTypes.insert(Ty.getAsOpaquePtr()))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002055 return false;
2056
2057 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2058 QualType PointeeTy = PointerTy->getPointeeType();
2059 // FIXME: Optimize this so that we don't keep trying to add the same types.
2060
2061 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
2062 // with all pointer conversions that don't cast away constness?
2063 if (!PointeeTy.isConstQualified())
2064 AddWithMoreQualifiedTypeVariants
2065 (Context.getPointerType(PointeeTy.withConst()));
2066 if (!PointeeTy.isVolatileQualified())
2067 AddWithMoreQualifiedTypeVariants
2068 (Context.getPointerType(PointeeTy.withVolatile()));
2069 if (!PointeeTy.isRestrictQualified())
2070 AddWithMoreQualifiedTypeVariants
2071 (Context.getPointerType(PointeeTy.withRestrict()));
2072 }
2073
2074 return true;
2075}
2076
2077/// AddTypesConvertedFrom - Add each of the types to which the type @p
2078/// Ty can be implicit converted to the given set of @p Types. We're
2079/// primarily interested in pointer types, enumeration types,
2080void BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2081 bool AllowUserConversions) {
2082 // Only deal with canonical types.
2083 Ty = Context.getCanonicalType(Ty);
2084
2085 // Look through reference types; they aren't part of the type of an
2086 // expression for the purposes of conversions.
2087 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2088 Ty = RefTy->getPointeeType();
2089
2090 // We don't care about qualifiers on the type.
2091 Ty = Ty.getUnqualifiedType();
2092
2093 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2094 QualType PointeeTy = PointerTy->getPointeeType();
2095
2096 // Insert our type, and its more-qualified variants, into the set
2097 // of types.
2098 if (!AddWithMoreQualifiedTypeVariants(Ty))
2099 return;
2100
2101 // Add 'cv void*' to our set of types.
2102 if (!Ty->isVoidType()) {
2103 QualType QualVoid
2104 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2105 AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2106 }
2107
2108 // If this is a pointer to a class type, add pointers to its bases
2109 // (with the same level of cv-qualification as the original
2110 // derived class, of course).
2111 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2112 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2113 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2114 Base != ClassDecl->bases_end(); ++Base) {
2115 QualType BaseTy = Context.getCanonicalType(Base->getType());
2116 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2117
2118 // Add the pointer type, recursively, so that we get all of
2119 // the indirect base classes, too.
2120 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false);
2121 }
2122 }
2123 } else if (Ty->isEnumeralType()) {
Douglas Gregorbf3af052008-11-13 20:12:29 +00002124 EnumerationTypes.insert(Ty.getAsOpaquePtr());
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002125 } else if (AllowUserConversions) {
2126 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2127 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2128 // FIXME: Visit conversion functions in the base classes, too.
2129 OverloadedFunctionDecl *Conversions
2130 = ClassDecl->getConversionFunctions();
2131 for (OverloadedFunctionDecl::function_iterator Func
2132 = Conversions->function_begin();
2133 Func != Conversions->function_end(); ++Func) {
2134 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
2135 AddTypesConvertedFrom(Conv->getConversionType(), false);
2136 }
2137 }
2138 }
2139}
2140
Douglas Gregor74253732008-11-19 15:42:04 +00002141/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2142/// operator overloads to the candidate set (C++ [over.built]), based
2143/// on the operator @p Op and the arguments given. For example, if the
2144/// operator is a binary '+', this routine might add "int
2145/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002146void
Douglas Gregor74253732008-11-19 15:42:04 +00002147Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2148 Expr **Args, unsigned NumArgs,
2149 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002150 // The set of "promoted arithmetic types", which are the arithmetic
2151 // types are that preserved by promotion (C++ [over.built]p2). Note
2152 // that the first few of these types are the promoted integral
2153 // types; these types need to be first.
2154 // FIXME: What about complex?
2155 const unsigned FirstIntegralType = 0;
2156 const unsigned LastIntegralType = 13;
2157 const unsigned FirstPromotedIntegralType = 7,
2158 LastPromotedIntegralType = 13;
2159 const unsigned FirstPromotedArithmeticType = 7,
2160 LastPromotedArithmeticType = 16;
2161 const unsigned NumArithmeticTypes = 16;
2162 QualType ArithmeticTypes[NumArithmeticTypes] = {
2163 Context.BoolTy, Context.CharTy, Context.WCharTy,
2164 Context.SignedCharTy, Context.ShortTy,
2165 Context.UnsignedCharTy, Context.UnsignedShortTy,
2166 Context.IntTy, Context.LongTy, Context.LongLongTy,
2167 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2168 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2169 };
2170
2171 // Find all of the types that the arguments can convert to, but only
2172 // if the operator we're looking at has built-in operator candidates
2173 // that make use of these types.
2174 BuiltinCandidateTypeSet CandidateTypes(Context);
2175 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2176 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00002177 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002178 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00002179 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
2180 (Op == OO_Star && NumArgs == 1)) {
2181 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002182 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType());
2183 }
2184
2185 bool isComparison = false;
2186 switch (Op) {
2187 case OO_None:
2188 case NUM_OVERLOADED_OPERATORS:
2189 assert(false && "Expected an overloaded operator");
2190 break;
2191
Douglas Gregor74253732008-11-19 15:42:04 +00002192 case OO_Star: // '*' is either unary or binary
2193 if (NumArgs == 1)
2194 goto UnaryStar;
2195 else
2196 goto BinaryStar;
2197 break;
2198
2199 case OO_Plus: // '+' is either unary or binary
2200 if (NumArgs == 1)
2201 goto UnaryPlus;
2202 else
2203 goto BinaryPlus;
2204 break;
2205
2206 case OO_Minus: // '-' is either unary or binary
2207 if (NumArgs == 1)
2208 goto UnaryMinus;
2209 else
2210 goto BinaryMinus;
2211 break;
2212
2213 case OO_Amp: // '&' is either unary or binary
2214 if (NumArgs == 1)
2215 goto UnaryAmp;
2216 else
2217 goto BinaryAmp;
2218
2219 case OO_PlusPlus:
2220 case OO_MinusMinus:
2221 // C++ [over.built]p3:
2222 //
2223 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2224 // is either volatile or empty, there exist candidate operator
2225 // functions of the form
2226 //
2227 // VQ T& operator++(VQ T&);
2228 // T operator++(VQ T&, int);
2229 //
2230 // C++ [over.built]p4:
2231 //
2232 // For every pair (T, VQ), where T is an arithmetic type other
2233 // than bool, and VQ is either volatile or empty, there exist
2234 // candidate operator functions of the form
2235 //
2236 // VQ T& operator--(VQ T&);
2237 // T operator--(VQ T&, int);
2238 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2239 Arith < NumArithmeticTypes; ++Arith) {
2240 QualType ArithTy = ArithmeticTypes[Arith];
2241 QualType ParamTypes[2]
2242 = { Context.getReferenceType(ArithTy), Context.IntTy };
2243
2244 // Non-volatile version.
2245 if (NumArgs == 1)
2246 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2247 else
2248 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2249
2250 // Volatile version
2251 ParamTypes[0] = Context.getReferenceType(ArithTy.withVolatile());
2252 if (NumArgs == 1)
2253 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2254 else
2255 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2256 }
2257
2258 // C++ [over.built]p5:
2259 //
2260 // For every pair (T, VQ), where T is a cv-qualified or
2261 // cv-unqualified object type, and VQ is either volatile or
2262 // empty, there exist candidate operator functions of the form
2263 //
2264 // T*VQ& operator++(T*VQ&);
2265 // T*VQ& operator--(T*VQ&);
2266 // T* operator++(T*VQ&, int);
2267 // T* operator--(T*VQ&, int);
2268 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2269 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2270 // Skip pointer types that aren't pointers to object types.
2271 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isObjectType())
2272 continue;
2273
2274 QualType ParamTypes[2] = {
2275 Context.getReferenceType(*Ptr), Context.IntTy
2276 };
2277
2278 // Without volatile
2279 if (NumArgs == 1)
2280 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2281 else
2282 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2283
2284 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2285 // With volatile
2286 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2287 if (NumArgs == 1)
2288 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2289 else
2290 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2291 }
2292 }
2293 break;
2294
2295 UnaryStar:
2296 // C++ [over.built]p6:
2297 // For every cv-qualified or cv-unqualified object type T, there
2298 // exist candidate operator functions of the form
2299 //
2300 // T& operator*(T*);
2301 //
2302 // C++ [over.built]p7:
2303 // For every function type T, there exist candidate operator
2304 // functions of the form
2305 // T& operator*(T*);
2306 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2307 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2308 QualType ParamTy = *Ptr;
2309 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
2310 AddBuiltinCandidate(Context.getReferenceType(PointeeTy),
2311 &ParamTy, Args, 1, CandidateSet);
2312 }
2313 break;
2314
2315 UnaryPlus:
2316 // C++ [over.built]p8:
2317 // For every type T, there exist candidate operator functions of
2318 // the form
2319 //
2320 // T* operator+(T*);
2321 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2322 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2323 QualType ParamTy = *Ptr;
2324 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2325 }
2326
2327 // Fall through
2328
2329 UnaryMinus:
2330 // C++ [over.built]p9:
2331 // For every promoted arithmetic type T, there exist candidate
2332 // operator functions of the form
2333 //
2334 // T operator+(T);
2335 // T operator-(T);
2336 for (unsigned Arith = FirstPromotedArithmeticType;
2337 Arith < LastPromotedArithmeticType; ++Arith) {
2338 QualType ArithTy = ArithmeticTypes[Arith];
2339 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2340 }
2341 break;
2342
2343 case OO_Tilde:
2344 // C++ [over.built]p10:
2345 // For every promoted integral type T, there exist candidate
2346 // operator functions of the form
2347 //
2348 // T operator~(T);
2349 for (unsigned Int = FirstPromotedIntegralType;
2350 Int < LastPromotedIntegralType; ++Int) {
2351 QualType IntTy = ArithmeticTypes[Int];
2352 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2353 }
2354 break;
2355
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002356 case OO_New:
2357 case OO_Delete:
2358 case OO_Array_New:
2359 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002360 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00002361 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002362 break;
2363
2364 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00002365 UnaryAmp:
2366 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002367 // C++ [over.match.oper]p3:
2368 // -- For the operator ',', the unary operator '&', or the
2369 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002370 break;
2371
2372 case OO_Less:
2373 case OO_Greater:
2374 case OO_LessEqual:
2375 case OO_GreaterEqual:
2376 case OO_EqualEqual:
2377 case OO_ExclaimEqual:
2378 // C++ [over.built]p15:
2379 //
2380 // For every pointer or enumeration type T, there exist
2381 // candidate operator functions of the form
2382 //
2383 // bool operator<(T, T);
2384 // bool operator>(T, T);
2385 // bool operator<=(T, T);
2386 // bool operator>=(T, T);
2387 // bool operator==(T, T);
2388 // bool operator!=(T, T);
2389 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2390 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2391 QualType ParamTypes[2] = { *Ptr, *Ptr };
2392 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2393 }
2394 for (BuiltinCandidateTypeSet::iterator Enum
2395 = CandidateTypes.enumeration_begin();
2396 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2397 QualType ParamTypes[2] = { *Enum, *Enum };
2398 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2399 }
2400
2401 // Fall through.
2402 isComparison = true;
2403
Douglas Gregor74253732008-11-19 15:42:04 +00002404 BinaryPlus:
2405 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002406 if (!isComparison) {
2407 // We didn't fall through, so we must have OO_Plus or OO_Minus.
2408
2409 // C++ [over.built]p13:
2410 //
2411 // For every cv-qualified or cv-unqualified object type T
2412 // there exist candidate operator functions of the form
2413 //
2414 // T* operator+(T*, ptrdiff_t);
2415 // T& operator[](T*, ptrdiff_t); [BELOW]
2416 // T* operator-(T*, ptrdiff_t);
2417 // T* operator+(ptrdiff_t, T*);
2418 // T& operator[](ptrdiff_t, T*); [BELOW]
2419 //
2420 // C++ [over.built]p14:
2421 //
2422 // For every T, where T is a pointer to object type, there
2423 // exist candidate operator functions of the form
2424 //
2425 // ptrdiff_t operator-(T, T);
2426 for (BuiltinCandidateTypeSet::iterator Ptr
2427 = CandidateTypes.pointer_begin();
2428 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2429 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2430
2431 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
2432 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2433
2434 if (Op == OO_Plus) {
2435 // T* operator+(ptrdiff_t, T*);
2436 ParamTypes[0] = ParamTypes[1];
2437 ParamTypes[1] = *Ptr;
2438 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2439 } else {
2440 // ptrdiff_t operator-(T, T);
2441 ParamTypes[1] = *Ptr;
2442 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
2443 Args, 2, CandidateSet);
2444 }
2445 }
2446 }
2447 // Fall through
2448
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002449 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00002450 BinaryStar:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002451 // C++ [over.built]p12:
2452 //
2453 // For every pair of promoted arithmetic types L and R, there
2454 // exist candidate operator functions of the form
2455 //
2456 // LR operator*(L, R);
2457 // LR operator/(L, R);
2458 // LR operator+(L, R);
2459 // LR operator-(L, R);
2460 // bool operator<(L, R);
2461 // bool operator>(L, R);
2462 // bool operator<=(L, R);
2463 // bool operator>=(L, R);
2464 // bool operator==(L, R);
2465 // bool operator!=(L, R);
2466 //
2467 // where LR is the result of the usual arithmetic conversions
2468 // between types L and R.
2469 for (unsigned Left = FirstPromotedArithmeticType;
2470 Left < LastPromotedArithmeticType; ++Left) {
2471 for (unsigned Right = FirstPromotedArithmeticType;
2472 Right < LastPromotedArithmeticType; ++Right) {
2473 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2474 QualType Result
2475 = isComparison? Context.BoolTy
2476 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2477 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2478 }
2479 }
2480 break;
2481
2482 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00002483 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002484 case OO_Caret:
2485 case OO_Pipe:
2486 case OO_LessLess:
2487 case OO_GreaterGreater:
2488 // C++ [over.built]p17:
2489 //
2490 // For every pair of promoted integral types L and R, there
2491 // exist candidate operator functions of the form
2492 //
2493 // LR operator%(L, R);
2494 // LR operator&(L, R);
2495 // LR operator^(L, R);
2496 // LR operator|(L, R);
2497 // L operator<<(L, R);
2498 // L operator>>(L, R);
2499 //
2500 // where LR is the result of the usual arithmetic conversions
2501 // between types L and R.
2502 for (unsigned Left = FirstPromotedIntegralType;
2503 Left < LastPromotedIntegralType; ++Left) {
2504 for (unsigned Right = FirstPromotedIntegralType;
2505 Right < LastPromotedIntegralType; ++Right) {
2506 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2507 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
2508 ? LandR[0]
2509 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2510 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2511 }
2512 }
2513 break;
2514
2515 case OO_Equal:
2516 // C++ [over.built]p20:
2517 //
2518 // For every pair (T, VQ), where T is an enumeration or
2519 // (FIXME:) pointer to member type and VQ is either volatile or
2520 // empty, there exist candidate operator functions of the form
2521 //
2522 // VQ T& operator=(VQ T&, T);
2523 for (BuiltinCandidateTypeSet::iterator Enum
2524 = CandidateTypes.enumeration_begin();
2525 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2526 QualType ParamTypes[2];
2527
2528 // T& operator=(T&, T)
2529 ParamTypes[0] = Context.getReferenceType(*Enum);
2530 ParamTypes[1] = *Enum;
2531 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2532
Douglas Gregor74253732008-11-19 15:42:04 +00002533 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
2534 // volatile T& operator=(volatile T&, T)
2535 ParamTypes[0] = Context.getReferenceType((*Enum).withVolatile());
2536 ParamTypes[1] = *Enum;
2537 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2538 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002539 }
2540 // Fall through.
2541
2542 case OO_PlusEqual:
2543 case OO_MinusEqual:
2544 // C++ [over.built]p19:
2545 //
2546 // For every pair (T, VQ), where T is any type and VQ is either
2547 // volatile or empty, there exist candidate operator functions
2548 // of the form
2549 //
2550 // T*VQ& operator=(T*VQ&, T*);
2551 //
2552 // C++ [over.built]p21:
2553 //
2554 // For every pair (T, VQ), where T is a cv-qualified or
2555 // cv-unqualified object type and VQ is either volatile or
2556 // empty, there exist candidate operator functions of the form
2557 //
2558 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
2559 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
2560 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2561 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2562 QualType ParamTypes[2];
2563 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
2564
2565 // non-volatile version
2566 ParamTypes[0] = Context.getReferenceType(*Ptr);
2567 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2568
Douglas Gregor74253732008-11-19 15:42:04 +00002569 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2570 // volatile version
2571 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2572 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2573 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002574 }
2575 // Fall through.
2576
2577 case OO_StarEqual:
2578 case OO_SlashEqual:
2579 // C++ [over.built]p18:
2580 //
2581 // For every triple (L, VQ, R), where L is an arithmetic type,
2582 // VQ is either volatile or empty, and R is a promoted
2583 // arithmetic type, there exist candidate operator functions of
2584 // the form
2585 //
2586 // VQ L& operator=(VQ L&, R);
2587 // VQ L& operator*=(VQ L&, R);
2588 // VQ L& operator/=(VQ L&, R);
2589 // VQ L& operator+=(VQ L&, R);
2590 // VQ L& operator-=(VQ L&, R);
2591 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
2592 for (unsigned Right = FirstPromotedArithmeticType;
2593 Right < LastPromotedArithmeticType; ++Right) {
2594 QualType ParamTypes[2];
2595 ParamTypes[1] = ArithmeticTypes[Right];
2596
2597 // Add this built-in operator as a candidate (VQ is empty).
2598 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
2599 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2600
2601 // Add this built-in operator as a candidate (VQ is 'volatile').
2602 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
2603 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
2604 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2605 }
2606 }
2607 break;
2608
2609 case OO_PercentEqual:
2610 case OO_LessLessEqual:
2611 case OO_GreaterGreaterEqual:
2612 case OO_AmpEqual:
2613 case OO_CaretEqual:
2614 case OO_PipeEqual:
2615 // C++ [over.built]p22:
2616 //
2617 // For every triple (L, VQ, R), where L is an integral type, VQ
2618 // is either volatile or empty, and R is a promoted integral
2619 // type, there exist candidate operator functions of the form
2620 //
2621 // VQ L& operator%=(VQ L&, R);
2622 // VQ L& operator<<=(VQ L&, R);
2623 // VQ L& operator>>=(VQ L&, R);
2624 // VQ L& operator&=(VQ L&, R);
2625 // VQ L& operator^=(VQ L&, R);
2626 // VQ L& operator|=(VQ L&, R);
2627 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
2628 for (unsigned Right = FirstPromotedIntegralType;
2629 Right < LastPromotedIntegralType; ++Right) {
2630 QualType ParamTypes[2];
2631 ParamTypes[1] = ArithmeticTypes[Right];
2632
2633 // Add this built-in operator as a candidate (VQ is empty).
2634 // FIXME: We should be caching these declarations somewhere,
2635 // rather than re-building them every time.
2636 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
2637 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2638
2639 // Add this built-in operator as a candidate (VQ is 'volatile').
2640 ParamTypes[0] = ArithmeticTypes[Left];
2641 ParamTypes[0].addVolatile();
2642 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
2643 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2644 }
2645 }
2646 break;
2647
Douglas Gregor74253732008-11-19 15:42:04 +00002648 case OO_Exclaim: {
2649 // C++ [over.operator]p23:
2650 //
2651 // There also exist candidate operator functions of the form
2652 //
2653 // bool operator!(bool);
2654 // bool operator&&(bool, bool); [BELOW]
2655 // bool operator||(bool, bool); [BELOW]
2656 QualType ParamTy = Context.BoolTy;
2657 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2658 break;
2659 }
2660
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002661 case OO_AmpAmp:
2662 case OO_PipePipe: {
2663 // C++ [over.operator]p23:
2664 //
2665 // There also exist candidate operator functions of the form
2666 //
Douglas Gregor74253732008-11-19 15:42:04 +00002667 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002668 // bool operator&&(bool, bool);
2669 // bool operator||(bool, bool);
2670 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
2671 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2672 break;
2673 }
2674
2675 case OO_Subscript:
2676 // C++ [over.built]p13:
2677 //
2678 // For every cv-qualified or cv-unqualified object type T there
2679 // exist candidate operator functions of the form
2680 //
2681 // T* operator+(T*, ptrdiff_t); [ABOVE]
2682 // T& operator[](T*, ptrdiff_t);
2683 // T* operator-(T*, ptrdiff_t); [ABOVE]
2684 // T* operator+(ptrdiff_t, T*); [ABOVE]
2685 // T& operator[](ptrdiff_t, T*);
2686 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2687 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2688 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2689 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
2690 QualType ResultTy = Context.getReferenceType(PointeeType);
2691
2692 // T& operator[](T*, ptrdiff_t)
2693 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
2694
2695 // T& operator[](ptrdiff_t, T*);
2696 ParamTypes[0] = ParamTypes[1];
2697 ParamTypes[1] = *Ptr;
2698 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
2699 }
2700 break;
2701
2702 case OO_ArrowStar:
2703 // FIXME: No support for pointer-to-members yet.
2704 break;
2705 }
2706}
2707
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002708/// AddOverloadCandidates - Add all of the function overloads in Ovl
2709/// to the candidate set.
2710void
Douglas Gregor18fe5682008-11-03 20:45:27 +00002711Sema::AddOverloadCandidates(const OverloadedFunctionDecl *Ovl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002712 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002713 OverloadCandidateSet& CandidateSet,
2714 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002715{
Douglas Gregor18fe5682008-11-03 20:45:27 +00002716 for (OverloadedFunctionDecl::function_const_iterator Func
2717 = Ovl->function_begin();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002718 Func != Ovl->function_end(); ++Func)
Douglas Gregor225c41e2008-11-03 19:09:14 +00002719 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet,
2720 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002721}
2722
2723/// isBetterOverloadCandidate - Determines whether the first overload
2724/// candidate is a better candidate than the second (C++ 13.3.3p1).
2725bool
2726Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
2727 const OverloadCandidate& Cand2)
2728{
2729 // Define viable functions to be better candidates than non-viable
2730 // functions.
2731 if (!Cand2.Viable)
2732 return Cand1.Viable;
2733 else if (!Cand1.Viable)
2734 return false;
2735
2736 // FIXME: Deal with the implicit object parameter for static member
2737 // functions. (C++ 13.3.3p1).
2738
2739 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
2740 // function than another viable function F2 if for all arguments i,
2741 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
2742 // then...
2743 unsigned NumArgs = Cand1.Conversions.size();
2744 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
2745 bool HasBetterConversion = false;
2746 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2747 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
2748 Cand2.Conversions[ArgIdx])) {
2749 case ImplicitConversionSequence::Better:
2750 // Cand1 has a better conversion sequence.
2751 HasBetterConversion = true;
2752 break;
2753
2754 case ImplicitConversionSequence::Worse:
2755 // Cand1 can't be better than Cand2.
2756 return false;
2757
2758 case ImplicitConversionSequence::Indistinguishable:
2759 // Do nothing.
2760 break;
2761 }
2762 }
2763
2764 if (HasBetterConversion)
2765 return true;
2766
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002767 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
2768 // implemented, but they require template support.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002769
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002770 // C++ [over.match.best]p1b4:
2771 //
2772 // -- the context is an initialization by user-defined conversion
2773 // (see 8.5, 13.3.1.5) and the standard conversion sequence
2774 // from the return type of F1 to the destination type (i.e.,
2775 // the type of the entity being initialized) is a better
2776 // conversion sequence than the standard conversion sequence
2777 // from the return type of F2 to the destination type.
Douglas Gregor447b69e2008-11-19 03:25:36 +00002778 if (Cand1.Function && Cand2.Function &&
2779 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002780 isa<CXXConversionDecl>(Cand2.Function)) {
2781 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
2782 Cand2.FinalConversion)) {
2783 case ImplicitConversionSequence::Better:
2784 // Cand1 has a better conversion sequence.
2785 return true;
2786
2787 case ImplicitConversionSequence::Worse:
2788 // Cand1 can't be better than Cand2.
2789 return false;
2790
2791 case ImplicitConversionSequence::Indistinguishable:
2792 // Do nothing
2793 break;
2794 }
2795 }
2796
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002797 return false;
2798}
2799
2800/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
2801/// within an overload candidate set. If overloading is successful,
2802/// the result will be OR_Success and Best will be set to point to the
2803/// best viable function within the candidate set. Otherwise, one of
2804/// several kinds of errors will be returned; see
2805/// Sema::OverloadingResult.
2806Sema::OverloadingResult
2807Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
2808 OverloadCandidateSet::iterator& Best)
2809{
2810 // Find the best viable function.
2811 Best = CandidateSet.end();
2812 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2813 Cand != CandidateSet.end(); ++Cand) {
2814 if (Cand->Viable) {
2815 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
2816 Best = Cand;
2817 }
2818 }
2819
2820 // If we didn't find any viable functions, abort.
2821 if (Best == CandidateSet.end())
2822 return OR_No_Viable_Function;
2823
2824 // Make sure that this function is better than every other viable
2825 // function. If not, we have an ambiguity.
2826 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2827 Cand != CandidateSet.end(); ++Cand) {
2828 if (Cand->Viable &&
2829 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002830 !isBetterOverloadCandidate(*Best, *Cand)) {
2831 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002832 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002833 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002834 }
2835
2836 // Best is the best viable function.
2837 return OR_Success;
2838}
2839
2840/// PrintOverloadCandidates - When overload resolution fails, prints
2841/// diagnostic messages containing the candidates in the candidate
2842/// set. If OnlyViable is true, only viable candidates will be printed.
2843void
2844Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
2845 bool OnlyViable)
2846{
2847 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
2848 LastCand = CandidateSet.end();
2849 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002850 if (Cand->Viable || !OnlyViable) {
2851 if (Cand->Function) {
2852 // Normal function
2853 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002854 } else if (Cand->IsSurrogate) {
Douglas Gregor621b3932008-11-21 02:54:28 +00002855 // Desugar the type of the surrogate down to a function type,
2856 // retaining as many typedefs as possible while still showing
2857 // the function type (and, therefore, its parameter types).
2858 QualType FnType = Cand->Surrogate->getConversionType();
2859 bool isReference = false;
2860 bool isPointer = false;
2861 if (const ReferenceType *FnTypeRef = FnType->getAsReferenceType()) {
2862 FnType = FnTypeRef->getPointeeType();
2863 isReference = true;
2864 }
2865 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
2866 FnType = FnTypePtr->getPointeeType();
2867 isPointer = true;
2868 }
2869 // Desugar down to a function type.
2870 FnType = QualType(FnType->getAsFunctionType(), 0);
2871 // Reconstruct the pointer/reference as appropriate.
2872 if (isPointer) FnType = Context.getPointerType(FnType);
2873 if (isReference) FnType = Context.getReferenceType(FnType);
2874
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002875 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattnerd1625842008-11-24 06:25:27 +00002876 << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002877 } else {
2878 // FIXME: We need to get the identifier in here
2879 // FIXME: Do we want the error message to point at the
2880 // operator? (built-ins won't have a location)
2881 QualType FnType
2882 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
2883 Cand->BuiltinTypes.ParamTypes,
2884 Cand->Conversions.size(),
2885 false, 0);
2886
Chris Lattnerd1625842008-11-24 06:25:27 +00002887 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002888 }
2889 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002890 }
2891}
2892
Douglas Gregor904eed32008-11-10 20:40:00 +00002893/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
2894/// an overloaded function (C++ [over.over]), where @p From is an
2895/// expression with overloaded function type and @p ToType is the type
2896/// we're trying to resolve to. For example:
2897///
2898/// @code
2899/// int f(double);
2900/// int f(int);
2901///
2902/// int (*pfd)(double) = f; // selects f(double)
2903/// @endcode
2904///
2905/// This routine returns the resulting FunctionDecl if it could be
2906/// resolved, and NULL otherwise. When @p Complain is true, this
2907/// routine will emit diagnostics if there is an error.
2908FunctionDecl *
2909Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
2910 bool Complain) {
2911 QualType FunctionType = ToType;
2912 if (const PointerLikeType *ToTypePtr = ToType->getAsPointerLikeType())
2913 FunctionType = ToTypePtr->getPointeeType();
2914
2915 // We only look at pointers or references to functions.
2916 if (!FunctionType->isFunctionType())
2917 return 0;
2918
2919 // Find the actual overloaded function declaration.
2920 OverloadedFunctionDecl *Ovl = 0;
2921
2922 // C++ [over.over]p1:
2923 // [...] [Note: any redundant set of parentheses surrounding the
2924 // overloaded function name is ignored (5.1). ]
2925 Expr *OvlExpr = From->IgnoreParens();
2926
2927 // C++ [over.over]p1:
2928 // [...] The overloaded function name can be preceded by the &
2929 // operator.
2930 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
2931 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2932 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
2933 }
2934
2935 // Try to dig out the overloaded function.
2936 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
2937 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
2938
2939 // If there's no overloaded function declaration, we're done.
2940 if (!Ovl)
2941 return 0;
2942
2943 // Look through all of the overloaded functions, searching for one
2944 // whose type matches exactly.
2945 // FIXME: When templates or using declarations come along, we'll actually
2946 // have to deal with duplicates, partial ordering, etc. For now, we
2947 // can just do a simple search.
2948 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
2949 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
2950 Fun != Ovl->function_end(); ++Fun) {
2951 // C++ [over.over]p3:
2952 // Non-member functions and static member functions match
2953 // targets of type “pointer-to-function”or
2954 // “reference-to-function.”
2955 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun))
2956 if (!Method->isStatic())
2957 continue;
2958
2959 if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
2960 return *Fun;
2961 }
2962
2963 return 0;
2964}
2965
Douglas Gregorf9eb9052008-11-19 21:05:33 +00002966/// BuildCallToObjectOfClassType - Build a call to an object of class
2967/// type (C++ [over.call.object]), which can end up invoking an
2968/// overloaded function call operator (@c operator()) or performing a
2969/// user-defined conversion on the object argument.
2970Action::ExprResult
2971Sema::BuildCallToObjectOfClassType(Expr *Object, SourceLocation LParenLoc,
2972 Expr **Args, unsigned NumArgs,
2973 SourceLocation *CommaLocs,
2974 SourceLocation RParenLoc) {
2975 assert(Object->getType()->isRecordType() && "Requires object type argument");
2976 const RecordType *Record = Object->getType()->getAsRecordType();
2977
2978 // C++ [over.call.object]p1:
2979 // If the primary-expression E in the function call syntax
2980 // evaluates to a class object of type “cv T”, then the set of
2981 // candidate functions includes at least the function call
2982 // operators of T. The function call operators of T are obtained by
2983 // ordinary lookup of the name operator() in the context of
2984 // (E).operator().
2985 OverloadCandidateSet CandidateSet;
2986 IdentifierResolver::iterator I
2987 = IdResolver.begin(Context.DeclarationNames.getCXXOperatorName(OO_Call),
2988 cast<CXXRecordType>(Record)->getDecl(),
2989 /*LookInParentCtx=*/false);
2990 NamedDecl *MemberOps = (I == IdResolver.end())? 0 : *I;
2991 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps))
2992 AddMethodCandidate(Method, Object, Args, NumArgs, CandidateSet,
2993 /*SuppressUserConversions=*/false);
2994 else if (OverloadedFunctionDecl *Ovl
2995 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) {
2996 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
2997 FEnd = Ovl->function_end();
2998 F != FEnd; ++F) {
2999 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F))
3000 AddMethodCandidate(Method, Object, Args, NumArgs, CandidateSet,
3001 /*SuppressUserConversions=*/false);
3002 }
3003 }
3004
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003005 // C++ [over.call.object]p2:
3006 // In addition, for each conversion function declared in T of the
3007 // form
3008 //
3009 // operator conversion-type-id () cv-qualifier;
3010 //
3011 // where cv-qualifier is the same cv-qualification as, or a
3012 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00003013 // denotes the type "pointer to function of (P1,...,Pn) returning
3014 // R", or the type "reference to pointer to function of
3015 // (P1,...,Pn) returning R", or the type "reference to function
3016 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003017 // is also considered as a candidate function. Similarly,
3018 // surrogate call functions are added to the set of candidate
3019 // functions for each conversion function declared in an
3020 // accessible base class provided the function is not hidden
3021 // within T by another intervening declaration.
3022 //
3023 // FIXME: Look in base classes for more conversion operators!
3024 OverloadedFunctionDecl *Conversions
3025 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor621b3932008-11-21 02:54:28 +00003026 for (OverloadedFunctionDecl::function_iterator
3027 Func = Conversions->function_begin(),
3028 FuncEnd = Conversions->function_end();
3029 Func != FuncEnd; ++Func) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003030 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
3031
3032 // Strip the reference type (if any) and then the pointer type (if
3033 // any) to get down to what might be a function type.
3034 QualType ConvType = Conv->getConversionType().getNonReferenceType();
3035 if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
3036 ConvType = ConvPtrType->getPointeeType();
3037
3038 if (const FunctionTypeProto *Proto = ConvType->getAsFunctionTypeProto())
3039 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
3040 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003041
3042 // Perform overload resolution.
3043 OverloadCandidateSet::iterator Best;
3044 switch (BestViableFunction(CandidateSet, Best)) {
3045 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003046 // Overload resolution succeeded; we'll build the appropriate call
3047 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003048 break;
3049
3050 case OR_No_Viable_Function:
Sebastian Redle4c452c2008-11-22 13:44:36 +00003051 Diag(Object->getSourceRange().getBegin(),
3052 diag::err_ovl_no_viable_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00003053 << Object->getType() << (unsigned)CandidateSet.size()
Sebastian Redle4c452c2008-11-22 13:44:36 +00003054 << Object->getSourceRange();
3055 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003056 break;
3057
3058 case OR_Ambiguous:
3059 Diag(Object->getSourceRange().getBegin(),
3060 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00003061 << Object->getType() << Object->getSourceRange();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003062 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3063 break;
3064 }
3065
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003066 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003067 // We had an error; delete all of the subexpressions and return
3068 // the error.
3069 delete Object;
3070 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3071 delete Args[ArgIdx];
3072 return true;
3073 }
3074
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003075 if (Best->Function == 0) {
3076 // Since there is no function declaration, this is one of the
3077 // surrogate candidates. Dig out the conversion function.
3078 CXXConversionDecl *Conv
3079 = cast<CXXConversionDecl>(
3080 Best->Conversions[0].UserDefined.ConversionFunction);
3081
3082 // We selected one of the surrogate functions that converts the
3083 // object parameter to a function pointer. Perform the conversion
3084 // on the object argument, then let ActOnCallExpr finish the job.
3085 // FIXME: Represent the user-defined conversion in the AST!
3086 ImpCastExprToType(Object,
3087 Conv->getConversionType().getNonReferenceType(),
3088 Conv->getConversionType()->isReferenceType());
3089 return ActOnCallExpr((ExprTy*)Object, LParenLoc, (ExprTy**)Args, NumArgs,
3090 CommaLocs, RParenLoc);
3091 }
3092
3093 // We found an overloaded operator(). Build a CXXOperatorCallExpr
3094 // that calls this method, using Object for the implicit object
3095 // parameter and passing along the remaining arguments.
3096 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003097 const FunctionTypeProto *Proto = Method->getType()->getAsFunctionTypeProto();
3098
3099 unsigned NumArgsInProto = Proto->getNumArgs();
3100 unsigned NumArgsToCheck = NumArgs;
3101
3102 // Build the full argument list for the method call (the
3103 // implicit object parameter is placed at the beginning of the
3104 // list).
3105 Expr **MethodArgs;
3106 if (NumArgs < NumArgsInProto) {
3107 NumArgsToCheck = NumArgsInProto;
3108 MethodArgs = new Expr*[NumArgsInProto + 1];
3109 } else {
3110 MethodArgs = new Expr*[NumArgs + 1];
3111 }
3112 MethodArgs[0] = Object;
3113 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3114 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
3115
3116 Expr *NewFn = new DeclRefExpr(Method, Method->getType(),
3117 SourceLocation());
3118 UsualUnaryConversions(NewFn);
3119
3120 // Once we've built TheCall, all of the expressions are properly
3121 // owned.
3122 QualType ResultTy = Method->getResultType().getNonReferenceType();
3123 llvm::OwningPtr<CXXOperatorCallExpr>
3124 TheCall(new CXXOperatorCallExpr(NewFn, MethodArgs, NumArgs + 1,
3125 ResultTy, RParenLoc));
3126 delete [] MethodArgs;
3127
3128 // Initialize the implicit object parameter.
3129 if (!PerformObjectArgumentInitialization(Object, Method))
3130 return true;
3131 TheCall->setArg(0, Object);
3132
3133 // Check the argument types.
3134 for (unsigned i = 0; i != NumArgsToCheck; i++) {
3135 QualType ProtoArgType = Proto->getArgType(i);
3136
3137 Expr *Arg;
3138 if (i < NumArgs)
3139 Arg = Args[i];
3140 else
3141 Arg = new CXXDefaultArgExpr(Method->getParamDecl(i));
3142 QualType ArgType = Arg->getType();
3143
3144 // Pass the argument.
3145 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3146 return true;
3147
3148 TheCall->setArg(i + 1, Arg);
3149 }
3150
3151 // If this is a variadic call, handle args passed through "...".
3152 if (Proto->isVariadic()) {
3153 // Promote the arguments (C99 6.5.2.2p7).
3154 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3155 Expr *Arg = Args[i];
3156 DefaultArgumentPromotion(Arg);
3157 TheCall->setArg(i + 1, Arg);
3158 }
3159 }
3160
3161 return CheckFunctionCall(Method, TheCall.take());
3162}
3163
Douglas Gregor8ba10742008-11-20 16:27:02 +00003164/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
3165/// (if one exists), where @c Base is an expression of class type and
3166/// @c Member is the name of the member we're trying to find.
3167Action::ExprResult
3168Sema::BuildOverloadedArrowExpr(Expr *Base, SourceLocation OpLoc,
3169 SourceLocation MemberLoc,
3170 IdentifierInfo &Member) {
3171 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
3172
3173 // C++ [over.ref]p1:
3174 //
3175 // [...] An expression x->m is interpreted as (x.operator->())->m
3176 // for a class object x of type T if T::operator->() exists and if
3177 // the operator is selected as the best match function by the
3178 // overload resolution mechanism (13.3).
3179 // FIXME: look in base classes.
3180 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
3181 OverloadCandidateSet CandidateSet;
3182 const RecordType *BaseRecord = Base->getType()->getAsRecordType();
3183 IdentifierResolver::iterator I
3184 = IdResolver.begin(OpName, cast<CXXRecordType>(BaseRecord)->getDecl(),
3185 /*LookInParentCtx=*/false);
3186 NamedDecl *MemberOps = (I == IdResolver.end())? 0 : *I;
3187 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps))
3188 AddMethodCandidate(Method, Base, 0, 0, CandidateSet,
3189 /*SuppressUserConversions=*/false);
3190 else if (OverloadedFunctionDecl *Ovl
3191 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) {
3192 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
3193 FEnd = Ovl->function_end();
3194 F != FEnd; ++F) {
3195 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F))
3196 AddMethodCandidate(Method, Base, 0, 0, CandidateSet,
3197 /*SuppressUserConversions=*/false);
3198 }
3199 }
3200
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003201 llvm::OwningPtr<Expr> BasePtr(Base);
3202
Douglas Gregor8ba10742008-11-20 16:27:02 +00003203 // Perform overload resolution.
3204 OverloadCandidateSet::iterator Best;
3205 switch (BestViableFunction(CandidateSet, Best)) {
3206 case OR_Success:
3207 // Overload resolution succeeded; we'll build the call below.
3208 break;
3209
3210 case OR_No_Viable_Function:
3211 if (CandidateSet.empty())
3212 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattnerd1625842008-11-24 06:25:27 +00003213 << BasePtr->getType() << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003214 else
3215 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Sebastian Redle4c452c2008-11-22 13:44:36 +00003216 << "operator->" << (unsigned)CandidateSet.size()
3217 << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003218 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003219 return true;
3220
3221 case OR_Ambiguous:
3222 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Chris Lattnerd1625842008-11-24 06:25:27 +00003223 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003224 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003225 return true;
3226 }
3227
3228 // Convert the object parameter.
3229 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003230 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregor8ba10742008-11-20 16:27:02 +00003231 return true;
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003232
3233 // No concerns about early exits now.
3234 BasePtr.take();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003235
3236 // Build the operator call.
3237 Expr *FnExpr = new DeclRefExpr(Method, Method->getType(), SourceLocation());
3238 UsualUnaryConversions(FnExpr);
3239 Base = new CXXOperatorCallExpr(FnExpr, &Base, 1,
3240 Method->getResultType().getNonReferenceType(),
3241 OpLoc);
3242 return ActOnMemberReferenceExpr(Base, OpLoc, tok::arrow, MemberLoc, Member);
3243}
3244
Douglas Gregor904eed32008-11-10 20:40:00 +00003245/// FixOverloadedFunctionReference - E is an expression that refers to
3246/// a C++ overloaded function (possibly with some parentheses and
3247/// perhaps a '&' around it). We have resolved the overloaded function
3248/// to the function declaration Fn, so patch up the expression E to
3249/// refer (possibly indirectly) to Fn.
3250void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
3251 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
3252 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
3253 E->setType(PE->getSubExpr()->getType());
3254 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
3255 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
3256 "Can only take the address of an overloaded function");
3257 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
3258 E->setType(Context.getPointerType(E->getType()));
3259 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
3260 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
3261 "Expected overloaded function");
3262 DR->setDecl(Fn);
3263 E->setType(Fn->getType());
3264 } else {
3265 assert(false && "Invalid reference to overloaded function");
3266 }
3267}
3268
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003269} // end namespace clang