blob: c967b043352869a560c97d453cf09de4332fe33e [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
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000124/// isPointerConversionToVoidPointer - Determines whether this
125/// conversion is a conversion of a pointer to a void pointer. This is
126/// used as part of the ranking of standard conversion sequences (C++
127/// 13.3.3.2p4).
128bool
129StandardConversionSequence::
130isPointerConversionToVoidPointer(ASTContext& Context) const
131{
132 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
133 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
134
135 // Note that FromType has not necessarily been transformed by the
136 // array-to-pointer implicit conversion, so check for its presence
137 // and redo the conversion to get a pointer.
138 if (First == ICK_Array_To_Pointer)
139 FromType = Context.getArrayDecayedType(FromType);
140
141 if (Second == ICK_Pointer_Conversion)
142 if (const PointerType* ToPtrType = ToType->getAsPointerType())
143 return ToPtrType->getPointeeType()->isVoidType();
144
145 return false;
146}
147
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000148/// DebugPrint - Print this standard conversion sequence to standard
149/// error. Useful for debugging overloading issues.
150void StandardConversionSequence::DebugPrint() const {
151 bool PrintedSomething = false;
152 if (First != ICK_Identity) {
153 fprintf(stderr, "%s", GetImplicitConversionName(First));
154 PrintedSomething = true;
155 }
156
157 if (Second != ICK_Identity) {
158 if (PrintedSomething) {
159 fprintf(stderr, " -> ");
160 }
161 fprintf(stderr, "%s", GetImplicitConversionName(Second));
162 PrintedSomething = true;
163 }
164
165 if (Third != ICK_Identity) {
166 if (PrintedSomething) {
167 fprintf(stderr, " -> ");
168 }
169 fprintf(stderr, "%s", GetImplicitConversionName(Third));
170 PrintedSomething = true;
171 }
172
173 if (!PrintedSomething) {
174 fprintf(stderr, "No conversions required");
175 }
176}
177
178/// DebugPrint - Print this user-defined conversion sequence to standard
179/// error. Useful for debugging overloading issues.
180void UserDefinedConversionSequence::DebugPrint() const {
181 if (Before.First || Before.Second || Before.Third) {
182 Before.DebugPrint();
183 fprintf(stderr, " -> ");
184 }
185 fprintf(stderr, "'%s'", ConversionFunction->getName());
186 if (After.First || After.Second || After.Third) {
187 fprintf(stderr, " -> ");
188 After.DebugPrint();
189 }
190}
191
192/// DebugPrint - Print this implicit conversion sequence to standard
193/// error. Useful for debugging overloading issues.
194void ImplicitConversionSequence::DebugPrint() const {
195 switch (ConversionKind) {
196 case StandardConversion:
197 fprintf(stderr, "Standard conversion: ");
198 Standard.DebugPrint();
199 break;
200 case UserDefinedConversion:
201 fprintf(stderr, "User-defined conversion: ");
202 UserDefined.DebugPrint();
203 break;
204 case EllipsisConversion:
205 fprintf(stderr, "Ellipsis conversion");
206 break;
207 case BadConversion:
208 fprintf(stderr, "Bad conversion");
209 break;
210 }
211
212 fprintf(stderr, "\n");
213}
214
215// IsOverload - Determine whether the given New declaration is an
216// overload of the Old declaration. This routine returns false if New
217// and Old cannot be overloaded, e.g., if they are functions with the
218// same signature (C++ 1.3.10) or if the Old declaration isn't a
219// function (or overload set). When it does return false and Old is an
220// OverloadedFunctionDecl, MatchedDecl will be set to point to the
221// FunctionDecl that New cannot be overloaded with.
222//
223// Example: Given the following input:
224//
225// void f(int, float); // #1
226// void f(int, int); // #2
227// int f(int, int); // #3
228//
229// When we process #1, there is no previous declaration of "f",
230// so IsOverload will not be used.
231//
232// When we process #2, Old is a FunctionDecl for #1. By comparing the
233// parameter types, we see that #1 and #2 are overloaded (since they
234// have different signatures), so this routine returns false;
235// MatchedDecl is unchanged.
236//
237// When we process #3, Old is an OverloadedFunctionDecl containing #1
238// and #2. We compare the signatures of #3 to #1 (they're overloaded,
239// so we do nothing) and then #3 to #2. Since the signatures of #3 and
240// #2 are identical (return types of functions are not part of the
241// signature), IsOverload returns false and MatchedDecl will be set to
242// point to the FunctionDecl for #2.
243bool
244Sema::IsOverload(FunctionDecl *New, Decl* OldD,
245 OverloadedFunctionDecl::function_iterator& MatchedDecl)
246{
247 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
248 // Is this new function an overload of every function in the
249 // overload set?
250 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
251 FuncEnd = Ovl->function_end();
252 for (; Func != FuncEnd; ++Func) {
253 if (!IsOverload(New, *Func, MatchedDecl)) {
254 MatchedDecl = Func;
255 return false;
256 }
257 }
258
259 // This function overloads every function in the overload set.
260 return true;
261 } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
262 // Is the function New an overload of the function Old?
263 QualType OldQType = Context.getCanonicalType(Old->getType());
264 QualType NewQType = Context.getCanonicalType(New->getType());
265
266 // Compare the signatures (C++ 1.3.10) of the two functions to
267 // determine whether they are overloads. If we find any mismatch
268 // in the signature, they are overloads.
269
270 // If either of these functions is a K&R-style function (no
271 // prototype), then we consider them to have matching signatures.
272 if (isa<FunctionTypeNoProto>(OldQType.getTypePtr()) ||
273 isa<FunctionTypeNoProto>(NewQType.getTypePtr()))
274 return false;
275
276 FunctionTypeProto* OldType = cast<FunctionTypeProto>(OldQType.getTypePtr());
277 FunctionTypeProto* NewType = cast<FunctionTypeProto>(NewQType.getTypePtr());
278
279 // The signature of a function includes the types of its
280 // parameters (C++ 1.3.10), which includes the presence or absence
281 // of the ellipsis; see C++ DR 357).
282 if (OldQType != NewQType &&
283 (OldType->getNumArgs() != NewType->getNumArgs() ||
284 OldType->isVariadic() != NewType->isVariadic() ||
285 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
286 NewType->arg_type_begin())))
287 return true;
288
289 // If the function is a class member, its signature includes the
290 // cv-qualifiers (if any) on the function itself.
291 //
292 // As part of this, also check whether one of the member functions
293 // is static, in which case they are not overloads (C++
294 // 13.1p2). While not part of the definition of the signature,
295 // this check is important to determine whether these functions
296 // can be overloaded.
297 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
298 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
299 if (OldMethod && NewMethod &&
300 !OldMethod->isStatic() && !NewMethod->isStatic() &&
301 OldQType.getCVRQualifiers() != NewQType.getCVRQualifiers())
302 return true;
303
304 // The signatures match; this is not an overload.
305 return false;
306 } else {
307 // (C++ 13p1):
308 // Only function declarations can be overloaded; object and type
309 // declarations cannot be overloaded.
310 return false;
311 }
312}
313
314/// TryCopyInitialization - Attempt to copy-initialize a value of the
315/// given type (ToType) from the given expression (Expr), as one would
316/// do when copy-initializing a function parameter. This function
317/// returns an implicit conversion sequence that can be used to
318/// perform the initialization. Given
319///
320/// void f(float f);
321/// void g(int i) { f(i); }
322///
323/// this routine would produce an implicit conversion sequence to
324/// describe the initialization of f from i, which will be a standard
325/// conversion sequence containing an lvalue-to-rvalue conversion (C++
326/// 4.1) followed by a floating-integral conversion (C++ 4.9).
327//
328/// Note that this routine only determines how the conversion can be
329/// performed; it does not actually perform the conversion. As such,
330/// it will not produce any diagnostics if no conversion is available,
331/// but will instead return an implicit conversion sequence of kind
332/// "BadConversion".
333ImplicitConversionSequence
334Sema::TryCopyInitialization(Expr* From, QualType ToType)
335{
336 ImplicitConversionSequence ICS;
337
338 QualType FromType = From->getType();
339
340 // Standard conversions (C++ 4)
341 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
342 ICS.Standard.Deprecated = false;
343 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
344
Douglas Gregor98cd5992008-10-21 23:43:52 +0000345 if (const ReferenceType *ToTypeRef = ToType->getAsReferenceType()) {
346 // FIXME: This is a hack to deal with the initialization of
347 // references the way that the C-centric code elsewhere deals with
348 // references, by only allowing them if the referred-to type is
349 // exactly the same. This means that we're only handling the
350 // direct-binding case. The code will be replaced by an
351 // implementation of C++ 13.3.3.1.4 once we have the
352 // initialization of references implemented.
353 QualType ToPointee = Context.getCanonicalType(ToTypeRef->getPointeeType());
354
355 // Get down to the canonical type that we're converting from.
356 if (const ReferenceType *FromTypeRef = FromType->getAsReferenceType())
357 FromType = FromTypeRef->getPointeeType();
358 FromType = Context.getCanonicalType(FromType);
359
360 ICS.Standard.First = ICK_Identity;
361 ICS.Standard.Second = ICK_Identity;
362 ICS.Standard.Third = ICK_Identity;
363 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
364
365 if (FromType != ToPointee)
366 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
367
368 return ICS;
369 }
370
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000371 // The first conversion can be an lvalue-to-rvalue conversion,
372 // array-to-pointer conversion, or function-to-pointer conversion
373 // (C++ 4p1).
374
375 // Lvalue-to-rvalue conversion (C++ 4.1):
376 // An lvalue (3.10) of a non-function, non-array type T can be
377 // converted to an rvalue.
378 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
379 if (argIsLvalue == Expr::LV_Valid &&
380 !FromType->isFunctionType() && !FromType->isArrayType()) {
381 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
382
383 // If T is a non-class type, the type of the rvalue is the
384 // cv-unqualified version of T. Otherwise, the type of the rvalue
385 // is T (C++ 4.1p1).
386 if (!FromType->isRecordType())
387 FromType = FromType.getUnqualifiedType();
388 }
389 // Array-to-pointer conversion (C++ 4.2)
390 else if (FromType->isArrayType()) {
391 ICS.Standard.First = ICK_Array_To_Pointer;
392
393 // An lvalue or rvalue of type "array of N T" or "array of unknown
394 // bound of T" can be converted to an rvalue of type "pointer to
395 // T" (C++ 4.2p1).
396 FromType = Context.getArrayDecayedType(FromType);
397
398 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
399 // This conversion is deprecated. (C++ D.4).
400 ICS.Standard.Deprecated = true;
401
402 // For the purpose of ranking in overload resolution
403 // (13.3.3.1.1), this conversion is considered an
404 // array-to-pointer conversion followed by a qualification
405 // conversion (4.4). (C++ 4.2p2)
406 ICS.Standard.Second = ICK_Identity;
407 ICS.Standard.Third = ICK_Qualification;
408 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
409 return ICS;
410 }
411 }
412 // Function-to-pointer conversion (C++ 4.3).
413 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
414 ICS.Standard.First = ICK_Function_To_Pointer;
415
416 // An lvalue of function type T can be converted to an rvalue of
417 // type "pointer to T." The result is a pointer to the
418 // function. (C++ 4.3p1).
419 FromType = Context.getPointerType(FromType);
420
421 // FIXME: Deal with overloaded functions here (C++ 4.3p2).
422 }
423 // We don't require any conversions for the first step.
424 else {
425 ICS.Standard.First = ICK_Identity;
426 }
427
428 // The second conversion can be an integral promotion, floating
429 // point promotion, integral conversion, floating point conversion,
430 // floating-integral conversion, pointer conversion,
431 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
432 if (Context.getCanonicalType(FromType).getUnqualifiedType() ==
433 Context.getCanonicalType(ToType).getUnqualifiedType()) {
434 // The unqualified versions of the types are the same: there's no
435 // conversion to do.
436 ICS.Standard.Second = ICK_Identity;
437 }
438 // Integral promotion (C++ 4.5).
439 else if (IsIntegralPromotion(From, FromType, ToType)) {
440 ICS.Standard.Second = ICK_Integral_Promotion;
441 FromType = ToType.getUnqualifiedType();
442 }
443 // Floating point promotion (C++ 4.6).
444 else if (IsFloatingPointPromotion(FromType, ToType)) {
445 ICS.Standard.Second = ICK_Floating_Promotion;
446 FromType = ToType.getUnqualifiedType();
447 }
448 // Integral conversions (C++ 4.7).
449 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
450 (ToType->isIntegralType() || ToType->isEnumeralType())) {
451 ICS.Standard.Second = ICK_Integral_Conversion;
452 FromType = ToType.getUnqualifiedType();
453 }
454 // Floating point conversions (C++ 4.8).
455 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
456 ICS.Standard.Second = ICK_Floating_Conversion;
457 FromType = ToType.getUnqualifiedType();
458 }
459 // Floating-integral conversions (C++ 4.9).
460 else if ((FromType->isFloatingType() &&
461 ToType->isIntegralType() && !ToType->isBooleanType()) ||
462 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
463 ToType->isFloatingType())) {
464 ICS.Standard.Second = ICK_Floating_Integral;
465 FromType = ToType.getUnqualifiedType();
466 }
467 // Pointer conversions (C++ 4.10).
468 else if (IsPointerConversion(From, FromType, ToType, FromType))
469 ICS.Standard.Second = ICK_Pointer_Conversion;
470 // FIXME: Pointer to member conversions (4.11).
471 // Boolean conversions (C++ 4.12).
472 // FIXME: pointer-to-member type
473 else if (ToType->isBooleanType() &&
474 (FromType->isArithmeticType() ||
475 FromType->isEnumeralType() ||
476 FromType->isPointerType())) {
477 ICS.Standard.Second = ICK_Boolean_Conversion;
478 FromType = Context.BoolTy;
479 } else {
480 // No second conversion required.
481 ICS.Standard.Second = ICK_Identity;
482 }
483
484 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000485 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000486 ICS.Standard.Third = ICK_Qualification;
487 FromType = ToType;
488 } else {
489 // No conversion required
490 ICS.Standard.Third = ICK_Identity;
491 }
492
493 // If we have not converted the argument type to the parameter type,
494 // this is a bad conversion sequence.
495 if (Context.getCanonicalType(FromType) != Context.getCanonicalType(ToType))
496 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
497
498 ICS.Standard.ToTypePtr = FromType.getAsOpaquePtr();
499 return ICS;
500}
501
502/// IsIntegralPromotion - Determines whether the conversion from the
503/// expression From (whose potentially-adjusted type is FromType) to
504/// ToType is an integral promotion (C++ 4.5). If so, returns true and
505/// sets PromotedType to the promoted type.
506bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
507{
508 const BuiltinType *To = ToType->getAsBuiltinType();
509
510 // An rvalue of type char, signed char, unsigned char, short int, or
511 // unsigned short int can be converted to an rvalue of type int if
512 // int can represent all the values of the source type; otherwise,
513 // the source rvalue can be converted to an rvalue of type unsigned
514 // int (C++ 4.5p1).
515 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && To) {
516 if (// We can promote any signed, promotable integer type to an int
517 (FromType->isSignedIntegerType() ||
518 // We can promote any unsigned integer type whose size is
519 // less than int to an int.
520 (!FromType->isSignedIntegerType() &&
521 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))))
522 return To->getKind() == BuiltinType::Int;
523
524 return To->getKind() == BuiltinType::UInt;
525 }
526
527 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
528 // can be converted to an rvalue of the first of the following types
529 // that can represent all the values of its underlying type: int,
530 // unsigned int, long, or unsigned long (C++ 4.5p2).
531 if ((FromType->isEnumeralType() || FromType->isWideCharType())
532 && ToType->isIntegerType()) {
533 // Determine whether the type we're converting from is signed or
534 // unsigned.
535 bool FromIsSigned;
536 uint64_t FromSize = Context.getTypeSize(FromType);
537 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
538 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
539 FromIsSigned = UnderlyingType->isSignedIntegerType();
540 } else {
541 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
542 FromIsSigned = true;
543 }
544
545 // The types we'll try to promote to, in the appropriate
546 // order. Try each of these types.
547 QualType PromoteTypes[4] = {
548 Context.IntTy, Context.UnsignedIntTy,
549 Context.LongTy, Context.UnsignedLongTy
550 };
551 for (int Idx = 0; Idx < 0; ++Idx) {
552 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
553 if (FromSize < ToSize ||
554 (FromSize == ToSize &&
555 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
556 // We found the type that we can promote to. If this is the
557 // type we wanted, we have a promotion. Otherwise, no
558 // promotion.
559 return Context.getCanonicalType(FromType).getUnqualifiedType()
560 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
561 }
562 }
563 }
564
565 // An rvalue for an integral bit-field (9.6) can be converted to an
566 // rvalue of type int if int can represent all the values of the
567 // bit-field; otherwise, it can be converted to unsigned int if
568 // unsigned int can represent all the values of the bit-field. If
569 // the bit-field is larger yet, no integral promotion applies to
570 // it. If the bit-field has an enumerated type, it is treated as any
571 // other value of that type for promotion purposes (C++ 4.5p3).
572 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) {
573 using llvm::APSInt;
574 FieldDecl *MemberDecl = MemRef->getMemberDecl();
575 APSInt BitWidth;
576 if (MemberDecl->isBitField() &&
577 FromType->isIntegralType() && !FromType->isEnumeralType() &&
578 From->isIntegerConstantExpr(BitWidth, Context)) {
579 APSInt ToSize(Context.getTypeSize(ToType));
580
581 // Are we promoting to an int from a bitfield that fits in an int?
582 if (BitWidth < ToSize ||
583 (FromType->isSignedIntegerType() && BitWidth <= ToSize))
584 return To->getKind() == BuiltinType::Int;
585
586 // Are we promoting to an unsigned int from an unsigned bitfield
587 // that fits into an unsigned int?
588 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize)
589 return To->getKind() == BuiltinType::UInt;
590
591 return false;
592 }
593 }
594
595 // An rvalue of type bool can be converted to an rvalue of type int,
596 // with false becoming zero and true becoming one (C++ 4.5p4).
597 if (FromType->isBooleanType() && To && To->getKind() == BuiltinType::Int)
598 return true;
599
600 return false;
601}
602
603/// IsFloatingPointPromotion - Determines whether the conversion from
604/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
605/// returns true and sets PromotedType to the promoted type.
606bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
607{
608 /// An rvalue of type float can be converted to an rvalue of type
609 /// double. (C++ 4.6p1).
610 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
611 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType())
612 if (FromBuiltin->getKind() == BuiltinType::Float &&
613 ToBuiltin->getKind() == BuiltinType::Double)
614 return true;
615
616 return false;
617}
618
619/// IsPointerConversion - Determines whether the conversion of the
620/// expression From, which has the (possibly adjusted) type FromType,
621/// can be converted to the type ToType via a pointer conversion (C++
622/// 4.10). If so, returns true and places the converted type (that
623/// might differ from ToType in its cv-qualifiers at some level) into
624/// ConvertedType.
625bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
626 QualType& ConvertedType)
627{
628 const PointerType* ToTypePtr = ToType->getAsPointerType();
629 if (!ToTypePtr)
630 return false;
631
632 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
633 if (From->isNullPointerConstant(Context)) {
634 ConvertedType = ToType;
635 return true;
636 }
637
638 // An rvalue of type "pointer to cv T," where T is an object type,
639 // can be converted to an rvalue of type "pointer to cv void" (C++
640 // 4.10p2).
641 if (FromType->isPointerType() &&
642 FromType->getAsPointerType()->getPointeeType()->isObjectType() &&
643 ToTypePtr->getPointeeType()->isVoidType()) {
644 // We need to produce a pointer to cv void, where cv is the same
645 // set of cv-qualifiers as we had on the incoming pointee type.
646 QualType toPointee = ToTypePtr->getPointeeType();
647 unsigned Quals = Context.getCanonicalType(FromType)->getAsPointerType()
648 ->getPointeeType().getCVRQualifiers();
649
650 if (Context.getCanonicalType(ToTypePtr->getPointeeType()).getCVRQualifiers()
651 == Quals) {
652 // ToType is exactly the type we want. Use it.
653 ConvertedType = ToType;
654 } else {
655 // Build a new type with the right qualifiers.
656 ConvertedType
657 = Context.getPointerType(Context.VoidTy.getQualifiedType(Quals));
658 }
659 return true;
660 }
661
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000662 // C++ [conv.ptr]p3:
663 //
664 // An rvalue of type "pointer to cv D," where D is a class type,
665 // can be converted to an rvalue of type "pointer to cv B," where
666 // B is a base class (clause 10) of D. If B is an inaccessible
667 // (clause 11) or ambiguous (10.2) base class of D, a program that
668 // necessitates this conversion is ill-formed. The result of the
669 // conversion is a pointer to the base class sub-object of the
670 // derived class object. The null pointer value is converted to
671 // the null pointer value of the destination type.
672 //
673 // Note that we do not check for ambiguity or inaccessibility here.
674 if (const PointerType *FromPtrType = FromType->getAsPointerType())
675 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
676 if (FromPtrType->getPointeeType()->isRecordType() &&
677 ToPtrType->getPointeeType()->isRecordType() &&
678 IsDerivedFrom(FromPtrType->getPointeeType(),
679 ToPtrType->getPointeeType())) {
680 // The conversion is okay. Now, we need to produce the type
681 // that results from this conversion, which will have the same
682 // qualifiers as the incoming type.
683 QualType CanonFromPointee
684 = Context.getCanonicalType(FromPtrType->getPointeeType());
685 QualType ToPointee = ToPtrType->getPointeeType();
686 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
687 unsigned Quals = CanonFromPointee.getCVRQualifiers();
688
689 if (CanonToPointee.getCVRQualifiers() == Quals) {
690 // ToType is exactly the type we want. Use it.
691 ConvertedType = ToType;
692 } else {
693 // Build a new type with the right qualifiers.
694 ConvertedType
695 = Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
696 }
697 return true;
698 }
699 }
700
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000701 return false;
702}
703
Douglas Gregor98cd5992008-10-21 23:43:52 +0000704/// IsQualificationConversion - Determines whether the conversion from
705/// an rvalue of type FromType to ToType is a qualification conversion
706/// (C++ 4.4).
707bool
708Sema::IsQualificationConversion(QualType FromType, QualType ToType)
709{
710 FromType = Context.getCanonicalType(FromType);
711 ToType = Context.getCanonicalType(ToType);
712
713 // If FromType and ToType are the same type, this is not a
714 // qualification conversion.
715 if (FromType == ToType)
716 return false;
717
718 // (C++ 4.4p4):
719 // A conversion can add cv-qualifiers at levels other than the first
720 // in multi-level pointers, subject to the following rules: [...]
721 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +0000722 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +0000723 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +0000724 // Within each iteration of the loop, we check the qualifiers to
725 // determine if this still looks like a qualification
726 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000727 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +0000728 // until there are no more pointers or pointers-to-members left to
729 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +0000730 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +0000731
732 // -- for every j > 0, if const is in cv 1,j then const is in cv
733 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +0000734 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +0000735 return false;
Douglas Gregor57373262008-10-22 14:17:15 +0000736
Douglas Gregor98cd5992008-10-21 23:43:52 +0000737 // -- if the cv 1,j and cv 2,j are different, then const is in
738 // every cv for 0 < k < j.
739 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +0000740 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +0000741 return false;
Douglas Gregor57373262008-10-22 14:17:15 +0000742
Douglas Gregor98cd5992008-10-21 23:43:52 +0000743 // Keep track of whether all prior cv-qualifiers in the "to" type
744 // include const.
745 PreviousToQualsIncludeConst
746 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +0000747 }
Douglas Gregor98cd5992008-10-21 23:43:52 +0000748
749 // We are left with FromType and ToType being the pointee types
750 // after unwrapping the original FromType and ToType the same number
751 // of types. If we unwrapped any pointers, and if FromType and
752 // ToType have the same unqualified type (since we checked
753 // qualifiers above), then this is a qualification conversion.
754 return UnwrappedAnyPointer &&
755 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
756}
757
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000758/// CompareImplicitConversionSequences - Compare two implicit
759/// conversion sequences to determine whether one is better than the
760/// other or if they are indistinguishable (C++ 13.3.3.2).
761ImplicitConversionSequence::CompareKind
762Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
763 const ImplicitConversionSequence& ICS2)
764{
765 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
766 // conversion sequences (as defined in 13.3.3.1)
767 // -- a standard conversion sequence (13.3.3.1.1) is a better
768 // conversion sequence than a user-defined conversion sequence or
769 // an ellipsis conversion sequence, and
770 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
771 // conversion sequence than an ellipsis conversion sequence
772 // (13.3.3.1.3).
773 //
774 if (ICS1.ConversionKind < ICS2.ConversionKind)
775 return ImplicitConversionSequence::Better;
776 else if (ICS2.ConversionKind < ICS1.ConversionKind)
777 return ImplicitConversionSequence::Worse;
778
779 // Two implicit conversion sequences of the same form are
780 // indistinguishable conversion sequences unless one of the
781 // following rules apply: (C++ 13.3.3.2p3):
782 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
783 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
784 else if (ICS1.ConversionKind ==
785 ImplicitConversionSequence::UserDefinedConversion) {
786 // User-defined conversion sequence U1 is a better conversion
787 // sequence than another user-defined conversion sequence U2 if
788 // they contain the same user-defined conversion function or
789 // constructor and if the second standard conversion sequence of
790 // U1 is better than the second standard conversion sequence of
791 // U2 (C++ 13.3.3.2p3).
792 if (ICS1.UserDefined.ConversionFunction ==
793 ICS2.UserDefined.ConversionFunction)
794 return CompareStandardConversionSequences(ICS1.UserDefined.After,
795 ICS2.UserDefined.After);
796 }
797
798 return ImplicitConversionSequence::Indistinguishable;
799}
800
801/// CompareStandardConversionSequences - Compare two standard
802/// conversion sequences to determine whether one is better than the
803/// other or if they are indistinguishable (C++ 13.3.3.2p3).
804ImplicitConversionSequence::CompareKind
805Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
806 const StandardConversionSequence& SCS2)
807{
808 // Standard conversion sequence S1 is a better conversion sequence
809 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
810
811 // -- S1 is a proper subsequence of S2 (comparing the conversion
812 // sequences in the canonical form defined by 13.3.3.1.1,
813 // excluding any Lvalue Transformation; the identity conversion
814 // sequence is considered to be a subsequence of any
815 // non-identity conversion sequence) or, if not that,
816 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
817 // Neither is a proper subsequence of the other. Do nothing.
818 ;
819 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
820 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
821 (SCS1.Second == ICK_Identity &&
822 SCS1.Third == ICK_Identity))
823 // SCS1 is a proper subsequence of SCS2.
824 return ImplicitConversionSequence::Better;
825 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
826 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
827 (SCS2.Second == ICK_Identity &&
828 SCS2.Third == ICK_Identity))
829 // SCS2 is a proper subsequence of SCS1.
830 return ImplicitConversionSequence::Worse;
831
832 // -- the rank of S1 is better than the rank of S2 (by the rules
833 // defined below), or, if not that,
834 ImplicitConversionRank Rank1 = SCS1.getRank();
835 ImplicitConversionRank Rank2 = SCS2.getRank();
836 if (Rank1 < Rank2)
837 return ImplicitConversionSequence::Better;
838 else if (Rank2 < Rank1)
839 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000840
Douglas Gregor57373262008-10-22 14:17:15 +0000841 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
842 // are indistinguishable unless one of the following rules
843 // applies:
844
845 // A conversion that is not a conversion of a pointer, or
846 // pointer to member, to bool is better than another conversion
847 // that is such a conversion.
848 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
849 return SCS2.isPointerConversionToBool()
850 ? ImplicitConversionSequence::Better
851 : ImplicitConversionSequence::Worse;
852
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000853 // C++ [over.ics.rank]p4b2:
854 //
855 // If class B is derived directly or indirectly from class A,
856 // conversion of B* to A* is better than conversion of B* to void*,
857 // and (FIXME) conversion of A* to void* is better than conversion of B*
858 // to void*.
859 bool SCS1ConvertsToVoid
860 = SCS1.isPointerConversionToVoidPointer(Context);
861 bool SCS2ConvertsToVoid
862 = SCS2.isPointerConversionToVoidPointer(Context);
863 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid)
864 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
865 : ImplicitConversionSequence::Worse;
866
867 if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid)
868 if (ImplicitConversionSequence::CompareKind DerivedCK
869 = CompareDerivedToBaseConversions(SCS1, SCS2))
870 return DerivedCK;
Douglas Gregor57373262008-10-22 14:17:15 +0000871
872 // Compare based on qualification conversions (C++ 13.3.3.2p3,
873 // bullet 3).
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000874 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +0000875 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000876 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +0000877
878 // FIXME: Handle comparison of reference bindings.
879
880 return ImplicitConversionSequence::Indistinguishable;
881}
882
883/// CompareQualificationConversions - Compares two standard conversion
884/// sequences to determine whether they can be ranked based on their
885/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
886ImplicitConversionSequence::CompareKind
887Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
888 const StandardConversionSequence& SCS2)
889{
Douglas Gregorba7e2102008-10-22 15:04:37 +0000890 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +0000891 // -- S1 and S2 differ only in their qualification conversion and
892 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
893 // cv-qualification signature of type T1 is a proper subset of
894 // the cv-qualification signature of type T2, and S1 is not the
895 // deprecated string literal array-to-pointer conversion (4.2).
896 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
897 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
898 return ImplicitConversionSequence::Indistinguishable;
899
900 // FIXME: the example in the standard doesn't use a qualification
901 // conversion (!)
902 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
903 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
904 T1 = Context.getCanonicalType(T1);
905 T2 = Context.getCanonicalType(T2);
906
907 // If the types are the same, we won't learn anything by unwrapped
908 // them.
909 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
910 return ImplicitConversionSequence::Indistinguishable;
911
912 ImplicitConversionSequence::CompareKind Result
913 = ImplicitConversionSequence::Indistinguishable;
914 while (UnwrapSimilarPointerTypes(T1, T2)) {
915 // Within each iteration of the loop, we check the qualifiers to
916 // determine if this still looks like a qualification
917 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000918 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +0000919 // until there are no more pointers or pointers-to-members left
920 // to unwrap. This essentially mimics what
921 // IsQualificationConversion does, but here we're checking for a
922 // strict subset of qualifiers.
923 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
924 // The qualifiers are the same, so this doesn't tell us anything
925 // about how the sequences rank.
926 ;
927 else if (T2.isMoreQualifiedThan(T1)) {
928 // T1 has fewer qualifiers, so it could be the better sequence.
929 if (Result == ImplicitConversionSequence::Worse)
930 // Neither has qualifiers that are a subset of the other's
931 // qualifiers.
932 return ImplicitConversionSequence::Indistinguishable;
933
934 Result = ImplicitConversionSequence::Better;
935 } else if (T1.isMoreQualifiedThan(T2)) {
936 // T2 has fewer qualifiers, so it could be the better sequence.
937 if (Result == ImplicitConversionSequence::Better)
938 // Neither has qualifiers that are a subset of the other's
939 // qualifiers.
940 return ImplicitConversionSequence::Indistinguishable;
941
942 Result = ImplicitConversionSequence::Worse;
943 } else {
944 // Qualifiers are disjoint.
945 return ImplicitConversionSequence::Indistinguishable;
946 }
947
948 // If the types after this point are equivalent, we're done.
949 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
950 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000951 }
952
Douglas Gregor57373262008-10-22 14:17:15 +0000953 // Check that the winning standard conversion sequence isn't using
954 // the deprecated string literal array to pointer conversion.
955 switch (Result) {
956 case ImplicitConversionSequence::Better:
957 if (SCS1.Deprecated)
958 Result = ImplicitConversionSequence::Indistinguishable;
959 break;
960
961 case ImplicitConversionSequence::Indistinguishable:
962 break;
963
964 case ImplicitConversionSequence::Worse:
965 if (SCS2.Deprecated)
966 Result = ImplicitConversionSequence::Indistinguishable;
967 break;
968 }
969
970 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000971}
972
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000973/// CompareDerivedToBaseConversions - Compares two standard conversion
974/// sequences to determine whether they can be ranked based on their
975/// various kinds of derived-to-base conversions (C++ [over.ics.rank]p4b3).
976ImplicitConversionSequence::CompareKind
977Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
978 const StandardConversionSequence& SCS2) {
979 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
980 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
981 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
982 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
983
984 // Adjust the types we're converting from via the array-to-pointer
985 // conversion, if we need to.
986 if (SCS1.First == ICK_Array_To_Pointer)
987 FromType1 = Context.getArrayDecayedType(FromType1);
988 if (SCS2.First == ICK_Array_To_Pointer)
989 FromType2 = Context.getArrayDecayedType(FromType2);
990
991 // Canonicalize all of the types.
992 FromType1 = Context.getCanonicalType(FromType1);
993 ToType1 = Context.getCanonicalType(ToType1);
994 FromType2 = Context.getCanonicalType(FromType2);
995 ToType2 = Context.getCanonicalType(ToType2);
996
997 // C++ [over.ics.rank]p4b4:
998 //
999 // If class B is derived directly or indirectly from class A and
1000 // class C is derived directly or indirectly from B,
1001 //
1002 // FIXME: Verify that in this section we're talking about the
1003 // unqualified forms of C, B, and A.
1004 if (SCS1.Second == ICK_Pointer_Conversion &&
1005 SCS2.Second == ICK_Pointer_Conversion) {
1006 // -- conversion of C* to B* is better than conversion of C* to A*,
1007 QualType FromPointee1
1008 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1009 QualType ToPointee1
1010 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1011 QualType FromPointee2
1012 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1013 QualType ToPointee2
1014 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1015 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1016 if (IsDerivedFrom(ToPointee1, ToPointee2))
1017 return ImplicitConversionSequence::Better;
1018 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1019 return ImplicitConversionSequence::Worse;
1020 }
1021 }
1022
1023 // FIXME: many more sub-bullets of C++ [over.ics.rank]p4b4 to
1024 // implement.
1025 return ImplicitConversionSequence::Indistinguishable;
1026}
1027
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001028/// AddOverloadCandidate - Adds the given function to the set of
1029/// candidate functions, using the given function call arguments.
1030void
1031Sema::AddOverloadCandidate(FunctionDecl *Function,
1032 Expr **Args, unsigned NumArgs,
1033 OverloadCandidateSet& CandidateSet)
1034{
1035 const FunctionTypeProto* Proto
1036 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType());
1037 assert(Proto && "Functions without a prototype cannot be overloaded");
1038
1039 // Add this candidate
1040 CandidateSet.push_back(OverloadCandidate());
1041 OverloadCandidate& Candidate = CandidateSet.back();
1042 Candidate.Function = Function;
1043
1044 unsigned NumArgsInProto = Proto->getNumArgs();
1045
1046 // (C++ 13.3.2p2): A candidate function having fewer than m
1047 // parameters is viable only if it has an ellipsis in its parameter
1048 // list (8.3.5).
1049 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1050 Candidate.Viable = false;
1051 return;
1052 }
1053
1054 // (C++ 13.3.2p2): A candidate function having more than m parameters
1055 // is viable only if the (m+1)st parameter has a default argument
1056 // (8.3.6). For the purposes of overload resolution, the
1057 // parameter list is truncated on the right, so that there are
1058 // exactly m parameters.
1059 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
1060 if (NumArgs < MinRequiredArgs) {
1061 // Not enough arguments.
1062 Candidate.Viable = false;
1063 return;
1064 }
1065
1066 // Determine the implicit conversion sequences for each of the
1067 // arguments.
1068 Candidate.Viable = true;
1069 Candidate.Conversions.resize(NumArgs);
1070 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1071 if (ArgIdx < NumArgsInProto) {
1072 // (C++ 13.3.2p3): for F to be a viable function, there shall
1073 // exist for each argument an implicit conversion sequence
1074 // (13.3.3.1) that converts that argument to the corresponding
1075 // parameter of F.
1076 QualType ParamType = Proto->getArgType(ArgIdx);
1077 Candidate.Conversions[ArgIdx]
1078 = TryCopyInitialization(Args[ArgIdx], ParamType);
1079 if (Candidate.Conversions[ArgIdx].ConversionKind
1080 == ImplicitConversionSequence::BadConversion)
1081 Candidate.Viable = false;
1082 } else {
1083 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1084 // argument for which there is no corresponding parameter is
1085 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1086 Candidate.Conversions[ArgIdx].ConversionKind
1087 = ImplicitConversionSequence::EllipsisConversion;
1088 }
1089 }
1090}
1091
1092/// AddOverloadCandidates - Add all of the function overloads in Ovl
1093/// to the candidate set.
1094void
1095Sema::AddOverloadCandidates(OverloadedFunctionDecl *Ovl,
1096 Expr **Args, unsigned NumArgs,
1097 OverloadCandidateSet& CandidateSet)
1098{
1099 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin();
1100 Func != Ovl->function_end(); ++Func)
1101 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
1102}
1103
1104/// isBetterOverloadCandidate - Determines whether the first overload
1105/// candidate is a better candidate than the second (C++ 13.3.3p1).
1106bool
1107Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
1108 const OverloadCandidate& Cand2)
1109{
1110 // Define viable functions to be better candidates than non-viable
1111 // functions.
1112 if (!Cand2.Viable)
1113 return Cand1.Viable;
1114 else if (!Cand1.Viable)
1115 return false;
1116
1117 // FIXME: Deal with the implicit object parameter for static member
1118 // functions. (C++ 13.3.3p1).
1119
1120 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
1121 // function than another viable function F2 if for all arguments i,
1122 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
1123 // then...
1124 unsigned NumArgs = Cand1.Conversions.size();
1125 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
1126 bool HasBetterConversion = false;
1127 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1128 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
1129 Cand2.Conversions[ArgIdx])) {
1130 case ImplicitConversionSequence::Better:
1131 // Cand1 has a better conversion sequence.
1132 HasBetterConversion = true;
1133 break;
1134
1135 case ImplicitConversionSequence::Worse:
1136 // Cand1 can't be better than Cand2.
1137 return false;
1138
1139 case ImplicitConversionSequence::Indistinguishable:
1140 // Do nothing.
1141 break;
1142 }
1143 }
1144
1145 if (HasBetterConversion)
1146 return true;
1147
1148 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be implemented.
1149
1150 return false;
1151}
1152
1153/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
1154/// within an overload candidate set. If overloading is successful,
1155/// the result will be OR_Success and Best will be set to point to the
1156/// best viable function within the candidate set. Otherwise, one of
1157/// several kinds of errors will be returned; see
1158/// Sema::OverloadingResult.
1159Sema::OverloadingResult
1160Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
1161 OverloadCandidateSet::iterator& Best)
1162{
1163 // Find the best viable function.
1164 Best = CandidateSet.end();
1165 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
1166 Cand != CandidateSet.end(); ++Cand) {
1167 if (Cand->Viable) {
1168 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
1169 Best = Cand;
1170 }
1171 }
1172
1173 // If we didn't find any viable functions, abort.
1174 if (Best == CandidateSet.end())
1175 return OR_No_Viable_Function;
1176
1177 // Make sure that this function is better than every other viable
1178 // function. If not, we have an ambiguity.
1179 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
1180 Cand != CandidateSet.end(); ++Cand) {
1181 if (Cand->Viable &&
1182 Cand != Best &&
1183 !isBetterOverloadCandidate(*Best, *Cand))
1184 return OR_Ambiguous;
1185 }
1186
1187 // Best is the best viable function.
1188 return OR_Success;
1189}
1190
1191/// PrintOverloadCandidates - When overload resolution fails, prints
1192/// diagnostic messages containing the candidates in the candidate
1193/// set. If OnlyViable is true, only viable candidates will be printed.
1194void
1195Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
1196 bool OnlyViable)
1197{
1198 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
1199 LastCand = CandidateSet.end();
1200 for (; Cand != LastCand; ++Cand) {
1201 if (Cand->Viable ||!OnlyViable)
1202 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
1203 }
1204}
1205
1206} // end namespace clang