blob: 749b916e0d62af8fb98900ff13285795a38d620e [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 Gregoreb8f3062008-11-12 17:17:38 +000020#include "clang/AST/TypeOrdering.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000021#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000022#include "llvm/Support/Compiler.h"
23#include <algorithm>
24
25namespace clang {
26
27/// GetConversionCategory - Retrieve the implicit conversion
28/// category corresponding to the given implicit conversion kind.
29ImplicitConversionCategory
30GetConversionCategory(ImplicitConversionKind Kind) {
31 static const ImplicitConversionCategory
32 Category[(int)ICK_Num_Conversion_Kinds] = {
33 ICC_Identity,
34 ICC_Lvalue_Transformation,
35 ICC_Lvalue_Transformation,
36 ICC_Lvalue_Transformation,
37 ICC_Qualification_Adjustment,
38 ICC_Promotion,
39 ICC_Promotion,
40 ICC_Conversion,
41 ICC_Conversion,
42 ICC_Conversion,
43 ICC_Conversion,
44 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000045 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000046 ICC_Conversion
47 };
48 return Category[(int)Kind];
49}
50
51/// GetConversionRank - Retrieve the implicit conversion rank
52/// corresponding to the given implicit conversion kind.
53ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
54 static const ImplicitConversionRank
55 Rank[(int)ICK_Num_Conversion_Kinds] = {
56 ICR_Exact_Match,
57 ICR_Exact_Match,
58 ICR_Exact_Match,
59 ICR_Exact_Match,
60 ICR_Exact_Match,
61 ICR_Promotion,
62 ICR_Promotion,
63 ICR_Conversion,
64 ICR_Conversion,
65 ICR_Conversion,
66 ICR_Conversion,
67 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000068 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000069 ICR_Conversion
70 };
71 return Rank[(int)Kind];
72}
73
74/// GetImplicitConversionName - Return the name of this kind of
75/// implicit conversion.
76const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
77 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
78 "No conversion",
79 "Lvalue-to-rvalue",
80 "Array-to-pointer",
81 "Function-to-pointer",
82 "Qualification",
83 "Integral promotion",
84 "Floating point promotion",
85 "Integral conversion",
86 "Floating conversion",
87 "Floating-integral conversion",
88 "Pointer conversion",
89 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +000090 "Boolean conversion",
91 "Derived-to-base conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000092 };
93 return Name[Kind];
94}
95
Douglas Gregor60d62c22008-10-31 16:23:19 +000096/// StandardConversionSequence - Set the standard conversion
97/// sequence to the identity conversion.
98void StandardConversionSequence::setAsIdentityConversion() {
99 First = ICK_Identity;
100 Second = ICK_Identity;
101 Third = ICK_Identity;
102 Deprecated = false;
103 ReferenceBinding = false;
104 DirectBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000105 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000106}
107
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000108/// getRank - Retrieve the rank of this standard conversion sequence
109/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
110/// implicit conversions.
111ImplicitConversionRank StandardConversionSequence::getRank() const {
112 ImplicitConversionRank Rank = ICR_Exact_Match;
113 if (GetConversionRank(First) > Rank)
114 Rank = GetConversionRank(First);
115 if (GetConversionRank(Second) > Rank)
116 Rank = GetConversionRank(Second);
117 if (GetConversionRank(Third) > Rank)
118 Rank = GetConversionRank(Third);
119 return Rank;
120}
121
122/// isPointerConversionToBool - Determines whether this conversion is
123/// a conversion of a pointer or pointer-to-member to bool. This is
124/// used as part of the ranking of standard conversion sequences
125/// (C++ 13.3.3.2p4).
126bool StandardConversionSequence::isPointerConversionToBool() const
127{
128 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
129 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
130
131 // Note that FromType has not necessarily been transformed by the
132 // array-to-pointer or function-to-pointer implicit conversions, so
133 // check for their presence as well as checking whether FromType is
134 // a pointer.
135 if (ToType->isBooleanType() &&
136 (FromType->isPointerType() ||
137 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
138 return true;
139
140 return false;
141}
142
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000143/// isPointerConversionToVoidPointer - Determines whether this
144/// conversion is a conversion of a pointer to a void pointer. This is
145/// used as part of the ranking of standard conversion sequences (C++
146/// 13.3.3.2p4).
147bool
148StandardConversionSequence::
149isPointerConversionToVoidPointer(ASTContext& Context) const
150{
151 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
152 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
153
154 // Note that FromType has not necessarily been transformed by the
155 // array-to-pointer implicit conversion, so check for its presence
156 // and redo the conversion to get a pointer.
157 if (First == ICK_Array_To_Pointer)
158 FromType = Context.getArrayDecayedType(FromType);
159
160 if (Second == ICK_Pointer_Conversion)
161 if (const PointerType* ToPtrType = ToType->getAsPointerType())
162 return ToPtrType->getPointeeType()->isVoidType();
163
164 return false;
165}
166
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000167/// DebugPrint - Print this standard conversion sequence to standard
168/// error. Useful for debugging overloading issues.
169void StandardConversionSequence::DebugPrint() const {
170 bool PrintedSomething = false;
171 if (First != ICK_Identity) {
172 fprintf(stderr, "%s", GetImplicitConversionName(First));
173 PrintedSomething = true;
174 }
175
176 if (Second != ICK_Identity) {
177 if (PrintedSomething) {
178 fprintf(stderr, " -> ");
179 }
180 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregor225c41e2008-11-03 19:09:14 +0000181
182 if (CopyConstructor) {
183 fprintf(stderr, " (by copy constructor)");
184 } else if (DirectBinding) {
185 fprintf(stderr, " (direct reference binding)");
186 } else if (ReferenceBinding) {
187 fprintf(stderr, " (reference binding)");
188 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000189 PrintedSomething = true;
190 }
191
192 if (Third != ICK_Identity) {
193 if (PrintedSomething) {
194 fprintf(stderr, " -> ");
195 }
196 fprintf(stderr, "%s", GetImplicitConversionName(Third));
197 PrintedSomething = true;
198 }
199
200 if (!PrintedSomething) {
201 fprintf(stderr, "No conversions required");
202 }
203}
204
205/// DebugPrint - Print this user-defined conversion sequence to standard
206/// error. Useful for debugging overloading issues.
207void UserDefinedConversionSequence::DebugPrint() const {
208 if (Before.First || Before.Second || Before.Third) {
209 Before.DebugPrint();
210 fprintf(stderr, " -> ");
211 }
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000212 fprintf(stderr, "'%s'", ConversionFunction->getName().c_str());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000213 if (After.First || After.Second || After.Third) {
214 fprintf(stderr, " -> ");
215 After.DebugPrint();
216 }
217}
218
219/// DebugPrint - Print this implicit conversion sequence to standard
220/// error. Useful for debugging overloading issues.
221void ImplicitConversionSequence::DebugPrint() const {
222 switch (ConversionKind) {
223 case StandardConversion:
224 fprintf(stderr, "Standard conversion: ");
225 Standard.DebugPrint();
226 break;
227 case UserDefinedConversion:
228 fprintf(stderr, "User-defined conversion: ");
229 UserDefined.DebugPrint();
230 break;
231 case EllipsisConversion:
232 fprintf(stderr, "Ellipsis conversion");
233 break;
234 case BadConversion:
235 fprintf(stderr, "Bad conversion");
236 break;
237 }
238
239 fprintf(stderr, "\n");
240}
241
242// IsOverload - Determine whether the given New declaration is an
243// overload of the Old declaration. This routine returns false if New
244// and Old cannot be overloaded, e.g., if they are functions with the
245// same signature (C++ 1.3.10) or if the Old declaration isn't a
246// function (or overload set). When it does return false and Old is an
247// OverloadedFunctionDecl, MatchedDecl will be set to point to the
248// FunctionDecl that New cannot be overloaded with.
249//
250// Example: Given the following input:
251//
252// void f(int, float); // #1
253// void f(int, int); // #2
254// int f(int, int); // #3
255//
256// When we process #1, there is no previous declaration of "f",
257// so IsOverload will not be used.
258//
259// When we process #2, Old is a FunctionDecl for #1. By comparing the
260// parameter types, we see that #1 and #2 are overloaded (since they
261// have different signatures), so this routine returns false;
262// MatchedDecl is unchanged.
263//
264// When we process #3, Old is an OverloadedFunctionDecl containing #1
265// and #2. We compare the signatures of #3 to #1 (they're overloaded,
266// so we do nothing) and then #3 to #2. Since the signatures of #3 and
267// #2 are identical (return types of functions are not part of the
268// signature), IsOverload returns false and MatchedDecl will be set to
269// point to the FunctionDecl for #2.
270bool
271Sema::IsOverload(FunctionDecl *New, Decl* OldD,
272 OverloadedFunctionDecl::function_iterator& MatchedDecl)
273{
274 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
275 // Is this new function an overload of every function in the
276 // overload set?
277 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
278 FuncEnd = Ovl->function_end();
279 for (; Func != FuncEnd; ++Func) {
280 if (!IsOverload(New, *Func, MatchedDecl)) {
281 MatchedDecl = Func;
282 return false;
283 }
284 }
285
286 // This function overloads every function in the overload set.
287 return true;
288 } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
289 // Is the function New an overload of the function Old?
290 QualType OldQType = Context.getCanonicalType(Old->getType());
291 QualType NewQType = Context.getCanonicalType(New->getType());
292
293 // Compare the signatures (C++ 1.3.10) of the two functions to
294 // determine whether they are overloads. If we find any mismatch
295 // in the signature, they are overloads.
296
297 // If either of these functions is a K&R-style function (no
298 // prototype), then we consider them to have matching signatures.
299 if (isa<FunctionTypeNoProto>(OldQType.getTypePtr()) ||
300 isa<FunctionTypeNoProto>(NewQType.getTypePtr()))
301 return false;
302
303 FunctionTypeProto* OldType = cast<FunctionTypeProto>(OldQType.getTypePtr());
304 FunctionTypeProto* NewType = cast<FunctionTypeProto>(NewQType.getTypePtr());
305
306 // The signature of a function includes the types of its
307 // parameters (C++ 1.3.10), which includes the presence or absence
308 // of the ellipsis; see C++ DR 357).
309 if (OldQType != NewQType &&
310 (OldType->getNumArgs() != NewType->getNumArgs() ||
311 OldType->isVariadic() != NewType->isVariadic() ||
312 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
313 NewType->arg_type_begin())))
314 return true;
315
316 // If the function is a class member, its signature includes the
317 // cv-qualifiers (if any) on the function itself.
318 //
319 // As part of this, also check whether one of the member functions
320 // is static, in which case they are not overloads (C++
321 // 13.1p2). While not part of the definition of the signature,
322 // this check is important to determine whether these functions
323 // can be overloaded.
324 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
325 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
326 if (OldMethod && NewMethod &&
327 !OldMethod->isStatic() && !NewMethod->isStatic() &&
328 OldQType.getCVRQualifiers() != NewQType.getCVRQualifiers())
329 return true;
330
331 // The signatures match; this is not an overload.
332 return false;
333 } else {
334 // (C++ 13p1):
335 // Only function declarations can be overloaded; object and type
336 // declarations cannot be overloaded.
337 return false;
338 }
339}
340
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000341/// TryImplicitConversion - Attempt to perform an implicit conversion
342/// from the given expression (Expr) to the given type (ToType). This
343/// function returns an implicit conversion sequence that can be used
344/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000345///
346/// void f(float f);
347/// void g(int i) { f(i); }
348///
349/// this routine would produce an implicit conversion sequence to
350/// describe the initialization of f from i, which will be a standard
351/// conversion sequence containing an lvalue-to-rvalue conversion (C++
352/// 4.1) followed by a floating-integral conversion (C++ 4.9).
353//
354/// Note that this routine only determines how the conversion can be
355/// performed; it does not actually perform the conversion. As such,
356/// it will not produce any diagnostics if no conversion is available,
357/// but will instead return an implicit conversion sequence of kind
358/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000359///
360/// If @p SuppressUserConversions, then user-defined conversions are
361/// not permitted.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000362ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +0000363Sema::TryImplicitConversion(Expr* From, QualType ToType,
364 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000365{
366 ImplicitConversionSequence ICS;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000367 if (IsStandardConversion(From, ToType, ICS.Standard))
368 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000369 else if (!SuppressUserConversions &&
370 IsUserDefinedConversion(From, ToType, ICS.UserDefined)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000371 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000372 // C++ [over.ics.user]p4:
373 // A conversion of an expression of class type to the same class
374 // type is given Exact Match rank, and a conversion of an
375 // expression of class type to a base class of that type is
376 // given Conversion rank, in spite of the fact that a copy
377 // constructor (i.e., a user-defined conversion function) is
378 // called for those cases.
379 if (CXXConstructorDecl *Constructor
380 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
381 if (Constructor->isCopyConstructor(Context)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000382 // Turn this into a "standard" conversion sequence, so that it
383 // gets ranked with standard conversion sequences.
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000384 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
385 ICS.Standard.setAsIdentityConversion();
386 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
387 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000388 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000389 if (IsDerivedFrom(From->getType().getUnqualifiedType(),
390 ToType.getUnqualifiedType()))
391 ICS.Standard.Second = ICK_Derived_To_Base;
392 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000393 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000394 } else
Douglas Gregor60d62c22008-10-31 16:23:19 +0000395 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000396
397 return ICS;
398}
399
400/// IsStandardConversion - Determines whether there is a standard
401/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
402/// expression From to the type ToType. Standard conversion sequences
403/// only consider non-class types; for conversions that involve class
404/// types, use TryImplicitConversion. If a conversion exists, SCS will
405/// contain the standard conversion sequence required to perform this
406/// conversion and this routine will return true. Otherwise, this
407/// routine will return false and the value of SCS is unspecified.
408bool
409Sema::IsStandardConversion(Expr* From, QualType ToType,
410 StandardConversionSequence &SCS)
411{
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000412 QualType FromType = From->getType();
413
Douglas Gregor60d62c22008-10-31 16:23:19 +0000414 // There are no standard conversions for class types, so abort early.
415 if (FromType->isRecordType() || ToType->isRecordType())
416 return false;
417
418 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000419 SCS.setAsIdentityConversion();
Douglas Gregor60d62c22008-10-31 16:23:19 +0000420 SCS.Deprecated = false;
421 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000422 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000423
424 // The first conversion can be an lvalue-to-rvalue conversion,
425 // array-to-pointer conversion, or function-to-pointer conversion
426 // (C++ 4p1).
427
428 // Lvalue-to-rvalue conversion (C++ 4.1):
429 // An lvalue (3.10) of a non-function, non-array type T can be
430 // converted to an rvalue.
431 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
432 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000433 !FromType->isFunctionType() && !FromType->isArrayType() &&
434 !FromType->isOverloadType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000435 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000436
437 // If T is a non-class type, the type of the rvalue is the
438 // cv-unqualified version of T. Otherwise, the type of the rvalue
439 // is T (C++ 4.1p1).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000440 FromType = FromType.getUnqualifiedType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000441 }
442 // Array-to-pointer conversion (C++ 4.2)
443 else if (FromType->isArrayType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000444 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000445
446 // An lvalue or rvalue of type "array of N T" or "array of unknown
447 // bound of T" can be converted to an rvalue of type "pointer to
448 // T" (C++ 4.2p1).
449 FromType = Context.getArrayDecayedType(FromType);
450
451 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
452 // This conversion is deprecated. (C++ D.4).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000453 SCS.Deprecated = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000454
455 // For the purpose of ranking in overload resolution
456 // (13.3.3.1.1), this conversion is considered an
457 // array-to-pointer conversion followed by a qualification
458 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000459 SCS.Second = ICK_Identity;
460 SCS.Third = ICK_Qualification;
461 SCS.ToTypePtr = ToType.getAsOpaquePtr();
462 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000463 }
464 }
465 // Function-to-pointer conversion (C++ 4.3).
466 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000467 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000468
469 // An lvalue of function type T can be converted to an rvalue of
470 // type "pointer to T." The result is a pointer to the
471 // function. (C++ 4.3p1).
472 FromType = Context.getPointerType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000473 }
Douglas Gregor904eed32008-11-10 20:40:00 +0000474 // Address of overloaded function (C++ [over.over]).
475 else if (FunctionDecl *Fn
476 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
477 SCS.First = ICK_Function_To_Pointer;
478
479 // We were able to resolve the address of the overloaded function,
480 // so we can convert to the type of that function.
481 FromType = Fn->getType();
482 if (ToType->isReferenceType())
483 FromType = Context.getReferenceType(FromType);
484 else
485 FromType = Context.getPointerType(FromType);
486 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000487 // We don't require any conversions for the first step.
488 else {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000489 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000490 }
491
492 // The second conversion can be an integral promotion, floating
493 // point promotion, integral conversion, floating point conversion,
494 // floating-integral conversion, pointer conversion,
495 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
496 if (Context.getCanonicalType(FromType).getUnqualifiedType() ==
497 Context.getCanonicalType(ToType).getUnqualifiedType()) {
498 // The unqualified versions of the types are the same: there's no
499 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000500 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000501 }
502 // Integral promotion (C++ 4.5).
503 else if (IsIntegralPromotion(From, FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000504 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000505 FromType = ToType.getUnqualifiedType();
506 }
507 // Floating point promotion (C++ 4.6).
508 else if (IsFloatingPointPromotion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000509 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000510 FromType = ToType.getUnqualifiedType();
511 }
512 // Integral conversions (C++ 4.7).
Sebastian Redl07779722008-10-31 14:43:28 +0000513 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000514 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000515 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000516 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000517 FromType = ToType.getUnqualifiedType();
518 }
519 // Floating point conversions (C++ 4.8).
520 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000521 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000522 FromType = ToType.getUnqualifiedType();
523 }
524 // Floating-integral conversions (C++ 4.9).
Sebastian Redl07779722008-10-31 14:43:28 +0000525 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000526 else if ((FromType->isFloatingType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000527 ToType->isIntegralType() && !ToType->isBooleanType() &&
528 !ToType->isEnumeralType()) ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000529 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
530 ToType->isFloatingType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000531 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000532 FromType = ToType.getUnqualifiedType();
533 }
534 // Pointer conversions (C++ 4.10).
Sebastian Redl07779722008-10-31 14:43:28 +0000535 else if (IsPointerConversion(From, FromType, ToType, FromType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000536 SCS.Second = ICK_Pointer_Conversion;
Sebastian Redl07779722008-10-31 14:43:28 +0000537 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000538 // FIXME: Pointer to member conversions (4.11).
539 // Boolean conversions (C++ 4.12).
540 // FIXME: pointer-to-member type
541 else if (ToType->isBooleanType() &&
542 (FromType->isArithmeticType() ||
543 FromType->isEnumeralType() ||
544 FromType->isPointerType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000545 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000546 FromType = Context.BoolTy;
547 } else {
548 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000549 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000550 }
551
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000552 QualType CanonFrom;
553 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000554 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000555 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000556 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000557 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000558 CanonFrom = Context.getCanonicalType(FromType);
559 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000560 } else {
561 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000562 SCS.Third = ICK_Identity;
563
564 // C++ [over.best.ics]p6:
565 // [...] Any difference in top-level cv-qualification is
566 // subsumed by the initialization itself and does not constitute
567 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000568 CanonFrom = Context.getCanonicalType(FromType);
569 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000570 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000571 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
572 FromType = ToType;
573 CanonFrom = CanonTo;
574 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000575 }
576
577 // If we have not converted the argument type to the parameter type,
578 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000579 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000580 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000581
Douglas Gregor60d62c22008-10-31 16:23:19 +0000582 SCS.ToTypePtr = FromType.getAsOpaquePtr();
583 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000584}
585
586/// IsIntegralPromotion - Determines whether the conversion from the
587/// expression From (whose potentially-adjusted type is FromType) to
588/// ToType is an integral promotion (C++ 4.5). If so, returns true and
589/// sets PromotedType to the promoted type.
590bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
591{
592 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000593 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000594 if (!To) {
595 return false;
596 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000597
598 // An rvalue of type char, signed char, unsigned char, short int, or
599 // unsigned short int can be converted to an rvalue of type int if
600 // int can represent all the values of the source type; otherwise,
601 // the source rvalue can be converted to an rvalue of type unsigned
602 // int (C++ 4.5p1).
Sebastian Redl07779722008-10-31 14:43:28 +0000603 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000604 if (// We can promote any signed, promotable integer type to an int
605 (FromType->isSignedIntegerType() ||
606 // We can promote any unsigned integer type whose size is
607 // less than int to an int.
608 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000609 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000610 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000611 }
612
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000613 return To->getKind() == BuiltinType::UInt;
614 }
615
616 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
617 // can be converted to an rvalue of the first of the following types
618 // that can represent all the values of its underlying type: int,
619 // unsigned int, long, or unsigned long (C++ 4.5p2).
620 if ((FromType->isEnumeralType() || FromType->isWideCharType())
621 && ToType->isIntegerType()) {
622 // Determine whether the type we're converting from is signed or
623 // unsigned.
624 bool FromIsSigned;
625 uint64_t FromSize = Context.getTypeSize(FromType);
626 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
627 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
628 FromIsSigned = UnderlyingType->isSignedIntegerType();
629 } else {
630 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
631 FromIsSigned = true;
632 }
633
634 // The types we'll try to promote to, in the appropriate
635 // order. Try each of these types.
636 QualType PromoteTypes[4] = {
637 Context.IntTy, Context.UnsignedIntTy,
638 Context.LongTy, Context.UnsignedLongTy
639 };
640 for (int Idx = 0; Idx < 0; ++Idx) {
641 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
642 if (FromSize < ToSize ||
643 (FromSize == ToSize &&
644 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
645 // We found the type that we can promote to. If this is the
646 // type we wanted, we have a promotion. Otherwise, no
647 // promotion.
Sebastian Redl07779722008-10-31 14:43:28 +0000648 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000649 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
650 }
651 }
652 }
653
654 // An rvalue for an integral bit-field (9.6) can be converted to an
655 // rvalue of type int if int can represent all the values of the
656 // bit-field; otherwise, it can be converted to unsigned int if
657 // unsigned int can represent all the values of the bit-field. If
658 // the bit-field is larger yet, no integral promotion applies to
659 // it. If the bit-field has an enumerated type, it is treated as any
660 // other value of that type for promotion purposes (C++ 4.5p3).
661 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) {
662 using llvm::APSInt;
663 FieldDecl *MemberDecl = MemRef->getMemberDecl();
664 APSInt BitWidth;
665 if (MemberDecl->isBitField() &&
666 FromType->isIntegralType() && !FromType->isEnumeralType() &&
667 From->isIntegerConstantExpr(BitWidth, Context)) {
668 APSInt ToSize(Context.getTypeSize(ToType));
669
670 // Are we promoting to an int from a bitfield that fits in an int?
671 if (BitWidth < ToSize ||
Sebastian Redl07779722008-10-31 14:43:28 +0000672 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000673 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000674 }
675
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000676 // Are we promoting to an unsigned int from an unsigned bitfield
677 // that fits into an unsigned int?
Sebastian Redl07779722008-10-31 14:43:28 +0000678 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000679 return To->getKind() == BuiltinType::UInt;
Sebastian Redl07779722008-10-31 14:43:28 +0000680 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000681
682 return false;
683 }
684 }
685
686 // An rvalue of type bool can be converted to an rvalue of type int,
687 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000688 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000689 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000690 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000691
692 return false;
693}
694
695/// IsFloatingPointPromotion - Determines whether the conversion from
696/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
697/// returns true and sets PromotedType to the promoted type.
698bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
699{
700 /// An rvalue of type float can be converted to an rvalue of type
701 /// double. (C++ 4.6p1).
702 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
703 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType())
704 if (FromBuiltin->getKind() == BuiltinType::Float &&
705 ToBuiltin->getKind() == BuiltinType::Double)
706 return true;
707
708 return false;
709}
710
711/// IsPointerConversion - Determines whether the conversion of the
712/// expression From, which has the (possibly adjusted) type FromType,
713/// can be converted to the type ToType via a pointer conversion (C++
714/// 4.10). If so, returns true and places the converted type (that
715/// might differ from ToType in its cv-qualifiers at some level) into
716/// ConvertedType.
717bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
718 QualType& ConvertedType)
719{
720 const PointerType* ToTypePtr = ToType->getAsPointerType();
721 if (!ToTypePtr)
722 return false;
723
724 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
725 if (From->isNullPointerConstant(Context)) {
726 ConvertedType = ToType;
727 return true;
728 }
Sebastian Redl07779722008-10-31 14:43:28 +0000729
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000730 // An rvalue of type "pointer to cv T," where T is an object type,
731 // can be converted to an rvalue of type "pointer to cv void" (C++
732 // 4.10p2).
733 if (FromType->isPointerType() &&
734 FromType->getAsPointerType()->getPointeeType()->isObjectType() &&
735 ToTypePtr->getPointeeType()->isVoidType()) {
736 // We need to produce a pointer to cv void, where cv is the same
737 // set of cv-qualifiers as we had on the incoming pointee type.
738 QualType toPointee = ToTypePtr->getPointeeType();
739 unsigned Quals = Context.getCanonicalType(FromType)->getAsPointerType()
740 ->getPointeeType().getCVRQualifiers();
741
742 if (Context.getCanonicalType(ToTypePtr->getPointeeType()).getCVRQualifiers()
743 == Quals) {
744 // ToType is exactly the type we want. Use it.
745 ConvertedType = ToType;
746 } else {
747 // Build a new type with the right qualifiers.
748 ConvertedType
749 = Context.getPointerType(Context.VoidTy.getQualifiedType(Quals));
750 }
751 return true;
752 }
753
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000754 // C++ [conv.ptr]p3:
755 //
756 // An rvalue of type "pointer to cv D," where D is a class type,
757 // can be converted to an rvalue of type "pointer to cv B," where
758 // B is a base class (clause 10) of D. If B is an inaccessible
759 // (clause 11) or ambiguous (10.2) base class of D, a program that
760 // necessitates this conversion is ill-formed. The result of the
761 // conversion is a pointer to the base class sub-object of the
762 // derived class object. The null pointer value is converted to
763 // the null pointer value of the destination type.
764 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000765 // Note that we do not check for ambiguity or inaccessibility
766 // here. That is handled by CheckPointerConversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000767 if (const PointerType *FromPtrType = FromType->getAsPointerType())
768 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
769 if (FromPtrType->getPointeeType()->isRecordType() &&
770 ToPtrType->getPointeeType()->isRecordType() &&
771 IsDerivedFrom(FromPtrType->getPointeeType(),
772 ToPtrType->getPointeeType())) {
773 // The conversion is okay. Now, we need to produce the type
774 // that results from this conversion, which will have the same
775 // qualifiers as the incoming type.
776 QualType CanonFromPointee
777 = Context.getCanonicalType(FromPtrType->getPointeeType());
778 QualType ToPointee = ToPtrType->getPointeeType();
779 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
780 unsigned Quals = CanonFromPointee.getCVRQualifiers();
781
782 if (CanonToPointee.getCVRQualifiers() == Quals) {
783 // ToType is exactly the type we want. Use it.
784 ConvertedType = ToType;
785 } else {
786 // Build a new type with the right qualifiers.
787 ConvertedType
788 = Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
789 }
790 return true;
791 }
792 }
793
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000794 return false;
795}
796
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000797/// CheckPointerConversion - Check the pointer conversion from the
798/// expression From to the type ToType. This routine checks for
799/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
800/// conversions for which IsPointerConversion has already returned
801/// true. It returns true and produces a diagnostic if there was an
802/// error, or returns false otherwise.
803bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
804 QualType FromType = From->getType();
805
806 if (const PointerType *FromPtrType = FromType->getAsPointerType())
807 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
Sebastian Redl07779722008-10-31 14:43:28 +0000808 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
809 /*DetectVirtual=*/false);
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000810 QualType FromPointeeType = FromPtrType->getPointeeType(),
811 ToPointeeType = ToPtrType->getPointeeType();
812 if (FromPointeeType->isRecordType() &&
813 ToPointeeType->isRecordType()) {
814 // We must have a derived-to-base conversion. Check an
815 // ambiguous or inaccessible conversion.
Douglas Gregor0575d4a2008-10-24 16:17:19 +0000816 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
817 From->getExprLoc(),
818 From->getSourceRange());
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000819 }
820 }
821
822 return false;
823}
824
Douglas Gregor98cd5992008-10-21 23:43:52 +0000825/// IsQualificationConversion - Determines whether the conversion from
826/// an rvalue of type FromType to ToType is a qualification conversion
827/// (C++ 4.4).
828bool
829Sema::IsQualificationConversion(QualType FromType, QualType ToType)
830{
831 FromType = Context.getCanonicalType(FromType);
832 ToType = Context.getCanonicalType(ToType);
833
834 // If FromType and ToType are the same type, this is not a
835 // qualification conversion.
836 if (FromType == ToType)
837 return false;
838
839 // (C++ 4.4p4):
840 // A conversion can add cv-qualifiers at levels other than the first
841 // in multi-level pointers, subject to the following rules: [...]
842 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +0000843 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +0000844 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +0000845 // Within each iteration of the loop, we check the qualifiers to
846 // determine if this still looks like a qualification
847 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000848 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +0000849 // until there are no more pointers or pointers-to-members left to
850 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +0000851 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +0000852
853 // -- for every j > 0, if const is in cv 1,j then const is in cv
854 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +0000855 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +0000856 return false;
Douglas Gregor57373262008-10-22 14:17:15 +0000857
Douglas Gregor98cd5992008-10-21 23:43:52 +0000858 // -- if the cv 1,j and cv 2,j are different, then const is in
859 // every cv for 0 < k < j.
860 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +0000861 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +0000862 return false;
Douglas Gregor57373262008-10-22 14:17:15 +0000863
Douglas Gregor98cd5992008-10-21 23:43:52 +0000864 // Keep track of whether all prior cv-qualifiers in the "to" type
865 // include const.
866 PreviousToQualsIncludeConst
867 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +0000868 }
Douglas Gregor98cd5992008-10-21 23:43:52 +0000869
870 // We are left with FromType and ToType being the pointee types
871 // after unwrapping the original FromType and ToType the same number
872 // of types. If we unwrapped any pointers, and if FromType and
873 // ToType have the same unqualified type (since we checked
874 // qualifiers above), then this is a qualification conversion.
875 return UnwrappedAnyPointer &&
876 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
877}
878
Douglas Gregor60d62c22008-10-31 16:23:19 +0000879/// IsUserDefinedConversion - Determines whether there is a
880/// user-defined conversion sequence (C++ [over.ics.user]) that
881/// converts expression From to the type ToType. If such a conversion
882/// exists, User will contain the user-defined conversion sequence
883/// that performs such a conversion and this routine will return
884/// true. Otherwise, this routine returns false and User is
885/// unspecified.
886bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
887 UserDefinedConversionSequence& User)
888{
889 OverloadCandidateSet CandidateSet;
890 if (const CXXRecordType *ToRecordType
891 = dyn_cast_or_null<CXXRecordType>(ToType->getAsRecordType())) {
892 // C++ [over.match.ctor]p1:
893 // When objects of class type are direct-initialized (8.5), or
894 // copy-initialized from an expression of the same or a
895 // derived class type (8.5), overload resolution selects the
896 // constructor. [...] For copy-initialization, the candidate
897 // functions are all the converting constructors (12.3.1) of
898 // that class. The argument list is the expression-list within
899 // the parentheses of the initializer.
900 CXXRecordDecl *ToRecordDecl = ToRecordType->getDecl();
901 const OverloadedFunctionDecl *Constructors = ToRecordDecl->getConstructors();
902 for (OverloadedFunctionDecl::function_const_iterator func
903 = Constructors->function_begin();
904 func != Constructors->function_end(); ++func) {
905 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*func);
906 if (Constructor->isConvertingConstructor())
Douglas Gregor225c41e2008-11-03 19:09:14 +0000907 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
908 /*SuppressUserConversions=*/true);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000909 }
910 }
911
Douglas Gregorf1991ea2008-11-07 22:36:19 +0000912 if (const CXXRecordType *FromRecordType
913 = dyn_cast_or_null<CXXRecordType>(From->getType()->getAsRecordType())) {
914 // Add all of the conversion functions as candidates.
915 // FIXME: Look for conversions in base classes!
916 CXXRecordDecl *FromRecordDecl = FromRecordType->getDecl();
917 OverloadedFunctionDecl *Conversions
918 = FromRecordDecl->getConversionFunctions();
919 for (OverloadedFunctionDecl::function_iterator Func
920 = Conversions->function_begin();
921 Func != Conversions->function_end(); ++Func) {
922 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
923 AddConversionCandidate(Conv, From, ToType, CandidateSet);
924 }
925 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000926
927 OverloadCandidateSet::iterator Best;
928 switch (BestViableFunction(CandidateSet, Best)) {
929 case OR_Success:
930 // Record the standard conversion we used and the conversion function.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000931 if (CXXConstructorDecl *Constructor
932 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
933 // C++ [over.ics.user]p1:
934 // If the user-defined conversion is specified by a
935 // constructor (12.3.1), the initial standard conversion
936 // sequence converts the source type to the type required by
937 // the argument of the constructor.
938 //
939 // FIXME: What about ellipsis conversions?
940 QualType ThisType = Constructor->getThisType(Context);
941 User.Before = Best->Conversions[0].Standard;
942 User.ConversionFunction = Constructor;
943 User.After.setAsIdentityConversion();
944 User.After.FromTypePtr
945 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
946 User.After.ToTypePtr = ToType.getAsOpaquePtr();
947 return true;
Douglas Gregorf1991ea2008-11-07 22:36:19 +0000948 } else if (CXXConversionDecl *Conversion
949 = dyn_cast<CXXConversionDecl>(Best->Function)) {
950 // C++ [over.ics.user]p1:
951 //
952 // [...] If the user-defined conversion is specified by a
953 // conversion function (12.3.2), the initial standard
954 // conversion sequence converts the source type to the
955 // implicit object parameter of the conversion function.
956 User.Before = Best->Conversions[0].Standard;
957 User.ConversionFunction = Conversion;
958
959 // C++ [over.ics.user]p2:
960 // The second standard conversion sequence converts the
961 // result of the user-defined conversion to the target type
962 // for the sequence. Since an implicit conversion sequence
963 // is an initialization, the special rules for
964 // initialization by user-defined conversion apply when
965 // selecting the best user-defined conversion for a
966 // user-defined conversion sequence (see 13.3.3 and
967 // 13.3.3.1).
968 User.After = Best->FinalConversion;
969 return true;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000970 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +0000971 assert(false && "Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000972 return false;
973 }
974
975 case OR_No_Viable_Function:
976 // No conversion here! We're done.
977 return false;
978
979 case OR_Ambiguous:
980 // FIXME: See C++ [over.best.ics]p10 for the handling of
981 // ambiguous conversion sequences.
982 return false;
983 }
984
985 return false;
986}
987
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000988/// CompareImplicitConversionSequences - Compare two implicit
989/// conversion sequences to determine whether one is better than the
990/// other or if they are indistinguishable (C++ 13.3.3.2).
991ImplicitConversionSequence::CompareKind
992Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
993 const ImplicitConversionSequence& ICS2)
994{
995 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
996 // conversion sequences (as defined in 13.3.3.1)
997 // -- a standard conversion sequence (13.3.3.1.1) is a better
998 // conversion sequence than a user-defined conversion sequence or
999 // an ellipsis conversion sequence, and
1000 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1001 // conversion sequence than an ellipsis conversion sequence
1002 // (13.3.3.1.3).
1003 //
1004 if (ICS1.ConversionKind < ICS2.ConversionKind)
1005 return ImplicitConversionSequence::Better;
1006 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1007 return ImplicitConversionSequence::Worse;
1008
1009 // Two implicit conversion sequences of the same form are
1010 // indistinguishable conversion sequences unless one of the
1011 // following rules apply: (C++ 13.3.3.2p3):
1012 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1013 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1014 else if (ICS1.ConversionKind ==
1015 ImplicitConversionSequence::UserDefinedConversion) {
1016 // User-defined conversion sequence U1 is a better conversion
1017 // sequence than another user-defined conversion sequence U2 if
1018 // they contain the same user-defined conversion function or
1019 // constructor and if the second standard conversion sequence of
1020 // U1 is better than the second standard conversion sequence of
1021 // U2 (C++ 13.3.3.2p3).
1022 if (ICS1.UserDefined.ConversionFunction ==
1023 ICS2.UserDefined.ConversionFunction)
1024 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1025 ICS2.UserDefined.After);
1026 }
1027
1028 return ImplicitConversionSequence::Indistinguishable;
1029}
1030
1031/// CompareStandardConversionSequences - Compare two standard
1032/// conversion sequences to determine whether one is better than the
1033/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1034ImplicitConversionSequence::CompareKind
1035Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1036 const StandardConversionSequence& SCS2)
1037{
1038 // Standard conversion sequence S1 is a better conversion sequence
1039 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1040
1041 // -- S1 is a proper subsequence of S2 (comparing the conversion
1042 // sequences in the canonical form defined by 13.3.3.1.1,
1043 // excluding any Lvalue Transformation; the identity conversion
1044 // sequence is considered to be a subsequence of any
1045 // non-identity conversion sequence) or, if not that,
1046 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1047 // Neither is a proper subsequence of the other. Do nothing.
1048 ;
1049 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1050 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1051 (SCS1.Second == ICK_Identity &&
1052 SCS1.Third == ICK_Identity))
1053 // SCS1 is a proper subsequence of SCS2.
1054 return ImplicitConversionSequence::Better;
1055 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1056 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1057 (SCS2.Second == ICK_Identity &&
1058 SCS2.Third == ICK_Identity))
1059 // SCS2 is a proper subsequence of SCS1.
1060 return ImplicitConversionSequence::Worse;
1061
1062 // -- the rank of S1 is better than the rank of S2 (by the rules
1063 // defined below), or, if not that,
1064 ImplicitConversionRank Rank1 = SCS1.getRank();
1065 ImplicitConversionRank Rank2 = SCS2.getRank();
1066 if (Rank1 < Rank2)
1067 return ImplicitConversionSequence::Better;
1068 else if (Rank2 < Rank1)
1069 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001070
Douglas Gregor57373262008-10-22 14:17:15 +00001071 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1072 // are indistinguishable unless one of the following rules
1073 // applies:
1074
1075 // A conversion that is not a conversion of a pointer, or
1076 // pointer to member, to bool is better than another conversion
1077 // that is such a conversion.
1078 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1079 return SCS2.isPointerConversionToBool()
1080 ? ImplicitConversionSequence::Better
1081 : ImplicitConversionSequence::Worse;
1082
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001083 // C++ [over.ics.rank]p4b2:
1084 //
1085 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001086 // conversion of B* to A* is better than conversion of B* to
1087 // void*, and conversion of A* to void* is better than conversion
1088 // of B* to void*.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001089 bool SCS1ConvertsToVoid
1090 = SCS1.isPointerConversionToVoidPointer(Context);
1091 bool SCS2ConvertsToVoid
1092 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001093 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1094 // Exactly one of the conversion sequences is a conversion to
1095 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001096 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1097 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001098 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1099 // Neither conversion sequence converts to a void pointer; compare
1100 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001101 if (ImplicitConversionSequence::CompareKind DerivedCK
1102 = CompareDerivedToBaseConversions(SCS1, SCS2))
1103 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001104 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1105 // Both conversion sequences are conversions to void
1106 // pointers. Compare the source types to determine if there's an
1107 // inheritance relationship in their sources.
1108 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1109 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1110
1111 // Adjust the types we're converting from via the array-to-pointer
1112 // conversion, if we need to.
1113 if (SCS1.First == ICK_Array_To_Pointer)
1114 FromType1 = Context.getArrayDecayedType(FromType1);
1115 if (SCS2.First == ICK_Array_To_Pointer)
1116 FromType2 = Context.getArrayDecayedType(FromType2);
1117
1118 QualType FromPointee1
1119 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1120 QualType FromPointee2
1121 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1122
1123 if (IsDerivedFrom(FromPointee2, FromPointee1))
1124 return ImplicitConversionSequence::Better;
1125 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1126 return ImplicitConversionSequence::Worse;
1127 }
Douglas Gregor57373262008-10-22 14:17:15 +00001128
1129 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1130 // bullet 3).
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001131 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001132 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001133 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001134
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001135 // C++ [over.ics.rank]p3b4:
1136 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1137 // which the references refer are the same type except for
1138 // top-level cv-qualifiers, and the type to which the reference
1139 // initialized by S2 refers is more cv-qualified than the type
1140 // to which the reference initialized by S1 refers.
1141 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1142 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1143 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1144 T1 = Context.getCanonicalType(T1);
1145 T2 = Context.getCanonicalType(T2);
1146 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1147 if (T2.isMoreQualifiedThan(T1))
1148 return ImplicitConversionSequence::Better;
1149 else if (T1.isMoreQualifiedThan(T2))
1150 return ImplicitConversionSequence::Worse;
1151 }
1152 }
Douglas Gregor57373262008-10-22 14:17:15 +00001153
1154 return ImplicitConversionSequence::Indistinguishable;
1155}
1156
1157/// CompareQualificationConversions - Compares two standard conversion
1158/// sequences to determine whether they can be ranked based on their
1159/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1160ImplicitConversionSequence::CompareKind
1161Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1162 const StandardConversionSequence& SCS2)
1163{
Douglas Gregorba7e2102008-10-22 15:04:37 +00001164 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001165 // -- S1 and S2 differ only in their qualification conversion and
1166 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1167 // cv-qualification signature of type T1 is a proper subset of
1168 // the cv-qualification signature of type T2, and S1 is not the
1169 // deprecated string literal array-to-pointer conversion (4.2).
1170 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1171 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1172 return ImplicitConversionSequence::Indistinguishable;
1173
1174 // FIXME: the example in the standard doesn't use a qualification
1175 // conversion (!)
1176 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1177 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1178 T1 = Context.getCanonicalType(T1);
1179 T2 = Context.getCanonicalType(T2);
1180
1181 // If the types are the same, we won't learn anything by unwrapped
1182 // them.
1183 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1184 return ImplicitConversionSequence::Indistinguishable;
1185
1186 ImplicitConversionSequence::CompareKind Result
1187 = ImplicitConversionSequence::Indistinguishable;
1188 while (UnwrapSimilarPointerTypes(T1, T2)) {
1189 // Within each iteration of the loop, we check the qualifiers to
1190 // determine if this still looks like a qualification
1191 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001192 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001193 // until there are no more pointers or pointers-to-members left
1194 // to unwrap. This essentially mimics what
1195 // IsQualificationConversion does, but here we're checking for a
1196 // strict subset of qualifiers.
1197 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1198 // The qualifiers are the same, so this doesn't tell us anything
1199 // about how the sequences rank.
1200 ;
1201 else if (T2.isMoreQualifiedThan(T1)) {
1202 // T1 has fewer qualifiers, so it could be the better sequence.
1203 if (Result == ImplicitConversionSequence::Worse)
1204 // Neither has qualifiers that are a subset of the other's
1205 // qualifiers.
1206 return ImplicitConversionSequence::Indistinguishable;
1207
1208 Result = ImplicitConversionSequence::Better;
1209 } else if (T1.isMoreQualifiedThan(T2)) {
1210 // T2 has fewer qualifiers, so it could be the better sequence.
1211 if (Result == ImplicitConversionSequence::Better)
1212 // Neither has qualifiers that are a subset of the other's
1213 // qualifiers.
1214 return ImplicitConversionSequence::Indistinguishable;
1215
1216 Result = ImplicitConversionSequence::Worse;
1217 } else {
1218 // Qualifiers are disjoint.
1219 return ImplicitConversionSequence::Indistinguishable;
1220 }
1221
1222 // If the types after this point are equivalent, we're done.
1223 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1224 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001225 }
1226
Douglas Gregor57373262008-10-22 14:17:15 +00001227 // Check that the winning standard conversion sequence isn't using
1228 // the deprecated string literal array to pointer conversion.
1229 switch (Result) {
1230 case ImplicitConversionSequence::Better:
1231 if (SCS1.Deprecated)
1232 Result = ImplicitConversionSequence::Indistinguishable;
1233 break;
1234
1235 case ImplicitConversionSequence::Indistinguishable:
1236 break;
1237
1238 case ImplicitConversionSequence::Worse:
1239 if (SCS2.Deprecated)
1240 Result = ImplicitConversionSequence::Indistinguishable;
1241 break;
1242 }
1243
1244 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001245}
1246
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001247/// CompareDerivedToBaseConversions - Compares two standard conversion
1248/// sequences to determine whether they can be ranked based on their
1249/// various kinds of derived-to-base conversions (C++ [over.ics.rank]p4b3).
1250ImplicitConversionSequence::CompareKind
1251Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1252 const StandardConversionSequence& SCS2) {
1253 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1254 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1255 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1256 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1257
1258 // Adjust the types we're converting from via the array-to-pointer
1259 // conversion, if we need to.
1260 if (SCS1.First == ICK_Array_To_Pointer)
1261 FromType1 = Context.getArrayDecayedType(FromType1);
1262 if (SCS2.First == ICK_Array_To_Pointer)
1263 FromType2 = Context.getArrayDecayedType(FromType2);
1264
1265 // Canonicalize all of the types.
1266 FromType1 = Context.getCanonicalType(FromType1);
1267 ToType1 = Context.getCanonicalType(ToType1);
1268 FromType2 = Context.getCanonicalType(FromType2);
1269 ToType2 = Context.getCanonicalType(ToType2);
1270
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001271 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001272 //
1273 // If class B is derived directly or indirectly from class A and
1274 // class C is derived directly or indirectly from B,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001275
1276 // Compare based on pointer conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001277 if (SCS1.Second == ICK_Pointer_Conversion &&
1278 SCS2.Second == ICK_Pointer_Conversion) {
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001279 QualType FromPointee1
1280 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1281 QualType ToPointee1
1282 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1283 QualType FromPointee2
1284 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1285 QualType ToPointee2
1286 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001287 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001288 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1289 if (IsDerivedFrom(ToPointee1, ToPointee2))
1290 return ImplicitConversionSequence::Better;
1291 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1292 return ImplicitConversionSequence::Worse;
1293 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001294
1295 // -- conversion of B* to A* is better than conversion of C* to A*,
1296 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1297 if (IsDerivedFrom(FromPointee2, FromPointee1))
1298 return ImplicitConversionSequence::Better;
1299 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1300 return ImplicitConversionSequence::Worse;
1301 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001302 }
1303
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001304 // Compare based on reference bindings.
1305 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1306 SCS1.Second == ICK_Derived_To_Base) {
1307 // -- binding of an expression of type C to a reference of type
1308 // B& is better than binding an expression of type C to a
1309 // reference of type A&,
1310 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1311 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1312 if (IsDerivedFrom(ToType1, ToType2))
1313 return ImplicitConversionSequence::Better;
1314 else if (IsDerivedFrom(ToType2, ToType1))
1315 return ImplicitConversionSequence::Worse;
1316 }
1317
Douglas Gregor225c41e2008-11-03 19:09:14 +00001318 // -- binding of an expression of type B to a reference of type
1319 // A& is better than binding an expression of type C to a
1320 // reference of type A&,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001321 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1322 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1323 if (IsDerivedFrom(FromType2, FromType1))
1324 return ImplicitConversionSequence::Better;
1325 else if (IsDerivedFrom(FromType1, FromType2))
1326 return ImplicitConversionSequence::Worse;
1327 }
1328 }
1329
1330
1331 // FIXME: conversion of A::* to B::* is better than conversion of
1332 // A::* to C::*,
1333
1334 // FIXME: conversion of B::* to C::* is better than conversion of
1335 // A::* to C::*, and
1336
Douglas Gregor225c41e2008-11-03 19:09:14 +00001337 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1338 SCS1.Second == ICK_Derived_To_Base) {
1339 // -- conversion of C to B is better than conversion of C to A,
1340 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1341 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1342 if (IsDerivedFrom(ToType1, ToType2))
1343 return ImplicitConversionSequence::Better;
1344 else if (IsDerivedFrom(ToType2, ToType1))
1345 return ImplicitConversionSequence::Worse;
1346 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001347
Douglas Gregor225c41e2008-11-03 19:09:14 +00001348 // -- conversion of B to A is better than conversion of C to A.
1349 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1350 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1351 if (IsDerivedFrom(FromType2, FromType1))
1352 return ImplicitConversionSequence::Better;
1353 else if (IsDerivedFrom(FromType1, FromType2))
1354 return ImplicitConversionSequence::Worse;
1355 }
1356 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001357
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001358 return ImplicitConversionSequence::Indistinguishable;
1359}
1360
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001361/// TryCopyInitialization - Try to copy-initialize a value of type
1362/// ToType from the expression From. Return the implicit conversion
1363/// sequence required to pass this argument, which may be a bad
1364/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00001365/// a parameter of this type). If @p SuppressUserConversions, then we
1366/// do not permit any user-defined conversion sequences.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001367ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +00001368Sema::TryCopyInitialization(Expr *From, QualType ToType,
1369 bool SuppressUserConversions) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001370 if (!getLangOptions().CPlusPlus) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001371 // In C, copy initialization is the same as performing an assignment.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001372 AssignConvertType ConvTy =
1373 CheckSingleAssignmentConstraints(ToType, From);
1374 ImplicitConversionSequence ICS;
1375 if (getLangOptions().NoExtensions? ConvTy != Compatible
1376 : ConvTy == Incompatible)
1377 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1378 else
1379 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1380 return ICS;
1381 } else if (ToType->isReferenceType()) {
1382 ImplicitConversionSequence ICS;
Douglas Gregor225c41e2008-11-03 19:09:14 +00001383 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001384 return ICS;
1385 } else {
Douglas Gregor225c41e2008-11-03 19:09:14 +00001386 return TryImplicitConversion(From, ToType, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001387 }
1388}
1389
1390/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1391/// type ToType. Returns true (and emits a diagnostic) if there was
1392/// an error, returns false if the initialization succeeded.
1393bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1394 const char* Flavor) {
1395 if (!getLangOptions().CPlusPlus) {
1396 // In C, argument passing is the same as performing an assignment.
1397 QualType FromType = From->getType();
1398 AssignConvertType ConvTy =
1399 CheckSingleAssignmentConstraints(ToType, From);
1400
1401 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1402 FromType, From, Flavor);
1403 } else if (ToType->isReferenceType()) {
1404 return CheckReferenceInit(From, ToType);
1405 } else {
1406 if (PerformImplicitConversion(From, ToType))
1407 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001408 diag::err_typecheck_convert_incompatible)
1409 << ToType.getAsString() << From->getType().getAsString()
1410 << Flavor << From->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001411 else
1412 return false;
1413 }
1414}
1415
Douglas Gregor96176b32008-11-18 23:14:02 +00001416/// TryObjectArgumentInitialization - Try to initialize the object
1417/// parameter of the given member function (@c Method) from the
1418/// expression @p From.
1419ImplicitConversionSequence
1420Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1421 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1422 unsigned MethodQuals = Method->getTypeQualifiers();
1423 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1424
1425 // Set up the conversion sequence as a "bad" conversion, to allow us
1426 // to exit early.
1427 ImplicitConversionSequence ICS;
1428 ICS.Standard.setAsIdentityConversion();
1429 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1430
1431 // We need to have an object of class type.
1432 QualType FromType = From->getType();
1433 if (!FromType->isRecordType())
1434 return ICS;
1435
1436 // The implicit object parmeter is has the type "reference to cv X",
1437 // where X is the class of which the function is a member
1438 // (C++ [over.match.funcs]p4). However, when finding an implicit
1439 // conversion sequence for the argument, we are not allowed to
1440 // create temporaries or perform user-defined conversions
1441 // (C++ [over.match.funcs]p5). We perform a simplified version of
1442 // reference binding here, that allows class rvalues to bind to
1443 // non-constant references.
1444
1445 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1446 // with the implicit object parameter (C++ [over.match.funcs]p5).
1447 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1448 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1449 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1450 return ICS;
1451
1452 // Check that we have either the same type or a derived type. It
1453 // affects the conversion rank.
1454 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1455 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1456 ICS.Standard.Second = ICK_Identity;
1457 else if (IsDerivedFrom(FromType, ClassType))
1458 ICS.Standard.Second = ICK_Derived_To_Base;
1459 else
1460 return ICS;
1461
1462 // Success. Mark this as a reference binding.
1463 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1464 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1465 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1466 ICS.Standard.ReferenceBinding = true;
1467 ICS.Standard.DirectBinding = true;
1468 return ICS;
1469}
1470
1471/// PerformObjectArgumentInitialization - Perform initialization of
1472/// the implicit object parameter for the given Method with the given
1473/// expression.
1474bool
1475Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
1476 QualType ImplicitParamType
1477 = Method->getThisType(Context)->getAsPointerType()->getPointeeType();
1478 ImplicitConversionSequence ICS
1479 = TryObjectArgumentInitialization(From, Method);
1480 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
1481 return Diag(From->getSourceRange().getBegin(),
1482 diag::err_implicit_object_parameter_init,
1483 ImplicitParamType.getAsString(), From->getType().getAsString(),
1484 From->getSourceRange());
1485
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;
1516
1517 unsigned NumArgsInProto = Proto->getNumArgs();
1518
1519 // (C++ 13.3.2p2): A candidate function having fewer than m
1520 // parameters is viable only if it has an ellipsis in its parameter
1521 // list (8.3.5).
1522 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1523 Candidate.Viable = false;
1524 return;
1525 }
1526
1527 // (C++ 13.3.2p2): A candidate function having more than m parameters
1528 // is viable only if the (m+1)st parameter has a default argument
1529 // (8.3.6). For the purposes of overload resolution, the
1530 // parameter list is truncated on the right, so that there are
1531 // exactly m parameters.
1532 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
1533 if (NumArgs < MinRequiredArgs) {
1534 // Not enough arguments.
1535 Candidate.Viable = false;
1536 return;
1537 }
1538
1539 // Determine the implicit conversion sequences for each of the
1540 // arguments.
1541 Candidate.Viable = true;
1542 Candidate.Conversions.resize(NumArgs);
1543 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1544 if (ArgIdx < NumArgsInProto) {
1545 // (C++ 13.3.2p3): for F to be a viable function, there shall
1546 // exist for each argument an implicit conversion sequence
1547 // (13.3.3.1) that converts that argument to the corresponding
1548 // parameter of F.
1549 QualType ParamType = Proto->getArgType(ArgIdx);
1550 Candidate.Conversions[ArgIdx]
Douglas Gregor225c41e2008-11-03 19:09:14 +00001551 = TryCopyInitialization(Args[ArgIdx], ParamType,
1552 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001553 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00001554 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001555 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001556 break;
1557 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001558 } else {
1559 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1560 // argument for which there is no corresponding parameter is
1561 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1562 Candidate.Conversions[ArgIdx].ConversionKind
1563 = ImplicitConversionSequence::EllipsisConversion;
1564 }
1565 }
1566}
1567
Douglas Gregor96176b32008-11-18 23:14:02 +00001568/// AddMethodCandidate - Adds the given C++ member function to the set
1569/// of candidate functions, using the given function call arguments
1570/// and the object argument (@c Object). For example, in a call
1571/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
1572/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
1573/// allow user-defined conversions via constructors or conversion
1574/// operators.
1575void
1576Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
1577 Expr **Args, unsigned NumArgs,
1578 OverloadCandidateSet& CandidateSet,
1579 bool SuppressUserConversions)
1580{
1581 const FunctionTypeProto* Proto
1582 = dyn_cast<FunctionTypeProto>(Method->getType()->getAsFunctionType());
1583 assert(Proto && "Methods without a prototype cannot be overloaded");
1584 assert(!isa<CXXConversionDecl>(Method) &&
1585 "Use AddConversionCandidate for conversion functions");
1586
1587 // Add this candidate
1588 CandidateSet.push_back(OverloadCandidate());
1589 OverloadCandidate& Candidate = CandidateSet.back();
1590 Candidate.Function = Method;
1591
1592 unsigned NumArgsInProto = Proto->getNumArgs();
1593
1594 // (C++ 13.3.2p2): A candidate function having fewer than m
1595 // parameters is viable only if it has an ellipsis in its parameter
1596 // list (8.3.5).
1597 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1598 Candidate.Viable = false;
1599 return;
1600 }
1601
1602 // (C++ 13.3.2p2): A candidate function having more than m parameters
1603 // is viable only if the (m+1)st parameter has a default argument
1604 // (8.3.6). For the purposes of overload resolution, the
1605 // parameter list is truncated on the right, so that there are
1606 // exactly m parameters.
1607 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
1608 if (NumArgs < MinRequiredArgs) {
1609 // Not enough arguments.
1610 Candidate.Viable = false;
1611 return;
1612 }
1613
1614 Candidate.Viable = true;
1615 Candidate.Conversions.resize(NumArgs + 1);
1616
1617 // Determine the implicit conversion sequence for the object
1618 // parameter.
1619 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
1620 if (Candidate.Conversions[0].ConversionKind
1621 == ImplicitConversionSequence::BadConversion) {
1622 Candidate.Viable = false;
1623 return;
1624 }
1625
1626 // Determine the implicit conversion sequences for each of the
1627 // arguments.
1628 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1629 if (ArgIdx < NumArgsInProto) {
1630 // (C++ 13.3.2p3): for F to be a viable function, there shall
1631 // exist for each argument an implicit conversion sequence
1632 // (13.3.3.1) that converts that argument to the corresponding
1633 // parameter of F.
1634 QualType ParamType = Proto->getArgType(ArgIdx);
1635 Candidate.Conversions[ArgIdx + 1]
1636 = TryCopyInitialization(Args[ArgIdx], ParamType,
1637 SuppressUserConversions);
1638 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
1639 == ImplicitConversionSequence::BadConversion) {
1640 Candidate.Viable = false;
1641 break;
1642 }
1643 } else {
1644 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1645 // argument for which there is no corresponding parameter is
1646 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1647 Candidate.Conversions[ArgIdx + 1].ConversionKind
1648 = ImplicitConversionSequence::EllipsisConversion;
1649 }
1650 }
1651}
1652
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001653/// AddConversionCandidate - Add a C++ conversion function as a
1654/// candidate in the candidate set (C++ [over.match.conv],
1655/// C++ [over.match.copy]). From is the expression we're converting from,
1656/// and ToType is the type that we're eventually trying to convert to
1657/// (which may or may not be the same type as the type that the
1658/// conversion function produces).
1659void
1660Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
1661 Expr *From, QualType ToType,
1662 OverloadCandidateSet& CandidateSet) {
1663 // Add this candidate
1664 CandidateSet.push_back(OverloadCandidate());
1665 OverloadCandidate& Candidate = CandidateSet.back();
1666 Candidate.Function = Conversion;
1667 Candidate.FinalConversion.setAsIdentityConversion();
1668 Candidate.FinalConversion.FromTypePtr
1669 = Conversion->getConversionType().getAsOpaquePtr();
1670 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
1671
Douglas Gregor96176b32008-11-18 23:14:02 +00001672 // Determine the implicit conversion sequence for the implicit
1673 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001674 Candidate.Viable = true;
1675 Candidate.Conversions.resize(1);
Douglas Gregor96176b32008-11-18 23:14:02 +00001676 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001677
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001678 if (Candidate.Conversions[0].ConversionKind
1679 == ImplicitConversionSequence::BadConversion) {
1680 Candidate.Viable = false;
1681 return;
1682 }
1683
1684 // To determine what the conversion from the result of calling the
1685 // conversion function to the type we're eventually trying to
1686 // convert to (ToType), we need to synthesize a call to the
1687 // conversion function and attempt copy initialization from it. This
1688 // makes sure that we get the right semantics with respect to
1689 // lvalues/rvalues and the type. Fortunately, we can allocate this
1690 // call on the stack and we don't need its arguments to be
1691 // well-formed.
1692 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
1693 SourceLocation());
1694 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001695 &ConversionRef, false);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001696 CallExpr Call(&ConversionFn, 0, 0,
1697 Conversion->getConversionType().getNonReferenceType(),
1698 SourceLocation());
1699 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
1700 switch (ICS.ConversionKind) {
1701 case ImplicitConversionSequence::StandardConversion:
1702 Candidate.FinalConversion = ICS.Standard;
1703 break;
1704
1705 case ImplicitConversionSequence::BadConversion:
1706 Candidate.Viable = false;
1707 break;
1708
1709 default:
1710 assert(false &&
1711 "Can only end up with a standard conversion sequence or failure");
1712 }
1713}
1714
Douglas Gregor96176b32008-11-18 23:14:02 +00001715/// AddOperatorCandidates - Add the overloaded operator candidates for
1716/// the operator Op that was used in an operator expression such as "x
1717/// Op y". S is the scope in which the expression occurred (used for
1718/// name lookup of the operator), Args/NumArgs provides the operator
1719/// arguments, and CandidateSet will store the added overload
1720/// candidates. (C++ [over.match.oper]).
1721void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
1722 Expr **Args, unsigned NumArgs,
1723 OverloadCandidateSet& CandidateSet) {
1724 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
1725
1726 // C++ [over.match.oper]p3:
1727 // For a unary operator @ with an operand of a type whose
1728 // cv-unqualified version is T1, and for a binary operator @ with
1729 // a left operand of a type whose cv-unqualified version is T1 and
1730 // a right operand of a type whose cv-unqualified version is T2,
1731 // three sets of candidate functions, designated member
1732 // candidates, non-member candidates and built-in candidates, are
1733 // constructed as follows:
1734 QualType T1 = Args[0]->getType();
1735 QualType T2;
1736 if (NumArgs > 1)
1737 T2 = Args[1]->getType();
1738
1739 // -- If T1 is a class type, the set of member candidates is the
1740 // result of the qualified lookup of T1::operator@
1741 // (13.3.1.1.1); otherwise, the set of member candidates is
1742 // empty.
1743 if (const RecordType *T1Rec = T1->getAsRecordType()) {
1744 IdentifierResolver::iterator I
1745 = IdResolver.begin(OpName, cast<CXXRecordType>(T1Rec)->getDecl(),
1746 /*LookInParentCtx=*/false);
1747 NamedDecl *MemberOps = (I == IdResolver.end())? 0 : *I;
1748 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps))
1749 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet,
1750 /*SuppressUserConversions=*/false);
1751 else if (OverloadedFunctionDecl *Ovl
1752 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) {
1753 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
1754 FEnd = Ovl->function_end();
1755 F != FEnd; ++F) {
1756 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F))
1757 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet,
1758 /*SuppressUserConversions=*/false);
1759 }
1760 }
1761 }
1762
1763 // -- The set of non-member candidates is the result of the
1764 // unqualified lookup of operator@ in the context of the
1765 // expression according to the usual rules for name lookup in
1766 // unqualified function calls (3.4.2) except that all member
1767 // functions are ignored. However, if no operand has a class
1768 // type, only those non-member functions in the lookup set
1769 // that have a first parameter of type T1 or “reference to
1770 // (possibly cv-qualified) T1”, when T1 is an enumeration
1771 // type, or (if there is a right operand) a second parameter
1772 // of type T2 or “reference to (possibly cv-qualified) T2”,
1773 // when T2 is an enumeration type, are candidate functions.
1774 {
1775 NamedDecl *NonMemberOps = 0;
1776 for (IdentifierResolver::iterator I
1777 = IdResolver.begin(OpName, CurContext, true/*LookInParentCtx*/);
1778 I != IdResolver.end(); ++I) {
1779 // We don't need to check the identifier namespace, because
1780 // operator names can only be ordinary identifiers.
1781
1782 // Ignore member functions.
1783 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(*I)) {
1784 if (SD->getDeclContext()->isCXXRecord())
1785 continue;
1786 }
1787
1788 // We found something with this name. We're done.
1789 NonMemberOps = *I;
1790 break;
1791 }
1792
1793 // FIXME: check that strange "However" condition above. It's going
1794 // to need a special test.
1795 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NonMemberOps))
1796 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
1797 /*SuppressUserConversions=*/false);
1798 else if (OverloadedFunctionDecl *Ovl
1799 = dyn_cast_or_null<OverloadedFunctionDecl>(NonMemberOps)) {
1800 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
1801 FEnd = Ovl->function_end();
1802 F != FEnd; ++F)
1803 AddOverloadCandidate(*F, Args, NumArgs, CandidateSet,
1804 /*SuppressUserConversions=*/false);
1805 }
1806 }
1807
1808 // Add builtin overload candidates (C++ [over.built]).
1809 if (NumArgs == 2)
1810 return AddBuiltinBinaryOperatorCandidates(Op, Args, CandidateSet);
1811}
1812
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001813/// AddBuiltinCandidate - Add a candidate for a built-in
1814/// operator. ResultTy and ParamTys are the result and parameter types
1815/// of the built-in candidate, respectively. Args and NumArgs are the
1816/// arguments being passed to the candidate.
1817void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
1818 Expr **Args, unsigned NumArgs,
1819 OverloadCandidateSet& CandidateSet) {
1820 // Add this candidate
1821 CandidateSet.push_back(OverloadCandidate());
1822 OverloadCandidate& Candidate = CandidateSet.back();
1823 Candidate.Function = 0;
1824 Candidate.BuiltinTypes.ResultTy = ResultTy;
1825 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
1826 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
1827
1828 // Determine the implicit conversion sequences for each of the
1829 // arguments.
1830 Candidate.Viable = true;
1831 Candidate.Conversions.resize(NumArgs);
1832 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1833 Candidate.Conversions[ArgIdx]
1834 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx], false);
1835 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00001836 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001837 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001838 break;
1839 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001840 }
1841}
1842
1843/// BuiltinCandidateTypeSet - A set of types that will be used for the
1844/// candidate operator functions for built-in operators (C++
1845/// [over.built]). The types are separated into pointer types and
1846/// enumeration types.
1847class BuiltinCandidateTypeSet {
1848 /// TypeSet - A set of types.
Douglas Gregorbf3af052008-11-13 20:12:29 +00001849 typedef llvm::SmallPtrSet<void*, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001850
1851 /// PointerTypes - The set of pointer types that will be used in the
1852 /// built-in candidates.
1853 TypeSet PointerTypes;
1854
1855 /// EnumerationTypes - The set of enumeration types that will be
1856 /// used in the built-in candidates.
1857 TypeSet EnumerationTypes;
1858
1859 /// Context - The AST context in which we will build the type sets.
1860 ASTContext &Context;
1861
1862 bool AddWithMoreQualifiedTypeVariants(QualType Ty);
1863
1864public:
1865 /// iterator - Iterates through the types that are part of the set.
Douglas Gregorbf3af052008-11-13 20:12:29 +00001866 class iterator {
1867 TypeSet::iterator Base;
1868
1869 public:
1870 typedef QualType value_type;
1871 typedef QualType reference;
1872 typedef QualType pointer;
1873 typedef std::ptrdiff_t difference_type;
1874 typedef std::input_iterator_tag iterator_category;
1875
1876 iterator(TypeSet::iterator B) : Base(B) { }
1877
1878 iterator& operator++() {
1879 ++Base;
1880 return *this;
1881 }
1882
1883 iterator operator++(int) {
1884 iterator tmp(*this);
1885 ++(*this);
1886 return tmp;
1887 }
1888
1889 reference operator*() const {
1890 return QualType::getFromOpaquePtr(*Base);
1891 }
1892
1893 pointer operator->() const {
1894 return **this;
1895 }
1896
1897 friend bool operator==(iterator LHS, iterator RHS) {
1898 return LHS.Base == RHS.Base;
1899 }
1900
1901 friend bool operator!=(iterator LHS, iterator RHS) {
1902 return LHS.Base != RHS.Base;
1903 }
1904 };
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001905
1906 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
1907
1908 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions = true);
1909
1910 /// pointer_begin - First pointer type found;
1911 iterator pointer_begin() { return PointerTypes.begin(); }
1912
1913 /// pointer_end - Last pointer type found;
1914 iterator pointer_end() { return PointerTypes.end(); }
1915
1916 /// enumeration_begin - First enumeration type found;
1917 iterator enumeration_begin() { return EnumerationTypes.begin(); }
1918
1919 /// enumeration_end - Last enumeration type found;
1920 iterator enumeration_end() { return EnumerationTypes.end(); }
1921};
1922
1923/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
1924/// the set of pointer types along with any more-qualified variants of
1925/// that type. For example, if @p Ty is "int const *", this routine
1926/// will add "int const *", "int const volatile *", "int const
1927/// restrict *", and "int const volatile restrict *" to the set of
1928/// pointer types. Returns true if the add of @p Ty itself succeeded,
1929/// false otherwise.
1930bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) {
1931 // Insert this type.
Douglas Gregorbf3af052008-11-13 20:12:29 +00001932 if (!PointerTypes.insert(Ty.getAsOpaquePtr()))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001933 return false;
1934
1935 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
1936 QualType PointeeTy = PointerTy->getPointeeType();
1937 // FIXME: Optimize this so that we don't keep trying to add the same types.
1938
1939 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
1940 // with all pointer conversions that don't cast away constness?
1941 if (!PointeeTy.isConstQualified())
1942 AddWithMoreQualifiedTypeVariants
1943 (Context.getPointerType(PointeeTy.withConst()));
1944 if (!PointeeTy.isVolatileQualified())
1945 AddWithMoreQualifiedTypeVariants
1946 (Context.getPointerType(PointeeTy.withVolatile()));
1947 if (!PointeeTy.isRestrictQualified())
1948 AddWithMoreQualifiedTypeVariants
1949 (Context.getPointerType(PointeeTy.withRestrict()));
1950 }
1951
1952 return true;
1953}
1954
1955/// AddTypesConvertedFrom - Add each of the types to which the type @p
1956/// Ty can be implicit converted to the given set of @p Types. We're
1957/// primarily interested in pointer types, enumeration types,
1958void BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
1959 bool AllowUserConversions) {
1960 // Only deal with canonical types.
1961 Ty = Context.getCanonicalType(Ty);
1962
1963 // Look through reference types; they aren't part of the type of an
1964 // expression for the purposes of conversions.
1965 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
1966 Ty = RefTy->getPointeeType();
1967
1968 // We don't care about qualifiers on the type.
1969 Ty = Ty.getUnqualifiedType();
1970
1971 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
1972 QualType PointeeTy = PointerTy->getPointeeType();
1973
1974 // Insert our type, and its more-qualified variants, into the set
1975 // of types.
1976 if (!AddWithMoreQualifiedTypeVariants(Ty))
1977 return;
1978
1979 // Add 'cv void*' to our set of types.
1980 if (!Ty->isVoidType()) {
1981 QualType QualVoid
1982 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
1983 AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
1984 }
1985
1986 // If this is a pointer to a class type, add pointers to its bases
1987 // (with the same level of cv-qualification as the original
1988 // derived class, of course).
1989 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
1990 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
1991 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1992 Base != ClassDecl->bases_end(); ++Base) {
1993 QualType BaseTy = Context.getCanonicalType(Base->getType());
1994 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
1995
1996 // Add the pointer type, recursively, so that we get all of
1997 // the indirect base classes, too.
1998 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false);
1999 }
2000 }
2001 } else if (Ty->isEnumeralType()) {
Douglas Gregorbf3af052008-11-13 20:12:29 +00002002 EnumerationTypes.insert(Ty.getAsOpaquePtr());
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002003 } else if (AllowUserConversions) {
2004 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2005 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2006 // FIXME: Visit conversion functions in the base classes, too.
2007 OverloadedFunctionDecl *Conversions
2008 = ClassDecl->getConversionFunctions();
2009 for (OverloadedFunctionDecl::function_iterator Func
2010 = Conversions->function_begin();
2011 Func != Conversions->function_end(); ++Func) {
2012 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
2013 AddTypesConvertedFrom(Conv->getConversionType(), false);
2014 }
2015 }
2016 }
2017}
2018
2019/// AddBuiltinCandidates - Add the appropriate built-in operator
2020/// overloads to the candidate set (C++ [over.built]), based on the
2021/// operator @p Op and the arguments given. For example, if the
2022/// operator is a binary '+', this routine might add
2023/// "int operator+(int, int)"
2024/// to cover integer addition.
2025void
2026Sema::AddBuiltinBinaryOperatorCandidates(OverloadedOperatorKind Op,
2027 Expr **Args,
2028 OverloadCandidateSet& CandidateSet) {
2029 // The set of "promoted arithmetic types", which are the arithmetic
2030 // types are that preserved by promotion (C++ [over.built]p2). Note
2031 // that the first few of these types are the promoted integral
2032 // types; these types need to be first.
2033 // FIXME: What about complex?
2034 const unsigned FirstIntegralType = 0;
2035 const unsigned LastIntegralType = 13;
2036 const unsigned FirstPromotedIntegralType = 7,
2037 LastPromotedIntegralType = 13;
2038 const unsigned FirstPromotedArithmeticType = 7,
2039 LastPromotedArithmeticType = 16;
2040 const unsigned NumArithmeticTypes = 16;
2041 QualType ArithmeticTypes[NumArithmeticTypes] = {
2042 Context.BoolTy, Context.CharTy, Context.WCharTy,
2043 Context.SignedCharTy, Context.ShortTy,
2044 Context.UnsignedCharTy, Context.UnsignedShortTy,
2045 Context.IntTy, Context.LongTy, Context.LongLongTy,
2046 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2047 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2048 };
2049
2050 // Find all of the types that the arguments can convert to, but only
2051 // if the operator we're looking at has built-in operator candidates
2052 // that make use of these types.
2053 BuiltinCandidateTypeSet CandidateTypes(Context);
2054 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2055 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
2056 Op == OO_Plus || Op == OO_Minus || Op == OO_Equal ||
2057 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
2058 Op == OO_ArrowStar) {
2059 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx)
2060 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType());
2061 }
2062
2063 bool isComparison = false;
2064 switch (Op) {
2065 case OO_None:
2066 case NUM_OVERLOADED_OPERATORS:
2067 assert(false && "Expected an overloaded operator");
2068 break;
2069
2070 case OO_New:
2071 case OO_Delete:
2072 case OO_Array_New:
2073 case OO_Array_Delete:
2074 case OO_Tilde:
2075 case OO_Exclaim:
2076 case OO_PlusPlus:
2077 case OO_MinusMinus:
2078 case OO_Arrow:
2079 case OO_Call:
2080 assert(false && "Expected a binary operator");
2081 break;
2082
2083 case OO_Comma:
2084 // C++ [over.match.oper]p3:
2085 // -- For the operator ',', the unary operator '&', or the
2086 // operator '->', the built-in candidates set is empty.
2087 // We don't check '&' or '->' here, since they are unary operators.
2088 break;
2089
2090 case OO_Less:
2091 case OO_Greater:
2092 case OO_LessEqual:
2093 case OO_GreaterEqual:
2094 case OO_EqualEqual:
2095 case OO_ExclaimEqual:
2096 // C++ [over.built]p15:
2097 //
2098 // For every pointer or enumeration type T, there exist
2099 // candidate operator functions of the form
2100 //
2101 // bool operator<(T, T);
2102 // bool operator>(T, T);
2103 // bool operator<=(T, T);
2104 // bool operator>=(T, T);
2105 // bool operator==(T, T);
2106 // bool operator!=(T, T);
2107 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2108 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2109 QualType ParamTypes[2] = { *Ptr, *Ptr };
2110 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2111 }
2112 for (BuiltinCandidateTypeSet::iterator Enum
2113 = CandidateTypes.enumeration_begin();
2114 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2115 QualType ParamTypes[2] = { *Enum, *Enum };
2116 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2117 }
2118
2119 // Fall through.
2120 isComparison = true;
2121
2122 case OO_Plus:
2123 case OO_Minus:
2124 if (!isComparison) {
2125 // We didn't fall through, so we must have OO_Plus or OO_Minus.
2126
2127 // C++ [over.built]p13:
2128 //
2129 // For every cv-qualified or cv-unqualified object type T
2130 // there exist candidate operator functions of the form
2131 //
2132 // T* operator+(T*, ptrdiff_t);
2133 // T& operator[](T*, ptrdiff_t); [BELOW]
2134 // T* operator-(T*, ptrdiff_t);
2135 // T* operator+(ptrdiff_t, T*);
2136 // T& operator[](ptrdiff_t, T*); [BELOW]
2137 //
2138 // C++ [over.built]p14:
2139 //
2140 // For every T, where T is a pointer to object type, there
2141 // exist candidate operator functions of the form
2142 //
2143 // ptrdiff_t operator-(T, T);
2144 for (BuiltinCandidateTypeSet::iterator Ptr
2145 = CandidateTypes.pointer_begin();
2146 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2147 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2148
2149 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
2150 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2151
2152 if (Op == OO_Plus) {
2153 // T* operator+(ptrdiff_t, T*);
2154 ParamTypes[0] = ParamTypes[1];
2155 ParamTypes[1] = *Ptr;
2156 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2157 } else {
2158 // ptrdiff_t operator-(T, T);
2159 ParamTypes[1] = *Ptr;
2160 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
2161 Args, 2, CandidateSet);
2162 }
2163 }
2164 }
2165 // Fall through
2166
2167 case OO_Star:
2168 case OO_Slash:
2169 // C++ [over.built]p12:
2170 //
2171 // For every pair of promoted arithmetic types L and R, there
2172 // exist candidate operator functions of the form
2173 //
2174 // LR operator*(L, R);
2175 // LR operator/(L, R);
2176 // LR operator+(L, R);
2177 // LR operator-(L, R);
2178 // bool operator<(L, R);
2179 // bool operator>(L, R);
2180 // bool operator<=(L, R);
2181 // bool operator>=(L, R);
2182 // bool operator==(L, R);
2183 // bool operator!=(L, R);
2184 //
2185 // where LR is the result of the usual arithmetic conversions
2186 // between types L and R.
2187 for (unsigned Left = FirstPromotedArithmeticType;
2188 Left < LastPromotedArithmeticType; ++Left) {
2189 for (unsigned Right = FirstPromotedArithmeticType;
2190 Right < LastPromotedArithmeticType; ++Right) {
2191 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2192 QualType Result
2193 = isComparison? Context.BoolTy
2194 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2195 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2196 }
2197 }
2198 break;
2199
2200 case OO_Percent:
2201 case OO_Amp:
2202 case OO_Caret:
2203 case OO_Pipe:
2204 case OO_LessLess:
2205 case OO_GreaterGreater:
2206 // C++ [over.built]p17:
2207 //
2208 // For every pair of promoted integral types L and R, there
2209 // exist candidate operator functions of the form
2210 //
2211 // LR operator%(L, R);
2212 // LR operator&(L, R);
2213 // LR operator^(L, R);
2214 // LR operator|(L, R);
2215 // L operator<<(L, R);
2216 // L operator>>(L, R);
2217 //
2218 // where LR is the result of the usual arithmetic conversions
2219 // between types L and R.
2220 for (unsigned Left = FirstPromotedIntegralType;
2221 Left < LastPromotedIntegralType; ++Left) {
2222 for (unsigned Right = FirstPromotedIntegralType;
2223 Right < LastPromotedIntegralType; ++Right) {
2224 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2225 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
2226 ? LandR[0]
2227 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2228 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2229 }
2230 }
2231 break;
2232
2233 case OO_Equal:
2234 // C++ [over.built]p20:
2235 //
2236 // For every pair (T, VQ), where T is an enumeration or
2237 // (FIXME:) pointer to member type and VQ is either volatile or
2238 // empty, there exist candidate operator functions of the form
2239 //
2240 // VQ T& operator=(VQ T&, T);
2241 for (BuiltinCandidateTypeSet::iterator Enum
2242 = CandidateTypes.enumeration_begin();
2243 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2244 QualType ParamTypes[2];
2245
2246 // T& operator=(T&, T)
2247 ParamTypes[0] = Context.getReferenceType(*Enum);
2248 ParamTypes[1] = *Enum;
2249 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2250
2251 // volatile T& operator=(volatile T&, T)
Douglas Gregorbf3af052008-11-13 20:12:29 +00002252 ParamTypes[0] = Context.getReferenceType((*Enum).withVolatile());
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002253 ParamTypes[1] = *Enum;
2254 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2255 }
2256 // Fall through.
2257
2258 case OO_PlusEqual:
2259 case OO_MinusEqual:
2260 // C++ [over.built]p19:
2261 //
2262 // For every pair (T, VQ), where T is any type and VQ is either
2263 // volatile or empty, there exist candidate operator functions
2264 // of the form
2265 //
2266 // T*VQ& operator=(T*VQ&, T*);
2267 //
2268 // C++ [over.built]p21:
2269 //
2270 // For every pair (T, VQ), where T is a cv-qualified or
2271 // cv-unqualified object type and VQ is either volatile or
2272 // empty, there exist candidate operator functions of the form
2273 //
2274 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
2275 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
2276 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2277 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2278 QualType ParamTypes[2];
2279 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
2280
2281 // non-volatile version
2282 ParamTypes[0] = Context.getReferenceType(*Ptr);
2283 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2284
2285 // volatile version
Douglas Gregorbf3af052008-11-13 20:12:29 +00002286 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002287 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2288 }
2289 // Fall through.
2290
2291 case OO_StarEqual:
2292 case OO_SlashEqual:
2293 // C++ [over.built]p18:
2294 //
2295 // For every triple (L, VQ, R), where L is an arithmetic type,
2296 // VQ is either volatile or empty, and R is a promoted
2297 // arithmetic type, there exist candidate operator functions of
2298 // the form
2299 //
2300 // VQ L& operator=(VQ L&, R);
2301 // VQ L& operator*=(VQ L&, R);
2302 // VQ L& operator/=(VQ L&, R);
2303 // VQ L& operator+=(VQ L&, R);
2304 // VQ L& operator-=(VQ L&, R);
2305 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
2306 for (unsigned Right = FirstPromotedArithmeticType;
2307 Right < LastPromotedArithmeticType; ++Right) {
2308 QualType ParamTypes[2];
2309 ParamTypes[1] = ArithmeticTypes[Right];
2310
2311 // Add this built-in operator as a candidate (VQ is empty).
2312 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
2313 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2314
2315 // Add this built-in operator as a candidate (VQ is 'volatile').
2316 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
2317 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
2318 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2319 }
2320 }
2321 break;
2322
2323 case OO_PercentEqual:
2324 case OO_LessLessEqual:
2325 case OO_GreaterGreaterEqual:
2326 case OO_AmpEqual:
2327 case OO_CaretEqual:
2328 case OO_PipeEqual:
2329 // C++ [over.built]p22:
2330 //
2331 // For every triple (L, VQ, R), where L is an integral type, VQ
2332 // is either volatile or empty, and R is a promoted integral
2333 // type, there exist candidate operator functions of the form
2334 //
2335 // VQ L& operator%=(VQ L&, R);
2336 // VQ L& operator<<=(VQ L&, R);
2337 // VQ L& operator>>=(VQ L&, R);
2338 // VQ L& operator&=(VQ L&, R);
2339 // VQ L& operator^=(VQ L&, R);
2340 // VQ L& operator|=(VQ L&, R);
2341 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
2342 for (unsigned Right = FirstPromotedIntegralType;
2343 Right < LastPromotedIntegralType; ++Right) {
2344 QualType ParamTypes[2];
2345 ParamTypes[1] = ArithmeticTypes[Right];
2346
2347 // Add this built-in operator as a candidate (VQ is empty).
2348 // FIXME: We should be caching these declarations somewhere,
2349 // rather than re-building them every time.
2350 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
2351 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2352
2353 // Add this built-in operator as a candidate (VQ is 'volatile').
2354 ParamTypes[0] = ArithmeticTypes[Left];
2355 ParamTypes[0].addVolatile();
2356 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
2357 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2358 }
2359 }
2360 break;
2361
2362 case OO_AmpAmp:
2363 case OO_PipePipe: {
2364 // C++ [over.operator]p23:
2365 //
2366 // There also exist candidate operator functions of the form
2367 //
2368 // bool operator!(bool); [In Unary version]
2369 // bool operator&&(bool, bool);
2370 // bool operator||(bool, bool);
2371 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
2372 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2373 break;
2374 }
2375
2376 case OO_Subscript:
2377 // C++ [over.built]p13:
2378 //
2379 // For every cv-qualified or cv-unqualified object type T there
2380 // exist candidate operator functions of the form
2381 //
2382 // T* operator+(T*, ptrdiff_t); [ABOVE]
2383 // T& operator[](T*, ptrdiff_t);
2384 // T* operator-(T*, ptrdiff_t); [ABOVE]
2385 // T* operator+(ptrdiff_t, T*); [ABOVE]
2386 // T& operator[](ptrdiff_t, T*);
2387 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2388 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2389 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2390 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
2391 QualType ResultTy = Context.getReferenceType(PointeeType);
2392
2393 // T& operator[](T*, ptrdiff_t)
2394 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
2395
2396 // T& operator[](ptrdiff_t, T*);
2397 ParamTypes[0] = ParamTypes[1];
2398 ParamTypes[1] = *Ptr;
2399 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
2400 }
2401 break;
2402
2403 case OO_ArrowStar:
2404 // FIXME: No support for pointer-to-members yet.
2405 break;
2406 }
2407}
2408
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002409/// AddOverloadCandidates - Add all of the function overloads in Ovl
2410/// to the candidate set.
2411void
Douglas Gregor18fe5682008-11-03 20:45:27 +00002412Sema::AddOverloadCandidates(const OverloadedFunctionDecl *Ovl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002413 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002414 OverloadCandidateSet& CandidateSet,
2415 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002416{
Douglas Gregor18fe5682008-11-03 20:45:27 +00002417 for (OverloadedFunctionDecl::function_const_iterator Func
2418 = Ovl->function_begin();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002419 Func != Ovl->function_end(); ++Func)
Douglas Gregor225c41e2008-11-03 19:09:14 +00002420 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet,
2421 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002422}
2423
2424/// isBetterOverloadCandidate - Determines whether the first overload
2425/// candidate is a better candidate than the second (C++ 13.3.3p1).
2426bool
2427Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
2428 const OverloadCandidate& Cand2)
2429{
2430 // Define viable functions to be better candidates than non-viable
2431 // functions.
2432 if (!Cand2.Viable)
2433 return Cand1.Viable;
2434 else if (!Cand1.Viable)
2435 return false;
2436
2437 // FIXME: Deal with the implicit object parameter for static member
2438 // functions. (C++ 13.3.3p1).
2439
2440 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
2441 // function than another viable function F2 if for all arguments i,
2442 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
2443 // then...
2444 unsigned NumArgs = Cand1.Conversions.size();
2445 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
2446 bool HasBetterConversion = false;
2447 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2448 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
2449 Cand2.Conversions[ArgIdx])) {
2450 case ImplicitConversionSequence::Better:
2451 // Cand1 has a better conversion sequence.
2452 HasBetterConversion = true;
2453 break;
2454
2455 case ImplicitConversionSequence::Worse:
2456 // Cand1 can't be better than Cand2.
2457 return false;
2458
2459 case ImplicitConversionSequence::Indistinguishable:
2460 // Do nothing.
2461 break;
2462 }
2463 }
2464
2465 if (HasBetterConversion)
2466 return true;
2467
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002468 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
2469 // implemented, but they require template support.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002470
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002471 // C++ [over.match.best]p1b4:
2472 //
2473 // -- the context is an initialization by user-defined conversion
2474 // (see 8.5, 13.3.1.5) and the standard conversion sequence
2475 // from the return type of F1 to the destination type (i.e.,
2476 // the type of the entity being initialized) is a better
2477 // conversion sequence than the standard conversion sequence
2478 // from the return type of F2 to the destination type.
2479 if (isa<CXXConversionDecl>(Cand1.Function) &&
2480 isa<CXXConversionDecl>(Cand2.Function)) {
2481 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
2482 Cand2.FinalConversion)) {
2483 case ImplicitConversionSequence::Better:
2484 // Cand1 has a better conversion sequence.
2485 return true;
2486
2487 case ImplicitConversionSequence::Worse:
2488 // Cand1 can't be better than Cand2.
2489 return false;
2490
2491 case ImplicitConversionSequence::Indistinguishable:
2492 // Do nothing
2493 break;
2494 }
2495 }
2496
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002497 return false;
2498}
2499
2500/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
2501/// within an overload candidate set. If overloading is successful,
2502/// the result will be OR_Success and Best will be set to point to the
2503/// best viable function within the candidate set. Otherwise, one of
2504/// several kinds of errors will be returned; see
2505/// Sema::OverloadingResult.
2506Sema::OverloadingResult
2507Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
2508 OverloadCandidateSet::iterator& Best)
2509{
2510 // Find the best viable function.
2511 Best = CandidateSet.end();
2512 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2513 Cand != CandidateSet.end(); ++Cand) {
2514 if (Cand->Viable) {
2515 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
2516 Best = Cand;
2517 }
2518 }
2519
2520 // If we didn't find any viable functions, abort.
2521 if (Best == CandidateSet.end())
2522 return OR_No_Viable_Function;
2523
2524 // Make sure that this function is better than every other viable
2525 // function. If not, we have an ambiguity.
2526 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2527 Cand != CandidateSet.end(); ++Cand) {
2528 if (Cand->Viable &&
2529 Cand != Best &&
2530 !isBetterOverloadCandidate(*Best, *Cand))
2531 return OR_Ambiguous;
2532 }
2533
2534 // Best is the best viable function.
2535 return OR_Success;
2536}
2537
2538/// PrintOverloadCandidates - When overload resolution fails, prints
2539/// diagnostic messages containing the candidates in the candidate
2540/// set. If OnlyViable is true, only viable candidates will be printed.
2541void
2542Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
2543 bool OnlyViable)
2544{
2545 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
2546 LastCand = CandidateSet.end();
2547 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002548 if (Cand->Viable || !OnlyViable) {
2549 if (Cand->Function) {
2550 // Normal function
2551 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
2552 } else {
2553 // FIXME: We need to get the identifier in here
2554 // FIXME: Do we want the error message to point at the
2555 // operator? (built-ins won't have a location)
2556 QualType FnType
2557 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
2558 Cand->BuiltinTypes.ParamTypes,
2559 Cand->Conversions.size(),
2560 false, 0);
2561
2562 Diag(SourceLocation(), diag::err_ovl_builtin_candidate,
2563 FnType.getAsString());
2564 }
2565 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002566 }
2567}
2568
Douglas Gregor904eed32008-11-10 20:40:00 +00002569/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
2570/// an overloaded function (C++ [over.over]), where @p From is an
2571/// expression with overloaded function type and @p ToType is the type
2572/// we're trying to resolve to. For example:
2573///
2574/// @code
2575/// int f(double);
2576/// int f(int);
2577///
2578/// int (*pfd)(double) = f; // selects f(double)
2579/// @endcode
2580///
2581/// This routine returns the resulting FunctionDecl if it could be
2582/// resolved, and NULL otherwise. When @p Complain is true, this
2583/// routine will emit diagnostics if there is an error.
2584FunctionDecl *
2585Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
2586 bool Complain) {
2587 QualType FunctionType = ToType;
2588 if (const PointerLikeType *ToTypePtr = ToType->getAsPointerLikeType())
2589 FunctionType = ToTypePtr->getPointeeType();
2590
2591 // We only look at pointers or references to functions.
2592 if (!FunctionType->isFunctionType())
2593 return 0;
2594
2595 // Find the actual overloaded function declaration.
2596 OverloadedFunctionDecl *Ovl = 0;
2597
2598 // C++ [over.over]p1:
2599 // [...] [Note: any redundant set of parentheses surrounding the
2600 // overloaded function name is ignored (5.1). ]
2601 Expr *OvlExpr = From->IgnoreParens();
2602
2603 // C++ [over.over]p1:
2604 // [...] The overloaded function name can be preceded by the &
2605 // operator.
2606 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
2607 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2608 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
2609 }
2610
2611 // Try to dig out the overloaded function.
2612 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
2613 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
2614
2615 // If there's no overloaded function declaration, we're done.
2616 if (!Ovl)
2617 return 0;
2618
2619 // Look through all of the overloaded functions, searching for one
2620 // whose type matches exactly.
2621 // FIXME: When templates or using declarations come along, we'll actually
2622 // have to deal with duplicates, partial ordering, etc. For now, we
2623 // can just do a simple search.
2624 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
2625 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
2626 Fun != Ovl->function_end(); ++Fun) {
2627 // C++ [over.over]p3:
2628 // Non-member functions and static member functions match
2629 // targets of type “pointer-to-function”or
2630 // “reference-to-function.”
2631 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun))
2632 if (!Method->isStatic())
2633 continue;
2634
2635 if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
2636 return *Fun;
2637 }
2638
2639 return 0;
2640}
2641
2642/// FixOverloadedFunctionReference - E is an expression that refers to
2643/// a C++ overloaded function (possibly with some parentheses and
2644/// perhaps a '&' around it). We have resolved the overloaded function
2645/// to the function declaration Fn, so patch up the expression E to
2646/// refer (possibly indirectly) to Fn.
2647void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
2648 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
2649 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
2650 E->setType(PE->getSubExpr()->getType());
2651 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
2652 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
2653 "Can only take the address of an overloaded function");
2654 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
2655 E->setType(Context.getPointerType(E->getType()));
2656 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
2657 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
2658 "Expected overloaded function");
2659 DR->setDecl(Fn);
2660 E->setType(Fn->getType());
2661 } else {
2662 assert(false && "Invalid reference to overloaded function");
2663 }
2664}
2665
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002666} // end namespace clang