blob: 88c209b6e00c99b2c62e6a9d86e9aabfc796c0bd [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"
15#include "clang/Basic/Diagnostic.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Expr.h"
18#include "llvm/Support/Compiler.h"
19#include <algorithm>
20
21namespace clang {
22
23/// GetConversionCategory - Retrieve the implicit conversion
24/// category corresponding to the given implicit conversion kind.
25ImplicitConversionCategory
26GetConversionCategory(ImplicitConversionKind Kind) {
27 static const ImplicitConversionCategory
28 Category[(int)ICK_Num_Conversion_Kinds] = {
29 ICC_Identity,
30 ICC_Lvalue_Transformation,
31 ICC_Lvalue_Transformation,
32 ICC_Lvalue_Transformation,
33 ICC_Qualification_Adjustment,
34 ICC_Promotion,
35 ICC_Promotion,
36 ICC_Conversion,
37 ICC_Conversion,
38 ICC_Conversion,
39 ICC_Conversion,
40 ICC_Conversion,
41 ICC_Conversion
42 };
43 return Category[(int)Kind];
44}
45
46/// GetConversionRank - Retrieve the implicit conversion rank
47/// corresponding to the given implicit conversion kind.
48ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
49 static const ImplicitConversionRank
50 Rank[(int)ICK_Num_Conversion_Kinds] = {
51 ICR_Exact_Match,
52 ICR_Exact_Match,
53 ICR_Exact_Match,
54 ICR_Exact_Match,
55 ICR_Exact_Match,
56 ICR_Promotion,
57 ICR_Promotion,
58 ICR_Conversion,
59 ICR_Conversion,
60 ICR_Conversion,
61 ICR_Conversion,
62 ICR_Conversion,
63 ICR_Conversion
64 };
65 return Rank[(int)Kind];
66}
67
68/// GetImplicitConversionName - Return the name of this kind of
69/// implicit conversion.
70const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
71 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
72 "No conversion",
73 "Lvalue-to-rvalue",
74 "Array-to-pointer",
75 "Function-to-pointer",
76 "Qualification",
77 "Integral promotion",
78 "Floating point promotion",
79 "Integral conversion",
80 "Floating conversion",
81 "Floating-integral conversion",
82 "Pointer conversion",
83 "Pointer-to-member conversion",
84 "Boolean conversion"
85 };
86 return Name[Kind];
87}
88
89/// getRank - Retrieve the rank of this standard conversion sequence
90/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
91/// implicit conversions.
92ImplicitConversionRank StandardConversionSequence::getRank() const {
93 ImplicitConversionRank Rank = ICR_Exact_Match;
94 if (GetConversionRank(First) > Rank)
95 Rank = GetConversionRank(First);
96 if (GetConversionRank(Second) > Rank)
97 Rank = GetConversionRank(Second);
98 if (GetConversionRank(Third) > Rank)
99 Rank = GetConversionRank(Third);
100 return Rank;
101}
102
103/// isPointerConversionToBool - Determines whether this conversion is
104/// a conversion of a pointer or pointer-to-member to bool. This is
105/// used as part of the ranking of standard conversion sequences
106/// (C++ 13.3.3.2p4).
107bool StandardConversionSequence::isPointerConversionToBool() const
108{
109 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
110 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
111
112 // Note that FromType has not necessarily been transformed by the
113 // array-to-pointer or function-to-pointer implicit conversions, so
114 // check for their presence as well as checking whether FromType is
115 // a pointer.
116 if (ToType->isBooleanType() &&
117 (FromType->isPointerType() ||
118 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
119 return true;
120
121 return false;
122}
123
124/// DebugPrint - Print this standard conversion sequence to standard
125/// error. Useful for debugging overloading issues.
126void StandardConversionSequence::DebugPrint() const {
127 bool PrintedSomething = false;
128 if (First != ICK_Identity) {
129 fprintf(stderr, "%s", GetImplicitConversionName(First));
130 PrintedSomething = true;
131 }
132
133 if (Second != ICK_Identity) {
134 if (PrintedSomething) {
135 fprintf(stderr, " -> ");
136 }
137 fprintf(stderr, "%s", GetImplicitConversionName(Second));
138 PrintedSomething = true;
139 }
140
141 if (Third != ICK_Identity) {
142 if (PrintedSomething) {
143 fprintf(stderr, " -> ");
144 }
145 fprintf(stderr, "%s", GetImplicitConversionName(Third));
146 PrintedSomething = true;
147 }
148
149 if (!PrintedSomething) {
150 fprintf(stderr, "No conversions required");
151 }
152}
153
154/// DebugPrint - Print this user-defined conversion sequence to standard
155/// error. Useful for debugging overloading issues.
156void UserDefinedConversionSequence::DebugPrint() const {
157 if (Before.First || Before.Second || Before.Third) {
158 Before.DebugPrint();
159 fprintf(stderr, " -> ");
160 }
161 fprintf(stderr, "'%s'", ConversionFunction->getName());
162 if (After.First || After.Second || After.Third) {
163 fprintf(stderr, " -> ");
164 After.DebugPrint();
165 }
166}
167
168/// DebugPrint - Print this implicit conversion sequence to standard
169/// error. Useful for debugging overloading issues.
170void ImplicitConversionSequence::DebugPrint() const {
171 switch (ConversionKind) {
172 case StandardConversion:
173 fprintf(stderr, "Standard conversion: ");
174 Standard.DebugPrint();
175 break;
176 case UserDefinedConversion:
177 fprintf(stderr, "User-defined conversion: ");
178 UserDefined.DebugPrint();
179 break;
180 case EllipsisConversion:
181 fprintf(stderr, "Ellipsis conversion");
182 break;
183 case BadConversion:
184 fprintf(stderr, "Bad conversion");
185 break;
186 }
187
188 fprintf(stderr, "\n");
189}
190
191// IsOverload - Determine whether the given New declaration is an
192// overload of the Old declaration. This routine returns false if New
193// and Old cannot be overloaded, e.g., if they are functions with the
194// same signature (C++ 1.3.10) or if the Old declaration isn't a
195// function (or overload set). When it does return false and Old is an
196// OverloadedFunctionDecl, MatchedDecl will be set to point to the
197// FunctionDecl that New cannot be overloaded with.
198//
199// Example: Given the following input:
200//
201// void f(int, float); // #1
202// void f(int, int); // #2
203// int f(int, int); // #3
204//
205// When we process #1, there is no previous declaration of "f",
206// so IsOverload will not be used.
207//
208// When we process #2, Old is a FunctionDecl for #1. By comparing the
209// parameter types, we see that #1 and #2 are overloaded (since they
210// have different signatures), so this routine returns false;
211// MatchedDecl is unchanged.
212//
213// When we process #3, Old is an OverloadedFunctionDecl containing #1
214// and #2. We compare the signatures of #3 to #1 (they're overloaded,
215// so we do nothing) and then #3 to #2. Since the signatures of #3 and
216// #2 are identical (return types of functions are not part of the
217// signature), IsOverload returns false and MatchedDecl will be set to
218// point to the FunctionDecl for #2.
219bool
220Sema::IsOverload(FunctionDecl *New, Decl* OldD,
221 OverloadedFunctionDecl::function_iterator& MatchedDecl)
222{
223 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
224 // Is this new function an overload of every function in the
225 // overload set?
226 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
227 FuncEnd = Ovl->function_end();
228 for (; Func != FuncEnd; ++Func) {
229 if (!IsOverload(New, *Func, MatchedDecl)) {
230 MatchedDecl = Func;
231 return false;
232 }
233 }
234
235 // This function overloads every function in the overload set.
236 return true;
237 } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
238 // Is the function New an overload of the function Old?
239 QualType OldQType = Context.getCanonicalType(Old->getType());
240 QualType NewQType = Context.getCanonicalType(New->getType());
241
242 // Compare the signatures (C++ 1.3.10) of the two functions to
243 // determine whether they are overloads. If we find any mismatch
244 // in the signature, they are overloads.
245
246 // If either of these functions is a K&R-style function (no
247 // prototype), then we consider them to have matching signatures.
248 if (isa<FunctionTypeNoProto>(OldQType.getTypePtr()) ||
249 isa<FunctionTypeNoProto>(NewQType.getTypePtr()))
250 return false;
251
252 FunctionTypeProto* OldType = cast<FunctionTypeProto>(OldQType.getTypePtr());
253 FunctionTypeProto* NewType = cast<FunctionTypeProto>(NewQType.getTypePtr());
254
255 // The signature of a function includes the types of its
256 // parameters (C++ 1.3.10), which includes the presence or absence
257 // of the ellipsis; see C++ DR 357).
258 if (OldQType != NewQType &&
259 (OldType->getNumArgs() != NewType->getNumArgs() ||
260 OldType->isVariadic() != NewType->isVariadic() ||
261 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
262 NewType->arg_type_begin())))
263 return true;
264
265 // If the function is a class member, its signature includes the
266 // cv-qualifiers (if any) on the function itself.
267 //
268 // As part of this, also check whether one of the member functions
269 // is static, in which case they are not overloads (C++
270 // 13.1p2). While not part of the definition of the signature,
271 // this check is important to determine whether these functions
272 // can be overloaded.
273 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
274 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
275 if (OldMethod && NewMethod &&
276 !OldMethod->isStatic() && !NewMethod->isStatic() &&
277 OldQType.getCVRQualifiers() != NewQType.getCVRQualifiers())
278 return true;
279
280 // The signatures match; this is not an overload.
281 return false;
282 } else {
283 // (C++ 13p1):
284 // Only function declarations can be overloaded; object and type
285 // declarations cannot be overloaded.
286 return false;
287 }
288}
289
290/// TryCopyInitialization - Attempt to copy-initialize a value of the
291/// given type (ToType) from the given expression (Expr), as one would
292/// do when copy-initializing a function parameter. This function
293/// returns an implicit conversion sequence that can be used to
294/// perform the initialization. Given
295///
296/// void f(float f);
297/// void g(int i) { f(i); }
298///
299/// this routine would produce an implicit conversion sequence to
300/// describe the initialization of f from i, which will be a standard
301/// conversion sequence containing an lvalue-to-rvalue conversion (C++
302/// 4.1) followed by a floating-integral conversion (C++ 4.9).
303//
304/// Note that this routine only determines how the conversion can be
305/// performed; it does not actually perform the conversion. As such,
306/// it will not produce any diagnostics if no conversion is available,
307/// but will instead return an implicit conversion sequence of kind
308/// "BadConversion".
309ImplicitConversionSequence
310Sema::TryCopyInitialization(Expr* From, QualType ToType)
311{
312 ImplicitConversionSequence ICS;
313
314 QualType FromType = From->getType();
315
316 // Standard conversions (C++ 4)
317 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
318 ICS.Standard.Deprecated = false;
319 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
320
321 // The first conversion can be an lvalue-to-rvalue conversion,
322 // array-to-pointer conversion, or function-to-pointer conversion
323 // (C++ 4p1).
324
325 // Lvalue-to-rvalue conversion (C++ 4.1):
326 // An lvalue (3.10) of a non-function, non-array type T can be
327 // converted to an rvalue.
328 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
329 if (argIsLvalue == Expr::LV_Valid &&
330 !FromType->isFunctionType() && !FromType->isArrayType()) {
331 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
332
333 // If T is a non-class type, the type of the rvalue is the
334 // cv-unqualified version of T. Otherwise, the type of the rvalue
335 // is T (C++ 4.1p1).
336 if (!FromType->isRecordType())
337 FromType = FromType.getUnqualifiedType();
338 }
339 // Array-to-pointer conversion (C++ 4.2)
340 else if (FromType->isArrayType()) {
341 ICS.Standard.First = ICK_Array_To_Pointer;
342
343 // An lvalue or rvalue of type "array of N T" or "array of unknown
344 // bound of T" can be converted to an rvalue of type "pointer to
345 // T" (C++ 4.2p1).
346 FromType = Context.getArrayDecayedType(FromType);
347
348 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
349 // This conversion is deprecated. (C++ D.4).
350 ICS.Standard.Deprecated = true;
351
352 // For the purpose of ranking in overload resolution
353 // (13.3.3.1.1), this conversion is considered an
354 // array-to-pointer conversion followed by a qualification
355 // conversion (4.4). (C++ 4.2p2)
356 ICS.Standard.Second = ICK_Identity;
357 ICS.Standard.Third = ICK_Qualification;
358 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
359 return ICS;
360 }
361 }
362 // Function-to-pointer conversion (C++ 4.3).
363 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
364 ICS.Standard.First = ICK_Function_To_Pointer;
365
366 // An lvalue of function type T can be converted to an rvalue of
367 // type "pointer to T." The result is a pointer to the
368 // function. (C++ 4.3p1).
369 FromType = Context.getPointerType(FromType);
370
371 // FIXME: Deal with overloaded functions here (C++ 4.3p2).
372 }
373 // We don't require any conversions for the first step.
374 else {
375 ICS.Standard.First = ICK_Identity;
376 }
377
378 // The second conversion can be an integral promotion, floating
379 // point promotion, integral conversion, floating point conversion,
380 // floating-integral conversion, pointer conversion,
381 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
382 if (Context.getCanonicalType(FromType).getUnqualifiedType() ==
383 Context.getCanonicalType(ToType).getUnqualifiedType()) {
384 // The unqualified versions of the types are the same: there's no
385 // conversion to do.
386 ICS.Standard.Second = ICK_Identity;
387 }
388 // Integral promotion (C++ 4.5).
389 else if (IsIntegralPromotion(From, FromType, ToType)) {
390 ICS.Standard.Second = ICK_Integral_Promotion;
391 FromType = ToType.getUnqualifiedType();
392 }
393 // Floating point promotion (C++ 4.6).
394 else if (IsFloatingPointPromotion(FromType, ToType)) {
395 ICS.Standard.Second = ICK_Floating_Promotion;
396 FromType = ToType.getUnqualifiedType();
397 }
398 // Integral conversions (C++ 4.7).
399 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
400 (ToType->isIntegralType() || ToType->isEnumeralType())) {
401 ICS.Standard.Second = ICK_Integral_Conversion;
402 FromType = ToType.getUnqualifiedType();
403 }
404 // Floating point conversions (C++ 4.8).
405 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
406 ICS.Standard.Second = ICK_Floating_Conversion;
407 FromType = ToType.getUnqualifiedType();
408 }
409 // Floating-integral conversions (C++ 4.9).
410 else if ((FromType->isFloatingType() &&
411 ToType->isIntegralType() && !ToType->isBooleanType()) ||
412 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
413 ToType->isFloatingType())) {
414 ICS.Standard.Second = ICK_Floating_Integral;
415 FromType = ToType.getUnqualifiedType();
416 }
417 // Pointer conversions (C++ 4.10).
418 else if (IsPointerConversion(From, FromType, ToType, FromType))
419 ICS.Standard.Second = ICK_Pointer_Conversion;
420 // FIXME: Pointer to member conversions (4.11).
421 // Boolean conversions (C++ 4.12).
422 // FIXME: pointer-to-member type
423 else if (ToType->isBooleanType() &&
424 (FromType->isArithmeticType() ||
425 FromType->isEnumeralType() ||
426 FromType->isPointerType())) {
427 ICS.Standard.Second = ICK_Boolean_Conversion;
428 FromType = Context.BoolTy;
429 } else {
430 // No second conversion required.
431 ICS.Standard.Second = ICK_Identity;
432 }
433
434 // The third conversion can be a qualification conversion (C++ 4p1).
435 // FIXME: CheckPointerTypesForAssignment isn't the right way to
436 // determine whether we have a qualification conversion.
437 if (Context.getCanonicalType(FromType) != Context.getCanonicalType(ToType)
438 && CheckPointerTypesForAssignment(ToType, FromType) == Compatible) {
439 ICS.Standard.Third = ICK_Qualification;
440 FromType = ToType;
441 } else {
442 // No conversion required
443 ICS.Standard.Third = ICK_Identity;
444 }
445
446 // If we have not converted the argument type to the parameter type,
447 // this is a bad conversion sequence.
448 if (Context.getCanonicalType(FromType) != Context.getCanonicalType(ToType))
449 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
450
451 ICS.Standard.ToTypePtr = FromType.getAsOpaquePtr();
452 return ICS;
453}
454
455/// IsIntegralPromotion - Determines whether the conversion from the
456/// expression From (whose potentially-adjusted type is FromType) to
457/// ToType is an integral promotion (C++ 4.5). If so, returns true and
458/// sets PromotedType to the promoted type.
459bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
460{
461 const BuiltinType *To = ToType->getAsBuiltinType();
462
463 // An rvalue of type char, signed char, unsigned char, short int, or
464 // unsigned short int can be converted to an rvalue of type int if
465 // int can represent all the values of the source type; otherwise,
466 // the source rvalue can be converted to an rvalue of type unsigned
467 // int (C++ 4.5p1).
468 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && To) {
469 if (// We can promote any signed, promotable integer type to an int
470 (FromType->isSignedIntegerType() ||
471 // We can promote any unsigned integer type whose size is
472 // less than int to an int.
473 (!FromType->isSignedIntegerType() &&
474 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))))
475 return To->getKind() == BuiltinType::Int;
476
477 return To->getKind() == BuiltinType::UInt;
478 }
479
480 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
481 // can be converted to an rvalue of the first of the following types
482 // that can represent all the values of its underlying type: int,
483 // unsigned int, long, or unsigned long (C++ 4.5p2).
484 if ((FromType->isEnumeralType() || FromType->isWideCharType())
485 && ToType->isIntegerType()) {
486 // Determine whether the type we're converting from is signed or
487 // unsigned.
488 bool FromIsSigned;
489 uint64_t FromSize = Context.getTypeSize(FromType);
490 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
491 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
492 FromIsSigned = UnderlyingType->isSignedIntegerType();
493 } else {
494 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
495 FromIsSigned = true;
496 }
497
498 // The types we'll try to promote to, in the appropriate
499 // order. Try each of these types.
500 QualType PromoteTypes[4] = {
501 Context.IntTy, Context.UnsignedIntTy,
502 Context.LongTy, Context.UnsignedLongTy
503 };
504 for (int Idx = 0; Idx < 0; ++Idx) {
505 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
506 if (FromSize < ToSize ||
507 (FromSize == ToSize &&
508 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
509 // We found the type that we can promote to. If this is the
510 // type we wanted, we have a promotion. Otherwise, no
511 // promotion.
512 return Context.getCanonicalType(FromType).getUnqualifiedType()
513 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
514 }
515 }
516 }
517
518 // An rvalue for an integral bit-field (9.6) can be converted to an
519 // rvalue of type int if int can represent all the values of the
520 // bit-field; otherwise, it can be converted to unsigned int if
521 // unsigned int can represent all the values of the bit-field. If
522 // the bit-field is larger yet, no integral promotion applies to
523 // it. If the bit-field has an enumerated type, it is treated as any
524 // other value of that type for promotion purposes (C++ 4.5p3).
525 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) {
526 using llvm::APSInt;
527 FieldDecl *MemberDecl = MemRef->getMemberDecl();
528 APSInt BitWidth;
529 if (MemberDecl->isBitField() &&
530 FromType->isIntegralType() && !FromType->isEnumeralType() &&
531 From->isIntegerConstantExpr(BitWidth, Context)) {
532 APSInt ToSize(Context.getTypeSize(ToType));
533
534 // Are we promoting to an int from a bitfield that fits in an int?
535 if (BitWidth < ToSize ||
536 (FromType->isSignedIntegerType() && BitWidth <= ToSize))
537 return To->getKind() == BuiltinType::Int;
538
539 // Are we promoting to an unsigned int from an unsigned bitfield
540 // that fits into an unsigned int?
541 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize)
542 return To->getKind() == BuiltinType::UInt;
543
544 return false;
545 }
546 }
547
548 // An rvalue of type bool can be converted to an rvalue of type int,
549 // with false becoming zero and true becoming one (C++ 4.5p4).
550 if (FromType->isBooleanType() && To && To->getKind() == BuiltinType::Int)
551 return true;
552
553 return false;
554}
555
556/// IsFloatingPointPromotion - Determines whether the conversion from
557/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
558/// returns true and sets PromotedType to the promoted type.
559bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
560{
561 /// An rvalue of type float can be converted to an rvalue of type
562 /// double. (C++ 4.6p1).
563 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
564 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType())
565 if (FromBuiltin->getKind() == BuiltinType::Float &&
566 ToBuiltin->getKind() == BuiltinType::Double)
567 return true;
568
569 return false;
570}
571
572/// IsPointerConversion - Determines whether the conversion of the
573/// expression From, which has the (possibly adjusted) type FromType,
574/// can be converted to the type ToType via a pointer conversion (C++
575/// 4.10). If so, returns true and places the converted type (that
576/// might differ from ToType in its cv-qualifiers at some level) into
577/// ConvertedType.
578bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
579 QualType& ConvertedType)
580{
581 const PointerType* ToTypePtr = ToType->getAsPointerType();
582 if (!ToTypePtr)
583 return false;
584
585 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
586 if (From->isNullPointerConstant(Context)) {
587 ConvertedType = ToType;
588 return true;
589 }
590
591 // An rvalue of type "pointer to cv T," where T is an object type,
592 // can be converted to an rvalue of type "pointer to cv void" (C++
593 // 4.10p2).
594 if (FromType->isPointerType() &&
595 FromType->getAsPointerType()->getPointeeType()->isObjectType() &&
596 ToTypePtr->getPointeeType()->isVoidType()) {
597 // We need to produce a pointer to cv void, where cv is the same
598 // set of cv-qualifiers as we had on the incoming pointee type.
599 QualType toPointee = ToTypePtr->getPointeeType();
600 unsigned Quals = Context.getCanonicalType(FromType)->getAsPointerType()
601 ->getPointeeType().getCVRQualifiers();
602
603 if (Context.getCanonicalType(ToTypePtr->getPointeeType()).getCVRQualifiers()
604 == Quals) {
605 // ToType is exactly the type we want. Use it.
606 ConvertedType = ToType;
607 } else {
608 // Build a new type with the right qualifiers.
609 ConvertedType
610 = Context.getPointerType(Context.VoidTy.getQualifiedType(Quals));
611 }
612 return true;
613 }
614
615 // FIXME: An rvalue of type "pointer to cv D," where D is a class
616 // type, can be converted to an rvalue of type "pointer to cv B,"
617 // where B is a base class (clause 10) of D (C++ 4.10p3).
618 return false;
619}
620
621/// CompareImplicitConversionSequences - Compare two implicit
622/// conversion sequences to determine whether one is better than the
623/// other or if they are indistinguishable (C++ 13.3.3.2).
624ImplicitConversionSequence::CompareKind
625Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
626 const ImplicitConversionSequence& ICS2)
627{
628 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
629 // conversion sequences (as defined in 13.3.3.1)
630 // -- a standard conversion sequence (13.3.3.1.1) is a better
631 // conversion sequence than a user-defined conversion sequence or
632 // an ellipsis conversion sequence, and
633 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
634 // conversion sequence than an ellipsis conversion sequence
635 // (13.3.3.1.3).
636 //
637 if (ICS1.ConversionKind < ICS2.ConversionKind)
638 return ImplicitConversionSequence::Better;
639 else if (ICS2.ConversionKind < ICS1.ConversionKind)
640 return ImplicitConversionSequence::Worse;
641
642 // Two implicit conversion sequences of the same form are
643 // indistinguishable conversion sequences unless one of the
644 // following rules apply: (C++ 13.3.3.2p3):
645 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
646 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
647 else if (ICS1.ConversionKind ==
648 ImplicitConversionSequence::UserDefinedConversion) {
649 // User-defined conversion sequence U1 is a better conversion
650 // sequence than another user-defined conversion sequence U2 if
651 // they contain the same user-defined conversion function or
652 // constructor and if the second standard conversion sequence of
653 // U1 is better than the second standard conversion sequence of
654 // U2 (C++ 13.3.3.2p3).
655 if (ICS1.UserDefined.ConversionFunction ==
656 ICS2.UserDefined.ConversionFunction)
657 return CompareStandardConversionSequences(ICS1.UserDefined.After,
658 ICS2.UserDefined.After);
659 }
660
661 return ImplicitConversionSequence::Indistinguishable;
662}
663
664/// CompareStandardConversionSequences - Compare two standard
665/// conversion sequences to determine whether one is better than the
666/// other or if they are indistinguishable (C++ 13.3.3.2p3).
667ImplicitConversionSequence::CompareKind
668Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
669 const StandardConversionSequence& SCS2)
670{
671 // Standard conversion sequence S1 is a better conversion sequence
672 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
673
674 // -- S1 is a proper subsequence of S2 (comparing the conversion
675 // sequences in the canonical form defined by 13.3.3.1.1,
676 // excluding any Lvalue Transformation; the identity conversion
677 // sequence is considered to be a subsequence of any
678 // non-identity conversion sequence) or, if not that,
679 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
680 // Neither is a proper subsequence of the other. Do nothing.
681 ;
682 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
683 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
684 (SCS1.Second == ICK_Identity &&
685 SCS1.Third == ICK_Identity))
686 // SCS1 is a proper subsequence of SCS2.
687 return ImplicitConversionSequence::Better;
688 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
689 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
690 (SCS2.Second == ICK_Identity &&
691 SCS2.Third == ICK_Identity))
692 // SCS2 is a proper subsequence of SCS1.
693 return ImplicitConversionSequence::Worse;
694
695 // -- the rank of S1 is better than the rank of S2 (by the rules
696 // defined below), or, if not that,
697 ImplicitConversionRank Rank1 = SCS1.getRank();
698 ImplicitConversionRank Rank2 = SCS2.getRank();
699 if (Rank1 < Rank2)
700 return ImplicitConversionSequence::Better;
701 else if (Rank2 < Rank1)
702 return ImplicitConversionSequence::Worse;
703 else {
704 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
705 // are indistinguishable unless one of the following rules
706 // applies:
707
708 // A conversion that is not a conversion of a pointer, or
709 // pointer to member, to bool is better than another conversion
710 // that is such a conversion.
711 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
712 return SCS2.isPointerConversionToBool()
713 ? ImplicitConversionSequence::Better
714 : ImplicitConversionSequence::Worse;
715
716 // FIXME: The other bullets in (C++ 13.3.3.2p4) require support
717 // for derived classes.
718 }
719
720 // FIXME: Handle comparison by qualifications.
721 // FIXME: Handle comparison of reference bindings.
722 return ImplicitConversionSequence::Indistinguishable;
723}
724
725/// AddOverloadCandidate - Adds the given function to the set of
726/// candidate functions, using the given function call arguments.
727void
728Sema::AddOverloadCandidate(FunctionDecl *Function,
729 Expr **Args, unsigned NumArgs,
730 OverloadCandidateSet& CandidateSet)
731{
732 const FunctionTypeProto* Proto
733 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType());
734 assert(Proto && "Functions without a prototype cannot be overloaded");
735
736 // Add this candidate
737 CandidateSet.push_back(OverloadCandidate());
738 OverloadCandidate& Candidate = CandidateSet.back();
739 Candidate.Function = Function;
740
741 unsigned NumArgsInProto = Proto->getNumArgs();
742
743 // (C++ 13.3.2p2): A candidate function having fewer than m
744 // parameters is viable only if it has an ellipsis in its parameter
745 // list (8.3.5).
746 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
747 Candidate.Viable = false;
748 return;
749 }
750
751 // (C++ 13.3.2p2): A candidate function having more than m parameters
752 // is viable only if the (m+1)st parameter has a default argument
753 // (8.3.6). For the purposes of overload resolution, the
754 // parameter list is truncated on the right, so that there are
755 // exactly m parameters.
756 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
757 if (NumArgs < MinRequiredArgs) {
758 // Not enough arguments.
759 Candidate.Viable = false;
760 return;
761 }
762
763 // Determine the implicit conversion sequences for each of the
764 // arguments.
765 Candidate.Viable = true;
766 Candidate.Conversions.resize(NumArgs);
767 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
768 if (ArgIdx < NumArgsInProto) {
769 // (C++ 13.3.2p3): for F to be a viable function, there shall
770 // exist for each argument an implicit conversion sequence
771 // (13.3.3.1) that converts that argument to the corresponding
772 // parameter of F.
773 QualType ParamType = Proto->getArgType(ArgIdx);
774 Candidate.Conversions[ArgIdx]
775 = TryCopyInitialization(Args[ArgIdx], ParamType);
776 if (Candidate.Conversions[ArgIdx].ConversionKind
777 == ImplicitConversionSequence::BadConversion)
778 Candidate.Viable = false;
779 } else {
780 // (C++ 13.3.2p2): For the purposes of overload resolution, any
781 // argument for which there is no corresponding parameter is
782 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
783 Candidate.Conversions[ArgIdx].ConversionKind
784 = ImplicitConversionSequence::EllipsisConversion;
785 }
786 }
787}
788
789/// AddOverloadCandidates - Add all of the function overloads in Ovl
790/// to the candidate set.
791void
792Sema::AddOverloadCandidates(OverloadedFunctionDecl *Ovl,
793 Expr **Args, unsigned NumArgs,
794 OverloadCandidateSet& CandidateSet)
795{
796 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin();
797 Func != Ovl->function_end(); ++Func)
798 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
799}
800
801/// isBetterOverloadCandidate - Determines whether the first overload
802/// candidate is a better candidate than the second (C++ 13.3.3p1).
803bool
804Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
805 const OverloadCandidate& Cand2)
806{
807 // Define viable functions to be better candidates than non-viable
808 // functions.
809 if (!Cand2.Viable)
810 return Cand1.Viable;
811 else if (!Cand1.Viable)
812 return false;
813
814 // FIXME: Deal with the implicit object parameter for static member
815 // functions. (C++ 13.3.3p1).
816
817 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
818 // function than another viable function F2 if for all arguments i,
819 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
820 // then...
821 unsigned NumArgs = Cand1.Conversions.size();
822 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
823 bool HasBetterConversion = false;
824 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
825 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
826 Cand2.Conversions[ArgIdx])) {
827 case ImplicitConversionSequence::Better:
828 // Cand1 has a better conversion sequence.
829 HasBetterConversion = true;
830 break;
831
832 case ImplicitConversionSequence::Worse:
833 // Cand1 can't be better than Cand2.
834 return false;
835
836 case ImplicitConversionSequence::Indistinguishable:
837 // Do nothing.
838 break;
839 }
840 }
841
842 if (HasBetterConversion)
843 return true;
844
845 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be implemented.
846
847 return false;
848}
849
850/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
851/// within an overload candidate set. If overloading is successful,
852/// the result will be OR_Success and Best will be set to point to the
853/// best viable function within the candidate set. Otherwise, one of
854/// several kinds of errors will be returned; see
855/// Sema::OverloadingResult.
856Sema::OverloadingResult
857Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
858 OverloadCandidateSet::iterator& Best)
859{
860 // Find the best viable function.
861 Best = CandidateSet.end();
862 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
863 Cand != CandidateSet.end(); ++Cand) {
864 if (Cand->Viable) {
865 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
866 Best = Cand;
867 }
868 }
869
870 // If we didn't find any viable functions, abort.
871 if (Best == CandidateSet.end())
872 return OR_No_Viable_Function;
873
874 // Make sure that this function is better than every other viable
875 // function. If not, we have an ambiguity.
876 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
877 Cand != CandidateSet.end(); ++Cand) {
878 if (Cand->Viable &&
879 Cand != Best &&
880 !isBetterOverloadCandidate(*Best, *Cand))
881 return OR_Ambiguous;
882 }
883
884 // Best is the best viable function.
885 return OR_Success;
886}
887
888/// PrintOverloadCandidates - When overload resolution fails, prints
889/// diagnostic messages containing the candidates in the candidate
890/// set. If OnlyViable is true, only viable candidates will be printed.
891void
892Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
893 bool OnlyViable)
894{
895 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
896 LastCand = CandidateSet.end();
897 for (; Cand != LastCand; ++Cand) {
898 if (Cand->Viable ||!OnlyViable)
899 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
900 }
901}
902
903} // end namespace clang