blob: bef41f06cce60634be6f6e751dd61335c0bbce48 [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 Gregor8e9bebd2008-10-21 16:13:35 +00001416/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00001417/// candidate functions, using the given function call arguments. If
1418/// @p SuppressUserConversions, then don't allow user-defined
1419/// conversions via constructors or conversion operators.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001420void
1421Sema::AddOverloadCandidate(FunctionDecl *Function,
1422 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00001423 OverloadCandidateSet& CandidateSet,
1424 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001425{
1426 const FunctionTypeProto* Proto
1427 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType());
1428 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001429 assert(!isa<CXXConversionDecl>(Function) &&
1430 "Use AddConversionCandidate for conversion functions");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001431
1432 // Add this candidate
1433 CandidateSet.push_back(OverloadCandidate());
1434 OverloadCandidate& Candidate = CandidateSet.back();
1435 Candidate.Function = Function;
1436
1437 unsigned NumArgsInProto = Proto->getNumArgs();
1438
1439 // (C++ 13.3.2p2): A candidate function having fewer than m
1440 // parameters is viable only if it has an ellipsis in its parameter
1441 // list (8.3.5).
1442 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1443 Candidate.Viable = false;
1444 return;
1445 }
1446
1447 // (C++ 13.3.2p2): A candidate function having more than m parameters
1448 // is viable only if the (m+1)st parameter has a default argument
1449 // (8.3.6). For the purposes of overload resolution, the
1450 // parameter list is truncated on the right, so that there are
1451 // exactly m parameters.
1452 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
1453 if (NumArgs < MinRequiredArgs) {
1454 // Not enough arguments.
1455 Candidate.Viable = false;
1456 return;
1457 }
1458
1459 // Determine the implicit conversion sequences for each of the
1460 // arguments.
1461 Candidate.Viable = true;
1462 Candidate.Conversions.resize(NumArgs);
1463 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1464 if (ArgIdx < NumArgsInProto) {
1465 // (C++ 13.3.2p3): for F to be a viable function, there shall
1466 // exist for each argument an implicit conversion sequence
1467 // (13.3.3.1) that converts that argument to the corresponding
1468 // parameter of F.
1469 QualType ParamType = Proto->getArgType(ArgIdx);
1470 Candidate.Conversions[ArgIdx]
Douglas Gregor225c41e2008-11-03 19:09:14 +00001471 = TryCopyInitialization(Args[ArgIdx], ParamType,
1472 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001473 if (Candidate.Conversions[ArgIdx].ConversionKind
1474 == ImplicitConversionSequence::BadConversion)
1475 Candidate.Viable = false;
1476 } else {
1477 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1478 // argument for which there is no corresponding parameter is
1479 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1480 Candidate.Conversions[ArgIdx].ConversionKind
1481 = ImplicitConversionSequence::EllipsisConversion;
1482 }
1483 }
1484}
1485
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001486/// AddConversionCandidate - Add a C++ conversion function as a
1487/// candidate in the candidate set (C++ [over.match.conv],
1488/// C++ [over.match.copy]). From is the expression we're converting from,
1489/// and ToType is the type that we're eventually trying to convert to
1490/// (which may or may not be the same type as the type that the
1491/// conversion function produces).
1492void
1493Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
1494 Expr *From, QualType ToType,
1495 OverloadCandidateSet& CandidateSet) {
1496 // Add this candidate
1497 CandidateSet.push_back(OverloadCandidate());
1498 OverloadCandidate& Candidate = CandidateSet.back();
1499 Candidate.Function = Conversion;
1500 Candidate.FinalConversion.setAsIdentityConversion();
1501 Candidate.FinalConversion.FromTypePtr
1502 = Conversion->getConversionType().getAsOpaquePtr();
1503 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
1504
1505 // Determine the implicit conversion sequences for each of the
1506 // arguments.
1507 Candidate.Viable = true;
1508 Candidate.Conversions.resize(1);
1509
1510 // FIXME: We need to follow the rules for the implicit object
1511 // parameter.
1512 QualType ImplicitObjectType
1513 = Context.getTypeDeclType(Conversion->getParent());
1514 ImplicitObjectType
1515 = ImplicitObjectType.getQualifiedType(Conversion->getTypeQualifiers());
1516 ImplicitObjectType = Context.getReferenceType(ImplicitObjectType);
1517 Candidate.Conversions[0] = TryCopyInitialization(From, ImplicitObjectType,
1518 true);
1519 if (Candidate.Conversions[0].ConversionKind
1520 == ImplicitConversionSequence::BadConversion) {
1521 Candidate.Viable = false;
1522 return;
1523 }
1524
1525 // To determine what the conversion from the result of calling the
1526 // conversion function to the type we're eventually trying to
1527 // convert to (ToType), we need to synthesize a call to the
1528 // conversion function and attempt copy initialization from it. This
1529 // makes sure that we get the right semantics with respect to
1530 // lvalues/rvalues and the type. Fortunately, we can allocate this
1531 // call on the stack and we don't need its arguments to be
1532 // well-formed.
1533 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
1534 SourceLocation());
1535 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001536 &ConversionRef, false);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001537 CallExpr Call(&ConversionFn, 0, 0,
1538 Conversion->getConversionType().getNonReferenceType(),
1539 SourceLocation());
1540 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
1541 switch (ICS.ConversionKind) {
1542 case ImplicitConversionSequence::StandardConversion:
1543 Candidate.FinalConversion = ICS.Standard;
1544 break;
1545
1546 case ImplicitConversionSequence::BadConversion:
1547 Candidate.Viable = false;
1548 break;
1549
1550 default:
1551 assert(false &&
1552 "Can only end up with a standard conversion sequence or failure");
1553 }
1554}
1555
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001556/// AddBuiltinCandidate - Add a candidate for a built-in
1557/// operator. ResultTy and ParamTys are the result and parameter types
1558/// of the built-in candidate, respectively. Args and NumArgs are the
1559/// arguments being passed to the candidate.
1560void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
1561 Expr **Args, unsigned NumArgs,
1562 OverloadCandidateSet& CandidateSet) {
1563 // Add this candidate
1564 CandidateSet.push_back(OverloadCandidate());
1565 OverloadCandidate& Candidate = CandidateSet.back();
1566 Candidate.Function = 0;
1567 Candidate.BuiltinTypes.ResultTy = ResultTy;
1568 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
1569 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
1570
1571 // Determine the implicit conversion sequences for each of the
1572 // arguments.
1573 Candidate.Viable = true;
1574 Candidate.Conversions.resize(NumArgs);
1575 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1576 Candidate.Conversions[ArgIdx]
1577 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx], false);
1578 if (Candidate.Conversions[ArgIdx].ConversionKind
1579 == ImplicitConversionSequence::BadConversion)
1580 Candidate.Viable = false;
1581 }
1582}
1583
1584/// BuiltinCandidateTypeSet - A set of types that will be used for the
1585/// candidate operator functions for built-in operators (C++
1586/// [over.built]). The types are separated into pointer types and
1587/// enumeration types.
1588class BuiltinCandidateTypeSet {
1589 /// TypeSet - A set of types.
Douglas Gregorbf3af052008-11-13 20:12:29 +00001590 typedef llvm::SmallPtrSet<void*, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001591
1592 /// PointerTypes - The set of pointer types that will be used in the
1593 /// built-in candidates.
1594 TypeSet PointerTypes;
1595
1596 /// EnumerationTypes - The set of enumeration types that will be
1597 /// used in the built-in candidates.
1598 TypeSet EnumerationTypes;
1599
1600 /// Context - The AST context in which we will build the type sets.
1601 ASTContext &Context;
1602
1603 bool AddWithMoreQualifiedTypeVariants(QualType Ty);
1604
1605public:
1606 /// iterator - Iterates through the types that are part of the set.
Douglas Gregorbf3af052008-11-13 20:12:29 +00001607 class iterator {
1608 TypeSet::iterator Base;
1609
1610 public:
1611 typedef QualType value_type;
1612 typedef QualType reference;
1613 typedef QualType pointer;
1614 typedef std::ptrdiff_t difference_type;
1615 typedef std::input_iterator_tag iterator_category;
1616
1617 iterator(TypeSet::iterator B) : Base(B) { }
1618
1619 iterator& operator++() {
1620 ++Base;
1621 return *this;
1622 }
1623
1624 iterator operator++(int) {
1625 iterator tmp(*this);
1626 ++(*this);
1627 return tmp;
1628 }
1629
1630 reference operator*() const {
1631 return QualType::getFromOpaquePtr(*Base);
1632 }
1633
1634 pointer operator->() const {
1635 return **this;
1636 }
1637
1638 friend bool operator==(iterator LHS, iterator RHS) {
1639 return LHS.Base == RHS.Base;
1640 }
1641
1642 friend bool operator!=(iterator LHS, iterator RHS) {
1643 return LHS.Base != RHS.Base;
1644 }
1645 };
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001646
1647 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
1648
1649 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions = true);
1650
1651 /// pointer_begin - First pointer type found;
1652 iterator pointer_begin() { return PointerTypes.begin(); }
1653
1654 /// pointer_end - Last pointer type found;
1655 iterator pointer_end() { return PointerTypes.end(); }
1656
1657 /// enumeration_begin - First enumeration type found;
1658 iterator enumeration_begin() { return EnumerationTypes.begin(); }
1659
1660 /// enumeration_end - Last enumeration type found;
1661 iterator enumeration_end() { return EnumerationTypes.end(); }
1662};
1663
1664/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
1665/// the set of pointer types along with any more-qualified variants of
1666/// that type. For example, if @p Ty is "int const *", this routine
1667/// will add "int const *", "int const volatile *", "int const
1668/// restrict *", and "int const volatile restrict *" to the set of
1669/// pointer types. Returns true if the add of @p Ty itself succeeded,
1670/// false otherwise.
1671bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) {
1672 // Insert this type.
Douglas Gregorbf3af052008-11-13 20:12:29 +00001673 if (!PointerTypes.insert(Ty.getAsOpaquePtr()))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001674 return false;
1675
1676 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
1677 QualType PointeeTy = PointerTy->getPointeeType();
1678 // FIXME: Optimize this so that we don't keep trying to add the same types.
1679
1680 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
1681 // with all pointer conversions that don't cast away constness?
1682 if (!PointeeTy.isConstQualified())
1683 AddWithMoreQualifiedTypeVariants
1684 (Context.getPointerType(PointeeTy.withConst()));
1685 if (!PointeeTy.isVolatileQualified())
1686 AddWithMoreQualifiedTypeVariants
1687 (Context.getPointerType(PointeeTy.withVolatile()));
1688 if (!PointeeTy.isRestrictQualified())
1689 AddWithMoreQualifiedTypeVariants
1690 (Context.getPointerType(PointeeTy.withRestrict()));
1691 }
1692
1693 return true;
1694}
1695
1696/// AddTypesConvertedFrom - Add each of the types to which the type @p
1697/// Ty can be implicit converted to the given set of @p Types. We're
1698/// primarily interested in pointer types, enumeration types,
1699void BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
1700 bool AllowUserConversions) {
1701 // Only deal with canonical types.
1702 Ty = Context.getCanonicalType(Ty);
1703
1704 // Look through reference types; they aren't part of the type of an
1705 // expression for the purposes of conversions.
1706 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
1707 Ty = RefTy->getPointeeType();
1708
1709 // We don't care about qualifiers on the type.
1710 Ty = Ty.getUnqualifiedType();
1711
1712 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
1713 QualType PointeeTy = PointerTy->getPointeeType();
1714
1715 // Insert our type, and its more-qualified variants, into the set
1716 // of types.
1717 if (!AddWithMoreQualifiedTypeVariants(Ty))
1718 return;
1719
1720 // Add 'cv void*' to our set of types.
1721 if (!Ty->isVoidType()) {
1722 QualType QualVoid
1723 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
1724 AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
1725 }
1726
1727 // If this is a pointer to a class type, add pointers to its bases
1728 // (with the same level of cv-qualification as the original
1729 // derived class, of course).
1730 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
1731 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
1732 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1733 Base != ClassDecl->bases_end(); ++Base) {
1734 QualType BaseTy = Context.getCanonicalType(Base->getType());
1735 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
1736
1737 // Add the pointer type, recursively, so that we get all of
1738 // the indirect base classes, too.
1739 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false);
1740 }
1741 }
1742 } else if (Ty->isEnumeralType()) {
Douglas Gregorbf3af052008-11-13 20:12:29 +00001743 EnumerationTypes.insert(Ty.getAsOpaquePtr());
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001744 } else if (AllowUserConversions) {
1745 if (const RecordType *TyRec = Ty->getAsRecordType()) {
1746 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
1747 // FIXME: Visit conversion functions in the base classes, too.
1748 OverloadedFunctionDecl *Conversions
1749 = ClassDecl->getConversionFunctions();
1750 for (OverloadedFunctionDecl::function_iterator Func
1751 = Conversions->function_begin();
1752 Func != Conversions->function_end(); ++Func) {
1753 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1754 AddTypesConvertedFrom(Conv->getConversionType(), false);
1755 }
1756 }
1757 }
1758}
1759
1760/// AddBuiltinCandidates - Add the appropriate built-in operator
1761/// overloads to the candidate set (C++ [over.built]), based on the
1762/// operator @p Op and the arguments given. For example, if the
1763/// operator is a binary '+', this routine might add
1764/// "int operator+(int, int)"
1765/// to cover integer addition.
1766void
1767Sema::AddBuiltinBinaryOperatorCandidates(OverloadedOperatorKind Op,
1768 Expr **Args,
1769 OverloadCandidateSet& CandidateSet) {
1770 // The set of "promoted arithmetic types", which are the arithmetic
1771 // types are that preserved by promotion (C++ [over.built]p2). Note
1772 // that the first few of these types are the promoted integral
1773 // types; these types need to be first.
1774 // FIXME: What about complex?
1775 const unsigned FirstIntegralType = 0;
1776 const unsigned LastIntegralType = 13;
1777 const unsigned FirstPromotedIntegralType = 7,
1778 LastPromotedIntegralType = 13;
1779 const unsigned FirstPromotedArithmeticType = 7,
1780 LastPromotedArithmeticType = 16;
1781 const unsigned NumArithmeticTypes = 16;
1782 QualType ArithmeticTypes[NumArithmeticTypes] = {
1783 Context.BoolTy, Context.CharTy, Context.WCharTy,
1784 Context.SignedCharTy, Context.ShortTy,
1785 Context.UnsignedCharTy, Context.UnsignedShortTy,
1786 Context.IntTy, Context.LongTy, Context.LongLongTy,
1787 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
1788 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
1789 };
1790
1791 // Find all of the types that the arguments can convert to, but only
1792 // if the operator we're looking at has built-in operator candidates
1793 // that make use of these types.
1794 BuiltinCandidateTypeSet CandidateTypes(Context);
1795 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
1796 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
1797 Op == OO_Plus || Op == OO_Minus || Op == OO_Equal ||
1798 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
1799 Op == OO_ArrowStar) {
1800 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx)
1801 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType());
1802 }
1803
1804 bool isComparison = false;
1805 switch (Op) {
1806 case OO_None:
1807 case NUM_OVERLOADED_OPERATORS:
1808 assert(false && "Expected an overloaded operator");
1809 break;
1810
1811 case OO_New:
1812 case OO_Delete:
1813 case OO_Array_New:
1814 case OO_Array_Delete:
1815 case OO_Tilde:
1816 case OO_Exclaim:
1817 case OO_PlusPlus:
1818 case OO_MinusMinus:
1819 case OO_Arrow:
1820 case OO_Call:
1821 assert(false && "Expected a binary operator");
1822 break;
1823
1824 case OO_Comma:
1825 // C++ [over.match.oper]p3:
1826 // -- For the operator ',', the unary operator '&', or the
1827 // operator '->', the built-in candidates set is empty.
1828 // We don't check '&' or '->' here, since they are unary operators.
1829 break;
1830
1831 case OO_Less:
1832 case OO_Greater:
1833 case OO_LessEqual:
1834 case OO_GreaterEqual:
1835 case OO_EqualEqual:
1836 case OO_ExclaimEqual:
1837 // C++ [over.built]p15:
1838 //
1839 // For every pointer or enumeration type T, there exist
1840 // candidate operator functions of the form
1841 //
1842 // bool operator<(T, T);
1843 // bool operator>(T, T);
1844 // bool operator<=(T, T);
1845 // bool operator>=(T, T);
1846 // bool operator==(T, T);
1847 // bool operator!=(T, T);
1848 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
1849 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
1850 QualType ParamTypes[2] = { *Ptr, *Ptr };
1851 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
1852 }
1853 for (BuiltinCandidateTypeSet::iterator Enum
1854 = CandidateTypes.enumeration_begin();
1855 Enum != CandidateTypes.enumeration_end(); ++Enum) {
1856 QualType ParamTypes[2] = { *Enum, *Enum };
1857 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
1858 }
1859
1860 // Fall through.
1861 isComparison = true;
1862
1863 case OO_Plus:
1864 case OO_Minus:
1865 if (!isComparison) {
1866 // We didn't fall through, so we must have OO_Plus or OO_Minus.
1867
1868 // C++ [over.built]p13:
1869 //
1870 // For every cv-qualified or cv-unqualified object type T
1871 // there exist candidate operator functions of the form
1872 //
1873 // T* operator+(T*, ptrdiff_t);
1874 // T& operator[](T*, ptrdiff_t); [BELOW]
1875 // T* operator-(T*, ptrdiff_t);
1876 // T* operator+(ptrdiff_t, T*);
1877 // T& operator[](ptrdiff_t, T*); [BELOW]
1878 //
1879 // C++ [over.built]p14:
1880 //
1881 // For every T, where T is a pointer to object type, there
1882 // exist candidate operator functions of the form
1883 //
1884 // ptrdiff_t operator-(T, T);
1885 for (BuiltinCandidateTypeSet::iterator Ptr
1886 = CandidateTypes.pointer_begin();
1887 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
1888 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
1889
1890 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
1891 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
1892
1893 if (Op == OO_Plus) {
1894 // T* operator+(ptrdiff_t, T*);
1895 ParamTypes[0] = ParamTypes[1];
1896 ParamTypes[1] = *Ptr;
1897 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
1898 } else {
1899 // ptrdiff_t operator-(T, T);
1900 ParamTypes[1] = *Ptr;
1901 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
1902 Args, 2, CandidateSet);
1903 }
1904 }
1905 }
1906 // Fall through
1907
1908 case OO_Star:
1909 case OO_Slash:
1910 // C++ [over.built]p12:
1911 //
1912 // For every pair of promoted arithmetic types L and R, there
1913 // exist candidate operator functions of the form
1914 //
1915 // LR operator*(L, R);
1916 // LR operator/(L, R);
1917 // LR operator+(L, R);
1918 // LR operator-(L, R);
1919 // bool operator<(L, R);
1920 // bool operator>(L, R);
1921 // bool operator<=(L, R);
1922 // bool operator>=(L, R);
1923 // bool operator==(L, R);
1924 // bool operator!=(L, R);
1925 //
1926 // where LR is the result of the usual arithmetic conversions
1927 // between types L and R.
1928 for (unsigned Left = FirstPromotedArithmeticType;
1929 Left < LastPromotedArithmeticType; ++Left) {
1930 for (unsigned Right = FirstPromotedArithmeticType;
1931 Right < LastPromotedArithmeticType; ++Right) {
1932 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
1933 QualType Result
1934 = isComparison? Context.BoolTy
1935 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
1936 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
1937 }
1938 }
1939 break;
1940
1941 case OO_Percent:
1942 case OO_Amp:
1943 case OO_Caret:
1944 case OO_Pipe:
1945 case OO_LessLess:
1946 case OO_GreaterGreater:
1947 // C++ [over.built]p17:
1948 //
1949 // For every pair of promoted integral types L and R, there
1950 // exist candidate operator functions of the form
1951 //
1952 // LR operator%(L, R);
1953 // LR operator&(L, R);
1954 // LR operator^(L, R);
1955 // LR operator|(L, R);
1956 // L operator<<(L, R);
1957 // L operator>>(L, R);
1958 //
1959 // where LR is the result of the usual arithmetic conversions
1960 // between types L and R.
1961 for (unsigned Left = FirstPromotedIntegralType;
1962 Left < LastPromotedIntegralType; ++Left) {
1963 for (unsigned Right = FirstPromotedIntegralType;
1964 Right < LastPromotedIntegralType; ++Right) {
1965 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
1966 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
1967 ? LandR[0]
1968 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
1969 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
1970 }
1971 }
1972 break;
1973
1974 case OO_Equal:
1975 // C++ [over.built]p20:
1976 //
1977 // For every pair (T, VQ), where T is an enumeration or
1978 // (FIXME:) pointer to member type and VQ is either volatile or
1979 // empty, there exist candidate operator functions of the form
1980 //
1981 // VQ T& operator=(VQ T&, T);
1982 for (BuiltinCandidateTypeSet::iterator Enum
1983 = CandidateTypes.enumeration_begin();
1984 Enum != CandidateTypes.enumeration_end(); ++Enum) {
1985 QualType ParamTypes[2];
1986
1987 // T& operator=(T&, T)
1988 ParamTypes[0] = Context.getReferenceType(*Enum);
1989 ParamTypes[1] = *Enum;
1990 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
1991
1992 // volatile T& operator=(volatile T&, T)
Douglas Gregorbf3af052008-11-13 20:12:29 +00001993 ParamTypes[0] = Context.getReferenceType((*Enum).withVolatile());
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001994 ParamTypes[1] = *Enum;
1995 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
1996 }
1997 // Fall through.
1998
1999 case OO_PlusEqual:
2000 case OO_MinusEqual:
2001 // C++ [over.built]p19:
2002 //
2003 // For every pair (T, VQ), where T is any type and VQ is either
2004 // volatile or empty, there exist candidate operator functions
2005 // of the form
2006 //
2007 // T*VQ& operator=(T*VQ&, T*);
2008 //
2009 // C++ [over.built]p21:
2010 //
2011 // For every pair (T, VQ), where T is a cv-qualified or
2012 // cv-unqualified object type and VQ is either volatile or
2013 // empty, there exist candidate operator functions of the form
2014 //
2015 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
2016 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
2017 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2018 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2019 QualType ParamTypes[2];
2020 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
2021
2022 // non-volatile version
2023 ParamTypes[0] = Context.getReferenceType(*Ptr);
2024 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2025
2026 // volatile version
Douglas Gregorbf3af052008-11-13 20:12:29 +00002027 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002028 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2029 }
2030 // Fall through.
2031
2032 case OO_StarEqual:
2033 case OO_SlashEqual:
2034 // C++ [over.built]p18:
2035 //
2036 // For every triple (L, VQ, R), where L is an arithmetic type,
2037 // VQ is either volatile or empty, and R is a promoted
2038 // arithmetic type, there exist candidate operator functions of
2039 // the form
2040 //
2041 // VQ L& operator=(VQ L&, R);
2042 // VQ L& operator*=(VQ L&, R);
2043 // VQ L& operator/=(VQ L&, R);
2044 // VQ L& operator+=(VQ L&, R);
2045 // VQ L& operator-=(VQ L&, R);
2046 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
2047 for (unsigned Right = FirstPromotedArithmeticType;
2048 Right < LastPromotedArithmeticType; ++Right) {
2049 QualType ParamTypes[2];
2050 ParamTypes[1] = ArithmeticTypes[Right];
2051
2052 // Add this built-in operator as a candidate (VQ is empty).
2053 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
2054 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2055
2056 // Add this built-in operator as a candidate (VQ is 'volatile').
2057 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
2058 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
2059 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2060 }
2061 }
2062 break;
2063
2064 case OO_PercentEqual:
2065 case OO_LessLessEqual:
2066 case OO_GreaterGreaterEqual:
2067 case OO_AmpEqual:
2068 case OO_CaretEqual:
2069 case OO_PipeEqual:
2070 // C++ [over.built]p22:
2071 //
2072 // For every triple (L, VQ, R), where L is an integral type, VQ
2073 // is either volatile or empty, and R is a promoted integral
2074 // type, there exist candidate operator functions of the form
2075 //
2076 // VQ L& operator%=(VQ L&, R);
2077 // VQ L& operator<<=(VQ L&, R);
2078 // VQ L& operator>>=(VQ L&, R);
2079 // VQ L& operator&=(VQ L&, R);
2080 // VQ L& operator^=(VQ L&, R);
2081 // VQ L& operator|=(VQ L&, R);
2082 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
2083 for (unsigned Right = FirstPromotedIntegralType;
2084 Right < LastPromotedIntegralType; ++Right) {
2085 QualType ParamTypes[2];
2086 ParamTypes[1] = ArithmeticTypes[Right];
2087
2088 // Add this built-in operator as a candidate (VQ is empty).
2089 // FIXME: We should be caching these declarations somewhere,
2090 // rather than re-building them every time.
2091 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
2092 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2093
2094 // Add this built-in operator as a candidate (VQ is 'volatile').
2095 ParamTypes[0] = ArithmeticTypes[Left];
2096 ParamTypes[0].addVolatile();
2097 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
2098 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2099 }
2100 }
2101 break;
2102
2103 case OO_AmpAmp:
2104 case OO_PipePipe: {
2105 // C++ [over.operator]p23:
2106 //
2107 // There also exist candidate operator functions of the form
2108 //
2109 // bool operator!(bool); [In Unary version]
2110 // bool operator&&(bool, bool);
2111 // bool operator||(bool, bool);
2112 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
2113 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2114 break;
2115 }
2116
2117 case OO_Subscript:
2118 // C++ [over.built]p13:
2119 //
2120 // For every cv-qualified or cv-unqualified object type T there
2121 // exist candidate operator functions of the form
2122 //
2123 // T* operator+(T*, ptrdiff_t); [ABOVE]
2124 // T& operator[](T*, ptrdiff_t);
2125 // T* operator-(T*, ptrdiff_t); [ABOVE]
2126 // T* operator+(ptrdiff_t, T*); [ABOVE]
2127 // T& operator[](ptrdiff_t, T*);
2128 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2129 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2130 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2131 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
2132 QualType ResultTy = Context.getReferenceType(PointeeType);
2133
2134 // T& operator[](T*, ptrdiff_t)
2135 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
2136
2137 // T& operator[](ptrdiff_t, T*);
2138 ParamTypes[0] = ParamTypes[1];
2139 ParamTypes[1] = *Ptr;
2140 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
2141 }
2142 break;
2143
2144 case OO_ArrowStar:
2145 // FIXME: No support for pointer-to-members yet.
2146 break;
2147 }
2148}
2149
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002150/// AddOverloadCandidates - Add all of the function overloads in Ovl
2151/// to the candidate set.
2152void
Douglas Gregor18fe5682008-11-03 20:45:27 +00002153Sema::AddOverloadCandidates(const OverloadedFunctionDecl *Ovl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002154 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002155 OverloadCandidateSet& CandidateSet,
2156 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002157{
Douglas Gregor18fe5682008-11-03 20:45:27 +00002158 for (OverloadedFunctionDecl::function_const_iterator Func
2159 = Ovl->function_begin();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002160 Func != Ovl->function_end(); ++Func)
Douglas Gregor225c41e2008-11-03 19:09:14 +00002161 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet,
2162 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002163}
2164
2165/// isBetterOverloadCandidate - Determines whether the first overload
2166/// candidate is a better candidate than the second (C++ 13.3.3p1).
2167bool
2168Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
2169 const OverloadCandidate& Cand2)
2170{
2171 // Define viable functions to be better candidates than non-viable
2172 // functions.
2173 if (!Cand2.Viable)
2174 return Cand1.Viable;
2175 else if (!Cand1.Viable)
2176 return false;
2177
2178 // FIXME: Deal with the implicit object parameter for static member
2179 // functions. (C++ 13.3.3p1).
2180
2181 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
2182 // function than another viable function F2 if for all arguments i,
2183 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
2184 // then...
2185 unsigned NumArgs = Cand1.Conversions.size();
2186 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
2187 bool HasBetterConversion = false;
2188 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2189 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
2190 Cand2.Conversions[ArgIdx])) {
2191 case ImplicitConversionSequence::Better:
2192 // Cand1 has a better conversion sequence.
2193 HasBetterConversion = true;
2194 break;
2195
2196 case ImplicitConversionSequence::Worse:
2197 // Cand1 can't be better than Cand2.
2198 return false;
2199
2200 case ImplicitConversionSequence::Indistinguishable:
2201 // Do nothing.
2202 break;
2203 }
2204 }
2205
2206 if (HasBetterConversion)
2207 return true;
2208
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002209 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
2210 // implemented, but they require template support.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002211
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002212 // C++ [over.match.best]p1b4:
2213 //
2214 // -- the context is an initialization by user-defined conversion
2215 // (see 8.5, 13.3.1.5) and the standard conversion sequence
2216 // from the return type of F1 to the destination type (i.e.,
2217 // the type of the entity being initialized) is a better
2218 // conversion sequence than the standard conversion sequence
2219 // from the return type of F2 to the destination type.
2220 if (isa<CXXConversionDecl>(Cand1.Function) &&
2221 isa<CXXConversionDecl>(Cand2.Function)) {
2222 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
2223 Cand2.FinalConversion)) {
2224 case ImplicitConversionSequence::Better:
2225 // Cand1 has a better conversion sequence.
2226 return true;
2227
2228 case ImplicitConversionSequence::Worse:
2229 // Cand1 can't be better than Cand2.
2230 return false;
2231
2232 case ImplicitConversionSequence::Indistinguishable:
2233 // Do nothing
2234 break;
2235 }
2236 }
2237
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002238 return false;
2239}
2240
2241/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
2242/// within an overload candidate set. If overloading is successful,
2243/// the result will be OR_Success and Best will be set to point to the
2244/// best viable function within the candidate set. Otherwise, one of
2245/// several kinds of errors will be returned; see
2246/// Sema::OverloadingResult.
2247Sema::OverloadingResult
2248Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
2249 OverloadCandidateSet::iterator& Best)
2250{
2251 // Find the best viable function.
2252 Best = CandidateSet.end();
2253 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2254 Cand != CandidateSet.end(); ++Cand) {
2255 if (Cand->Viable) {
2256 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
2257 Best = Cand;
2258 }
2259 }
2260
2261 // If we didn't find any viable functions, abort.
2262 if (Best == CandidateSet.end())
2263 return OR_No_Viable_Function;
2264
2265 // Make sure that this function is better than every other viable
2266 // function. If not, we have an ambiguity.
2267 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2268 Cand != CandidateSet.end(); ++Cand) {
2269 if (Cand->Viable &&
2270 Cand != Best &&
2271 !isBetterOverloadCandidate(*Best, *Cand))
2272 return OR_Ambiguous;
2273 }
2274
2275 // Best is the best viable function.
2276 return OR_Success;
2277}
2278
2279/// PrintOverloadCandidates - When overload resolution fails, prints
2280/// diagnostic messages containing the candidates in the candidate
2281/// set. If OnlyViable is true, only viable candidates will be printed.
2282void
2283Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
2284 bool OnlyViable)
2285{
2286 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
2287 LastCand = CandidateSet.end();
2288 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002289 if (Cand->Viable || !OnlyViable) {
2290 if (Cand->Function) {
2291 // Normal function
2292 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
2293 } else {
2294 // FIXME: We need to get the identifier in here
2295 // FIXME: Do we want the error message to point at the
2296 // operator? (built-ins won't have a location)
2297 QualType FnType
2298 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
2299 Cand->BuiltinTypes.ParamTypes,
2300 Cand->Conversions.size(),
2301 false, 0);
2302
2303 Diag(SourceLocation(), diag::err_ovl_builtin_candidate,
2304 FnType.getAsString());
2305 }
2306 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002307 }
2308}
2309
Douglas Gregor904eed32008-11-10 20:40:00 +00002310/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
2311/// an overloaded function (C++ [over.over]), where @p From is an
2312/// expression with overloaded function type and @p ToType is the type
2313/// we're trying to resolve to. For example:
2314///
2315/// @code
2316/// int f(double);
2317/// int f(int);
2318///
2319/// int (*pfd)(double) = f; // selects f(double)
2320/// @endcode
2321///
2322/// This routine returns the resulting FunctionDecl if it could be
2323/// resolved, and NULL otherwise. When @p Complain is true, this
2324/// routine will emit diagnostics if there is an error.
2325FunctionDecl *
2326Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
2327 bool Complain) {
2328 QualType FunctionType = ToType;
2329 if (const PointerLikeType *ToTypePtr = ToType->getAsPointerLikeType())
2330 FunctionType = ToTypePtr->getPointeeType();
2331
2332 // We only look at pointers or references to functions.
2333 if (!FunctionType->isFunctionType())
2334 return 0;
2335
2336 // Find the actual overloaded function declaration.
2337 OverloadedFunctionDecl *Ovl = 0;
2338
2339 // C++ [over.over]p1:
2340 // [...] [Note: any redundant set of parentheses surrounding the
2341 // overloaded function name is ignored (5.1). ]
2342 Expr *OvlExpr = From->IgnoreParens();
2343
2344 // C++ [over.over]p1:
2345 // [...] The overloaded function name can be preceded by the &
2346 // operator.
2347 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
2348 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2349 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
2350 }
2351
2352 // Try to dig out the overloaded function.
2353 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
2354 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
2355
2356 // If there's no overloaded function declaration, we're done.
2357 if (!Ovl)
2358 return 0;
2359
2360 // Look through all of the overloaded functions, searching for one
2361 // whose type matches exactly.
2362 // FIXME: When templates or using declarations come along, we'll actually
2363 // have to deal with duplicates, partial ordering, etc. For now, we
2364 // can just do a simple search.
2365 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
2366 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
2367 Fun != Ovl->function_end(); ++Fun) {
2368 // C++ [over.over]p3:
2369 // Non-member functions and static member functions match
2370 // targets of type “pointer-to-function”or
2371 // “reference-to-function.”
2372 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun))
2373 if (!Method->isStatic())
2374 continue;
2375
2376 if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
2377 return *Fun;
2378 }
2379
2380 return 0;
2381}
2382
2383/// FixOverloadedFunctionReference - E is an expression that refers to
2384/// a C++ overloaded function (possibly with some parentheses and
2385/// perhaps a '&' around it). We have resolved the overloaded function
2386/// to the function declaration Fn, so patch up the expression E to
2387/// refer (possibly indirectly) to Fn.
2388void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
2389 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
2390 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
2391 E->setType(PE->getSubExpr()->getType());
2392 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
2393 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
2394 "Can only take the address of an overloaded function");
2395 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
2396 E->setType(Context.getPointerType(E->getType()));
2397 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
2398 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
2399 "Expected overloaded function");
2400 DR->setDecl(Fn);
2401 E->setType(Fn->getType());
2402 } else {
2403 assert(false && "Invalid reference to overloaded function");
2404 }
2405}
2406
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002407} // end namespace clang