blob: 1fa703c775ab4157830c3bfc1a958225b748bc79 [file] [log] [blame]
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor94b1dd22008-10-24 04:54:22 +000015#include "SemaInherit.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000020#include "clang/AST/ExprCXX.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000022#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000023#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000024#include "llvm/Support/Compiler.h"
25#include <algorithm>
26
27namespace clang {
28
29/// GetConversionCategory - Retrieve the implicit conversion
30/// category corresponding to the given implicit conversion kind.
31ImplicitConversionCategory
32GetConversionCategory(ImplicitConversionKind Kind) {
33 static const ImplicitConversionCategory
34 Category[(int)ICK_Num_Conversion_Kinds] = {
35 ICC_Identity,
36 ICC_Lvalue_Transformation,
37 ICC_Lvalue_Transformation,
38 ICC_Lvalue_Transformation,
39 ICC_Qualification_Adjustment,
40 ICC_Promotion,
41 ICC_Promotion,
42 ICC_Conversion,
43 ICC_Conversion,
44 ICC_Conversion,
45 ICC_Conversion,
46 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000047 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000048 ICC_Conversion
49 };
50 return Category[(int)Kind];
51}
52
53/// GetConversionRank - Retrieve the implicit conversion rank
54/// corresponding to the given implicit conversion kind.
55ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
56 static const ImplicitConversionRank
57 Rank[(int)ICK_Num_Conversion_Kinds] = {
58 ICR_Exact_Match,
59 ICR_Exact_Match,
60 ICR_Exact_Match,
61 ICR_Exact_Match,
62 ICR_Exact_Match,
63 ICR_Promotion,
64 ICR_Promotion,
65 ICR_Conversion,
66 ICR_Conversion,
67 ICR_Conversion,
68 ICR_Conversion,
69 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000070 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000071 ICR_Conversion
72 };
73 return Rank[(int)Kind];
74}
75
76/// GetImplicitConversionName - Return the name of this kind of
77/// implicit conversion.
78const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
79 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
80 "No conversion",
81 "Lvalue-to-rvalue",
82 "Array-to-pointer",
83 "Function-to-pointer",
84 "Qualification",
85 "Integral promotion",
86 "Floating point promotion",
87 "Integral conversion",
88 "Floating conversion",
89 "Floating-integral conversion",
90 "Pointer conversion",
91 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +000092 "Boolean conversion",
93 "Derived-to-base conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000094 };
95 return Name[Kind];
96}
97
Douglas Gregor60d62c22008-10-31 16:23:19 +000098/// StandardConversionSequence - Set the standard conversion
99/// sequence to the identity conversion.
100void StandardConversionSequence::setAsIdentityConversion() {
101 First = ICK_Identity;
102 Second = ICK_Identity;
103 Third = ICK_Identity;
104 Deprecated = false;
105 ReferenceBinding = false;
106 DirectBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000107 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000108}
109
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000110/// getRank - Retrieve the rank of this standard conversion sequence
111/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
112/// implicit conversions.
113ImplicitConversionRank StandardConversionSequence::getRank() const {
114 ImplicitConversionRank Rank = ICR_Exact_Match;
115 if (GetConversionRank(First) > Rank)
116 Rank = GetConversionRank(First);
117 if (GetConversionRank(Second) > Rank)
118 Rank = GetConversionRank(Second);
119 if (GetConversionRank(Third) > Rank)
120 Rank = GetConversionRank(Third);
121 return Rank;
122}
123
124/// isPointerConversionToBool - Determines whether this conversion is
125/// a conversion of a pointer or pointer-to-member to bool. This is
126/// used as part of the ranking of standard conversion sequences
127/// (C++ 13.3.3.2p4).
128bool StandardConversionSequence::isPointerConversionToBool() const
129{
130 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
131 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
132
133 // Note that FromType has not necessarily been transformed by the
134 // array-to-pointer or function-to-pointer implicit conversions, so
135 // check for their presence as well as checking whether FromType is
136 // a pointer.
137 if (ToType->isBooleanType() &&
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000138 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000139 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
140 return true;
141
142 return false;
143}
144
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000145/// isPointerConversionToVoidPointer - Determines whether this
146/// conversion is a conversion of a pointer to a void pointer. This is
147/// used as part of the ranking of standard conversion sequences (C++
148/// 13.3.3.2p4).
149bool
150StandardConversionSequence::
151isPointerConversionToVoidPointer(ASTContext& Context) const
152{
153 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
154 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
155
156 // Note that FromType has not necessarily been transformed by the
157 // array-to-pointer implicit conversion, so check for its presence
158 // and redo the conversion to get a pointer.
159 if (First == ICK_Array_To_Pointer)
160 FromType = Context.getArrayDecayedType(FromType);
161
162 if (Second == ICK_Pointer_Conversion)
163 if (const PointerType* ToPtrType = ToType->getAsPointerType())
164 return ToPtrType->getPointeeType()->isVoidType();
165
166 return false;
167}
168
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000169/// DebugPrint - Print this standard conversion sequence to standard
170/// error. Useful for debugging overloading issues.
171void StandardConversionSequence::DebugPrint() const {
172 bool PrintedSomething = false;
173 if (First != ICK_Identity) {
174 fprintf(stderr, "%s", GetImplicitConversionName(First));
175 PrintedSomething = true;
176 }
177
178 if (Second != ICK_Identity) {
179 if (PrintedSomething) {
180 fprintf(stderr, " -> ");
181 }
182 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregor225c41e2008-11-03 19:09:14 +0000183
184 if (CopyConstructor) {
185 fprintf(stderr, " (by copy constructor)");
186 } else if (DirectBinding) {
187 fprintf(stderr, " (direct reference binding)");
188 } else if (ReferenceBinding) {
189 fprintf(stderr, " (reference binding)");
190 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000191 PrintedSomething = true;
192 }
193
194 if (Third != ICK_Identity) {
195 if (PrintedSomething) {
196 fprintf(stderr, " -> ");
197 }
198 fprintf(stderr, "%s", GetImplicitConversionName(Third));
199 PrintedSomething = true;
200 }
201
202 if (!PrintedSomething) {
203 fprintf(stderr, "No conversions required");
204 }
205}
206
207/// DebugPrint - Print this user-defined conversion sequence to standard
208/// error. Useful for debugging overloading issues.
209void UserDefinedConversionSequence::DebugPrint() const {
210 if (Before.First || Before.Second || Before.Third) {
211 Before.DebugPrint();
212 fprintf(stderr, " -> ");
213 }
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000214 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000215 if (After.First || After.Second || After.Third) {
216 fprintf(stderr, " -> ");
217 After.DebugPrint();
218 }
219}
220
221/// DebugPrint - Print this implicit conversion sequence to standard
222/// error. Useful for debugging overloading issues.
223void ImplicitConversionSequence::DebugPrint() const {
224 switch (ConversionKind) {
225 case StandardConversion:
226 fprintf(stderr, "Standard conversion: ");
227 Standard.DebugPrint();
228 break;
229 case UserDefinedConversion:
230 fprintf(stderr, "User-defined conversion: ");
231 UserDefined.DebugPrint();
232 break;
233 case EllipsisConversion:
234 fprintf(stderr, "Ellipsis conversion");
235 break;
236 case BadConversion:
237 fprintf(stderr, "Bad conversion");
238 break;
239 }
240
241 fprintf(stderr, "\n");
242}
243
244// IsOverload - Determine whether the given New declaration is an
245// overload of the Old declaration. This routine returns false if New
246// and Old cannot be overloaded, e.g., if they are functions with the
247// same signature (C++ 1.3.10) or if the Old declaration isn't a
248// function (or overload set). When it does return false and Old is an
249// OverloadedFunctionDecl, MatchedDecl will be set to point to the
250// FunctionDecl that New cannot be overloaded with.
251//
252// Example: Given the following input:
253//
254// void f(int, float); // #1
255// void f(int, int); // #2
256// int f(int, int); // #3
257//
258// When we process #1, there is no previous declaration of "f",
259// so IsOverload will not be used.
260//
261// When we process #2, Old is a FunctionDecl for #1. By comparing the
262// parameter types, we see that #1 and #2 are overloaded (since they
263// have different signatures), so this routine returns false;
264// MatchedDecl is unchanged.
265//
266// When we process #3, Old is an OverloadedFunctionDecl containing #1
267// and #2. We compare the signatures of #3 to #1 (they're overloaded,
268// so we do nothing) and then #3 to #2. Since the signatures of #3 and
269// #2 are identical (return types of functions are not part of the
270// signature), IsOverload returns false and MatchedDecl will be set to
271// point to the FunctionDecl for #2.
272bool
273Sema::IsOverload(FunctionDecl *New, Decl* OldD,
274 OverloadedFunctionDecl::function_iterator& MatchedDecl)
275{
276 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
277 // Is this new function an overload of every function in the
278 // overload set?
279 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
280 FuncEnd = Ovl->function_end();
281 for (; Func != FuncEnd; ++Func) {
282 if (!IsOverload(New, *Func, MatchedDecl)) {
283 MatchedDecl = Func;
284 return false;
285 }
286 }
287
288 // This function overloads every function in the overload set.
289 return true;
290 } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
291 // Is the function New an overload of the function Old?
292 QualType OldQType = Context.getCanonicalType(Old->getType());
293 QualType NewQType = Context.getCanonicalType(New->getType());
294
295 // Compare the signatures (C++ 1.3.10) of the two functions to
296 // determine whether they are overloads. If we find any mismatch
297 // in the signature, they are overloads.
298
299 // If either of these functions is a K&R-style function (no
300 // prototype), then we consider them to have matching signatures.
301 if (isa<FunctionTypeNoProto>(OldQType.getTypePtr()) ||
302 isa<FunctionTypeNoProto>(NewQType.getTypePtr()))
303 return false;
304
305 FunctionTypeProto* OldType = cast<FunctionTypeProto>(OldQType.getTypePtr());
306 FunctionTypeProto* NewType = cast<FunctionTypeProto>(NewQType.getTypePtr());
307
308 // The signature of a function includes the types of its
309 // parameters (C++ 1.3.10), which includes the presence or absence
310 // of the ellipsis; see C++ DR 357).
311 if (OldQType != NewQType &&
312 (OldType->getNumArgs() != NewType->getNumArgs() ||
313 OldType->isVariadic() != NewType->isVariadic() ||
314 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
315 NewType->arg_type_begin())))
316 return true;
317
318 // If the function is a class member, its signature includes the
319 // cv-qualifiers (if any) on the function itself.
320 //
321 // As part of this, also check whether one of the member functions
322 // is static, in which case they are not overloads (C++
323 // 13.1p2). While not part of the definition of the signature,
324 // this check is important to determine whether these functions
325 // can be overloaded.
326 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
327 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
328 if (OldMethod && NewMethod &&
329 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor1ca50c32008-11-21 15:36:28 +0000330 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000331 return true;
332
333 // The signatures match; this is not an overload.
334 return false;
335 } else {
336 // (C++ 13p1):
337 // Only function declarations can be overloaded; object and type
338 // declarations cannot be overloaded.
339 return false;
340 }
341}
342
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000343/// TryImplicitConversion - Attempt to perform an implicit conversion
344/// from the given expression (Expr) to the given type (ToType). This
345/// function returns an implicit conversion sequence that can be used
346/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000347///
348/// void f(float f);
349/// void g(int i) { f(i); }
350///
351/// this routine would produce an implicit conversion sequence to
352/// describe the initialization of f from i, which will be a standard
353/// conversion sequence containing an lvalue-to-rvalue conversion (C++
354/// 4.1) followed by a floating-integral conversion (C++ 4.9).
355//
356/// Note that this routine only determines how the conversion can be
357/// performed; it does not actually perform the conversion. As such,
358/// it will not produce any diagnostics if no conversion is available,
359/// but will instead return an implicit conversion sequence of kind
360/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000361///
362/// If @p SuppressUserConversions, then user-defined conversions are
363/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000364/// If @p AllowExplicit, then explicit user-defined conversions are
365/// permitted.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000366ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +0000367Sema::TryImplicitConversion(Expr* From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000368 bool SuppressUserConversions,
Douglas Gregor734d9862009-01-30 23:27:23 +0000369 bool AllowExplicit)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000370{
371 ImplicitConversionSequence ICS;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000372 if (IsStandardConversion(From, ToType, ICS.Standard))
373 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregor734d9862009-01-30 23:27:23 +0000374 else if (IsUserDefinedConversion(From, ToType, ICS.UserDefined,
375 !SuppressUserConversions, AllowExplicit)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000376 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000377 // C++ [over.ics.user]p4:
378 // A conversion of an expression of class type to the same class
379 // type is given Exact Match rank, and a conversion of an
380 // expression of class type to a base class of that type is
381 // given Conversion rank, in spite of the fact that a copy
382 // constructor (i.e., a user-defined conversion function) is
383 // called for those cases.
384 if (CXXConstructorDecl *Constructor
385 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
386 if (Constructor->isCopyConstructor(Context)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000387 // Turn this into a "standard" conversion sequence, so that it
388 // gets ranked with standard conversion sequences.
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000389 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
390 ICS.Standard.setAsIdentityConversion();
391 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
392 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000393 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000394 if (IsDerivedFrom(From->getType().getUnqualifiedType(),
395 ToType.getUnqualifiedType()))
396 ICS.Standard.Second = ICK_Derived_To_Base;
397 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000398 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000399
400 // C++ [over.best.ics]p4:
401 // However, when considering the argument of a user-defined
402 // conversion function that is a candidate by 13.3.1.3 when
403 // invoked for the copying of the temporary in the second step
404 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
405 // 13.3.1.6 in all cases, only standard conversion sequences and
406 // ellipsis conversion sequences are allowed.
407 if (SuppressUserConversions &&
408 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
409 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000410 } else
Douglas Gregor60d62c22008-10-31 16:23:19 +0000411 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000412
413 return ICS;
414}
415
416/// IsStandardConversion - Determines whether there is a standard
417/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
418/// expression From to the type ToType. Standard conversion sequences
419/// only consider non-class types; for conversions that involve class
420/// types, use TryImplicitConversion. If a conversion exists, SCS will
421/// contain the standard conversion sequence required to perform this
422/// conversion and this routine will return true. Otherwise, this
423/// routine will return false and the value of SCS is unspecified.
424bool
425Sema::IsStandardConversion(Expr* From, QualType ToType,
426 StandardConversionSequence &SCS)
427{
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000428 QualType FromType = From->getType();
429
Douglas Gregor60d62c22008-10-31 16:23:19 +0000430 // There are no standard conversions for class types, so abort early.
431 if (FromType->isRecordType() || ToType->isRecordType())
432 return false;
433
434 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000435 SCS.setAsIdentityConversion();
Douglas Gregor60d62c22008-10-31 16:23:19 +0000436 SCS.Deprecated = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000437 SCS.IncompatibleObjC = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000438 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000439 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000440
441 // The first conversion can be an lvalue-to-rvalue conversion,
442 // array-to-pointer conversion, or function-to-pointer conversion
443 // (C++ 4p1).
444
445 // Lvalue-to-rvalue conversion (C++ 4.1):
446 // An lvalue (3.10) of a non-function, non-array type T can be
447 // converted to an rvalue.
448 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
449 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000450 !FromType->isFunctionType() && !FromType->isArrayType() &&
451 !FromType->isOverloadType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000452 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000453
454 // If T is a non-class type, the type of the rvalue is the
455 // cv-unqualified version of T. Otherwise, the type of the rvalue
456 // is T (C++ 4.1p1).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000457 FromType = FromType.getUnqualifiedType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000458 }
459 // Array-to-pointer conversion (C++ 4.2)
460 else if (FromType->isArrayType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000461 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000462
463 // An lvalue or rvalue of type "array of N T" or "array of unknown
464 // bound of T" can be converted to an rvalue of type "pointer to
465 // T" (C++ 4.2p1).
466 FromType = Context.getArrayDecayedType(FromType);
467
468 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
469 // This conversion is deprecated. (C++ D.4).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000470 SCS.Deprecated = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000471
472 // For the purpose of ranking in overload resolution
473 // (13.3.3.1.1), this conversion is considered an
474 // array-to-pointer conversion followed by a qualification
475 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000476 SCS.Second = ICK_Identity;
477 SCS.Third = ICK_Qualification;
478 SCS.ToTypePtr = ToType.getAsOpaquePtr();
479 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000480 }
481 }
482 // Function-to-pointer conversion (C++ 4.3).
483 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000484 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000485
486 // An lvalue of function type T can be converted to an rvalue of
487 // type "pointer to T." The result is a pointer to the
488 // function. (C++ 4.3p1).
489 FromType = Context.getPointerType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000490 }
Douglas Gregor904eed32008-11-10 20:40:00 +0000491 // Address of overloaded function (C++ [over.over]).
492 else if (FunctionDecl *Fn
493 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
494 SCS.First = ICK_Function_To_Pointer;
495
496 // We were able to resolve the address of the overloaded function,
497 // so we can convert to the type of that function.
498 FromType = Fn->getType();
499 if (ToType->isReferenceType())
500 FromType = Context.getReferenceType(FromType);
501 else
502 FromType = Context.getPointerType(FromType);
503 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000504 // We don't require any conversions for the first step.
505 else {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000506 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000507 }
508
509 // The second conversion can be an integral promotion, floating
510 // point promotion, integral conversion, floating point conversion,
511 // floating-integral conversion, pointer conversion,
512 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor45920e82008-12-19 17:40:08 +0000513 bool IncompatibleObjC = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000514 if (Context.getCanonicalType(FromType).getUnqualifiedType() ==
515 Context.getCanonicalType(ToType).getUnqualifiedType()) {
516 // The unqualified versions of the types are the same: there's no
517 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000518 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000519 }
520 // Integral promotion (C++ 4.5).
521 else if (IsIntegralPromotion(From, FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000522 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000523 FromType = ToType.getUnqualifiedType();
524 }
525 // Floating point promotion (C++ 4.6).
526 else if (IsFloatingPointPromotion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000527 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000528 FromType = ToType.getUnqualifiedType();
529 }
530 // Integral conversions (C++ 4.7).
Sebastian Redl07779722008-10-31 14:43:28 +0000531 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000532 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000533 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000534 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000535 FromType = ToType.getUnqualifiedType();
536 }
537 // Floating point conversions (C++ 4.8).
538 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000539 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000540 FromType = ToType.getUnqualifiedType();
541 }
542 // Floating-integral conversions (C++ 4.9).
Sebastian Redl07779722008-10-31 14:43:28 +0000543 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000544 else if ((FromType->isFloatingType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000545 ToType->isIntegralType() && !ToType->isBooleanType() &&
546 !ToType->isEnumeralType()) ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000547 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
548 ToType->isFloatingType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000549 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000550 FromType = ToType.getUnqualifiedType();
551 }
552 // Pointer conversions (C++ 4.10).
Douglas Gregor45920e82008-12-19 17:40:08 +0000553 else if (IsPointerConversion(From, FromType, ToType, FromType,
554 IncompatibleObjC)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000555 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000556 SCS.IncompatibleObjC = IncompatibleObjC;
Sebastian Redl07779722008-10-31 14:43:28 +0000557 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000558 // Pointer to member conversions (4.11).
559 else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
560 SCS.Second = ICK_Pointer_Member;
561 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000562 // Boolean conversions (C++ 4.12).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000563 else if (ToType->isBooleanType() &&
564 (FromType->isArithmeticType() ||
565 FromType->isEnumeralType() ||
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000566 FromType->isPointerType() ||
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000567 FromType->isBlockPointerType() ||
568 FromType->isMemberPointerType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000569 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000570 FromType = Context.BoolTy;
571 } else {
572 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000573 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000574 }
575
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000576 QualType CanonFrom;
577 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000578 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000579 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000580 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000581 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000582 CanonFrom = Context.getCanonicalType(FromType);
583 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000584 } else {
585 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000586 SCS.Third = ICK_Identity;
587
588 // C++ [over.best.ics]p6:
589 // [...] Any difference in top-level cv-qualification is
590 // subsumed by the initialization itself and does not constitute
591 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000592 CanonFrom = Context.getCanonicalType(FromType);
593 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000594 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000595 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
596 FromType = ToType;
597 CanonFrom = CanonTo;
598 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000599 }
600
601 // If we have not converted the argument type to the parameter type,
602 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000603 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000604 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000605
Douglas Gregor60d62c22008-10-31 16:23:19 +0000606 SCS.ToTypePtr = FromType.getAsOpaquePtr();
607 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000608}
609
610/// IsIntegralPromotion - Determines whether the conversion from the
611/// expression From (whose potentially-adjusted type is FromType) to
612/// ToType is an integral promotion (C++ 4.5). If so, returns true and
613/// sets PromotedType to the promoted type.
614bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
615{
616 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000617 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000618 if (!To) {
619 return false;
620 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000621
622 // An rvalue of type char, signed char, unsigned char, short int, or
623 // unsigned short int can be converted to an rvalue of type int if
624 // int can represent all the values of the source type; otherwise,
625 // the source rvalue can be converted to an rvalue of type unsigned
626 // int (C++ 4.5p1).
Sebastian Redl07779722008-10-31 14:43:28 +0000627 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000628 if (// We can promote any signed, promotable integer type to an int
629 (FromType->isSignedIntegerType() ||
630 // We can promote any unsigned integer type whose size is
631 // less than int to an int.
632 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000633 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000634 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000635 }
636
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000637 return To->getKind() == BuiltinType::UInt;
638 }
639
640 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
641 // can be converted to an rvalue of the first of the following types
642 // that can represent all the values of its underlying type: int,
643 // unsigned int, long, or unsigned long (C++ 4.5p2).
644 if ((FromType->isEnumeralType() || FromType->isWideCharType())
645 && ToType->isIntegerType()) {
646 // Determine whether the type we're converting from is signed or
647 // unsigned.
648 bool FromIsSigned;
649 uint64_t FromSize = Context.getTypeSize(FromType);
650 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
651 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
652 FromIsSigned = UnderlyingType->isSignedIntegerType();
653 } else {
654 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
655 FromIsSigned = true;
656 }
657
658 // The types we'll try to promote to, in the appropriate
659 // order. Try each of these types.
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000660 QualType PromoteTypes[6] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000661 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000662 Context.LongTy, Context.UnsignedLongTy ,
663 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000664 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000665 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000666 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
667 if (FromSize < ToSize ||
668 (FromSize == ToSize &&
669 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
670 // We found the type that we can promote to. If this is the
671 // type we wanted, we have a promotion. Otherwise, no
672 // promotion.
Sebastian Redl07779722008-10-31 14:43:28 +0000673 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000674 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
675 }
676 }
677 }
678
679 // An rvalue for an integral bit-field (9.6) can be converted to an
680 // rvalue of type int if int can represent all the values of the
681 // bit-field; otherwise, it can be converted to unsigned int if
682 // unsigned int can represent all the values of the bit-field. If
683 // the bit-field is larger yet, no integral promotion applies to
684 // it. If the bit-field has an enumerated type, it is treated as any
685 // other value of that type for promotion purposes (C++ 4.5p3).
686 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) {
687 using llvm::APSInt;
Douglas Gregor86f19402008-12-20 23:49:58 +0000688 if (FieldDecl *MemberDecl = dyn_cast<FieldDecl>(MemRef->getMemberDecl())) {
689 APSInt BitWidth;
690 if (MemberDecl->isBitField() &&
691 FromType->isIntegralType() && !FromType->isEnumeralType() &&
692 From->isIntegerConstantExpr(BitWidth, Context)) {
693 APSInt ToSize(Context.getTypeSize(ToType));
694
695 // Are we promoting to an int from a bitfield that fits in an int?
696 if (BitWidth < ToSize ||
697 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
698 return To->getKind() == BuiltinType::Int;
699 }
700
701 // Are we promoting to an unsigned int from an unsigned bitfield
702 // that fits into an unsigned int?
703 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
704 return To->getKind() == BuiltinType::UInt;
705 }
706
707 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000708 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000709 }
710 }
711
712 // An rvalue of type bool can be converted to an rvalue of type int,
713 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000714 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000715 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000716 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000717
718 return false;
719}
720
721/// IsFloatingPointPromotion - Determines whether the conversion from
722/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
723/// returns true and sets PromotedType to the promoted type.
724bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
725{
726 /// An rvalue of type float can be converted to an rvalue of type
727 /// double. (C++ 4.6p1).
728 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
729 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType())
730 if (FromBuiltin->getKind() == BuiltinType::Float &&
731 ToBuiltin->getKind() == BuiltinType::Double)
732 return true;
733
734 return false;
735}
736
Douglas Gregorcb7de522008-11-26 23:31:11 +0000737/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
738/// the pointer type FromPtr to a pointer to type ToPointee, with the
739/// same type qualifiers as FromPtr has on its pointee type. ToType,
740/// if non-empty, will be a pointer to ToType that may or may not have
741/// the right set of qualifiers on its pointee.
742static QualType
743BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
744 QualType ToPointee, QualType ToType,
745 ASTContext &Context) {
746 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
747 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
748 unsigned Quals = CanonFromPointee.getCVRQualifiers();
749
750 // Exact qualifier match -> return the pointer type we're converting to.
751 if (CanonToPointee.getCVRQualifiers() == Quals) {
752 // ToType is exactly what we need. Return it.
753 if (ToType.getTypePtr())
754 return ToType;
755
756 // Build a pointer to ToPointee. It has the right qualifiers
757 // already.
758 return Context.getPointerType(ToPointee);
759 }
760
761 // Just build a canonical type that has the right qualifiers.
762 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
763}
764
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000765/// IsPointerConversion - Determines whether the conversion of the
766/// expression From, which has the (possibly adjusted) type FromType,
767/// can be converted to the type ToType via a pointer conversion (C++
768/// 4.10). If so, returns true and places the converted type (that
769/// might differ from ToType in its cv-qualifiers at some level) into
770/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000771///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000772/// This routine also supports conversions to and from block pointers
773/// and conversions with Objective-C's 'id', 'id<protocols...>', and
774/// pointers to interfaces. FIXME: Once we've determined the
775/// appropriate overloading rules for Objective-C, we may want to
776/// split the Objective-C checks into a different routine; however,
777/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000778/// conversions, so for now they live here. IncompatibleObjC will be
779/// set if the conversion is an allowed Objective-C conversion that
780/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000781bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000782 QualType& ConvertedType,
783 bool &IncompatibleObjC)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000784{
Douglas Gregor45920e82008-12-19 17:40:08 +0000785 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +0000786 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
787 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +0000788
Douglas Gregor27b09ac2008-12-22 20:51:52 +0000789 // Conversion from a null pointer constant to any Objective-C pointer type.
790 if (Context.isObjCObjectPointerType(ToType) &&
791 From->isNullPointerConstant(Context)) {
792 ConvertedType = ToType;
793 return true;
794 }
795
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000796 // Blocks: Block pointers can be converted to void*.
797 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
798 ToType->getAsPointerType()->getPointeeType()->isVoidType()) {
799 ConvertedType = ToType;
800 return true;
801 }
802 // Blocks: A null pointer constant can be converted to a block
803 // pointer type.
804 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
805 ConvertedType = ToType;
806 return true;
807 }
808
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000809 const PointerType* ToTypePtr = ToType->getAsPointerType();
810 if (!ToTypePtr)
811 return false;
812
813 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
814 if (From->isNullPointerConstant(Context)) {
815 ConvertedType = ToType;
816 return true;
817 }
Sebastian Redl07779722008-10-31 14:43:28 +0000818
Douglas Gregorcb7de522008-11-26 23:31:11 +0000819 // Beyond this point, both types need to be pointers.
820 const PointerType *FromTypePtr = FromType->getAsPointerType();
821 if (!FromTypePtr)
822 return false;
823
824 QualType FromPointeeType = FromTypePtr->getPointeeType();
825 QualType ToPointeeType = ToTypePtr->getPointeeType();
826
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000827 // An rvalue of type "pointer to cv T," where T is an object type,
828 // can be converted to an rvalue of type "pointer to cv void" (C++
829 // 4.10p2).
Douglas Gregorc7887512008-12-19 19:13:09 +0000830 if (FromPointeeType->isIncompleteOrObjectType() &&
831 ToPointeeType->isVoidType()) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000832 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
833 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000834 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000835 return true;
836 }
837
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000838 // C++ [conv.ptr]p3:
839 //
840 // An rvalue of type "pointer to cv D," where D is a class type,
841 // can be converted to an rvalue of type "pointer to cv B," where
842 // B is a base class (clause 10) of D. If B is an inaccessible
843 // (clause 11) or ambiguous (10.2) base class of D, a program that
844 // necessitates this conversion is ill-formed. The result of the
845 // conversion is a pointer to the base class sub-object of the
846 // derived class object. The null pointer value is converted to
847 // the null pointer value of the destination type.
848 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000849 // Note that we do not check for ambiguity or inaccessibility
850 // here. That is handled by CheckPointerConversion.
Douglas Gregorcb7de522008-11-26 23:31:11 +0000851 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
852 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000853 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
854 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000855 ToType, Context);
856 return true;
857 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000858
Douglas Gregorc7887512008-12-19 19:13:09 +0000859 return false;
860}
861
862/// isObjCPointerConversion - Determines whether this is an
863/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
864/// with the same arguments and return values.
865bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
866 QualType& ConvertedType,
867 bool &IncompatibleObjC) {
868 if (!getLangOptions().ObjC1)
869 return false;
870
871 // Conversions with Objective-C's id<...>.
872 if ((FromType->isObjCQualifiedIdType() || ToType->isObjCQualifiedIdType()) &&
873 ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) {
874 ConvertedType = ToType;
875 return true;
876 }
877
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000878 // Beyond this point, both types need to be pointers or block pointers.
879 QualType ToPointeeType;
Douglas Gregorc7887512008-12-19 19:13:09 +0000880 const PointerType* ToTypePtr = ToType->getAsPointerType();
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000881 if (ToTypePtr)
882 ToPointeeType = ToTypePtr->getPointeeType();
883 else if (const BlockPointerType *ToBlockPtr = ToType->getAsBlockPointerType())
884 ToPointeeType = ToBlockPtr->getPointeeType();
885 else
Douglas Gregorc7887512008-12-19 19:13:09 +0000886 return false;
887
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000888 QualType FromPointeeType;
Douglas Gregorc7887512008-12-19 19:13:09 +0000889 const PointerType *FromTypePtr = FromType->getAsPointerType();
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000890 if (FromTypePtr)
891 FromPointeeType = FromTypePtr->getPointeeType();
892 else if (const BlockPointerType *FromBlockPtr
893 = FromType->getAsBlockPointerType())
894 FromPointeeType = FromBlockPtr->getPointeeType();
895 else
Douglas Gregorc7887512008-12-19 19:13:09 +0000896 return false;
897
Douglas Gregorcb7de522008-11-26 23:31:11 +0000898 // Objective C++: We're able to convert from a pointer to an
899 // interface to a pointer to a different interface.
900 const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType();
901 const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType();
902 if (FromIface && ToIface &&
903 Context.canAssignObjCInterfaces(ToIface, FromIface)) {
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000904 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +0000905 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000906 ToType, Context);
907 return true;
908 }
909
Douglas Gregor45920e82008-12-19 17:40:08 +0000910 if (FromIface && ToIface &&
911 Context.canAssignObjCInterfaces(FromIface, ToIface)) {
912 // Okay: this is some kind of implicit downcast of Objective-C
913 // interfaces, which is permitted. However, we're going to
914 // complain about it.
915 IncompatibleObjC = true;
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000916 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor45920e82008-12-19 17:40:08 +0000917 ToPointeeType,
918 ToType, Context);
919 return true;
920 }
921
Douglas Gregorcb7de522008-11-26 23:31:11 +0000922 // Objective C++: We're able to convert between "id" and a pointer
923 // to any interface (in both directions).
924 if ((FromIface && Context.isObjCIdType(ToPointeeType))
925 || (ToIface && Context.isObjCIdType(FromPointeeType))) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000926 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
927 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000928 ToType, Context);
929 return true;
930 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000931
Douglas Gregordda78892008-12-18 23:43:31 +0000932 // Objective C++: Allow conversions between the Objective-C "id" and
933 // "Class", in either direction.
934 if ((Context.isObjCIdType(FromPointeeType) &&
935 Context.isObjCClassType(ToPointeeType)) ||
936 (Context.isObjCClassType(FromPointeeType) &&
937 Context.isObjCIdType(ToPointeeType))) {
938 ConvertedType = ToType;
939 return true;
940 }
941
Douglas Gregorc7887512008-12-19 19:13:09 +0000942 // If we have pointers to pointers, recursively check whether this
943 // is an Objective-C conversion.
944 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
945 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
946 IncompatibleObjC)) {
947 // We always complain about this conversion.
948 IncompatibleObjC = true;
949 ConvertedType = ToType;
950 return true;
951 }
952
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000953 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +0000954 // differences in the argument and result types are in Objective-C
955 // pointer conversions. If so, we permit the conversion (but
956 // complain about it).
957 const FunctionTypeProto *FromFunctionType
958 = FromPointeeType->getAsFunctionTypeProto();
959 const FunctionTypeProto *ToFunctionType
960 = ToPointeeType->getAsFunctionTypeProto();
961 if (FromFunctionType && ToFunctionType) {
962 // If the function types are exactly the same, this isn't an
963 // Objective-C pointer conversion.
964 if (Context.getCanonicalType(FromPointeeType)
965 == Context.getCanonicalType(ToPointeeType))
966 return false;
967
968 // Perform the quick checks that will tell us whether these
969 // function types are obviously different.
970 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
971 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
972 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
973 return false;
974
975 bool HasObjCConversion = false;
976 if (Context.getCanonicalType(FromFunctionType->getResultType())
977 == Context.getCanonicalType(ToFunctionType->getResultType())) {
978 // Okay, the types match exactly. Nothing to do.
979 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
980 ToFunctionType->getResultType(),
981 ConvertedType, IncompatibleObjC)) {
982 // Okay, we have an Objective-C pointer conversion.
983 HasObjCConversion = true;
984 } else {
985 // Function types are too different. Abort.
986 return false;
987 }
988
989 // Check argument types.
990 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
991 ArgIdx != NumArgs; ++ArgIdx) {
992 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
993 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
994 if (Context.getCanonicalType(FromArgType)
995 == Context.getCanonicalType(ToArgType)) {
996 // Okay, the types match exactly. Nothing to do.
997 } else if (isObjCPointerConversion(FromArgType, ToArgType,
998 ConvertedType, IncompatibleObjC)) {
999 // Okay, we have an Objective-C pointer conversion.
1000 HasObjCConversion = true;
1001 } else {
1002 // Argument types are too different. Abort.
1003 return false;
1004 }
1005 }
1006
1007 if (HasObjCConversion) {
1008 // We had an Objective-C conversion. Allow this pointer
1009 // conversion, but complain about it.
1010 ConvertedType = ToType;
1011 IncompatibleObjC = true;
1012 return true;
1013 }
1014 }
1015
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001016 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001017}
1018
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001019/// CheckPointerConversion - Check the pointer conversion from the
1020/// expression From to the type ToType. This routine checks for
1021/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
1022/// conversions for which IsPointerConversion has already returned
1023/// true. It returns true and produces a diagnostic if there was an
1024/// error, or returns false otherwise.
1025bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1026 QualType FromType = From->getType();
1027
1028 if (const PointerType *FromPtrType = FromType->getAsPointerType())
1029 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001030 QualType FromPointeeType = FromPtrType->getPointeeType(),
1031 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001032
1033 // Objective-C++ conversions are always okay.
1034 // FIXME: We should have a different class of conversions for
1035 // the Objective-C++ implicit conversions.
1036 if (Context.isObjCIdType(FromPointeeType) ||
1037 Context.isObjCIdType(ToPointeeType) ||
1038 Context.isObjCClassType(FromPointeeType) ||
1039 Context.isObjCClassType(ToPointeeType))
1040 return false;
1041
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001042 if (FromPointeeType->isRecordType() &&
1043 ToPointeeType->isRecordType()) {
1044 // We must have a derived-to-base conversion. Check an
1045 // ambiguous or inaccessible conversion.
Douglas Gregor0575d4a2008-10-24 16:17:19 +00001046 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1047 From->getExprLoc(),
1048 From->getSourceRange());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001049 }
1050 }
1051
1052 return false;
1053}
1054
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001055/// IsMemberPointerConversion - Determines whether the conversion of the
1056/// expression From, which has the (possibly adjusted) type FromType, can be
1057/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1058/// If so, returns true and places the converted type (that might differ from
1059/// ToType in its cv-qualifiers at some level) into ConvertedType.
1060bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1061 QualType ToType, QualType &ConvertedType)
1062{
1063 const MemberPointerType *ToTypePtr = ToType->getAsMemberPointerType();
1064 if (!ToTypePtr)
1065 return false;
1066
1067 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1068 if (From->isNullPointerConstant(Context)) {
1069 ConvertedType = ToType;
1070 return true;
1071 }
1072
1073 // Otherwise, both types have to be member pointers.
1074 const MemberPointerType *FromTypePtr = FromType->getAsMemberPointerType();
1075 if (!FromTypePtr)
1076 return false;
1077
1078 // A pointer to member of B can be converted to a pointer to member of D,
1079 // where D is derived from B (C++ 4.11p2).
1080 QualType FromClass(FromTypePtr->getClass(), 0);
1081 QualType ToClass(ToTypePtr->getClass(), 0);
1082 // FIXME: What happens when these are dependent? Is this function even called?
1083
1084 if (IsDerivedFrom(ToClass, FromClass)) {
1085 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1086 ToClass.getTypePtr());
1087 return true;
1088 }
1089
1090 return false;
1091}
1092
1093/// CheckMemberPointerConversion - Check the member pointer conversion from the
1094/// expression From to the type ToType. This routine checks for ambiguous or
1095/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1096/// for which IsMemberPointerConversion has already returned true. It returns
1097/// true and produces a diagnostic if there was an error, or returns false
1098/// otherwise.
1099bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType) {
1100 QualType FromType = From->getType();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001101 const MemberPointerType *FromPtrType = FromType->getAsMemberPointerType();
1102 if (!FromPtrType)
1103 return false;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001104
Sebastian Redl21593ac2009-01-28 18:33:18 +00001105 const MemberPointerType *ToPtrType = ToType->getAsMemberPointerType();
1106 assert(ToPtrType && "No member pointer cast has a target type "
1107 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001108
Sebastian Redl21593ac2009-01-28 18:33:18 +00001109 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1110 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001111
Sebastian Redl21593ac2009-01-28 18:33:18 +00001112 // FIXME: What about dependent types?
1113 assert(FromClass->isRecordType() && "Pointer into non-class.");
1114 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001115
Sebastian Redl21593ac2009-01-28 18:33:18 +00001116 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1117 /*DetectVirtual=*/true);
1118 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1119 assert(DerivationOkay &&
1120 "Should not have been called if derivation isn't OK.");
1121 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001122
Sebastian Redl21593ac2009-01-28 18:33:18 +00001123 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1124 getUnqualifiedType())) {
1125 // Derivation is ambiguous. Redo the check to find the exact paths.
1126 Paths.clear();
1127 Paths.setRecordingPaths(true);
1128 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1129 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1130 (void)StillOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001131
Sebastian Redl21593ac2009-01-28 18:33:18 +00001132 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1133 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1134 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1135 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001136 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001137
1138 if (const CXXRecordType *VBase = Paths.getDetectedVirtual()) {
1139 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1140 << FromClass << ToClass << QualType(VBase, 0)
1141 << From->getSourceRange();
1142 return true;
1143 }
1144
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001145 return false;
1146}
1147
Douglas Gregor98cd5992008-10-21 23:43:52 +00001148/// IsQualificationConversion - Determines whether the conversion from
1149/// an rvalue of type FromType to ToType is a qualification conversion
1150/// (C++ 4.4).
1151bool
1152Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1153{
1154 FromType = Context.getCanonicalType(FromType);
1155 ToType = Context.getCanonicalType(ToType);
1156
1157 // If FromType and ToType are the same type, this is not a
1158 // qualification conversion.
1159 if (FromType == ToType)
1160 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001161
Douglas Gregor98cd5992008-10-21 23:43:52 +00001162 // (C++ 4.4p4):
1163 // A conversion can add cv-qualifiers at levels other than the first
1164 // in multi-level pointers, subject to the following rules: [...]
1165 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001166 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001167 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001168 // Within each iteration of the loop, we check the qualifiers to
1169 // determine if this still looks like a qualification
1170 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001171 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001172 // until there are no more pointers or pointers-to-members left to
1173 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001174 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001175
1176 // -- for every j > 0, if const is in cv 1,j then const is in cv
1177 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001178 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001179 return false;
Douglas Gregor57373262008-10-22 14:17:15 +00001180
Douglas Gregor98cd5992008-10-21 23:43:52 +00001181 // -- if the cv 1,j and cv 2,j are different, then const is in
1182 // every cv for 0 < k < j.
1183 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001184 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001185 return false;
Douglas Gregor57373262008-10-22 14:17:15 +00001186
Douglas Gregor98cd5992008-10-21 23:43:52 +00001187 // Keep track of whether all prior cv-qualifiers in the "to" type
1188 // include const.
1189 PreviousToQualsIncludeConst
1190 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001191 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001192
1193 // We are left with FromType and ToType being the pointee types
1194 // after unwrapping the original FromType and ToType the same number
1195 // of types. If we unwrapped any pointers, and if FromType and
1196 // ToType have the same unqualified type (since we checked
1197 // qualifiers above), then this is a qualification conversion.
1198 return UnwrappedAnyPointer &&
1199 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1200}
1201
Douglas Gregor734d9862009-01-30 23:27:23 +00001202/// Determines whether there is a user-defined conversion sequence
1203/// (C++ [over.ics.user]) that converts expression From to the type
1204/// ToType. If such a conversion exists, User will contain the
1205/// user-defined conversion sequence that performs such a conversion
1206/// and this routine will return true. Otherwise, this routine returns
1207/// false and User is unspecified.
1208///
1209/// \param AllowConversionFunctions true if the conversion should
1210/// consider conversion functions at all. If false, only constructors
1211/// will be considered.
1212///
1213/// \param AllowExplicit true if the conversion should consider C++0x
1214/// "explicit" conversion functions as well as non-explicit conversion
1215/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001216bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001217 UserDefinedConversionSequence& User,
Douglas Gregor734d9862009-01-30 23:27:23 +00001218 bool AllowConversionFunctions,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001219 bool AllowExplicit)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001220{
1221 OverloadCandidateSet CandidateSet;
1222 if (const CXXRecordType *ToRecordType
1223 = dyn_cast_or_null<CXXRecordType>(ToType->getAsRecordType())) {
1224 // C++ [over.match.ctor]p1:
1225 // When objects of class type are direct-initialized (8.5), or
1226 // copy-initialized from an expression of the same or a
1227 // derived class type (8.5), overload resolution selects the
1228 // constructor. [...] For copy-initialization, the candidate
1229 // functions are all the converting constructors (12.3.1) of
1230 // that class. The argument list is the expression-list within
1231 // the parentheses of the initializer.
1232 CXXRecordDecl *ToRecordDecl = ToRecordType->getDecl();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001233 DeclarationName ConstructorName
1234 = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregore63ef482009-01-13 00:11:19 +00001235 Context.getCanonicalType(ToType).getUnqualifiedType());
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001236 DeclContext::lookup_iterator Con, ConEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00001237 for (llvm::tie(Con, ConEnd) = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001238 Con != ConEnd; ++Con) {
1239 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001240 if (Constructor->isConvertingConstructor())
Douglas Gregor225c41e2008-11-03 19:09:14 +00001241 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1242 /*SuppressUserConversions=*/true);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001243 }
1244 }
1245
Douglas Gregor734d9862009-01-30 23:27:23 +00001246 if (!AllowConversionFunctions) {
1247 // Don't allow any conversion functions to enter the overload set.
1248 } else if (const CXXRecordType *FromRecordType
1249 = dyn_cast_or_null<CXXRecordType>(
1250 From->getType()->getAsRecordType())) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001251 // Add all of the conversion functions as candidates.
1252 // FIXME: Look for conversions in base classes!
1253 CXXRecordDecl *FromRecordDecl = FromRecordType->getDecl();
1254 OverloadedFunctionDecl *Conversions
1255 = FromRecordDecl->getConversionFunctions();
1256 for (OverloadedFunctionDecl::function_iterator Func
1257 = Conversions->function_begin();
1258 Func != Conversions->function_end(); ++Func) {
1259 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001260 if (AllowExplicit || !Conv->isExplicit())
1261 AddConversionCandidate(Conv, From, ToType, CandidateSet);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001262 }
1263 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001264
1265 OverloadCandidateSet::iterator Best;
1266 switch (BestViableFunction(CandidateSet, Best)) {
1267 case OR_Success:
1268 // Record the standard conversion we used and the conversion function.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001269 if (CXXConstructorDecl *Constructor
1270 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1271 // C++ [over.ics.user]p1:
1272 // If the user-defined conversion is specified by a
1273 // constructor (12.3.1), the initial standard conversion
1274 // sequence converts the source type to the type required by
1275 // the argument of the constructor.
1276 //
1277 // FIXME: What about ellipsis conversions?
1278 QualType ThisType = Constructor->getThisType(Context);
1279 User.Before = Best->Conversions[0].Standard;
1280 User.ConversionFunction = Constructor;
1281 User.After.setAsIdentityConversion();
1282 User.After.FromTypePtr
1283 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
1284 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1285 return true;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001286 } else if (CXXConversionDecl *Conversion
1287 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1288 // C++ [over.ics.user]p1:
1289 //
1290 // [...] If the user-defined conversion is specified by a
1291 // conversion function (12.3.2), the initial standard
1292 // conversion sequence converts the source type to the
1293 // implicit object parameter of the conversion function.
1294 User.Before = Best->Conversions[0].Standard;
1295 User.ConversionFunction = Conversion;
1296
1297 // C++ [over.ics.user]p2:
1298 // The second standard conversion sequence converts the
1299 // result of the user-defined conversion to the target type
1300 // for the sequence. Since an implicit conversion sequence
1301 // is an initialization, the special rules for
1302 // initialization by user-defined conversion apply when
1303 // selecting the best user-defined conversion for a
1304 // user-defined conversion sequence (see 13.3.3 and
1305 // 13.3.3.1).
1306 User.After = Best->FinalConversion;
1307 return true;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001308 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001309 assert(false && "Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001310 return false;
1311 }
1312
1313 case OR_No_Viable_Function:
1314 // No conversion here! We're done.
1315 return false;
1316
1317 case OR_Ambiguous:
1318 // FIXME: See C++ [over.best.ics]p10 for the handling of
1319 // ambiguous conversion sequences.
1320 return false;
1321 }
1322
1323 return false;
1324}
1325
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001326/// CompareImplicitConversionSequences - Compare two implicit
1327/// conversion sequences to determine whether one is better than the
1328/// other or if they are indistinguishable (C++ 13.3.3.2).
1329ImplicitConversionSequence::CompareKind
1330Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1331 const ImplicitConversionSequence& ICS2)
1332{
1333 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1334 // conversion sequences (as defined in 13.3.3.1)
1335 // -- a standard conversion sequence (13.3.3.1.1) is a better
1336 // conversion sequence than a user-defined conversion sequence or
1337 // an ellipsis conversion sequence, and
1338 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1339 // conversion sequence than an ellipsis conversion sequence
1340 // (13.3.3.1.3).
1341 //
1342 if (ICS1.ConversionKind < ICS2.ConversionKind)
1343 return ImplicitConversionSequence::Better;
1344 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1345 return ImplicitConversionSequence::Worse;
1346
1347 // Two implicit conversion sequences of the same form are
1348 // indistinguishable conversion sequences unless one of the
1349 // following rules apply: (C++ 13.3.3.2p3):
1350 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1351 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1352 else if (ICS1.ConversionKind ==
1353 ImplicitConversionSequence::UserDefinedConversion) {
1354 // User-defined conversion sequence U1 is a better conversion
1355 // sequence than another user-defined conversion sequence U2 if
1356 // they contain the same user-defined conversion function or
1357 // constructor and if the second standard conversion sequence of
1358 // U1 is better than the second standard conversion sequence of
1359 // U2 (C++ 13.3.3.2p3).
1360 if (ICS1.UserDefined.ConversionFunction ==
1361 ICS2.UserDefined.ConversionFunction)
1362 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1363 ICS2.UserDefined.After);
1364 }
1365
1366 return ImplicitConversionSequence::Indistinguishable;
1367}
1368
1369/// CompareStandardConversionSequences - Compare two standard
1370/// conversion sequences to determine whether one is better than the
1371/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1372ImplicitConversionSequence::CompareKind
1373Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1374 const StandardConversionSequence& SCS2)
1375{
1376 // Standard conversion sequence S1 is a better conversion sequence
1377 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1378
1379 // -- S1 is a proper subsequence of S2 (comparing the conversion
1380 // sequences in the canonical form defined by 13.3.3.1.1,
1381 // excluding any Lvalue Transformation; the identity conversion
1382 // sequence is considered to be a subsequence of any
1383 // non-identity conversion sequence) or, if not that,
1384 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1385 // Neither is a proper subsequence of the other. Do nothing.
1386 ;
1387 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1388 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1389 (SCS1.Second == ICK_Identity &&
1390 SCS1.Third == ICK_Identity))
1391 // SCS1 is a proper subsequence of SCS2.
1392 return ImplicitConversionSequence::Better;
1393 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1394 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1395 (SCS2.Second == ICK_Identity &&
1396 SCS2.Third == ICK_Identity))
1397 // SCS2 is a proper subsequence of SCS1.
1398 return ImplicitConversionSequence::Worse;
1399
1400 // -- the rank of S1 is better than the rank of S2 (by the rules
1401 // defined below), or, if not that,
1402 ImplicitConversionRank Rank1 = SCS1.getRank();
1403 ImplicitConversionRank Rank2 = SCS2.getRank();
1404 if (Rank1 < Rank2)
1405 return ImplicitConversionSequence::Better;
1406 else if (Rank2 < Rank1)
1407 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001408
Douglas Gregor57373262008-10-22 14:17:15 +00001409 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1410 // are indistinguishable unless one of the following rules
1411 // applies:
1412
1413 // A conversion that is not a conversion of a pointer, or
1414 // pointer to member, to bool is better than another conversion
1415 // that is such a conversion.
1416 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1417 return SCS2.isPointerConversionToBool()
1418 ? ImplicitConversionSequence::Better
1419 : ImplicitConversionSequence::Worse;
1420
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001421 // C++ [over.ics.rank]p4b2:
1422 //
1423 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001424 // conversion of B* to A* is better than conversion of B* to
1425 // void*, and conversion of A* to void* is better than conversion
1426 // of B* to void*.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001427 bool SCS1ConvertsToVoid
1428 = SCS1.isPointerConversionToVoidPointer(Context);
1429 bool SCS2ConvertsToVoid
1430 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001431 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1432 // Exactly one of the conversion sequences is a conversion to
1433 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001434 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1435 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001436 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1437 // Neither conversion sequence converts to a void pointer; compare
1438 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001439 if (ImplicitConversionSequence::CompareKind DerivedCK
1440 = CompareDerivedToBaseConversions(SCS1, SCS2))
1441 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001442 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1443 // Both conversion sequences are conversions to void
1444 // pointers. Compare the source types to determine if there's an
1445 // inheritance relationship in their sources.
1446 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1447 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1448
1449 // Adjust the types we're converting from via the array-to-pointer
1450 // conversion, if we need to.
1451 if (SCS1.First == ICK_Array_To_Pointer)
1452 FromType1 = Context.getArrayDecayedType(FromType1);
1453 if (SCS2.First == ICK_Array_To_Pointer)
1454 FromType2 = Context.getArrayDecayedType(FromType2);
1455
1456 QualType FromPointee1
1457 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1458 QualType FromPointee2
1459 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1460
1461 if (IsDerivedFrom(FromPointee2, FromPointee1))
1462 return ImplicitConversionSequence::Better;
1463 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1464 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001465
1466 // Objective-C++: If one interface is more specific than the
1467 // other, it is the better one.
1468 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1469 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1470 if (FromIface1 && FromIface1) {
1471 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1472 return ImplicitConversionSequence::Better;
1473 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1474 return ImplicitConversionSequence::Worse;
1475 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001476 }
Douglas Gregor57373262008-10-22 14:17:15 +00001477
1478 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1479 // bullet 3).
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001480 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001481 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001482 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001483
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001484 // C++ [over.ics.rank]p3b4:
1485 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1486 // which the references refer are the same type except for
1487 // top-level cv-qualifiers, and the type to which the reference
1488 // initialized by S2 refers is more cv-qualified than the type
1489 // to which the reference initialized by S1 refers.
1490 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1491 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1492 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1493 T1 = Context.getCanonicalType(T1);
1494 T2 = Context.getCanonicalType(T2);
1495 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1496 if (T2.isMoreQualifiedThan(T1))
1497 return ImplicitConversionSequence::Better;
1498 else if (T1.isMoreQualifiedThan(T2))
1499 return ImplicitConversionSequence::Worse;
1500 }
1501 }
Douglas Gregor57373262008-10-22 14:17:15 +00001502
1503 return ImplicitConversionSequence::Indistinguishable;
1504}
1505
1506/// CompareQualificationConversions - Compares two standard conversion
1507/// sequences to determine whether they can be ranked based on their
1508/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1509ImplicitConversionSequence::CompareKind
1510Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1511 const StandardConversionSequence& SCS2)
1512{
Douglas Gregorba7e2102008-10-22 15:04:37 +00001513 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001514 // -- S1 and S2 differ only in their qualification conversion and
1515 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1516 // cv-qualification signature of type T1 is a proper subset of
1517 // the cv-qualification signature of type T2, and S1 is not the
1518 // deprecated string literal array-to-pointer conversion (4.2).
1519 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1520 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1521 return ImplicitConversionSequence::Indistinguishable;
1522
1523 // FIXME: the example in the standard doesn't use a qualification
1524 // conversion (!)
1525 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1526 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1527 T1 = Context.getCanonicalType(T1);
1528 T2 = Context.getCanonicalType(T2);
1529
1530 // If the types are the same, we won't learn anything by unwrapped
1531 // them.
1532 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1533 return ImplicitConversionSequence::Indistinguishable;
1534
1535 ImplicitConversionSequence::CompareKind Result
1536 = ImplicitConversionSequence::Indistinguishable;
1537 while (UnwrapSimilarPointerTypes(T1, T2)) {
1538 // Within each iteration of the loop, we check the qualifiers to
1539 // determine if this still looks like a qualification
1540 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001541 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001542 // until there are no more pointers or pointers-to-members left
1543 // to unwrap. This essentially mimics what
1544 // IsQualificationConversion does, but here we're checking for a
1545 // strict subset of qualifiers.
1546 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1547 // The qualifiers are the same, so this doesn't tell us anything
1548 // about how the sequences rank.
1549 ;
1550 else if (T2.isMoreQualifiedThan(T1)) {
1551 // T1 has fewer qualifiers, so it could be the better sequence.
1552 if (Result == ImplicitConversionSequence::Worse)
1553 // Neither has qualifiers that are a subset of the other's
1554 // qualifiers.
1555 return ImplicitConversionSequence::Indistinguishable;
1556
1557 Result = ImplicitConversionSequence::Better;
1558 } else if (T1.isMoreQualifiedThan(T2)) {
1559 // T2 has fewer qualifiers, so it could be the better sequence.
1560 if (Result == ImplicitConversionSequence::Better)
1561 // Neither has qualifiers that are a subset of the other's
1562 // qualifiers.
1563 return ImplicitConversionSequence::Indistinguishable;
1564
1565 Result = ImplicitConversionSequence::Worse;
1566 } else {
1567 // Qualifiers are disjoint.
1568 return ImplicitConversionSequence::Indistinguishable;
1569 }
1570
1571 // If the types after this point are equivalent, we're done.
1572 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1573 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001574 }
1575
Douglas Gregor57373262008-10-22 14:17:15 +00001576 // Check that the winning standard conversion sequence isn't using
1577 // the deprecated string literal array to pointer conversion.
1578 switch (Result) {
1579 case ImplicitConversionSequence::Better:
1580 if (SCS1.Deprecated)
1581 Result = ImplicitConversionSequence::Indistinguishable;
1582 break;
1583
1584 case ImplicitConversionSequence::Indistinguishable:
1585 break;
1586
1587 case ImplicitConversionSequence::Worse:
1588 if (SCS2.Deprecated)
1589 Result = ImplicitConversionSequence::Indistinguishable;
1590 break;
1591 }
1592
1593 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001594}
1595
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001596/// CompareDerivedToBaseConversions - Compares two standard conversion
1597/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00001598/// various kinds of derived-to-base conversions (C++
1599/// [over.ics.rank]p4b3). As part of these checks, we also look at
1600/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001601ImplicitConversionSequence::CompareKind
1602Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1603 const StandardConversionSequence& SCS2) {
1604 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1605 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1606 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1607 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1608
1609 // Adjust the types we're converting from via the array-to-pointer
1610 // conversion, if we need to.
1611 if (SCS1.First == ICK_Array_To_Pointer)
1612 FromType1 = Context.getArrayDecayedType(FromType1);
1613 if (SCS2.First == ICK_Array_To_Pointer)
1614 FromType2 = Context.getArrayDecayedType(FromType2);
1615
1616 // Canonicalize all of the types.
1617 FromType1 = Context.getCanonicalType(FromType1);
1618 ToType1 = Context.getCanonicalType(ToType1);
1619 FromType2 = Context.getCanonicalType(FromType2);
1620 ToType2 = Context.getCanonicalType(ToType2);
1621
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001622 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001623 //
1624 // If class B is derived directly or indirectly from class A and
1625 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001626 //
1627 // For Objective-C, we let A, B, and C also be Objective-C
1628 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001629
1630 // Compare based on pointer conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001631 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00001632 SCS2.Second == ICK_Pointer_Conversion &&
1633 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1634 FromType1->isPointerType() && FromType2->isPointerType() &&
1635 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001636 QualType FromPointee1
1637 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1638 QualType ToPointee1
1639 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1640 QualType FromPointee2
1641 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1642 QualType ToPointee2
1643 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001644
1645 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1646 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1647 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1648 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1649
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001650 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001651 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1652 if (IsDerivedFrom(ToPointee1, ToPointee2))
1653 return ImplicitConversionSequence::Better;
1654 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1655 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001656
1657 if (ToIface1 && ToIface2) {
1658 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1659 return ImplicitConversionSequence::Better;
1660 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1661 return ImplicitConversionSequence::Worse;
1662 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001663 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001664
1665 // -- conversion of B* to A* is better than conversion of C* to A*,
1666 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1667 if (IsDerivedFrom(FromPointee2, FromPointee1))
1668 return ImplicitConversionSequence::Better;
1669 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1670 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001671
1672 if (FromIface1 && FromIface2) {
1673 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1674 return ImplicitConversionSequence::Better;
1675 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1676 return ImplicitConversionSequence::Worse;
1677 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001678 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001679 }
1680
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001681 // Compare based on reference bindings.
1682 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1683 SCS1.Second == ICK_Derived_To_Base) {
1684 // -- binding of an expression of type C to a reference of type
1685 // B& is better than binding an expression of type C to a
1686 // reference of type A&,
1687 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1688 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1689 if (IsDerivedFrom(ToType1, ToType2))
1690 return ImplicitConversionSequence::Better;
1691 else if (IsDerivedFrom(ToType2, ToType1))
1692 return ImplicitConversionSequence::Worse;
1693 }
1694
Douglas Gregor225c41e2008-11-03 19:09:14 +00001695 // -- binding of an expression of type B to a reference of type
1696 // A& is better than binding an expression of type C to a
1697 // reference of type A&,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001698 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1699 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1700 if (IsDerivedFrom(FromType2, FromType1))
1701 return ImplicitConversionSequence::Better;
1702 else if (IsDerivedFrom(FromType1, FromType2))
1703 return ImplicitConversionSequence::Worse;
1704 }
1705 }
1706
1707
1708 // FIXME: conversion of A::* to B::* is better than conversion of
1709 // A::* to C::*,
1710
1711 // FIXME: conversion of B::* to C::* is better than conversion of
1712 // A::* to C::*, and
1713
Douglas Gregor225c41e2008-11-03 19:09:14 +00001714 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1715 SCS1.Second == ICK_Derived_To_Base) {
1716 // -- conversion of C to B is better than conversion of C to A,
1717 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1718 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1719 if (IsDerivedFrom(ToType1, ToType2))
1720 return ImplicitConversionSequence::Better;
1721 else if (IsDerivedFrom(ToType2, ToType1))
1722 return ImplicitConversionSequence::Worse;
1723 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001724
Douglas Gregor225c41e2008-11-03 19:09:14 +00001725 // -- conversion of B to A is better than conversion of C to A.
1726 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1727 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1728 if (IsDerivedFrom(FromType2, FromType1))
1729 return ImplicitConversionSequence::Better;
1730 else if (IsDerivedFrom(FromType1, FromType2))
1731 return ImplicitConversionSequence::Worse;
1732 }
1733 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001734
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001735 return ImplicitConversionSequence::Indistinguishable;
1736}
1737
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001738/// TryCopyInitialization - Try to copy-initialize a value of type
1739/// ToType from the expression From. Return the implicit conversion
1740/// sequence required to pass this argument, which may be a bad
1741/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00001742/// a parameter of this type). If @p SuppressUserConversions, then we
1743/// do not permit any user-defined conversion sequences.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001744ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +00001745Sema::TryCopyInitialization(Expr *From, QualType ToType,
1746 bool SuppressUserConversions) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001747 if (!getLangOptions().CPlusPlus) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001748 // In C, copy initialization is the same as performing an assignment.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001749 AssignConvertType ConvTy =
1750 CheckSingleAssignmentConstraints(ToType, From);
1751 ImplicitConversionSequence ICS;
1752 if (getLangOptions().NoExtensions? ConvTy != Compatible
1753 : ConvTy == Incompatible)
1754 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1755 else
1756 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1757 return ICS;
1758 } else if (ToType->isReferenceType()) {
1759 ImplicitConversionSequence ICS;
Douglas Gregor225c41e2008-11-03 19:09:14 +00001760 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001761 return ICS;
1762 } else {
Douglas Gregor225c41e2008-11-03 19:09:14 +00001763 return TryImplicitConversion(From, ToType, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001764 }
1765}
1766
1767/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1768/// type ToType. Returns true (and emits a diagnostic) if there was
1769/// an error, returns false if the initialization succeeded.
1770bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1771 const char* Flavor) {
1772 if (!getLangOptions().CPlusPlus) {
1773 // In C, argument passing is the same as performing an assignment.
1774 QualType FromType = From->getType();
1775 AssignConvertType ConvTy =
1776 CheckSingleAssignmentConstraints(ToType, From);
1777
1778 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1779 FromType, From, Flavor);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001780 }
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001781
1782 if (ToType->isReferenceType())
1783 return CheckReferenceInit(From, ToType);
1784
Douglas Gregor45920e82008-12-19 17:40:08 +00001785 if (!PerformImplicitConversion(From, ToType, Flavor))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001786 return false;
1787
1788 return Diag(From->getSourceRange().getBegin(),
1789 diag::err_typecheck_convert_incompatible)
1790 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001791}
1792
Douglas Gregor96176b32008-11-18 23:14:02 +00001793/// TryObjectArgumentInitialization - Try to initialize the object
1794/// parameter of the given member function (@c Method) from the
1795/// expression @p From.
1796ImplicitConversionSequence
1797Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1798 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1799 unsigned MethodQuals = Method->getTypeQualifiers();
1800 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1801
1802 // Set up the conversion sequence as a "bad" conversion, to allow us
1803 // to exit early.
1804 ImplicitConversionSequence ICS;
1805 ICS.Standard.setAsIdentityConversion();
1806 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1807
1808 // We need to have an object of class type.
1809 QualType FromType = From->getType();
1810 if (!FromType->isRecordType())
1811 return ICS;
1812
1813 // The implicit object parmeter is has the type "reference to cv X",
1814 // where X is the class of which the function is a member
1815 // (C++ [over.match.funcs]p4). However, when finding an implicit
1816 // conversion sequence for the argument, we are not allowed to
1817 // create temporaries or perform user-defined conversions
1818 // (C++ [over.match.funcs]p5). We perform a simplified version of
1819 // reference binding here, that allows class rvalues to bind to
1820 // non-constant references.
1821
1822 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1823 // with the implicit object parameter (C++ [over.match.funcs]p5).
1824 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1825 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1826 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1827 return ICS;
1828
1829 // Check that we have either the same type or a derived type. It
1830 // affects the conversion rank.
1831 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1832 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1833 ICS.Standard.Second = ICK_Identity;
1834 else if (IsDerivedFrom(FromType, ClassType))
1835 ICS.Standard.Second = ICK_Derived_To_Base;
1836 else
1837 return ICS;
1838
1839 // Success. Mark this as a reference binding.
1840 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1841 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1842 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1843 ICS.Standard.ReferenceBinding = true;
1844 ICS.Standard.DirectBinding = true;
1845 return ICS;
1846}
1847
1848/// PerformObjectArgumentInitialization - Perform initialization of
1849/// the implicit object parameter for the given Method with the given
1850/// expression.
1851bool
1852Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
1853 QualType ImplicitParamType
1854 = Method->getThisType(Context)->getAsPointerType()->getPointeeType();
1855 ImplicitConversionSequence ICS
1856 = TryObjectArgumentInitialization(From, Method);
1857 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
1858 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001859 diag::err_implicit_object_parameter_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00001860 << ImplicitParamType << From->getType() << From->getSourceRange();
Douglas Gregor96176b32008-11-18 23:14:02 +00001861
1862 if (ICS.Standard.Second == ICK_Derived_To_Base &&
1863 CheckDerivedToBaseConversion(From->getType(), ImplicitParamType,
1864 From->getSourceRange().getBegin(),
1865 From->getSourceRange()))
1866 return true;
1867
1868 ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true);
1869 return false;
1870}
1871
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001872/// TryContextuallyConvertToBool - Attempt to contextually convert the
1873/// expression From to bool (C++0x [conv]p3).
1874ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
1875 return TryImplicitConversion(From, Context.BoolTy, false, true);
1876}
1877
1878/// PerformContextuallyConvertToBool - Perform a contextual conversion
1879/// of the expression From to bool (C++0x [conv]p3).
1880bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
1881 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
1882 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
1883 return false;
1884
1885 return Diag(From->getSourceRange().getBegin(),
1886 diag::err_typecheck_bool_condition)
1887 << From->getType() << From->getSourceRange();
1888}
1889
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001890/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00001891/// candidate functions, using the given function call arguments. If
1892/// @p SuppressUserConversions, then don't allow user-defined
1893/// conversions via constructors or conversion operators.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001894void
1895Sema::AddOverloadCandidate(FunctionDecl *Function,
1896 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00001897 OverloadCandidateSet& CandidateSet,
1898 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001899{
1900 const FunctionTypeProto* Proto
1901 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType());
1902 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001903 assert(!isa<CXXConversionDecl>(Function) &&
1904 "Use AddConversionCandidate for conversion functions");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001905
Douglas Gregor88a35142008-12-22 05:46:06 +00001906 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
1907 // If we get here, it's because we're calling a member function
1908 // that is named without a member access expression (e.g.,
1909 // "this->f") that was either written explicitly or created
1910 // implicitly. This can happen with a qualified call to a member
1911 // function, e.g., X::f(). We use a NULL object as the implied
1912 // object argument (C++ [over.call.func]p3).
1913 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
1914 SuppressUserConversions);
1915 return;
1916 }
1917
1918
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001919 // Add this candidate
1920 CandidateSet.push_back(OverloadCandidate());
1921 OverloadCandidate& Candidate = CandidateSet.back();
1922 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00001923 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001924 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00001925 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001926
1927 unsigned NumArgsInProto = Proto->getNumArgs();
1928
1929 // (C++ 13.3.2p2): A candidate function having fewer than m
1930 // parameters is viable only if it has an ellipsis in its parameter
1931 // list (8.3.5).
1932 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1933 Candidate.Viable = false;
1934 return;
1935 }
1936
1937 // (C++ 13.3.2p2): A candidate function having more than m parameters
1938 // is viable only if the (m+1)st parameter has a default argument
1939 // (8.3.6). For the purposes of overload resolution, the
1940 // parameter list is truncated on the right, so that there are
1941 // exactly m parameters.
1942 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
1943 if (NumArgs < MinRequiredArgs) {
1944 // Not enough arguments.
1945 Candidate.Viable = false;
1946 return;
1947 }
1948
1949 // Determine the implicit conversion sequences for each of the
1950 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001951 Candidate.Conversions.resize(NumArgs);
1952 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1953 if (ArgIdx < NumArgsInProto) {
1954 // (C++ 13.3.2p3): for F to be a viable function, there shall
1955 // exist for each argument an implicit conversion sequence
1956 // (13.3.3.1) that converts that argument to the corresponding
1957 // parameter of F.
1958 QualType ParamType = Proto->getArgType(ArgIdx);
1959 Candidate.Conversions[ArgIdx]
Douglas Gregor225c41e2008-11-03 19:09:14 +00001960 = TryCopyInitialization(Args[ArgIdx], ParamType,
1961 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001962 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00001963 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001964 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001965 break;
1966 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001967 } else {
1968 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1969 // argument for which there is no corresponding parameter is
1970 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1971 Candidate.Conversions[ArgIdx].ConversionKind
1972 = ImplicitConversionSequence::EllipsisConversion;
1973 }
1974 }
1975}
1976
Douglas Gregor96176b32008-11-18 23:14:02 +00001977/// AddMethodCandidate - Adds the given C++ member function to the set
1978/// of candidate functions, using the given function call arguments
1979/// and the object argument (@c Object). For example, in a call
1980/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
1981/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
1982/// allow user-defined conversions via constructors or conversion
1983/// operators.
1984void
1985Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
1986 Expr **Args, unsigned NumArgs,
1987 OverloadCandidateSet& CandidateSet,
1988 bool SuppressUserConversions)
1989{
1990 const FunctionTypeProto* Proto
1991 = dyn_cast<FunctionTypeProto>(Method->getType()->getAsFunctionType());
1992 assert(Proto && "Methods without a prototype cannot be overloaded");
1993 assert(!isa<CXXConversionDecl>(Method) &&
1994 "Use AddConversionCandidate for conversion functions");
1995
1996 // Add this candidate
1997 CandidateSet.push_back(OverloadCandidate());
1998 OverloadCandidate& Candidate = CandidateSet.back();
1999 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002000 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002001 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002002
2003 unsigned NumArgsInProto = Proto->getNumArgs();
2004
2005 // (C++ 13.3.2p2): A candidate function having fewer than m
2006 // parameters is viable only if it has an ellipsis in its parameter
2007 // list (8.3.5).
2008 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2009 Candidate.Viable = false;
2010 return;
2011 }
2012
2013 // (C++ 13.3.2p2): A candidate function having more than m parameters
2014 // is viable only if the (m+1)st parameter has a default argument
2015 // (8.3.6). For the purposes of overload resolution, the
2016 // parameter list is truncated on the right, so that there are
2017 // exactly m parameters.
2018 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2019 if (NumArgs < MinRequiredArgs) {
2020 // Not enough arguments.
2021 Candidate.Viable = false;
2022 return;
2023 }
2024
2025 Candidate.Viable = true;
2026 Candidate.Conversions.resize(NumArgs + 1);
2027
Douglas Gregor88a35142008-12-22 05:46:06 +00002028 if (Method->isStatic() || !Object)
2029 // The implicit object argument is ignored.
2030 Candidate.IgnoreObjectArgument = true;
2031 else {
2032 // Determine the implicit conversion sequence for the object
2033 // parameter.
2034 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2035 if (Candidate.Conversions[0].ConversionKind
2036 == ImplicitConversionSequence::BadConversion) {
2037 Candidate.Viable = false;
2038 return;
2039 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002040 }
2041
2042 // Determine the implicit conversion sequences for each of the
2043 // arguments.
2044 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2045 if (ArgIdx < NumArgsInProto) {
2046 // (C++ 13.3.2p3): for F to be a viable function, there shall
2047 // exist for each argument an implicit conversion sequence
2048 // (13.3.3.1) that converts that argument to the corresponding
2049 // parameter of F.
2050 QualType ParamType = Proto->getArgType(ArgIdx);
2051 Candidate.Conversions[ArgIdx + 1]
2052 = TryCopyInitialization(Args[ArgIdx], ParamType,
2053 SuppressUserConversions);
2054 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2055 == ImplicitConversionSequence::BadConversion) {
2056 Candidate.Viable = false;
2057 break;
2058 }
2059 } else {
2060 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2061 // argument for which there is no corresponding parameter is
2062 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2063 Candidate.Conversions[ArgIdx + 1].ConversionKind
2064 = ImplicitConversionSequence::EllipsisConversion;
2065 }
2066 }
2067}
2068
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002069/// AddConversionCandidate - Add a C++ conversion function as a
2070/// candidate in the candidate set (C++ [over.match.conv],
2071/// C++ [over.match.copy]). From is the expression we're converting from,
2072/// and ToType is the type that we're eventually trying to convert to
2073/// (which may or may not be the same type as the type that the
2074/// conversion function produces).
2075void
2076Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2077 Expr *From, QualType ToType,
2078 OverloadCandidateSet& CandidateSet) {
2079 // Add this candidate
2080 CandidateSet.push_back(OverloadCandidate());
2081 OverloadCandidate& Candidate = CandidateSet.back();
2082 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002083 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002084 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002085 Candidate.FinalConversion.setAsIdentityConversion();
2086 Candidate.FinalConversion.FromTypePtr
2087 = Conversion->getConversionType().getAsOpaquePtr();
2088 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2089
Douglas Gregor96176b32008-11-18 23:14:02 +00002090 // Determine the implicit conversion sequence for the implicit
2091 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002092 Candidate.Viable = true;
2093 Candidate.Conversions.resize(1);
Douglas Gregor96176b32008-11-18 23:14:02 +00002094 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002095
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002096 if (Candidate.Conversions[0].ConversionKind
2097 == ImplicitConversionSequence::BadConversion) {
2098 Candidate.Viable = false;
2099 return;
2100 }
2101
2102 // To determine what the conversion from the result of calling the
2103 // conversion function to the type we're eventually trying to
2104 // convert to (ToType), we need to synthesize a call to the
2105 // conversion function and attempt copy initialization from it. This
2106 // makes sure that we get the right semantics with respect to
2107 // lvalues/rvalues and the type. Fortunately, we can allocate this
2108 // call on the stack and we don't need its arguments to be
2109 // well-formed.
2110 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2111 SourceLocation());
2112 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002113 &ConversionRef, false);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002114 CallExpr Call(&ConversionFn, 0, 0,
2115 Conversion->getConversionType().getNonReferenceType(),
2116 SourceLocation());
2117 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2118 switch (ICS.ConversionKind) {
2119 case ImplicitConversionSequence::StandardConversion:
2120 Candidate.FinalConversion = ICS.Standard;
2121 break;
2122
2123 case ImplicitConversionSequence::BadConversion:
2124 Candidate.Viable = false;
2125 break;
2126
2127 default:
2128 assert(false &&
2129 "Can only end up with a standard conversion sequence or failure");
2130 }
2131}
2132
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002133/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2134/// converts the given @c Object to a function pointer via the
2135/// conversion function @c Conversion, and then attempts to call it
2136/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2137/// the type of function that we'll eventually be calling.
2138void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
2139 const FunctionTypeProto *Proto,
2140 Expr *Object, Expr **Args, unsigned NumArgs,
2141 OverloadCandidateSet& CandidateSet) {
2142 CandidateSet.push_back(OverloadCandidate());
2143 OverloadCandidate& Candidate = CandidateSet.back();
2144 Candidate.Function = 0;
2145 Candidate.Surrogate = Conversion;
2146 Candidate.Viable = true;
2147 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002148 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002149 Candidate.Conversions.resize(NumArgs + 1);
2150
2151 // Determine the implicit conversion sequence for the implicit
2152 // object parameter.
2153 ImplicitConversionSequence ObjectInit
2154 = TryObjectArgumentInitialization(Object, Conversion);
2155 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2156 Candidate.Viable = false;
2157 return;
2158 }
2159
2160 // The first conversion is actually a user-defined conversion whose
2161 // first conversion is ObjectInit's standard conversion (which is
2162 // effectively a reference binding). Record it as such.
2163 Candidate.Conversions[0].ConversionKind
2164 = ImplicitConversionSequence::UserDefinedConversion;
2165 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2166 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2167 Candidate.Conversions[0].UserDefined.After
2168 = Candidate.Conversions[0].UserDefined.Before;
2169 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2170
2171 // Find the
2172 unsigned NumArgsInProto = Proto->getNumArgs();
2173
2174 // (C++ 13.3.2p2): A candidate function having fewer than m
2175 // parameters is viable only if it has an ellipsis in its parameter
2176 // list (8.3.5).
2177 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2178 Candidate.Viable = false;
2179 return;
2180 }
2181
2182 // Function types don't have any default arguments, so just check if
2183 // we have enough arguments.
2184 if (NumArgs < NumArgsInProto) {
2185 // Not enough arguments.
2186 Candidate.Viable = false;
2187 return;
2188 }
2189
2190 // Determine the implicit conversion sequences for each of the
2191 // arguments.
2192 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2193 if (ArgIdx < NumArgsInProto) {
2194 // (C++ 13.3.2p3): for F to be a viable function, there shall
2195 // exist for each argument an implicit conversion sequence
2196 // (13.3.3.1) that converts that argument to the corresponding
2197 // parameter of F.
2198 QualType ParamType = Proto->getArgType(ArgIdx);
2199 Candidate.Conversions[ArgIdx + 1]
2200 = TryCopyInitialization(Args[ArgIdx], ParamType,
2201 /*SuppressUserConversions=*/false);
2202 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2203 == ImplicitConversionSequence::BadConversion) {
2204 Candidate.Viable = false;
2205 break;
2206 }
2207 } else {
2208 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2209 // argument for which there is no corresponding parameter is
2210 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2211 Candidate.Conversions[ArgIdx + 1].ConversionKind
2212 = ImplicitConversionSequence::EllipsisConversion;
2213 }
2214 }
2215}
2216
Douglas Gregor447b69e2008-11-19 03:25:36 +00002217/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2218/// an acceptable non-member overloaded operator for a call whose
2219/// arguments have types T1 (and, if non-empty, T2). This routine
2220/// implements the check in C++ [over.match.oper]p3b2 concerning
2221/// enumeration types.
2222static bool
2223IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2224 QualType T1, QualType T2,
2225 ASTContext &Context) {
2226 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2227 return true;
2228
2229 const FunctionTypeProto *Proto = Fn->getType()->getAsFunctionTypeProto();
2230 if (Proto->getNumArgs() < 1)
2231 return false;
2232
2233 if (T1->isEnumeralType()) {
2234 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
2235 if (Context.getCanonicalType(T1).getUnqualifiedType()
2236 == Context.getCanonicalType(ArgType).getUnqualifiedType())
2237 return true;
2238 }
2239
2240 if (Proto->getNumArgs() < 2)
2241 return false;
2242
2243 if (!T2.isNull() && T2->isEnumeralType()) {
2244 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
2245 if (Context.getCanonicalType(T2).getUnqualifiedType()
2246 == Context.getCanonicalType(ArgType).getUnqualifiedType())
2247 return true;
2248 }
2249
2250 return false;
2251}
2252
Douglas Gregor96176b32008-11-18 23:14:02 +00002253/// AddOperatorCandidates - Add the overloaded operator candidates for
2254/// the operator Op that was used in an operator expression such as "x
2255/// Op y". S is the scope in which the expression occurred (used for
2256/// name lookup of the operator), Args/NumArgs provides the operator
2257/// arguments, and CandidateSet will store the added overload
2258/// candidates. (C++ [over.match.oper]).
2259void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
2260 Expr **Args, unsigned NumArgs,
2261 OverloadCandidateSet& CandidateSet) {
2262 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2263
2264 // C++ [over.match.oper]p3:
2265 // For a unary operator @ with an operand of a type whose
2266 // cv-unqualified version is T1, and for a binary operator @ with
2267 // a left operand of a type whose cv-unqualified version is T1 and
2268 // a right operand of a type whose cv-unqualified version is T2,
2269 // three sets of candidate functions, designated member
2270 // candidates, non-member candidates and built-in candidates, are
2271 // constructed as follows:
2272 QualType T1 = Args[0]->getType();
2273 QualType T2;
2274 if (NumArgs > 1)
2275 T2 = Args[1]->getType();
2276
2277 // -- If T1 is a class type, the set of member candidates is the
2278 // result of the qualified lookup of T1::operator@
2279 // (13.3.1.1.1); otherwise, the set of member candidates is
2280 // empty.
2281 if (const RecordType *T1Rec = T1->getAsRecordType()) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002282 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00002283 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002284 Oper != OperEnd; ++Oper)
2285 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2286 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor96176b32008-11-18 23:14:02 +00002287 /*SuppressUserConversions=*/false);
Douglas Gregor96176b32008-11-18 23:14:02 +00002288 }
2289
2290 // -- The set of non-member candidates is the result of the
2291 // unqualified lookup of operator@ in the context of the
2292 // expression according to the usual rules for name lookup in
2293 // unqualified function calls (3.4.2) except that all member
2294 // functions are ignored. However, if no operand has a class
2295 // type, only those non-member functions in the lookup set
2296 // that have a first parameter of type T1 or “reference to
2297 // (possibly cv-qualified) T1”, when T1 is an enumeration
2298 // type, or (if there is a right operand) a second parameter
2299 // of type T2 or “reference to (possibly cv-qualified) T2”,
2300 // when T2 is an enumeration type, are candidate functions.
2301 {
Douglas Gregor4c921ae2009-01-30 01:04:22 +00002302 IdentifierResolver::iterator I = IdResolver.begin(OpName),
2303 IEnd = IdResolver.end();
Douglas Gregor6ed40e32008-12-23 21:05:05 +00002304 for (; I != IEnd; ++I) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002305 // We don't need to check the identifier namespace, because
2306 // operator names can only be ordinary identifiers.
2307
2308 // Ignore member functions.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002309 if ((*I)->getDeclContext()->isRecord())
2310 continue;
Douglas Gregor96176b32008-11-18 23:14:02 +00002311
2312 // We found something with this name. We're done.
Douglas Gregor96176b32008-11-18 23:14:02 +00002313 break;
2314 }
2315
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002316 if (I != IEnd) {
2317 Decl *FirstDecl = *I;
Douglas Gregor6ed40e32008-12-23 21:05:05 +00002318 for (; I != IEnd; ++I) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002319 if (FirstDecl->getDeclContext() != (*I)->getDeclContext())
Douglas Gregor6ed40e32008-12-23 21:05:05 +00002320 break;
2321
2322 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I))
2323 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
2324 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2325 /*SuppressUserConversions=*/false);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002326 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002327 }
2328 }
2329
2330 // Add builtin overload candidates (C++ [over.built]).
Douglas Gregor74253732008-11-19 15:42:04 +00002331 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
Douglas Gregor96176b32008-11-18 23:14:02 +00002332}
2333
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002334/// AddBuiltinCandidate - Add a candidate for a built-in
2335/// operator. ResultTy and ParamTys are the result and parameter types
2336/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002337/// arguments being passed to the candidate. IsAssignmentOperator
2338/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002339/// operator. NumContextualBoolArguments is the number of arguments
2340/// (at the beginning of the argument list) that will be contextually
2341/// converted to bool.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002342void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2343 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002344 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002345 bool IsAssignmentOperator,
2346 unsigned NumContextualBoolArguments) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002347 // Add this candidate
2348 CandidateSet.push_back(OverloadCandidate());
2349 OverloadCandidate& Candidate = CandidateSet.back();
2350 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00002351 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002352 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002353 Candidate.BuiltinTypes.ResultTy = ResultTy;
2354 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2355 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2356
2357 // Determine the implicit conversion sequences for each of the
2358 // arguments.
2359 Candidate.Viable = true;
2360 Candidate.Conversions.resize(NumArgs);
2361 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002362 // C++ [over.match.oper]p4:
2363 // For the built-in assignment operators, conversions of the
2364 // left operand are restricted as follows:
2365 // -- no temporaries are introduced to hold the left operand, and
2366 // -- no user-defined conversions are applied to the left
2367 // operand to achieve a type match with the left-most
2368 // parameter of a built-in candidate.
2369 //
2370 // We block these conversions by turning off user-defined
2371 // conversions, since that is the only way that initialization of
2372 // a reference to a non-class type can occur from something that
2373 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002374 if (ArgIdx < NumContextualBoolArguments) {
2375 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2376 "Contextual conversion to bool requires bool type");
2377 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2378 } else {
2379 Candidate.Conversions[ArgIdx]
2380 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2381 ArgIdx == 0 && IsAssignmentOperator);
2382 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002383 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002384 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002385 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002386 break;
2387 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002388 }
2389}
2390
2391/// BuiltinCandidateTypeSet - A set of types that will be used for the
2392/// candidate operator functions for built-in operators (C++
2393/// [over.built]). The types are separated into pointer types and
2394/// enumeration types.
2395class BuiltinCandidateTypeSet {
2396 /// TypeSet - A set of types.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002397 typedef llvm::SmallPtrSet<void*, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002398
2399 /// PointerTypes - The set of pointer types that will be used in the
2400 /// built-in candidates.
2401 TypeSet PointerTypes;
2402
2403 /// EnumerationTypes - The set of enumeration types that will be
2404 /// used in the built-in candidates.
2405 TypeSet EnumerationTypes;
2406
2407 /// Context - The AST context in which we will build the type sets.
2408 ASTContext &Context;
2409
2410 bool AddWithMoreQualifiedTypeVariants(QualType Ty);
2411
2412public:
2413 /// iterator - Iterates through the types that are part of the set.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002414 class iterator {
2415 TypeSet::iterator Base;
2416
2417 public:
2418 typedef QualType value_type;
2419 typedef QualType reference;
2420 typedef QualType pointer;
2421 typedef std::ptrdiff_t difference_type;
2422 typedef std::input_iterator_tag iterator_category;
2423
2424 iterator(TypeSet::iterator B) : Base(B) { }
2425
2426 iterator& operator++() {
2427 ++Base;
2428 return *this;
2429 }
2430
2431 iterator operator++(int) {
2432 iterator tmp(*this);
2433 ++(*this);
2434 return tmp;
2435 }
2436
2437 reference operator*() const {
2438 return QualType::getFromOpaquePtr(*Base);
2439 }
2440
2441 pointer operator->() const {
2442 return **this;
2443 }
2444
2445 friend bool operator==(iterator LHS, iterator RHS) {
2446 return LHS.Base == RHS.Base;
2447 }
2448
2449 friend bool operator!=(iterator LHS, iterator RHS) {
2450 return LHS.Base != RHS.Base;
2451 }
2452 };
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002453
2454 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2455
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002456 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2457 bool AllowExplicitConversions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002458
2459 /// pointer_begin - First pointer type found;
2460 iterator pointer_begin() { return PointerTypes.begin(); }
2461
2462 /// pointer_end - Last pointer type found;
2463 iterator pointer_end() { return PointerTypes.end(); }
2464
2465 /// enumeration_begin - First enumeration type found;
2466 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2467
2468 /// enumeration_end - Last enumeration type found;
2469 iterator enumeration_end() { return EnumerationTypes.end(); }
2470};
2471
2472/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2473/// the set of pointer types along with any more-qualified variants of
2474/// that type. For example, if @p Ty is "int const *", this routine
2475/// will add "int const *", "int const volatile *", "int const
2476/// restrict *", and "int const volatile restrict *" to the set of
2477/// pointer types. Returns true if the add of @p Ty itself succeeded,
2478/// false otherwise.
2479bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) {
2480 // Insert this type.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002481 if (!PointerTypes.insert(Ty.getAsOpaquePtr()))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002482 return false;
2483
2484 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2485 QualType PointeeTy = PointerTy->getPointeeType();
2486 // FIXME: Optimize this so that we don't keep trying to add the same types.
2487
2488 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
2489 // with all pointer conversions that don't cast away constness?
2490 if (!PointeeTy.isConstQualified())
2491 AddWithMoreQualifiedTypeVariants
2492 (Context.getPointerType(PointeeTy.withConst()));
2493 if (!PointeeTy.isVolatileQualified())
2494 AddWithMoreQualifiedTypeVariants
2495 (Context.getPointerType(PointeeTy.withVolatile()));
2496 if (!PointeeTy.isRestrictQualified())
2497 AddWithMoreQualifiedTypeVariants
2498 (Context.getPointerType(PointeeTy.withRestrict()));
2499 }
2500
2501 return true;
2502}
2503
2504/// AddTypesConvertedFrom - Add each of the types to which the type @p
2505/// Ty can be implicit converted to the given set of @p Types. We're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002506/// primarily interested in pointer types and enumeration types.
2507/// AllowUserConversions is true if we should look at the conversion
2508/// functions of a class type, and AllowExplicitConversions if we
2509/// should also include the explicit conversion functions of a class
2510/// type.
2511void
2512BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2513 bool AllowUserConversions,
2514 bool AllowExplicitConversions) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002515 // Only deal with canonical types.
2516 Ty = Context.getCanonicalType(Ty);
2517
2518 // Look through reference types; they aren't part of the type of an
2519 // expression for the purposes of conversions.
2520 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2521 Ty = RefTy->getPointeeType();
2522
2523 // We don't care about qualifiers on the type.
2524 Ty = Ty.getUnqualifiedType();
2525
2526 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2527 QualType PointeeTy = PointerTy->getPointeeType();
2528
2529 // Insert our type, and its more-qualified variants, into the set
2530 // of types.
2531 if (!AddWithMoreQualifiedTypeVariants(Ty))
2532 return;
2533
2534 // Add 'cv void*' to our set of types.
2535 if (!Ty->isVoidType()) {
2536 QualType QualVoid
2537 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2538 AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2539 }
2540
2541 // If this is a pointer to a class type, add pointers to its bases
2542 // (with the same level of cv-qualification as the original
2543 // derived class, of course).
2544 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2545 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2546 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2547 Base != ClassDecl->bases_end(); ++Base) {
2548 QualType BaseTy = Context.getCanonicalType(Base->getType());
2549 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2550
2551 // Add the pointer type, recursively, so that we get all of
2552 // the indirect base classes, too.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002553 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002554 }
2555 }
2556 } else if (Ty->isEnumeralType()) {
Douglas Gregorbf3af052008-11-13 20:12:29 +00002557 EnumerationTypes.insert(Ty.getAsOpaquePtr());
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002558 } else if (AllowUserConversions) {
2559 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2560 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2561 // FIXME: Visit conversion functions in the base classes, too.
2562 OverloadedFunctionDecl *Conversions
2563 = ClassDecl->getConversionFunctions();
2564 for (OverloadedFunctionDecl::function_iterator Func
2565 = Conversions->function_begin();
2566 Func != Conversions->function_end(); ++Func) {
2567 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002568 if (AllowExplicitConversions || !Conv->isExplicit())
2569 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002570 }
2571 }
2572 }
2573}
2574
Douglas Gregor74253732008-11-19 15:42:04 +00002575/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2576/// operator overloads to the candidate set (C++ [over.built]), based
2577/// on the operator @p Op and the arguments given. For example, if the
2578/// operator is a binary '+', this routine might add "int
2579/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002580void
Douglas Gregor74253732008-11-19 15:42:04 +00002581Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2582 Expr **Args, unsigned NumArgs,
2583 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002584 // The set of "promoted arithmetic types", which are the arithmetic
2585 // types are that preserved by promotion (C++ [over.built]p2). Note
2586 // that the first few of these types are the promoted integral
2587 // types; these types need to be first.
2588 // FIXME: What about complex?
2589 const unsigned FirstIntegralType = 0;
2590 const unsigned LastIntegralType = 13;
2591 const unsigned FirstPromotedIntegralType = 7,
2592 LastPromotedIntegralType = 13;
2593 const unsigned FirstPromotedArithmeticType = 7,
2594 LastPromotedArithmeticType = 16;
2595 const unsigned NumArithmeticTypes = 16;
2596 QualType ArithmeticTypes[NumArithmeticTypes] = {
2597 Context.BoolTy, Context.CharTy, Context.WCharTy,
2598 Context.SignedCharTy, Context.ShortTy,
2599 Context.UnsignedCharTy, Context.UnsignedShortTy,
2600 Context.IntTy, Context.LongTy, Context.LongLongTy,
2601 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2602 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2603 };
2604
2605 // Find all of the types that the arguments can convert to, but only
2606 // if the operator we're looking at has built-in operator candidates
2607 // that make use of these types.
2608 BuiltinCandidateTypeSet CandidateTypes(Context);
2609 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2610 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00002611 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002612 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00002613 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
2614 (Op == OO_Star && NumArgs == 1)) {
2615 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002616 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2617 true,
2618 (Op == OO_Exclaim ||
2619 Op == OO_AmpAmp ||
2620 Op == OO_PipePipe));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002621 }
2622
2623 bool isComparison = false;
2624 switch (Op) {
2625 case OO_None:
2626 case NUM_OVERLOADED_OPERATORS:
2627 assert(false && "Expected an overloaded operator");
2628 break;
2629
Douglas Gregor74253732008-11-19 15:42:04 +00002630 case OO_Star: // '*' is either unary or binary
2631 if (NumArgs == 1)
2632 goto UnaryStar;
2633 else
2634 goto BinaryStar;
2635 break;
2636
2637 case OO_Plus: // '+' is either unary or binary
2638 if (NumArgs == 1)
2639 goto UnaryPlus;
2640 else
2641 goto BinaryPlus;
2642 break;
2643
2644 case OO_Minus: // '-' is either unary or binary
2645 if (NumArgs == 1)
2646 goto UnaryMinus;
2647 else
2648 goto BinaryMinus;
2649 break;
2650
2651 case OO_Amp: // '&' is either unary or binary
2652 if (NumArgs == 1)
2653 goto UnaryAmp;
2654 else
2655 goto BinaryAmp;
2656
2657 case OO_PlusPlus:
2658 case OO_MinusMinus:
2659 // C++ [over.built]p3:
2660 //
2661 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2662 // is either volatile or empty, there exist candidate operator
2663 // functions of the form
2664 //
2665 // VQ T& operator++(VQ T&);
2666 // T operator++(VQ T&, int);
2667 //
2668 // C++ [over.built]p4:
2669 //
2670 // For every pair (T, VQ), where T is an arithmetic type other
2671 // than bool, and VQ is either volatile or empty, there exist
2672 // candidate operator functions of the form
2673 //
2674 // VQ T& operator--(VQ T&);
2675 // T operator--(VQ T&, int);
2676 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2677 Arith < NumArithmeticTypes; ++Arith) {
2678 QualType ArithTy = ArithmeticTypes[Arith];
2679 QualType ParamTypes[2]
2680 = { Context.getReferenceType(ArithTy), Context.IntTy };
2681
2682 // Non-volatile version.
2683 if (NumArgs == 1)
2684 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2685 else
2686 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2687
2688 // Volatile version
2689 ParamTypes[0] = Context.getReferenceType(ArithTy.withVolatile());
2690 if (NumArgs == 1)
2691 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2692 else
2693 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2694 }
2695
2696 // C++ [over.built]p5:
2697 //
2698 // For every pair (T, VQ), where T is a cv-qualified or
2699 // cv-unqualified object type, and VQ is either volatile or
2700 // empty, there exist candidate operator functions of the form
2701 //
2702 // T*VQ& operator++(T*VQ&);
2703 // T*VQ& operator--(T*VQ&);
2704 // T* operator++(T*VQ&, int);
2705 // T* operator--(T*VQ&, int);
2706 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2707 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2708 // Skip pointer types that aren't pointers to object types.
Douglas Gregorcb7de522008-11-26 23:31:11 +00002709 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00002710 continue;
2711
2712 QualType ParamTypes[2] = {
2713 Context.getReferenceType(*Ptr), Context.IntTy
2714 };
2715
2716 // Without volatile
2717 if (NumArgs == 1)
2718 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2719 else
2720 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2721
2722 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2723 // With volatile
2724 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2725 if (NumArgs == 1)
2726 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2727 else
2728 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2729 }
2730 }
2731 break;
2732
2733 UnaryStar:
2734 // C++ [over.built]p6:
2735 // For every cv-qualified or cv-unqualified object type T, there
2736 // exist candidate operator functions of the form
2737 //
2738 // T& operator*(T*);
2739 //
2740 // C++ [over.built]p7:
2741 // For every function type T, there exist candidate operator
2742 // functions of the form
2743 // T& operator*(T*);
2744 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2745 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2746 QualType ParamTy = *Ptr;
2747 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
2748 AddBuiltinCandidate(Context.getReferenceType(PointeeTy),
2749 &ParamTy, Args, 1, CandidateSet);
2750 }
2751 break;
2752
2753 UnaryPlus:
2754 // C++ [over.built]p8:
2755 // For every type T, there exist candidate operator functions of
2756 // the form
2757 //
2758 // T* operator+(T*);
2759 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2760 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2761 QualType ParamTy = *Ptr;
2762 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2763 }
2764
2765 // Fall through
2766
2767 UnaryMinus:
2768 // C++ [over.built]p9:
2769 // For every promoted arithmetic type T, there exist candidate
2770 // operator functions of the form
2771 //
2772 // T operator+(T);
2773 // T operator-(T);
2774 for (unsigned Arith = FirstPromotedArithmeticType;
2775 Arith < LastPromotedArithmeticType; ++Arith) {
2776 QualType ArithTy = ArithmeticTypes[Arith];
2777 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2778 }
2779 break;
2780
2781 case OO_Tilde:
2782 // C++ [over.built]p10:
2783 // For every promoted integral type T, there exist candidate
2784 // operator functions of the form
2785 //
2786 // T operator~(T);
2787 for (unsigned Int = FirstPromotedIntegralType;
2788 Int < LastPromotedIntegralType; ++Int) {
2789 QualType IntTy = ArithmeticTypes[Int];
2790 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2791 }
2792 break;
2793
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002794 case OO_New:
2795 case OO_Delete:
2796 case OO_Array_New:
2797 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002798 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00002799 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002800 break;
2801
2802 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00002803 UnaryAmp:
2804 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002805 // C++ [over.match.oper]p3:
2806 // -- For the operator ',', the unary operator '&', or the
2807 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002808 break;
2809
2810 case OO_Less:
2811 case OO_Greater:
2812 case OO_LessEqual:
2813 case OO_GreaterEqual:
2814 case OO_EqualEqual:
2815 case OO_ExclaimEqual:
2816 // C++ [over.built]p15:
2817 //
2818 // For every pointer or enumeration type T, there exist
2819 // candidate operator functions of the form
2820 //
2821 // bool operator<(T, T);
2822 // bool operator>(T, T);
2823 // bool operator<=(T, T);
2824 // bool operator>=(T, T);
2825 // bool operator==(T, T);
2826 // bool operator!=(T, T);
2827 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2828 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2829 QualType ParamTypes[2] = { *Ptr, *Ptr };
2830 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2831 }
2832 for (BuiltinCandidateTypeSet::iterator Enum
2833 = CandidateTypes.enumeration_begin();
2834 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2835 QualType ParamTypes[2] = { *Enum, *Enum };
2836 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2837 }
2838
2839 // Fall through.
2840 isComparison = true;
2841
Douglas Gregor74253732008-11-19 15:42:04 +00002842 BinaryPlus:
2843 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002844 if (!isComparison) {
2845 // We didn't fall through, so we must have OO_Plus or OO_Minus.
2846
2847 // C++ [over.built]p13:
2848 //
2849 // For every cv-qualified or cv-unqualified object type T
2850 // there exist candidate operator functions of the form
2851 //
2852 // T* operator+(T*, ptrdiff_t);
2853 // T& operator[](T*, ptrdiff_t); [BELOW]
2854 // T* operator-(T*, ptrdiff_t);
2855 // T* operator+(ptrdiff_t, T*);
2856 // T& operator[](ptrdiff_t, T*); [BELOW]
2857 //
2858 // C++ [over.built]p14:
2859 //
2860 // For every T, where T is a pointer to object type, there
2861 // exist candidate operator functions of the form
2862 //
2863 // ptrdiff_t operator-(T, T);
2864 for (BuiltinCandidateTypeSet::iterator Ptr
2865 = CandidateTypes.pointer_begin();
2866 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2867 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2868
2869 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
2870 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2871
2872 if (Op == OO_Plus) {
2873 // T* operator+(ptrdiff_t, T*);
2874 ParamTypes[0] = ParamTypes[1];
2875 ParamTypes[1] = *Ptr;
2876 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2877 } else {
2878 // ptrdiff_t operator-(T, T);
2879 ParamTypes[1] = *Ptr;
2880 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
2881 Args, 2, CandidateSet);
2882 }
2883 }
2884 }
2885 // Fall through
2886
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002887 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00002888 BinaryStar:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002889 // C++ [over.built]p12:
2890 //
2891 // For every pair of promoted arithmetic types L and R, there
2892 // exist candidate operator functions of the form
2893 //
2894 // LR operator*(L, R);
2895 // LR operator/(L, R);
2896 // LR operator+(L, R);
2897 // LR operator-(L, R);
2898 // bool operator<(L, R);
2899 // bool operator>(L, R);
2900 // bool operator<=(L, R);
2901 // bool operator>=(L, R);
2902 // bool operator==(L, R);
2903 // bool operator!=(L, R);
2904 //
2905 // where LR is the result of the usual arithmetic conversions
2906 // between types L and R.
2907 for (unsigned Left = FirstPromotedArithmeticType;
2908 Left < LastPromotedArithmeticType; ++Left) {
2909 for (unsigned Right = FirstPromotedArithmeticType;
2910 Right < LastPromotedArithmeticType; ++Right) {
2911 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2912 QualType Result
2913 = isComparison? Context.BoolTy
2914 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2915 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2916 }
2917 }
2918 break;
2919
2920 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00002921 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002922 case OO_Caret:
2923 case OO_Pipe:
2924 case OO_LessLess:
2925 case OO_GreaterGreater:
2926 // C++ [over.built]p17:
2927 //
2928 // For every pair of promoted integral types L and R, there
2929 // exist candidate operator functions of the form
2930 //
2931 // LR operator%(L, R);
2932 // LR operator&(L, R);
2933 // LR operator^(L, R);
2934 // LR operator|(L, R);
2935 // L operator<<(L, R);
2936 // L operator>>(L, R);
2937 //
2938 // where LR is the result of the usual arithmetic conversions
2939 // between types L and R.
2940 for (unsigned Left = FirstPromotedIntegralType;
2941 Left < LastPromotedIntegralType; ++Left) {
2942 for (unsigned Right = FirstPromotedIntegralType;
2943 Right < LastPromotedIntegralType; ++Right) {
2944 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2945 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
2946 ? LandR[0]
2947 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2948 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2949 }
2950 }
2951 break;
2952
2953 case OO_Equal:
2954 // C++ [over.built]p20:
2955 //
2956 // For every pair (T, VQ), where T is an enumeration or
2957 // (FIXME:) pointer to member type and VQ is either volatile or
2958 // empty, there exist candidate operator functions of the form
2959 //
2960 // VQ T& operator=(VQ T&, T);
2961 for (BuiltinCandidateTypeSet::iterator Enum
2962 = CandidateTypes.enumeration_begin();
2963 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2964 QualType ParamTypes[2];
2965
2966 // T& operator=(T&, T)
2967 ParamTypes[0] = Context.getReferenceType(*Enum);
2968 ParamTypes[1] = *Enum;
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002969 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002970 /*IsAssignmentOperator=*/false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002971
Douglas Gregor74253732008-11-19 15:42:04 +00002972 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
2973 // volatile T& operator=(volatile T&, T)
2974 ParamTypes[0] = Context.getReferenceType((*Enum).withVolatile());
2975 ParamTypes[1] = *Enum;
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002976 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002977 /*IsAssignmentOperator=*/false);
Douglas Gregor74253732008-11-19 15:42:04 +00002978 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002979 }
2980 // Fall through.
2981
2982 case OO_PlusEqual:
2983 case OO_MinusEqual:
2984 // C++ [over.built]p19:
2985 //
2986 // For every pair (T, VQ), where T is any type and VQ is either
2987 // volatile or empty, there exist candidate operator functions
2988 // of the form
2989 //
2990 // T*VQ& operator=(T*VQ&, T*);
2991 //
2992 // C++ [over.built]p21:
2993 //
2994 // For every pair (T, VQ), where T is a cv-qualified or
2995 // cv-unqualified object type and VQ is either volatile or
2996 // empty, there exist candidate operator functions of the form
2997 //
2998 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
2999 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3000 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3001 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3002 QualType ParamTypes[2];
3003 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3004
3005 // non-volatile version
3006 ParamTypes[0] = Context.getReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003007 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3008 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003009
Douglas Gregor74253732008-11-19 15:42:04 +00003010 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3011 // volatile version
3012 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003013 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3014 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00003015 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003016 }
3017 // Fall through.
3018
3019 case OO_StarEqual:
3020 case OO_SlashEqual:
3021 // C++ [over.built]p18:
3022 //
3023 // For every triple (L, VQ, R), where L is an arithmetic type,
3024 // VQ is either volatile or empty, and R is a promoted
3025 // arithmetic type, there exist candidate operator functions of
3026 // the form
3027 //
3028 // VQ L& operator=(VQ L&, R);
3029 // VQ L& operator*=(VQ L&, R);
3030 // VQ L& operator/=(VQ L&, R);
3031 // VQ L& operator+=(VQ L&, R);
3032 // VQ L& operator-=(VQ L&, R);
3033 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3034 for (unsigned Right = FirstPromotedArithmeticType;
3035 Right < LastPromotedArithmeticType; ++Right) {
3036 QualType ParamTypes[2];
3037 ParamTypes[1] = ArithmeticTypes[Right];
3038
3039 // Add this built-in operator as a candidate (VQ is empty).
3040 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003041 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3042 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003043
3044 // Add this built-in operator as a candidate (VQ is 'volatile').
3045 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
3046 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003047 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3048 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003049 }
3050 }
3051 break;
3052
3053 case OO_PercentEqual:
3054 case OO_LessLessEqual:
3055 case OO_GreaterGreaterEqual:
3056 case OO_AmpEqual:
3057 case OO_CaretEqual:
3058 case OO_PipeEqual:
3059 // C++ [over.built]p22:
3060 //
3061 // For every triple (L, VQ, R), where L is an integral type, VQ
3062 // is either volatile or empty, and R is a promoted integral
3063 // type, there exist candidate operator functions of the form
3064 //
3065 // VQ L& operator%=(VQ L&, R);
3066 // VQ L& operator<<=(VQ L&, R);
3067 // VQ L& operator>>=(VQ L&, R);
3068 // VQ L& operator&=(VQ L&, R);
3069 // VQ L& operator^=(VQ L&, R);
3070 // VQ L& operator|=(VQ L&, R);
3071 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3072 for (unsigned Right = FirstPromotedIntegralType;
3073 Right < LastPromotedIntegralType; ++Right) {
3074 QualType ParamTypes[2];
3075 ParamTypes[1] = ArithmeticTypes[Right];
3076
3077 // Add this built-in operator as a candidate (VQ is empty).
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003078 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
3079 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3080
3081 // Add this built-in operator as a candidate (VQ is 'volatile').
3082 ParamTypes[0] = ArithmeticTypes[Left];
3083 ParamTypes[0].addVolatile();
3084 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
3085 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3086 }
3087 }
3088 break;
3089
Douglas Gregor74253732008-11-19 15:42:04 +00003090 case OO_Exclaim: {
3091 // C++ [over.operator]p23:
3092 //
3093 // There also exist candidate operator functions of the form
3094 //
3095 // bool operator!(bool);
3096 // bool operator&&(bool, bool); [BELOW]
3097 // bool operator||(bool, bool); [BELOW]
3098 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003099 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3100 /*IsAssignmentOperator=*/false,
3101 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00003102 break;
3103 }
3104
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003105 case OO_AmpAmp:
3106 case OO_PipePipe: {
3107 // C++ [over.operator]p23:
3108 //
3109 // There also exist candidate operator functions of the form
3110 //
Douglas Gregor74253732008-11-19 15:42:04 +00003111 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003112 // bool operator&&(bool, bool);
3113 // bool operator||(bool, bool);
3114 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003115 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3116 /*IsAssignmentOperator=*/false,
3117 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003118 break;
3119 }
3120
3121 case OO_Subscript:
3122 // C++ [over.built]p13:
3123 //
3124 // For every cv-qualified or cv-unqualified object type T there
3125 // exist candidate operator functions of the form
3126 //
3127 // T* operator+(T*, ptrdiff_t); [ABOVE]
3128 // T& operator[](T*, ptrdiff_t);
3129 // T* operator-(T*, ptrdiff_t); [ABOVE]
3130 // T* operator+(ptrdiff_t, T*); [ABOVE]
3131 // T& operator[](ptrdiff_t, T*);
3132 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3133 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3134 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3135 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
3136 QualType ResultTy = Context.getReferenceType(PointeeType);
3137
3138 // T& operator[](T*, ptrdiff_t)
3139 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3140
3141 // T& operator[](ptrdiff_t, T*);
3142 ParamTypes[0] = ParamTypes[1];
3143 ParamTypes[1] = *Ptr;
3144 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3145 }
3146 break;
3147
3148 case OO_ArrowStar:
3149 // FIXME: No support for pointer-to-members yet.
3150 break;
3151 }
3152}
3153
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003154/// AddOverloadCandidates - Add all of the function overloads in Ovl
3155/// to the candidate set.
3156void
Douglas Gregor18fe5682008-11-03 20:45:27 +00003157Sema::AddOverloadCandidates(const OverloadedFunctionDecl *Ovl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003158 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00003159 OverloadCandidateSet& CandidateSet,
3160 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003161{
Douglas Gregor18fe5682008-11-03 20:45:27 +00003162 for (OverloadedFunctionDecl::function_const_iterator Func
3163 = Ovl->function_begin();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003164 Func != Ovl->function_end(); ++Func)
Douglas Gregor225c41e2008-11-03 19:09:14 +00003165 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet,
3166 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003167}
3168
3169/// isBetterOverloadCandidate - Determines whether the first overload
3170/// candidate is a better candidate than the second (C++ 13.3.3p1).
3171bool
3172Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3173 const OverloadCandidate& Cand2)
3174{
3175 // Define viable functions to be better candidates than non-viable
3176 // functions.
3177 if (!Cand2.Viable)
3178 return Cand1.Viable;
3179 else if (!Cand1.Viable)
3180 return false;
3181
Douglas Gregor88a35142008-12-22 05:46:06 +00003182 // C++ [over.match.best]p1:
3183 //
3184 // -- if F is a static member function, ICS1(F) is defined such
3185 // that ICS1(F) is neither better nor worse than ICS1(G) for
3186 // any function G, and, symmetrically, ICS1(G) is neither
3187 // better nor worse than ICS1(F).
3188 unsigned StartArg = 0;
3189 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3190 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003191
3192 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
3193 // function than another viable function F2 if for all arguments i,
3194 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
3195 // then...
3196 unsigned NumArgs = Cand1.Conversions.size();
3197 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3198 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003199 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003200 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3201 Cand2.Conversions[ArgIdx])) {
3202 case ImplicitConversionSequence::Better:
3203 // Cand1 has a better conversion sequence.
3204 HasBetterConversion = true;
3205 break;
3206
3207 case ImplicitConversionSequence::Worse:
3208 // Cand1 can't be better than Cand2.
3209 return false;
3210
3211 case ImplicitConversionSequence::Indistinguishable:
3212 // Do nothing.
3213 break;
3214 }
3215 }
3216
3217 if (HasBetterConversion)
3218 return true;
3219
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003220 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
3221 // implemented, but they require template support.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003222
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003223 // C++ [over.match.best]p1b4:
3224 //
3225 // -- the context is an initialization by user-defined conversion
3226 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3227 // from the return type of F1 to the destination type (i.e.,
3228 // the type of the entity being initialized) is a better
3229 // conversion sequence than the standard conversion sequence
3230 // from the return type of F2 to the destination type.
Douglas Gregor447b69e2008-11-19 03:25:36 +00003231 if (Cand1.Function && Cand2.Function &&
3232 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003233 isa<CXXConversionDecl>(Cand2.Function)) {
3234 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3235 Cand2.FinalConversion)) {
3236 case ImplicitConversionSequence::Better:
3237 // Cand1 has a better conversion sequence.
3238 return true;
3239
3240 case ImplicitConversionSequence::Worse:
3241 // Cand1 can't be better than Cand2.
3242 return false;
3243
3244 case ImplicitConversionSequence::Indistinguishable:
3245 // Do nothing
3246 break;
3247 }
3248 }
3249
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003250 return false;
3251}
3252
3253/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
3254/// within an overload candidate set. If overloading is successful,
3255/// the result will be OR_Success and Best will be set to point to the
3256/// best viable function within the candidate set. Otherwise, one of
3257/// several kinds of errors will be returned; see
3258/// Sema::OverloadingResult.
3259Sema::OverloadingResult
3260Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
3261 OverloadCandidateSet::iterator& Best)
3262{
3263 // Find the best viable function.
3264 Best = CandidateSet.end();
3265 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3266 Cand != CandidateSet.end(); ++Cand) {
3267 if (Cand->Viable) {
3268 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3269 Best = Cand;
3270 }
3271 }
3272
3273 // If we didn't find any viable functions, abort.
3274 if (Best == CandidateSet.end())
3275 return OR_No_Viable_Function;
3276
3277 // Make sure that this function is better than every other viable
3278 // function. If not, we have an ambiguity.
3279 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3280 Cand != CandidateSet.end(); ++Cand) {
3281 if (Cand->Viable &&
3282 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003283 !isBetterOverloadCandidate(*Best, *Cand)) {
3284 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003285 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003286 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003287 }
3288
3289 // Best is the best viable function.
3290 return OR_Success;
3291}
3292
3293/// PrintOverloadCandidates - When overload resolution fails, prints
3294/// diagnostic messages containing the candidates in the candidate
3295/// set. If OnlyViable is true, only viable candidates will be printed.
3296void
3297Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3298 bool OnlyViable)
3299{
3300 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3301 LastCand = CandidateSet.end();
3302 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003303 if (Cand->Viable || !OnlyViable) {
3304 if (Cand->Function) {
3305 // Normal function
3306 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003307 } else if (Cand->IsSurrogate) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003308 // Desugar the type of the surrogate down to a function type,
3309 // retaining as many typedefs as possible while still showing
3310 // the function type (and, therefore, its parameter types).
3311 QualType FnType = Cand->Surrogate->getConversionType();
3312 bool isReference = false;
3313 bool isPointer = false;
3314 if (const ReferenceType *FnTypeRef = FnType->getAsReferenceType()) {
3315 FnType = FnTypeRef->getPointeeType();
3316 isReference = true;
3317 }
3318 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
3319 FnType = FnTypePtr->getPointeeType();
3320 isPointer = true;
3321 }
3322 // Desugar down to a function type.
3323 FnType = QualType(FnType->getAsFunctionType(), 0);
3324 // Reconstruct the pointer/reference as appropriate.
3325 if (isPointer) FnType = Context.getPointerType(FnType);
3326 if (isReference) FnType = Context.getReferenceType(FnType);
3327
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003328 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003329 << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003330 } else {
3331 // FIXME: We need to get the identifier in here
3332 // FIXME: Do we want the error message to point at the
3333 // operator? (built-ins won't have a location)
3334 QualType FnType
3335 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3336 Cand->BuiltinTypes.ParamTypes,
3337 Cand->Conversions.size(),
3338 false, 0);
3339
Chris Lattnerd1625842008-11-24 06:25:27 +00003340 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003341 }
3342 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003343 }
3344}
3345
Douglas Gregor904eed32008-11-10 20:40:00 +00003346/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3347/// an overloaded function (C++ [over.over]), where @p From is an
3348/// expression with overloaded function type and @p ToType is the type
3349/// we're trying to resolve to. For example:
3350///
3351/// @code
3352/// int f(double);
3353/// int f(int);
3354///
3355/// int (*pfd)(double) = f; // selects f(double)
3356/// @endcode
3357///
3358/// This routine returns the resulting FunctionDecl if it could be
3359/// resolved, and NULL otherwise. When @p Complain is true, this
3360/// routine will emit diagnostics if there is an error.
3361FunctionDecl *
3362Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
3363 bool Complain) {
3364 QualType FunctionType = ToType;
3365 if (const PointerLikeType *ToTypePtr = ToType->getAsPointerLikeType())
3366 FunctionType = ToTypePtr->getPointeeType();
3367
3368 // We only look at pointers or references to functions.
3369 if (!FunctionType->isFunctionType())
3370 return 0;
3371
3372 // Find the actual overloaded function declaration.
3373 OverloadedFunctionDecl *Ovl = 0;
3374
3375 // C++ [over.over]p1:
3376 // [...] [Note: any redundant set of parentheses surrounding the
3377 // overloaded function name is ignored (5.1). ]
3378 Expr *OvlExpr = From->IgnoreParens();
3379
3380 // C++ [over.over]p1:
3381 // [...] The overloaded function name can be preceded by the &
3382 // operator.
3383 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3384 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3385 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3386 }
3387
3388 // Try to dig out the overloaded function.
3389 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
3390 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
3391
3392 // If there's no overloaded function declaration, we're done.
3393 if (!Ovl)
3394 return 0;
3395
3396 // Look through all of the overloaded functions, searching for one
3397 // whose type matches exactly.
3398 // FIXME: When templates or using declarations come along, we'll actually
3399 // have to deal with duplicates, partial ordering, etc. For now, we
3400 // can just do a simple search.
3401 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
3402 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
3403 Fun != Ovl->function_end(); ++Fun) {
3404 // C++ [over.over]p3:
3405 // Non-member functions and static member functions match
3406 // targets of type “pointer-to-function”or
3407 // “reference-to-function.”
3408 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun))
3409 if (!Method->isStatic())
3410 continue;
3411
3412 if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
3413 return *Fun;
3414 }
3415
3416 return 0;
3417}
3418
Douglas Gregorf6b89692008-11-26 05:54:23 +00003419/// ResolveOverloadedCallFn - Given the call expression that calls Fn
3420/// (which eventually refers to the set of overloaded functions in
3421/// Ovl) and the call arguments Args/NumArgs, attempt to resolve the
3422/// function call down to a specific function. If overload resolution
Douglas Gregor0a396682008-11-26 06:01:48 +00003423/// succeeds, returns the function declaration produced by overload
3424/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00003425/// arguments and Fn, and returns NULL.
Douglas Gregor0a396682008-11-26 06:01:48 +00003426FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, OverloadedFunctionDecl *Ovl,
3427 SourceLocation LParenLoc,
3428 Expr **Args, unsigned NumArgs,
3429 SourceLocation *CommaLocs,
3430 SourceLocation RParenLoc) {
Douglas Gregorf6b89692008-11-26 05:54:23 +00003431 OverloadCandidateSet CandidateSet;
3432 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet);
3433 OverloadCandidateSet::iterator Best;
3434 switch (BestViableFunction(CandidateSet, Best)) {
Douglas Gregor0a396682008-11-26 06:01:48 +00003435 case OR_Success:
3436 return Best->Function;
Douglas Gregorf6b89692008-11-26 05:54:23 +00003437
3438 case OR_No_Viable_Function:
3439 Diag(Fn->getSourceRange().getBegin(),
3440 diag::err_ovl_no_viable_function_in_call)
3441 << Ovl->getDeclName() << (unsigned)CandidateSet.size()
3442 << Fn->getSourceRange();
3443 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3444 break;
3445
3446 case OR_Ambiguous:
3447 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
3448 << Ovl->getDeclName() << Fn->getSourceRange();
3449 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3450 break;
3451 }
3452
3453 // Overload resolution failed. Destroy all of the subexpressions and
3454 // return NULL.
3455 Fn->Destroy(Context);
3456 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3457 Args[Arg]->Destroy(Context);
3458 return 0;
3459}
3460
Douglas Gregor88a35142008-12-22 05:46:06 +00003461/// BuildCallToMemberFunction - Build a call to a member
3462/// function. MemExpr is the expression that refers to the member
3463/// function (and includes the object parameter), Args/NumArgs are the
3464/// arguments to the function call (not including the object
3465/// parameter). The caller needs to validate that the member
3466/// expression refers to a member function or an overloaded member
3467/// function.
3468Sema::ExprResult
3469Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
3470 SourceLocation LParenLoc, Expr **Args,
3471 unsigned NumArgs, SourceLocation *CommaLocs,
3472 SourceLocation RParenLoc) {
3473 // Dig out the member expression. This holds both the object
3474 // argument and the member function we're referring to.
3475 MemberExpr *MemExpr = 0;
3476 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
3477 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
3478 else
3479 MemExpr = dyn_cast<MemberExpr>(MemExprE);
3480 assert(MemExpr && "Building member call without member expression");
3481
3482 // Extract the object argument.
3483 Expr *ObjectArg = MemExpr->getBase();
3484 if (MemExpr->isArrow())
3485 ObjectArg = new UnaryOperator(ObjectArg, UnaryOperator::Deref,
3486 ObjectArg->getType()->getAsPointerType()->getPointeeType(),
3487 SourceLocation());
3488 CXXMethodDecl *Method = 0;
3489 if (OverloadedFunctionDecl *Ovl
3490 = dyn_cast<OverloadedFunctionDecl>(MemExpr->getMemberDecl())) {
3491 // Add overload candidates
3492 OverloadCandidateSet CandidateSet;
3493 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3494 FuncEnd = Ovl->function_end();
3495 Func != FuncEnd; ++Func) {
3496 assert(isa<CXXMethodDecl>(*Func) && "Function is not a method");
3497 Method = cast<CXXMethodDecl>(*Func);
3498 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
3499 /*SuppressUserConversions=*/false);
3500 }
3501
3502 OverloadCandidateSet::iterator Best;
3503 switch (BestViableFunction(CandidateSet, Best)) {
3504 case OR_Success:
3505 Method = cast<CXXMethodDecl>(Best->Function);
3506 break;
3507
3508 case OR_No_Viable_Function:
3509 Diag(MemExpr->getSourceRange().getBegin(),
3510 diag::err_ovl_no_viable_member_function_in_call)
3511 << Ovl->getDeclName() << (unsigned)CandidateSet.size()
3512 << MemExprE->getSourceRange();
3513 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3514 // FIXME: Leaking incoming expressions!
3515 return true;
3516
3517 case OR_Ambiguous:
3518 Diag(MemExpr->getSourceRange().getBegin(),
3519 diag::err_ovl_ambiguous_member_call)
3520 << Ovl->getDeclName() << MemExprE->getSourceRange();
3521 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3522 // FIXME: Leaking incoming expressions!
3523 return true;
3524 }
3525
3526 FixOverloadedFunctionReference(MemExpr, Method);
3527 } else {
3528 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
3529 }
3530
3531 assert(Method && "Member call to something that isn't a method?");
3532 llvm::OwningPtr<CXXMemberCallExpr>
3533 TheCall(new CXXMemberCallExpr(MemExpr, Args, NumArgs,
3534 Method->getResultType().getNonReferenceType(),
3535 RParenLoc));
3536
3537 // Convert the object argument (for a non-static member function call).
3538 if (!Method->isStatic() &&
3539 PerformObjectArgumentInitialization(ObjectArg, Method))
3540 return true;
3541 MemExpr->setBase(ObjectArg);
3542
3543 // Convert the rest of the arguments
3544 const FunctionTypeProto *Proto = cast<FunctionTypeProto>(Method->getType());
3545 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
3546 RParenLoc))
3547 return true;
3548
Sebastian Redl0eb23302009-01-19 00:08:26 +00003549 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregor88a35142008-12-22 05:46:06 +00003550}
3551
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003552/// BuildCallToObjectOfClassType - Build a call to an object of class
3553/// type (C++ [over.call.object]), which can end up invoking an
3554/// overloaded function call operator (@c operator()) or performing a
3555/// user-defined conversion on the object argument.
Douglas Gregor88a35142008-12-22 05:46:06 +00003556Sema::ExprResult
Douglas Gregor5c37de72008-12-06 00:22:45 +00003557Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
3558 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003559 Expr **Args, unsigned NumArgs,
3560 SourceLocation *CommaLocs,
3561 SourceLocation RParenLoc) {
3562 assert(Object->getType()->isRecordType() && "Requires object type argument");
3563 const RecordType *Record = Object->getType()->getAsRecordType();
3564
3565 // C++ [over.call.object]p1:
3566 // If the primary-expression E in the function call syntax
3567 // evaluates to a class object of type “cv T”, then the set of
3568 // candidate functions includes at least the function call
3569 // operators of T. The function call operators of T are obtained by
3570 // ordinary lookup of the name operator() in the context of
3571 // (E).operator().
3572 OverloadCandidateSet CandidateSet;
Douglas Gregor44b43212008-12-11 16:49:14 +00003573 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003574 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00003575 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003576 Oper != OperEnd; ++Oper)
3577 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
3578 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003579
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003580 // C++ [over.call.object]p2:
3581 // In addition, for each conversion function declared in T of the
3582 // form
3583 //
3584 // operator conversion-type-id () cv-qualifier;
3585 //
3586 // where cv-qualifier is the same cv-qualification as, or a
3587 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00003588 // denotes the type "pointer to function of (P1,...,Pn) returning
3589 // R", or the type "reference to pointer to function of
3590 // (P1,...,Pn) returning R", or the type "reference to function
3591 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003592 // is also considered as a candidate function. Similarly,
3593 // surrogate call functions are added to the set of candidate
3594 // functions for each conversion function declared in an
3595 // accessible base class provided the function is not hidden
3596 // within T by another intervening declaration.
3597 //
3598 // FIXME: Look in base classes for more conversion operators!
3599 OverloadedFunctionDecl *Conversions
3600 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor621b3932008-11-21 02:54:28 +00003601 for (OverloadedFunctionDecl::function_iterator
3602 Func = Conversions->function_begin(),
3603 FuncEnd = Conversions->function_end();
3604 Func != FuncEnd; ++Func) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003605 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
3606
3607 // Strip the reference type (if any) and then the pointer type (if
3608 // any) to get down to what might be a function type.
3609 QualType ConvType = Conv->getConversionType().getNonReferenceType();
3610 if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
3611 ConvType = ConvPtrType->getPointeeType();
3612
3613 if (const FunctionTypeProto *Proto = ConvType->getAsFunctionTypeProto())
3614 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
3615 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003616
3617 // Perform overload resolution.
3618 OverloadCandidateSet::iterator Best;
3619 switch (BestViableFunction(CandidateSet, Best)) {
3620 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003621 // Overload resolution succeeded; we'll build the appropriate call
3622 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003623 break;
3624
3625 case OR_No_Viable_Function:
Sebastian Redle4c452c2008-11-22 13:44:36 +00003626 Diag(Object->getSourceRange().getBegin(),
3627 diag::err_ovl_no_viable_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00003628 << Object->getType() << (unsigned)CandidateSet.size()
Sebastian Redle4c452c2008-11-22 13:44:36 +00003629 << Object->getSourceRange();
3630 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003631 break;
3632
3633 case OR_Ambiguous:
3634 Diag(Object->getSourceRange().getBegin(),
3635 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00003636 << Object->getType() << Object->getSourceRange();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003637 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3638 break;
3639 }
3640
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003641 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003642 // We had an error; delete all of the subexpressions and return
3643 // the error.
3644 delete Object;
3645 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3646 delete Args[ArgIdx];
3647 return true;
3648 }
3649
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003650 if (Best->Function == 0) {
3651 // Since there is no function declaration, this is one of the
3652 // surrogate candidates. Dig out the conversion function.
3653 CXXConversionDecl *Conv
3654 = cast<CXXConversionDecl>(
3655 Best->Conversions[0].UserDefined.ConversionFunction);
3656
3657 // We selected one of the surrogate functions that converts the
3658 // object parameter to a function pointer. Perform the conversion
3659 // on the object argument, then let ActOnCallExpr finish the job.
3660 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl0eb23302009-01-19 00:08:26 +00003661 ImpCastExprToType(Object,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003662 Conv->getConversionType().getNonReferenceType(),
3663 Conv->getConversionType()->isReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003664 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
3665 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
3666 CommaLocs, RParenLoc).release();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003667 }
3668
3669 // We found an overloaded operator(). Build a CXXOperatorCallExpr
3670 // that calls this method, using Object for the implicit object
3671 // parameter and passing along the remaining arguments.
3672 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003673 const FunctionTypeProto *Proto = Method->getType()->getAsFunctionTypeProto();
3674
3675 unsigned NumArgsInProto = Proto->getNumArgs();
3676 unsigned NumArgsToCheck = NumArgs;
3677
3678 // Build the full argument list for the method call (the
3679 // implicit object parameter is placed at the beginning of the
3680 // list).
3681 Expr **MethodArgs;
3682 if (NumArgs < NumArgsInProto) {
3683 NumArgsToCheck = NumArgsInProto;
3684 MethodArgs = new Expr*[NumArgsInProto + 1];
3685 } else {
3686 MethodArgs = new Expr*[NumArgs + 1];
3687 }
3688 MethodArgs[0] = Object;
3689 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3690 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
3691
3692 Expr *NewFn = new DeclRefExpr(Method, Method->getType(),
3693 SourceLocation());
3694 UsualUnaryConversions(NewFn);
3695
3696 // Once we've built TheCall, all of the expressions are properly
3697 // owned.
3698 QualType ResultTy = Method->getResultType().getNonReferenceType();
3699 llvm::OwningPtr<CXXOperatorCallExpr>
3700 TheCall(new CXXOperatorCallExpr(NewFn, MethodArgs, NumArgs + 1,
3701 ResultTy, RParenLoc));
3702 delete [] MethodArgs;
3703
Douglas Gregor518fda12009-01-13 05:10:00 +00003704 // We may have default arguments. If so, we need to allocate more
3705 // slots in the call for them.
3706 if (NumArgs < NumArgsInProto)
3707 TheCall->setNumArgs(NumArgsInProto + 1);
3708 else if (NumArgs > NumArgsInProto)
3709 NumArgsToCheck = NumArgsInProto;
3710
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003711 // Initialize the implicit object parameter.
Douglas Gregor518fda12009-01-13 05:10:00 +00003712 if (PerformObjectArgumentInitialization(Object, Method))
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003713 return true;
3714 TheCall->setArg(0, Object);
3715
3716 // Check the argument types.
3717 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003718 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00003719 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003720 Arg = Args[i];
Douglas Gregor518fda12009-01-13 05:10:00 +00003721
3722 // Pass the argument.
3723 QualType ProtoArgType = Proto->getArgType(i);
3724 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3725 return true;
3726 } else {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003727 Arg = new CXXDefaultArgExpr(Method->getParamDecl(i));
Douglas Gregor518fda12009-01-13 05:10:00 +00003728 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003729
3730 TheCall->setArg(i + 1, Arg);
3731 }
3732
3733 // If this is a variadic call, handle args passed through "...".
3734 if (Proto->isVariadic()) {
3735 // Promote the arguments (C99 6.5.2.2p7).
3736 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3737 Expr *Arg = Args[i];
Anders Carlsson906fed02009-01-13 05:48:52 +00003738
Anders Carlssondce5e2c2009-01-16 16:48:51 +00003739 DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003740 TheCall->setArg(i + 1, Arg);
3741 }
3742 }
3743
Sebastian Redl0eb23302009-01-19 00:08:26 +00003744 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003745}
3746
Douglas Gregor8ba10742008-11-20 16:27:02 +00003747/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
3748/// (if one exists), where @c Base is an expression of class type and
3749/// @c Member is the name of the member we're trying to find.
3750Action::ExprResult
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003751Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
Douglas Gregor8ba10742008-11-20 16:27:02 +00003752 SourceLocation MemberLoc,
3753 IdentifierInfo &Member) {
3754 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
3755
3756 // C++ [over.ref]p1:
3757 //
3758 // [...] An expression x->m is interpreted as (x.operator->())->m
3759 // for a class object x of type T if T::operator->() exists and if
3760 // the operator is selected as the best match function by the
3761 // overload resolution mechanism (13.3).
3762 // FIXME: look in base classes.
3763 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
3764 OverloadCandidateSet CandidateSet;
3765 const RecordType *BaseRecord = Base->getType()->getAsRecordType();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003766
3767 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00003768 for (llvm::tie(Oper, OperEnd) = BaseRecord->getDecl()->lookup(OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003769 Oper != OperEnd; ++Oper)
3770 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00003771 /*SuppressUserConversions=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003772
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003773 llvm::OwningPtr<Expr> BasePtr(Base);
3774
Douglas Gregor8ba10742008-11-20 16:27:02 +00003775 // Perform overload resolution.
3776 OverloadCandidateSet::iterator Best;
3777 switch (BestViableFunction(CandidateSet, Best)) {
3778 case OR_Success:
3779 // Overload resolution succeeded; we'll build the call below.
3780 break;
3781
3782 case OR_No_Viable_Function:
3783 if (CandidateSet.empty())
3784 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattnerd1625842008-11-24 06:25:27 +00003785 << BasePtr->getType() << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003786 else
3787 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Sebastian Redle4c452c2008-11-22 13:44:36 +00003788 << "operator->" << (unsigned)CandidateSet.size()
3789 << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003790 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003791 return true;
3792
3793 case OR_Ambiguous:
3794 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Chris Lattnerd1625842008-11-24 06:25:27 +00003795 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003796 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003797 return true;
3798 }
3799
3800 // Convert the object parameter.
3801 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003802 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregor8ba10742008-11-20 16:27:02 +00003803 return true;
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003804
3805 // No concerns about early exits now.
3806 BasePtr.take();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003807
3808 // Build the operator call.
3809 Expr *FnExpr = new DeclRefExpr(Method, Method->getType(), SourceLocation());
3810 UsualUnaryConversions(FnExpr);
3811 Base = new CXXOperatorCallExpr(FnExpr, &Base, 1,
3812 Method->getResultType().getNonReferenceType(),
3813 OpLoc);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003814 return ActOnMemberReferenceExpr(S, ExprArg(*this, Base), OpLoc, tok::arrow,
3815 MemberLoc, Member).release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003816}
3817
Douglas Gregor904eed32008-11-10 20:40:00 +00003818/// FixOverloadedFunctionReference - E is an expression that refers to
3819/// a C++ overloaded function (possibly with some parentheses and
3820/// perhaps a '&' around it). We have resolved the overloaded function
3821/// to the function declaration Fn, so patch up the expression E to
3822/// refer (possibly indirectly) to Fn.
3823void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
3824 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
3825 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
3826 E->setType(PE->getSubExpr()->getType());
3827 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
3828 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
3829 "Can only take the address of an overloaded function");
3830 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
3831 E->setType(Context.getPointerType(E->getType()));
3832 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
3833 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
3834 "Expected overloaded function");
3835 DR->setDecl(Fn);
3836 E->setType(Fn->getType());
Douglas Gregor88a35142008-12-22 05:46:06 +00003837 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
3838 MemExpr->setMemberDecl(Fn);
3839 E->setType(Fn->getType());
Douglas Gregor904eed32008-11-10 20:40:00 +00003840 } else {
3841 assert(false && "Invalid reference to overloaded function");
3842 }
3843}
3844
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003845} // end namespace clang