blob: 44cd5b5e53523644060cee802809a71ebbb0474c [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)) {
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000386 QualType FromCanon
387 = Context.getCanonicalType(From->getType().getUnqualifiedType());
388 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
389 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000390 // Turn this into a "standard" conversion sequence, so that it
391 // gets ranked with standard conversion sequences.
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000392 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
393 ICS.Standard.setAsIdentityConversion();
394 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
395 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000396 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000397 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000398 ICS.Standard.Second = ICK_Derived_To_Base;
399 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000400 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000401
402 // C++ [over.best.ics]p4:
403 // However, when considering the argument of a user-defined
404 // conversion function that is a candidate by 13.3.1.3 when
405 // invoked for the copying of the temporary in the second step
406 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
407 // 13.3.1.6 in all cases, only standard conversion sequences and
408 // ellipsis conversion sequences are allowed.
409 if (SuppressUserConversions &&
410 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
411 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000412 } else
Douglas Gregor60d62c22008-10-31 16:23:19 +0000413 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000414
415 return ICS;
416}
417
418/// IsStandardConversion - Determines whether there is a standard
419/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
420/// expression From to the type ToType. Standard conversion sequences
421/// only consider non-class types; for conversions that involve class
422/// types, use TryImplicitConversion. If a conversion exists, SCS will
423/// contain the standard conversion sequence required to perform this
424/// conversion and this routine will return true. Otherwise, this
425/// routine will return false and the value of SCS is unspecified.
426bool
427Sema::IsStandardConversion(Expr* From, QualType ToType,
428 StandardConversionSequence &SCS)
429{
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000430 QualType FromType = From->getType();
431
Douglas Gregor60d62c22008-10-31 16:23:19 +0000432 // There are no standard conversions for class types, so abort early.
433 if (FromType->isRecordType() || ToType->isRecordType())
434 return false;
435
436 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000437 SCS.setAsIdentityConversion();
Douglas Gregor60d62c22008-10-31 16:23:19 +0000438 SCS.Deprecated = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000439 SCS.IncompatibleObjC = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000440 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000441 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000442
443 // The first conversion can be an lvalue-to-rvalue conversion,
444 // array-to-pointer conversion, or function-to-pointer conversion
445 // (C++ 4p1).
446
447 // Lvalue-to-rvalue conversion (C++ 4.1):
448 // An lvalue (3.10) of a non-function, non-array type T can be
449 // converted to an rvalue.
450 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
451 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000452 !FromType->isFunctionType() && !FromType->isArrayType() &&
453 !FromType->isOverloadType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000454 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000455
456 // If T is a non-class type, the type of the rvalue is the
457 // cv-unqualified version of T. Otherwise, the type of the rvalue
458 // is T (C++ 4.1p1).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000459 FromType = FromType.getUnqualifiedType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000460 }
461 // Array-to-pointer conversion (C++ 4.2)
462 else if (FromType->isArrayType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000463 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000464
465 // An lvalue or rvalue of type "array of N T" or "array of unknown
466 // bound of T" can be converted to an rvalue of type "pointer to
467 // T" (C++ 4.2p1).
468 FromType = Context.getArrayDecayedType(FromType);
469
470 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
471 // This conversion is deprecated. (C++ D.4).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000472 SCS.Deprecated = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000473
474 // For the purpose of ranking in overload resolution
475 // (13.3.3.1.1), this conversion is considered an
476 // array-to-pointer conversion followed by a qualification
477 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000478 SCS.Second = ICK_Identity;
479 SCS.Third = ICK_Qualification;
480 SCS.ToTypePtr = ToType.getAsOpaquePtr();
481 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000482 }
483 }
484 // Function-to-pointer conversion (C++ 4.3).
485 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000486 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000487
488 // An lvalue of function type T can be converted to an rvalue of
489 // type "pointer to T." The result is a pointer to the
490 // function. (C++ 4.3p1).
491 FromType = Context.getPointerType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000492 }
Douglas Gregor904eed32008-11-10 20:40:00 +0000493 // Address of overloaded function (C++ [over.over]).
494 else if (FunctionDecl *Fn
495 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
496 SCS.First = ICK_Function_To_Pointer;
497
498 // We were able to resolve the address of the overloaded function,
499 // so we can convert to the type of that function.
500 FromType = Fn->getType();
501 if (ToType->isReferenceType())
502 FromType = Context.getReferenceType(FromType);
503 else
504 FromType = Context.getPointerType(FromType);
505 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000506 // We don't require any conversions for the first step.
507 else {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000508 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000509 }
510
511 // The second conversion can be an integral promotion, floating
512 // point promotion, integral conversion, floating point conversion,
513 // floating-integral conversion, pointer conversion,
514 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor45920e82008-12-19 17:40:08 +0000515 bool IncompatibleObjC = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000516 if (Context.getCanonicalType(FromType).getUnqualifiedType() ==
517 Context.getCanonicalType(ToType).getUnqualifiedType()) {
518 // The unqualified versions of the types are the same: there's no
519 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000520 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000521 }
522 // Integral promotion (C++ 4.5).
523 else if (IsIntegralPromotion(From, FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000524 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000525 FromType = ToType.getUnqualifiedType();
526 }
527 // Floating point promotion (C++ 4.6).
528 else if (IsFloatingPointPromotion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000529 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000530 FromType = ToType.getUnqualifiedType();
531 }
532 // Integral conversions (C++ 4.7).
Sebastian Redl07779722008-10-31 14:43:28 +0000533 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000534 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000535 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000536 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000537 FromType = ToType.getUnqualifiedType();
538 }
539 // Floating point conversions (C++ 4.8).
540 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000541 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000542 FromType = ToType.getUnqualifiedType();
543 }
544 // Floating-integral conversions (C++ 4.9).
Sebastian Redl07779722008-10-31 14:43:28 +0000545 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000546 else if ((FromType->isFloatingType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000547 ToType->isIntegralType() && !ToType->isBooleanType() &&
548 !ToType->isEnumeralType()) ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000549 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
550 ToType->isFloatingType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000551 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000552 FromType = ToType.getUnqualifiedType();
553 }
554 // Pointer conversions (C++ 4.10).
Douglas Gregor45920e82008-12-19 17:40:08 +0000555 else if (IsPointerConversion(From, FromType, ToType, FromType,
556 IncompatibleObjC)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000557 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000558 SCS.IncompatibleObjC = IncompatibleObjC;
Sebastian Redl07779722008-10-31 14:43:28 +0000559 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000560 // Pointer to member conversions (4.11).
561 else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
562 SCS.Second = ICK_Pointer_Member;
563 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000564 // Boolean conversions (C++ 4.12).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000565 else if (ToType->isBooleanType() &&
566 (FromType->isArithmeticType() ||
567 FromType->isEnumeralType() ||
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000568 FromType->isPointerType() ||
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000569 FromType->isBlockPointerType() ||
570 FromType->isMemberPointerType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000571 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000572 FromType = Context.BoolTy;
573 } else {
574 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000575 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000576 }
577
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000578 QualType CanonFrom;
579 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000580 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000581 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000582 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000583 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000584 CanonFrom = Context.getCanonicalType(FromType);
585 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000586 } else {
587 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000588 SCS.Third = ICK_Identity;
589
590 // C++ [over.best.ics]p6:
591 // [...] Any difference in top-level cv-qualification is
592 // subsumed by the initialization itself and does not constitute
593 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000594 CanonFrom = Context.getCanonicalType(FromType);
595 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000596 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000597 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
598 FromType = ToType;
599 CanonFrom = CanonTo;
600 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000601 }
602
603 // If we have not converted the argument type to the parameter type,
604 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000605 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000606 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000607
Douglas Gregor60d62c22008-10-31 16:23:19 +0000608 SCS.ToTypePtr = FromType.getAsOpaquePtr();
609 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000610}
611
612/// IsIntegralPromotion - Determines whether the conversion from the
613/// expression From (whose potentially-adjusted type is FromType) to
614/// ToType is an integral promotion (C++ 4.5). If so, returns true and
615/// sets PromotedType to the promoted type.
616bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
617{
618 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000619 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000620 if (!To) {
621 return false;
622 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000623
624 // An rvalue of type char, signed char, unsigned char, short int, or
625 // unsigned short int can be converted to an rvalue of type int if
626 // int can represent all the values of the source type; otherwise,
627 // the source rvalue can be converted to an rvalue of type unsigned
628 // int (C++ 4.5p1).
Sebastian Redl07779722008-10-31 14:43:28 +0000629 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000630 if (// We can promote any signed, promotable integer type to an int
631 (FromType->isSignedIntegerType() ||
632 // We can promote any unsigned integer type whose size is
633 // less than int to an int.
634 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000635 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000636 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000637 }
638
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000639 return To->getKind() == BuiltinType::UInt;
640 }
641
642 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
643 // can be converted to an rvalue of the first of the following types
644 // that can represent all the values of its underlying type: int,
645 // unsigned int, long, or unsigned long (C++ 4.5p2).
646 if ((FromType->isEnumeralType() || FromType->isWideCharType())
647 && ToType->isIntegerType()) {
648 // Determine whether the type we're converting from is signed or
649 // unsigned.
650 bool FromIsSigned;
651 uint64_t FromSize = Context.getTypeSize(FromType);
652 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
653 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
654 FromIsSigned = UnderlyingType->isSignedIntegerType();
655 } else {
656 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
657 FromIsSigned = true;
658 }
659
660 // The types we'll try to promote to, in the appropriate
661 // order. Try each of these types.
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000662 QualType PromoteTypes[6] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000663 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000664 Context.LongTy, Context.UnsignedLongTy ,
665 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000666 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000667 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000668 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
669 if (FromSize < ToSize ||
670 (FromSize == ToSize &&
671 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
672 // We found the type that we can promote to. If this is the
673 // type we wanted, we have a promotion. Otherwise, no
674 // promotion.
Sebastian Redl07779722008-10-31 14:43:28 +0000675 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000676 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
677 }
678 }
679 }
680
681 // An rvalue for an integral bit-field (9.6) can be converted to an
682 // rvalue of type int if int can represent all the values of the
683 // bit-field; otherwise, it can be converted to unsigned int if
684 // unsigned int can represent all the values of the bit-field. If
685 // the bit-field is larger yet, no integral promotion applies to
686 // it. If the bit-field has an enumerated type, it is treated as any
687 // other value of that type for promotion purposes (C++ 4.5p3).
688 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) {
689 using llvm::APSInt;
Douglas Gregor86f19402008-12-20 23:49:58 +0000690 if (FieldDecl *MemberDecl = dyn_cast<FieldDecl>(MemRef->getMemberDecl())) {
691 APSInt BitWidth;
692 if (MemberDecl->isBitField() &&
693 FromType->isIntegralType() && !FromType->isEnumeralType() &&
694 From->isIntegerConstantExpr(BitWidth, Context)) {
695 APSInt ToSize(Context.getTypeSize(ToType));
696
697 // Are we promoting to an int from a bitfield that fits in an int?
698 if (BitWidth < ToSize ||
699 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
700 return To->getKind() == BuiltinType::Int;
701 }
702
703 // Are we promoting to an unsigned int from an unsigned bitfield
704 // that fits into an unsigned int?
705 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
706 return To->getKind() == BuiltinType::UInt;
707 }
708
709 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000710 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000711 }
712 }
713
714 // An rvalue of type bool can be converted to an rvalue of type int,
715 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000716 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000717 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000718 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000719
720 return false;
721}
722
723/// IsFloatingPointPromotion - Determines whether the conversion from
724/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
725/// returns true and sets PromotedType to the promoted type.
726bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
727{
728 /// An rvalue of type float can be converted to an rvalue of type
729 /// double. (C++ 4.6p1).
730 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
731 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType())
732 if (FromBuiltin->getKind() == BuiltinType::Float &&
733 ToBuiltin->getKind() == BuiltinType::Double)
734 return true;
735
736 return false;
737}
738
Douglas Gregorcb7de522008-11-26 23:31:11 +0000739/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
740/// the pointer type FromPtr to a pointer to type ToPointee, with the
741/// same type qualifiers as FromPtr has on its pointee type. ToType,
742/// if non-empty, will be a pointer to ToType that may or may not have
743/// the right set of qualifiers on its pointee.
744static QualType
745BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
746 QualType ToPointee, QualType ToType,
747 ASTContext &Context) {
748 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
749 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
750 unsigned Quals = CanonFromPointee.getCVRQualifiers();
751
752 // Exact qualifier match -> return the pointer type we're converting to.
753 if (CanonToPointee.getCVRQualifiers() == Quals) {
754 // ToType is exactly what we need. Return it.
755 if (ToType.getTypePtr())
756 return ToType;
757
758 // Build a pointer to ToPointee. It has the right qualifiers
759 // already.
760 return Context.getPointerType(ToPointee);
761 }
762
763 // Just build a canonical type that has the right qualifiers.
764 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
765}
766
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000767/// IsPointerConversion - Determines whether the conversion of the
768/// expression From, which has the (possibly adjusted) type FromType,
769/// can be converted to the type ToType via a pointer conversion (C++
770/// 4.10). If so, returns true and places the converted type (that
771/// might differ from ToType in its cv-qualifiers at some level) into
772/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000773///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000774/// This routine also supports conversions to and from block pointers
775/// and conversions with Objective-C's 'id', 'id<protocols...>', and
776/// pointers to interfaces. FIXME: Once we've determined the
777/// appropriate overloading rules for Objective-C, we may want to
778/// split the Objective-C checks into a different routine; however,
779/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000780/// conversions, so for now they live here. IncompatibleObjC will be
781/// set if the conversion is an allowed Objective-C conversion that
782/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000783bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000784 QualType& ConvertedType,
785 bool &IncompatibleObjC)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000786{
Douglas Gregor45920e82008-12-19 17:40:08 +0000787 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +0000788 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
789 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +0000790
Douglas Gregor27b09ac2008-12-22 20:51:52 +0000791 // Conversion from a null pointer constant to any Objective-C pointer type.
792 if (Context.isObjCObjectPointerType(ToType) &&
793 From->isNullPointerConstant(Context)) {
794 ConvertedType = ToType;
795 return true;
796 }
797
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000798 // Blocks: Block pointers can be converted to void*.
799 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
800 ToType->getAsPointerType()->getPointeeType()->isVoidType()) {
801 ConvertedType = ToType;
802 return true;
803 }
804 // Blocks: A null pointer constant can be converted to a block
805 // pointer type.
806 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
807 ConvertedType = ToType;
808 return true;
809 }
810
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000811 const PointerType* ToTypePtr = ToType->getAsPointerType();
812 if (!ToTypePtr)
813 return false;
814
815 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
816 if (From->isNullPointerConstant(Context)) {
817 ConvertedType = ToType;
818 return true;
819 }
Sebastian Redl07779722008-10-31 14:43:28 +0000820
Douglas Gregorcb7de522008-11-26 23:31:11 +0000821 // Beyond this point, both types need to be pointers.
822 const PointerType *FromTypePtr = FromType->getAsPointerType();
823 if (!FromTypePtr)
824 return false;
825
826 QualType FromPointeeType = FromTypePtr->getPointeeType();
827 QualType ToPointeeType = ToTypePtr->getPointeeType();
828
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000829 // An rvalue of type "pointer to cv T," where T is an object type,
830 // can be converted to an rvalue of type "pointer to cv void" (C++
831 // 4.10p2).
Douglas Gregorc7887512008-12-19 19:13:09 +0000832 if (FromPointeeType->isIncompleteOrObjectType() &&
833 ToPointeeType->isVoidType()) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000834 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
835 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000836 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000837 return true;
838 }
839
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000840 // C++ [conv.ptr]p3:
841 //
842 // An rvalue of type "pointer to cv D," where D is a class type,
843 // can be converted to an rvalue of type "pointer to cv B," where
844 // B is a base class (clause 10) of D. If B is an inaccessible
845 // (clause 11) or ambiguous (10.2) base class of D, a program that
846 // necessitates this conversion is ill-formed. The result of the
847 // conversion is a pointer to the base class sub-object of the
848 // derived class object. The null pointer value is converted to
849 // the null pointer value of the destination type.
850 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000851 // Note that we do not check for ambiguity or inaccessibility
852 // here. That is handled by CheckPointerConversion.
Douglas Gregorcb7de522008-11-26 23:31:11 +0000853 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
854 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000855 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
856 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000857 ToType, Context);
858 return true;
859 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000860
Douglas Gregorc7887512008-12-19 19:13:09 +0000861 return false;
862}
863
864/// isObjCPointerConversion - Determines whether this is an
865/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
866/// with the same arguments and return values.
867bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
868 QualType& ConvertedType,
869 bool &IncompatibleObjC) {
870 if (!getLangOptions().ObjC1)
871 return false;
872
873 // Conversions with Objective-C's id<...>.
874 if ((FromType->isObjCQualifiedIdType() || ToType->isObjCQualifiedIdType()) &&
875 ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) {
876 ConvertedType = ToType;
877 return true;
878 }
879
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000880 // Beyond this point, both types need to be pointers or block pointers.
881 QualType ToPointeeType;
Douglas Gregorc7887512008-12-19 19:13:09 +0000882 const PointerType* ToTypePtr = ToType->getAsPointerType();
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000883 if (ToTypePtr)
884 ToPointeeType = ToTypePtr->getPointeeType();
885 else if (const BlockPointerType *ToBlockPtr = ToType->getAsBlockPointerType())
886 ToPointeeType = ToBlockPtr->getPointeeType();
887 else
Douglas Gregorc7887512008-12-19 19:13:09 +0000888 return false;
889
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000890 QualType FromPointeeType;
Douglas Gregorc7887512008-12-19 19:13:09 +0000891 const PointerType *FromTypePtr = FromType->getAsPointerType();
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000892 if (FromTypePtr)
893 FromPointeeType = FromTypePtr->getPointeeType();
894 else if (const BlockPointerType *FromBlockPtr
895 = FromType->getAsBlockPointerType())
896 FromPointeeType = FromBlockPtr->getPointeeType();
897 else
Douglas Gregorc7887512008-12-19 19:13:09 +0000898 return false;
899
Douglas Gregorcb7de522008-11-26 23:31:11 +0000900 // Objective C++: We're able to convert from a pointer to an
901 // interface to a pointer to a different interface.
902 const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType();
903 const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType();
904 if (FromIface && ToIface &&
905 Context.canAssignObjCInterfaces(ToIface, FromIface)) {
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000906 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +0000907 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000908 ToType, Context);
909 return true;
910 }
911
Douglas Gregor45920e82008-12-19 17:40:08 +0000912 if (FromIface && ToIface &&
913 Context.canAssignObjCInterfaces(FromIface, ToIface)) {
914 // Okay: this is some kind of implicit downcast of Objective-C
915 // interfaces, which is permitted. However, we're going to
916 // complain about it.
917 IncompatibleObjC = true;
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000918 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor45920e82008-12-19 17:40:08 +0000919 ToPointeeType,
920 ToType, Context);
921 return true;
922 }
923
Douglas Gregorcb7de522008-11-26 23:31:11 +0000924 // Objective C++: We're able to convert between "id" and a pointer
925 // to any interface (in both directions).
926 if ((FromIface && Context.isObjCIdType(ToPointeeType))
927 || (ToIface && Context.isObjCIdType(FromPointeeType))) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000928 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
929 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000930 ToType, Context);
931 return true;
932 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000933
Douglas Gregordda78892008-12-18 23:43:31 +0000934 // Objective C++: Allow conversions between the Objective-C "id" and
935 // "Class", in either direction.
936 if ((Context.isObjCIdType(FromPointeeType) &&
937 Context.isObjCClassType(ToPointeeType)) ||
938 (Context.isObjCClassType(FromPointeeType) &&
939 Context.isObjCIdType(ToPointeeType))) {
940 ConvertedType = ToType;
941 return true;
942 }
943
Douglas Gregorc7887512008-12-19 19:13:09 +0000944 // If we have pointers to pointers, recursively check whether this
945 // is an Objective-C conversion.
946 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
947 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
948 IncompatibleObjC)) {
949 // We always complain about this conversion.
950 IncompatibleObjC = true;
951 ConvertedType = ToType;
952 return true;
953 }
954
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000955 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +0000956 // differences in the argument and result types are in Objective-C
957 // pointer conversions. If so, we permit the conversion (but
958 // complain about it).
959 const FunctionTypeProto *FromFunctionType
960 = FromPointeeType->getAsFunctionTypeProto();
961 const FunctionTypeProto *ToFunctionType
962 = ToPointeeType->getAsFunctionTypeProto();
963 if (FromFunctionType && ToFunctionType) {
964 // If the function types are exactly the same, this isn't an
965 // Objective-C pointer conversion.
966 if (Context.getCanonicalType(FromPointeeType)
967 == Context.getCanonicalType(ToPointeeType))
968 return false;
969
970 // Perform the quick checks that will tell us whether these
971 // function types are obviously different.
972 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
973 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
974 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
975 return false;
976
977 bool HasObjCConversion = false;
978 if (Context.getCanonicalType(FromFunctionType->getResultType())
979 == Context.getCanonicalType(ToFunctionType->getResultType())) {
980 // Okay, the types match exactly. Nothing to do.
981 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
982 ToFunctionType->getResultType(),
983 ConvertedType, IncompatibleObjC)) {
984 // Okay, we have an Objective-C pointer conversion.
985 HasObjCConversion = true;
986 } else {
987 // Function types are too different. Abort.
988 return false;
989 }
990
991 // Check argument types.
992 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
993 ArgIdx != NumArgs; ++ArgIdx) {
994 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
995 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
996 if (Context.getCanonicalType(FromArgType)
997 == Context.getCanonicalType(ToArgType)) {
998 // Okay, the types match exactly. Nothing to do.
999 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1000 ConvertedType, IncompatibleObjC)) {
1001 // Okay, we have an Objective-C pointer conversion.
1002 HasObjCConversion = true;
1003 } else {
1004 // Argument types are too different. Abort.
1005 return false;
1006 }
1007 }
1008
1009 if (HasObjCConversion) {
1010 // We had an Objective-C conversion. Allow this pointer
1011 // conversion, but complain about it.
1012 ConvertedType = ToType;
1013 IncompatibleObjC = true;
1014 return true;
1015 }
1016 }
1017
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001018 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001019}
1020
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001021/// CheckPointerConversion - Check the pointer conversion from the
1022/// expression From to the type ToType. This routine checks for
1023/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
1024/// conversions for which IsPointerConversion has already returned
1025/// true. It returns true and produces a diagnostic if there was an
1026/// error, or returns false otherwise.
1027bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1028 QualType FromType = From->getType();
1029
1030 if (const PointerType *FromPtrType = FromType->getAsPointerType())
1031 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001032 QualType FromPointeeType = FromPtrType->getPointeeType(),
1033 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001034
1035 // Objective-C++ conversions are always okay.
1036 // FIXME: We should have a different class of conversions for
1037 // the Objective-C++ implicit conversions.
1038 if (Context.isObjCIdType(FromPointeeType) ||
1039 Context.isObjCIdType(ToPointeeType) ||
1040 Context.isObjCClassType(FromPointeeType) ||
1041 Context.isObjCClassType(ToPointeeType))
1042 return false;
1043
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001044 if (FromPointeeType->isRecordType() &&
1045 ToPointeeType->isRecordType()) {
1046 // We must have a derived-to-base conversion. Check an
1047 // ambiguous or inaccessible conversion.
Douglas Gregor0575d4a2008-10-24 16:17:19 +00001048 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1049 From->getExprLoc(),
1050 From->getSourceRange());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001051 }
1052 }
1053
1054 return false;
1055}
1056
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001057/// IsMemberPointerConversion - Determines whether the conversion of the
1058/// expression From, which has the (possibly adjusted) type FromType, can be
1059/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1060/// If so, returns true and places the converted type (that might differ from
1061/// ToType in its cv-qualifiers at some level) into ConvertedType.
1062bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1063 QualType ToType, QualType &ConvertedType)
1064{
1065 const MemberPointerType *ToTypePtr = ToType->getAsMemberPointerType();
1066 if (!ToTypePtr)
1067 return false;
1068
1069 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1070 if (From->isNullPointerConstant(Context)) {
1071 ConvertedType = ToType;
1072 return true;
1073 }
1074
1075 // Otherwise, both types have to be member pointers.
1076 const MemberPointerType *FromTypePtr = FromType->getAsMemberPointerType();
1077 if (!FromTypePtr)
1078 return false;
1079
1080 // A pointer to member of B can be converted to a pointer to member of D,
1081 // where D is derived from B (C++ 4.11p2).
1082 QualType FromClass(FromTypePtr->getClass(), 0);
1083 QualType ToClass(ToTypePtr->getClass(), 0);
1084 // FIXME: What happens when these are dependent? Is this function even called?
1085
1086 if (IsDerivedFrom(ToClass, FromClass)) {
1087 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1088 ToClass.getTypePtr());
1089 return true;
1090 }
1091
1092 return false;
1093}
1094
1095/// CheckMemberPointerConversion - Check the member pointer conversion from the
1096/// expression From to the type ToType. This routine checks for ambiguous or
1097/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1098/// for which IsMemberPointerConversion has already returned true. It returns
1099/// true and produces a diagnostic if there was an error, or returns false
1100/// otherwise.
1101bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType) {
1102 QualType FromType = From->getType();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001103 const MemberPointerType *FromPtrType = FromType->getAsMemberPointerType();
1104 if (!FromPtrType)
1105 return false;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001106
Sebastian Redl21593ac2009-01-28 18:33:18 +00001107 const MemberPointerType *ToPtrType = ToType->getAsMemberPointerType();
1108 assert(ToPtrType && "No member pointer cast has a target type "
1109 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001110
Sebastian Redl21593ac2009-01-28 18:33:18 +00001111 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1112 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001113
Sebastian Redl21593ac2009-01-28 18:33:18 +00001114 // FIXME: What about dependent types?
1115 assert(FromClass->isRecordType() && "Pointer into non-class.");
1116 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001117
Sebastian Redl21593ac2009-01-28 18:33:18 +00001118 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1119 /*DetectVirtual=*/true);
1120 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1121 assert(DerivationOkay &&
1122 "Should not have been called if derivation isn't OK.");
1123 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001124
Sebastian Redl21593ac2009-01-28 18:33:18 +00001125 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1126 getUnqualifiedType())) {
1127 // Derivation is ambiguous. Redo the check to find the exact paths.
1128 Paths.clear();
1129 Paths.setRecordingPaths(true);
1130 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1131 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1132 (void)StillOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001133
Sebastian Redl21593ac2009-01-28 18:33:18 +00001134 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1135 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1136 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1137 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001138 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001139
1140 if (const CXXRecordType *VBase = Paths.getDetectedVirtual()) {
1141 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1142 << FromClass << ToClass << QualType(VBase, 0)
1143 << From->getSourceRange();
1144 return true;
1145 }
1146
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001147 return false;
1148}
1149
Douglas Gregor98cd5992008-10-21 23:43:52 +00001150/// IsQualificationConversion - Determines whether the conversion from
1151/// an rvalue of type FromType to ToType is a qualification conversion
1152/// (C++ 4.4).
1153bool
1154Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1155{
1156 FromType = Context.getCanonicalType(FromType);
1157 ToType = Context.getCanonicalType(ToType);
1158
1159 // If FromType and ToType are the same type, this is not a
1160 // qualification conversion.
1161 if (FromType == ToType)
1162 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001163
Douglas Gregor98cd5992008-10-21 23:43:52 +00001164 // (C++ 4.4p4):
1165 // A conversion can add cv-qualifiers at levels other than the first
1166 // in multi-level pointers, subject to the following rules: [...]
1167 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001168 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001169 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001170 // Within each iteration of the loop, we check the qualifiers to
1171 // determine if this still looks like a qualification
1172 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001173 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001174 // until there are no more pointers or pointers-to-members left to
1175 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001176 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001177
1178 // -- for every j > 0, if const is in cv 1,j then const is in cv
1179 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001180 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001181 return false;
Douglas Gregor57373262008-10-22 14:17:15 +00001182
Douglas Gregor98cd5992008-10-21 23:43:52 +00001183 // -- if the cv 1,j and cv 2,j are different, then const is in
1184 // every cv for 0 < k < j.
1185 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001186 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001187 return false;
Douglas Gregor57373262008-10-22 14:17:15 +00001188
Douglas Gregor98cd5992008-10-21 23:43:52 +00001189 // Keep track of whether all prior cv-qualifiers in the "to" type
1190 // include const.
1191 PreviousToQualsIncludeConst
1192 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001193 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001194
1195 // We are left with FromType and ToType being the pointee types
1196 // after unwrapping the original FromType and ToType the same number
1197 // of types. If we unwrapped any pointers, and if FromType and
1198 // ToType have the same unqualified type (since we checked
1199 // qualifiers above), then this is a qualification conversion.
1200 return UnwrappedAnyPointer &&
1201 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1202}
1203
Douglas Gregor734d9862009-01-30 23:27:23 +00001204/// Determines whether there is a user-defined conversion sequence
1205/// (C++ [over.ics.user]) that converts expression From to the type
1206/// ToType. If such a conversion exists, User will contain the
1207/// user-defined conversion sequence that performs such a conversion
1208/// and this routine will return true. Otherwise, this routine returns
1209/// false and User is unspecified.
1210///
1211/// \param AllowConversionFunctions true if the conversion should
1212/// consider conversion functions at all. If false, only constructors
1213/// will be considered.
1214///
1215/// \param AllowExplicit true if the conversion should consider C++0x
1216/// "explicit" conversion functions as well as non-explicit conversion
1217/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001218bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001219 UserDefinedConversionSequence& User,
Douglas Gregor734d9862009-01-30 23:27:23 +00001220 bool AllowConversionFunctions,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001221 bool AllowExplicit)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001222{
1223 OverloadCandidateSet CandidateSet;
1224 if (const CXXRecordType *ToRecordType
1225 = dyn_cast_or_null<CXXRecordType>(ToType->getAsRecordType())) {
1226 // C++ [over.match.ctor]p1:
1227 // When objects of class type are direct-initialized (8.5), or
1228 // copy-initialized from an expression of the same or a
1229 // derived class type (8.5), overload resolution selects the
1230 // constructor. [...] For copy-initialization, the candidate
1231 // functions are all the converting constructors (12.3.1) of
1232 // that class. The argument list is the expression-list within
1233 // the parentheses of the initializer.
1234 CXXRecordDecl *ToRecordDecl = ToRecordType->getDecl();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001235 DeclarationName ConstructorName
1236 = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregore63ef482009-01-13 00:11:19 +00001237 Context.getCanonicalType(ToType).getUnqualifiedType());
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001238 DeclContext::lookup_iterator Con, ConEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00001239 for (llvm::tie(Con, ConEnd) = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001240 Con != ConEnd; ++Con) {
1241 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001242 if (Constructor->isConvertingConstructor())
Douglas Gregor225c41e2008-11-03 19:09:14 +00001243 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1244 /*SuppressUserConversions=*/true);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001245 }
1246 }
1247
Douglas Gregor734d9862009-01-30 23:27:23 +00001248 if (!AllowConversionFunctions) {
1249 // Don't allow any conversion functions to enter the overload set.
1250 } else if (const CXXRecordType *FromRecordType
1251 = dyn_cast_or_null<CXXRecordType>(
1252 From->getType()->getAsRecordType())) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001253 // Add all of the conversion functions as candidates.
1254 // FIXME: Look for conversions in base classes!
1255 CXXRecordDecl *FromRecordDecl = FromRecordType->getDecl();
1256 OverloadedFunctionDecl *Conversions
1257 = FromRecordDecl->getConversionFunctions();
1258 for (OverloadedFunctionDecl::function_iterator Func
1259 = Conversions->function_begin();
1260 Func != Conversions->function_end(); ++Func) {
1261 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001262 if (AllowExplicit || !Conv->isExplicit())
1263 AddConversionCandidate(Conv, From, ToType, CandidateSet);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001264 }
1265 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001266
1267 OverloadCandidateSet::iterator Best;
1268 switch (BestViableFunction(CandidateSet, Best)) {
1269 case OR_Success:
1270 // Record the standard conversion we used and the conversion function.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001271 if (CXXConstructorDecl *Constructor
1272 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1273 // C++ [over.ics.user]p1:
1274 // If the user-defined conversion is specified by a
1275 // constructor (12.3.1), the initial standard conversion
1276 // sequence converts the source type to the type required by
1277 // the argument of the constructor.
1278 //
1279 // FIXME: What about ellipsis conversions?
1280 QualType ThisType = Constructor->getThisType(Context);
1281 User.Before = Best->Conversions[0].Standard;
1282 User.ConversionFunction = Constructor;
1283 User.After.setAsIdentityConversion();
1284 User.After.FromTypePtr
1285 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
1286 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1287 return true;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001288 } else if (CXXConversionDecl *Conversion
1289 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1290 // C++ [over.ics.user]p1:
1291 //
1292 // [...] If the user-defined conversion is specified by a
1293 // conversion function (12.3.2), the initial standard
1294 // conversion sequence converts the source type to the
1295 // implicit object parameter of the conversion function.
1296 User.Before = Best->Conversions[0].Standard;
1297 User.ConversionFunction = Conversion;
1298
1299 // C++ [over.ics.user]p2:
1300 // The second standard conversion sequence converts the
1301 // result of the user-defined conversion to the target type
1302 // for the sequence. Since an implicit conversion sequence
1303 // is an initialization, the special rules for
1304 // initialization by user-defined conversion apply when
1305 // selecting the best user-defined conversion for a
1306 // user-defined conversion sequence (see 13.3.3 and
1307 // 13.3.3.1).
1308 User.After = Best->FinalConversion;
1309 return true;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001310 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001311 assert(false && "Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001312 return false;
1313 }
1314
1315 case OR_No_Viable_Function:
1316 // No conversion here! We're done.
1317 return false;
1318
1319 case OR_Ambiguous:
1320 // FIXME: See C++ [over.best.ics]p10 for the handling of
1321 // ambiguous conversion sequences.
1322 return false;
1323 }
1324
1325 return false;
1326}
1327
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001328/// CompareImplicitConversionSequences - Compare two implicit
1329/// conversion sequences to determine whether one is better than the
1330/// other or if they are indistinguishable (C++ 13.3.3.2).
1331ImplicitConversionSequence::CompareKind
1332Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1333 const ImplicitConversionSequence& ICS2)
1334{
1335 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1336 // conversion sequences (as defined in 13.3.3.1)
1337 // -- a standard conversion sequence (13.3.3.1.1) is a better
1338 // conversion sequence than a user-defined conversion sequence or
1339 // an ellipsis conversion sequence, and
1340 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1341 // conversion sequence than an ellipsis conversion sequence
1342 // (13.3.3.1.3).
1343 //
1344 if (ICS1.ConversionKind < ICS2.ConversionKind)
1345 return ImplicitConversionSequence::Better;
1346 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1347 return ImplicitConversionSequence::Worse;
1348
1349 // Two implicit conversion sequences of the same form are
1350 // indistinguishable conversion sequences unless one of the
1351 // following rules apply: (C++ 13.3.3.2p3):
1352 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1353 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1354 else if (ICS1.ConversionKind ==
1355 ImplicitConversionSequence::UserDefinedConversion) {
1356 // User-defined conversion sequence U1 is a better conversion
1357 // sequence than another user-defined conversion sequence U2 if
1358 // they contain the same user-defined conversion function or
1359 // constructor and if the second standard conversion sequence of
1360 // U1 is better than the second standard conversion sequence of
1361 // U2 (C++ 13.3.3.2p3).
1362 if (ICS1.UserDefined.ConversionFunction ==
1363 ICS2.UserDefined.ConversionFunction)
1364 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1365 ICS2.UserDefined.After);
1366 }
1367
1368 return ImplicitConversionSequence::Indistinguishable;
1369}
1370
1371/// CompareStandardConversionSequences - Compare two standard
1372/// conversion sequences to determine whether one is better than the
1373/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1374ImplicitConversionSequence::CompareKind
1375Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1376 const StandardConversionSequence& SCS2)
1377{
1378 // Standard conversion sequence S1 is a better conversion sequence
1379 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1380
1381 // -- S1 is a proper subsequence of S2 (comparing the conversion
1382 // sequences in the canonical form defined by 13.3.3.1.1,
1383 // excluding any Lvalue Transformation; the identity conversion
1384 // sequence is considered to be a subsequence of any
1385 // non-identity conversion sequence) or, if not that,
1386 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1387 // Neither is a proper subsequence of the other. Do nothing.
1388 ;
1389 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1390 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1391 (SCS1.Second == ICK_Identity &&
1392 SCS1.Third == ICK_Identity))
1393 // SCS1 is a proper subsequence of SCS2.
1394 return ImplicitConversionSequence::Better;
1395 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1396 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1397 (SCS2.Second == ICK_Identity &&
1398 SCS2.Third == ICK_Identity))
1399 // SCS2 is a proper subsequence of SCS1.
1400 return ImplicitConversionSequence::Worse;
1401
1402 // -- the rank of S1 is better than the rank of S2 (by the rules
1403 // defined below), or, if not that,
1404 ImplicitConversionRank Rank1 = SCS1.getRank();
1405 ImplicitConversionRank Rank2 = SCS2.getRank();
1406 if (Rank1 < Rank2)
1407 return ImplicitConversionSequence::Better;
1408 else if (Rank2 < Rank1)
1409 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001410
Douglas Gregor57373262008-10-22 14:17:15 +00001411 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1412 // are indistinguishable unless one of the following rules
1413 // applies:
1414
1415 // A conversion that is not a conversion of a pointer, or
1416 // pointer to member, to bool is better than another conversion
1417 // that is such a conversion.
1418 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1419 return SCS2.isPointerConversionToBool()
1420 ? ImplicitConversionSequence::Better
1421 : ImplicitConversionSequence::Worse;
1422
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001423 // C++ [over.ics.rank]p4b2:
1424 //
1425 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001426 // conversion of B* to A* is better than conversion of B* to
1427 // void*, and conversion of A* to void* is better than conversion
1428 // of B* to void*.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001429 bool SCS1ConvertsToVoid
1430 = SCS1.isPointerConversionToVoidPointer(Context);
1431 bool SCS2ConvertsToVoid
1432 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001433 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1434 // Exactly one of the conversion sequences is a conversion to
1435 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001436 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1437 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001438 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1439 // Neither conversion sequence converts to a void pointer; compare
1440 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001441 if (ImplicitConversionSequence::CompareKind DerivedCK
1442 = CompareDerivedToBaseConversions(SCS1, SCS2))
1443 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001444 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1445 // Both conversion sequences are conversions to void
1446 // pointers. Compare the source types to determine if there's an
1447 // inheritance relationship in their sources.
1448 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1449 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1450
1451 // Adjust the types we're converting from via the array-to-pointer
1452 // conversion, if we need to.
1453 if (SCS1.First == ICK_Array_To_Pointer)
1454 FromType1 = Context.getArrayDecayedType(FromType1);
1455 if (SCS2.First == ICK_Array_To_Pointer)
1456 FromType2 = Context.getArrayDecayedType(FromType2);
1457
1458 QualType FromPointee1
1459 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1460 QualType FromPointee2
1461 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1462
1463 if (IsDerivedFrom(FromPointee2, FromPointee1))
1464 return ImplicitConversionSequence::Better;
1465 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1466 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001467
1468 // Objective-C++: If one interface is more specific than the
1469 // other, it is the better one.
1470 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1471 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1472 if (FromIface1 && FromIface1) {
1473 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1474 return ImplicitConversionSequence::Better;
1475 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1476 return ImplicitConversionSequence::Worse;
1477 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001478 }
Douglas Gregor57373262008-10-22 14:17:15 +00001479
1480 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1481 // bullet 3).
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001482 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001483 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001484 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001485
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001486 // C++ [over.ics.rank]p3b4:
1487 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1488 // which the references refer are the same type except for
1489 // top-level cv-qualifiers, and the type to which the reference
1490 // initialized by S2 refers is more cv-qualified than the type
1491 // to which the reference initialized by S1 refers.
1492 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1493 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1494 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1495 T1 = Context.getCanonicalType(T1);
1496 T2 = Context.getCanonicalType(T2);
1497 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1498 if (T2.isMoreQualifiedThan(T1))
1499 return ImplicitConversionSequence::Better;
1500 else if (T1.isMoreQualifiedThan(T2))
1501 return ImplicitConversionSequence::Worse;
1502 }
1503 }
Douglas Gregor57373262008-10-22 14:17:15 +00001504
1505 return ImplicitConversionSequence::Indistinguishable;
1506}
1507
1508/// CompareQualificationConversions - Compares two standard conversion
1509/// sequences to determine whether they can be ranked based on their
1510/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1511ImplicitConversionSequence::CompareKind
1512Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1513 const StandardConversionSequence& SCS2)
1514{
Douglas Gregorba7e2102008-10-22 15:04:37 +00001515 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001516 // -- S1 and S2 differ only in their qualification conversion and
1517 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1518 // cv-qualification signature of type T1 is a proper subset of
1519 // the cv-qualification signature of type T2, and S1 is not the
1520 // deprecated string literal array-to-pointer conversion (4.2).
1521 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1522 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1523 return ImplicitConversionSequence::Indistinguishable;
1524
1525 // FIXME: the example in the standard doesn't use a qualification
1526 // conversion (!)
1527 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1528 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1529 T1 = Context.getCanonicalType(T1);
1530 T2 = Context.getCanonicalType(T2);
1531
1532 // If the types are the same, we won't learn anything by unwrapped
1533 // them.
1534 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1535 return ImplicitConversionSequence::Indistinguishable;
1536
1537 ImplicitConversionSequence::CompareKind Result
1538 = ImplicitConversionSequence::Indistinguishable;
1539 while (UnwrapSimilarPointerTypes(T1, T2)) {
1540 // Within each iteration of the loop, we check the qualifiers to
1541 // determine if this still looks like a qualification
1542 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001543 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001544 // until there are no more pointers or pointers-to-members left
1545 // to unwrap. This essentially mimics what
1546 // IsQualificationConversion does, but here we're checking for a
1547 // strict subset of qualifiers.
1548 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1549 // The qualifiers are the same, so this doesn't tell us anything
1550 // about how the sequences rank.
1551 ;
1552 else if (T2.isMoreQualifiedThan(T1)) {
1553 // T1 has fewer qualifiers, so it could be the better sequence.
1554 if (Result == ImplicitConversionSequence::Worse)
1555 // Neither has qualifiers that are a subset of the other's
1556 // qualifiers.
1557 return ImplicitConversionSequence::Indistinguishable;
1558
1559 Result = ImplicitConversionSequence::Better;
1560 } else if (T1.isMoreQualifiedThan(T2)) {
1561 // T2 has fewer qualifiers, so it could be the better sequence.
1562 if (Result == ImplicitConversionSequence::Better)
1563 // Neither has qualifiers that are a subset of the other's
1564 // qualifiers.
1565 return ImplicitConversionSequence::Indistinguishable;
1566
1567 Result = ImplicitConversionSequence::Worse;
1568 } else {
1569 // Qualifiers are disjoint.
1570 return ImplicitConversionSequence::Indistinguishable;
1571 }
1572
1573 // If the types after this point are equivalent, we're done.
1574 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1575 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001576 }
1577
Douglas Gregor57373262008-10-22 14:17:15 +00001578 // Check that the winning standard conversion sequence isn't using
1579 // the deprecated string literal array to pointer conversion.
1580 switch (Result) {
1581 case ImplicitConversionSequence::Better:
1582 if (SCS1.Deprecated)
1583 Result = ImplicitConversionSequence::Indistinguishable;
1584 break;
1585
1586 case ImplicitConversionSequence::Indistinguishable:
1587 break;
1588
1589 case ImplicitConversionSequence::Worse:
1590 if (SCS2.Deprecated)
1591 Result = ImplicitConversionSequence::Indistinguishable;
1592 break;
1593 }
1594
1595 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001596}
1597
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001598/// CompareDerivedToBaseConversions - Compares two standard conversion
1599/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00001600/// various kinds of derived-to-base conversions (C++
1601/// [over.ics.rank]p4b3). As part of these checks, we also look at
1602/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001603ImplicitConversionSequence::CompareKind
1604Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1605 const StandardConversionSequence& SCS2) {
1606 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1607 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1608 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1609 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1610
1611 // Adjust the types we're converting from via the array-to-pointer
1612 // conversion, if we need to.
1613 if (SCS1.First == ICK_Array_To_Pointer)
1614 FromType1 = Context.getArrayDecayedType(FromType1);
1615 if (SCS2.First == ICK_Array_To_Pointer)
1616 FromType2 = Context.getArrayDecayedType(FromType2);
1617
1618 // Canonicalize all of the types.
1619 FromType1 = Context.getCanonicalType(FromType1);
1620 ToType1 = Context.getCanonicalType(ToType1);
1621 FromType2 = Context.getCanonicalType(FromType2);
1622 ToType2 = Context.getCanonicalType(ToType2);
1623
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001624 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001625 //
1626 // If class B is derived directly or indirectly from class A and
1627 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001628 //
1629 // For Objective-C, we let A, B, and C also be Objective-C
1630 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001631
1632 // Compare based on pointer conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001633 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00001634 SCS2.Second == ICK_Pointer_Conversion &&
1635 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1636 FromType1->isPointerType() && FromType2->isPointerType() &&
1637 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001638 QualType FromPointee1
1639 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1640 QualType ToPointee1
1641 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1642 QualType FromPointee2
1643 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1644 QualType ToPointee2
1645 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001646
1647 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1648 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1649 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1650 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1651
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001652 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001653 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1654 if (IsDerivedFrom(ToPointee1, ToPointee2))
1655 return ImplicitConversionSequence::Better;
1656 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1657 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001658
1659 if (ToIface1 && ToIface2) {
1660 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1661 return ImplicitConversionSequence::Better;
1662 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1663 return ImplicitConversionSequence::Worse;
1664 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001665 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001666
1667 // -- conversion of B* to A* is better than conversion of C* to A*,
1668 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1669 if (IsDerivedFrom(FromPointee2, FromPointee1))
1670 return ImplicitConversionSequence::Better;
1671 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1672 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001673
1674 if (FromIface1 && FromIface2) {
1675 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1676 return ImplicitConversionSequence::Better;
1677 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1678 return ImplicitConversionSequence::Worse;
1679 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001680 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001681 }
1682
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001683 // Compare based on reference bindings.
1684 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1685 SCS1.Second == ICK_Derived_To_Base) {
1686 // -- binding of an expression of type C to a reference of type
1687 // B& is better than binding an expression of type C to a
1688 // reference of type A&,
1689 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1690 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1691 if (IsDerivedFrom(ToType1, ToType2))
1692 return ImplicitConversionSequence::Better;
1693 else if (IsDerivedFrom(ToType2, ToType1))
1694 return ImplicitConversionSequence::Worse;
1695 }
1696
Douglas Gregor225c41e2008-11-03 19:09:14 +00001697 // -- binding of an expression of type B to a reference of type
1698 // A& is better than binding an expression of type C to a
1699 // reference of type A&,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001700 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1701 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1702 if (IsDerivedFrom(FromType2, FromType1))
1703 return ImplicitConversionSequence::Better;
1704 else if (IsDerivedFrom(FromType1, FromType2))
1705 return ImplicitConversionSequence::Worse;
1706 }
1707 }
1708
1709
1710 // FIXME: conversion of A::* to B::* is better than conversion of
1711 // A::* to C::*,
1712
1713 // FIXME: conversion of B::* to C::* is better than conversion of
1714 // A::* to C::*, and
1715
Douglas Gregor225c41e2008-11-03 19:09:14 +00001716 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1717 SCS1.Second == ICK_Derived_To_Base) {
1718 // -- conversion of C to B is better than conversion of C to A,
1719 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1720 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1721 if (IsDerivedFrom(ToType1, ToType2))
1722 return ImplicitConversionSequence::Better;
1723 else if (IsDerivedFrom(ToType2, ToType1))
1724 return ImplicitConversionSequence::Worse;
1725 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001726
Douglas Gregor225c41e2008-11-03 19:09:14 +00001727 // -- conversion of B to A is better than conversion of C to A.
1728 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1729 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1730 if (IsDerivedFrom(FromType2, FromType1))
1731 return ImplicitConversionSequence::Better;
1732 else if (IsDerivedFrom(FromType1, FromType2))
1733 return ImplicitConversionSequence::Worse;
1734 }
1735 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001736
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001737 return ImplicitConversionSequence::Indistinguishable;
1738}
1739
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001740/// TryCopyInitialization - Try to copy-initialize a value of type
1741/// ToType from the expression From. Return the implicit conversion
1742/// sequence required to pass this argument, which may be a bad
1743/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00001744/// a parameter of this type). If @p SuppressUserConversions, then we
1745/// do not permit any user-defined conversion sequences.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001746ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +00001747Sema::TryCopyInitialization(Expr *From, QualType ToType,
1748 bool SuppressUserConversions) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001749 if (!getLangOptions().CPlusPlus) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001750 // In C, copy initialization is the same as performing an assignment.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001751 AssignConvertType ConvTy =
1752 CheckSingleAssignmentConstraints(ToType, From);
1753 ImplicitConversionSequence ICS;
1754 if (getLangOptions().NoExtensions? ConvTy != Compatible
1755 : ConvTy == Incompatible)
1756 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1757 else
1758 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1759 return ICS;
1760 } else if (ToType->isReferenceType()) {
1761 ImplicitConversionSequence ICS;
Douglas Gregor225c41e2008-11-03 19:09:14 +00001762 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001763 return ICS;
1764 } else {
Douglas Gregor225c41e2008-11-03 19:09:14 +00001765 return TryImplicitConversion(From, ToType, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001766 }
1767}
1768
1769/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1770/// type ToType. Returns true (and emits a diagnostic) if there was
1771/// an error, returns false if the initialization succeeded.
1772bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1773 const char* Flavor) {
1774 if (!getLangOptions().CPlusPlus) {
1775 // In C, argument passing is the same as performing an assignment.
1776 QualType FromType = From->getType();
1777 AssignConvertType ConvTy =
1778 CheckSingleAssignmentConstraints(ToType, From);
1779
1780 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1781 FromType, From, Flavor);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001782 }
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001783
1784 if (ToType->isReferenceType())
1785 return CheckReferenceInit(From, ToType);
1786
Douglas Gregor45920e82008-12-19 17:40:08 +00001787 if (!PerformImplicitConversion(From, ToType, Flavor))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001788 return false;
1789
1790 return Diag(From->getSourceRange().getBegin(),
1791 diag::err_typecheck_convert_incompatible)
1792 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001793}
1794
Douglas Gregor96176b32008-11-18 23:14:02 +00001795/// TryObjectArgumentInitialization - Try to initialize the object
1796/// parameter of the given member function (@c Method) from the
1797/// expression @p From.
1798ImplicitConversionSequence
1799Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1800 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1801 unsigned MethodQuals = Method->getTypeQualifiers();
1802 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1803
1804 // Set up the conversion sequence as a "bad" conversion, to allow us
1805 // to exit early.
1806 ImplicitConversionSequence ICS;
1807 ICS.Standard.setAsIdentityConversion();
1808 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1809
1810 // We need to have an object of class type.
1811 QualType FromType = From->getType();
1812 if (!FromType->isRecordType())
1813 return ICS;
1814
1815 // The implicit object parmeter is has the type "reference to cv X",
1816 // where X is the class of which the function is a member
1817 // (C++ [over.match.funcs]p4). However, when finding an implicit
1818 // conversion sequence for the argument, we are not allowed to
1819 // create temporaries or perform user-defined conversions
1820 // (C++ [over.match.funcs]p5). We perform a simplified version of
1821 // reference binding here, that allows class rvalues to bind to
1822 // non-constant references.
1823
1824 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1825 // with the implicit object parameter (C++ [over.match.funcs]p5).
1826 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1827 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1828 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1829 return ICS;
1830
1831 // Check that we have either the same type or a derived type. It
1832 // affects the conversion rank.
1833 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1834 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1835 ICS.Standard.Second = ICK_Identity;
1836 else if (IsDerivedFrom(FromType, ClassType))
1837 ICS.Standard.Second = ICK_Derived_To_Base;
1838 else
1839 return ICS;
1840
1841 // Success. Mark this as a reference binding.
1842 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1843 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1844 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1845 ICS.Standard.ReferenceBinding = true;
1846 ICS.Standard.DirectBinding = true;
1847 return ICS;
1848}
1849
1850/// PerformObjectArgumentInitialization - Perform initialization of
1851/// the implicit object parameter for the given Method with the given
1852/// expression.
1853bool
1854Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
1855 QualType ImplicitParamType
1856 = Method->getThisType(Context)->getAsPointerType()->getPointeeType();
1857 ImplicitConversionSequence ICS
1858 = TryObjectArgumentInitialization(From, Method);
1859 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
1860 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001861 diag::err_implicit_object_parameter_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00001862 << ImplicitParamType << From->getType() << From->getSourceRange();
Douglas Gregor96176b32008-11-18 23:14:02 +00001863
1864 if (ICS.Standard.Second == ICK_Derived_To_Base &&
1865 CheckDerivedToBaseConversion(From->getType(), ImplicitParamType,
1866 From->getSourceRange().getBegin(),
1867 From->getSourceRange()))
1868 return true;
1869
1870 ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true);
1871 return false;
1872}
1873
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001874/// TryContextuallyConvertToBool - Attempt to contextually convert the
1875/// expression From to bool (C++0x [conv]p3).
1876ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
1877 return TryImplicitConversion(From, Context.BoolTy, false, true);
1878}
1879
1880/// PerformContextuallyConvertToBool - Perform a contextual conversion
1881/// of the expression From to bool (C++0x [conv]p3).
1882bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
1883 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
1884 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
1885 return false;
1886
1887 return Diag(From->getSourceRange().getBegin(),
1888 diag::err_typecheck_bool_condition)
1889 << From->getType() << From->getSourceRange();
1890}
1891
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001892/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00001893/// candidate functions, using the given function call arguments. If
1894/// @p SuppressUserConversions, then don't allow user-defined
1895/// conversions via constructors or conversion operators.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001896void
1897Sema::AddOverloadCandidate(FunctionDecl *Function,
1898 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00001899 OverloadCandidateSet& CandidateSet,
1900 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001901{
1902 const FunctionTypeProto* Proto
1903 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType());
1904 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001905 assert(!isa<CXXConversionDecl>(Function) &&
1906 "Use AddConversionCandidate for conversion functions");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001907
Douglas Gregor88a35142008-12-22 05:46:06 +00001908 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
1909 // If we get here, it's because we're calling a member function
1910 // that is named without a member access expression (e.g.,
1911 // "this->f") that was either written explicitly or created
1912 // implicitly. This can happen with a qualified call to a member
1913 // function, e.g., X::f(). We use a NULL object as the implied
1914 // object argument (C++ [over.call.func]p3).
1915 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
1916 SuppressUserConversions);
1917 return;
1918 }
1919
1920
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001921 // Add this candidate
1922 CandidateSet.push_back(OverloadCandidate());
1923 OverloadCandidate& Candidate = CandidateSet.back();
1924 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00001925 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001926 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00001927 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001928
1929 unsigned NumArgsInProto = Proto->getNumArgs();
1930
1931 // (C++ 13.3.2p2): A candidate function having fewer than m
1932 // parameters is viable only if it has an ellipsis in its parameter
1933 // list (8.3.5).
1934 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1935 Candidate.Viable = false;
1936 return;
1937 }
1938
1939 // (C++ 13.3.2p2): A candidate function having more than m parameters
1940 // is viable only if the (m+1)st parameter has a default argument
1941 // (8.3.6). For the purposes of overload resolution, the
1942 // parameter list is truncated on the right, so that there are
1943 // exactly m parameters.
1944 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
1945 if (NumArgs < MinRequiredArgs) {
1946 // Not enough arguments.
1947 Candidate.Viable = false;
1948 return;
1949 }
1950
1951 // Determine the implicit conversion sequences for each of the
1952 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001953 Candidate.Conversions.resize(NumArgs);
1954 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1955 if (ArgIdx < NumArgsInProto) {
1956 // (C++ 13.3.2p3): for F to be a viable function, there shall
1957 // exist for each argument an implicit conversion sequence
1958 // (13.3.3.1) that converts that argument to the corresponding
1959 // parameter of F.
1960 QualType ParamType = Proto->getArgType(ArgIdx);
1961 Candidate.Conversions[ArgIdx]
Douglas Gregor225c41e2008-11-03 19:09:14 +00001962 = TryCopyInitialization(Args[ArgIdx], ParamType,
1963 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001964 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00001965 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001966 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001967 break;
1968 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001969 } else {
1970 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1971 // argument for which there is no corresponding parameter is
1972 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1973 Candidate.Conversions[ArgIdx].ConversionKind
1974 = ImplicitConversionSequence::EllipsisConversion;
1975 }
1976 }
1977}
1978
Douglas Gregor96176b32008-11-18 23:14:02 +00001979/// AddMethodCandidate - Adds the given C++ member function to the set
1980/// of candidate functions, using the given function call arguments
1981/// and the object argument (@c Object). For example, in a call
1982/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
1983/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
1984/// allow user-defined conversions via constructors or conversion
1985/// operators.
1986void
1987Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
1988 Expr **Args, unsigned NumArgs,
1989 OverloadCandidateSet& CandidateSet,
1990 bool SuppressUserConversions)
1991{
1992 const FunctionTypeProto* Proto
1993 = dyn_cast<FunctionTypeProto>(Method->getType()->getAsFunctionType());
1994 assert(Proto && "Methods without a prototype cannot be overloaded");
1995 assert(!isa<CXXConversionDecl>(Method) &&
1996 "Use AddConversionCandidate for conversion functions");
1997
1998 // Add this candidate
1999 CandidateSet.push_back(OverloadCandidate());
2000 OverloadCandidate& Candidate = CandidateSet.back();
2001 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002002 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002003 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002004
2005 unsigned NumArgsInProto = Proto->getNumArgs();
2006
2007 // (C++ 13.3.2p2): A candidate function having fewer than m
2008 // parameters is viable only if it has an ellipsis in its parameter
2009 // list (8.3.5).
2010 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2011 Candidate.Viable = false;
2012 return;
2013 }
2014
2015 // (C++ 13.3.2p2): A candidate function having more than m parameters
2016 // is viable only if the (m+1)st parameter has a default argument
2017 // (8.3.6). For the purposes of overload resolution, the
2018 // parameter list is truncated on the right, so that there are
2019 // exactly m parameters.
2020 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2021 if (NumArgs < MinRequiredArgs) {
2022 // Not enough arguments.
2023 Candidate.Viable = false;
2024 return;
2025 }
2026
2027 Candidate.Viable = true;
2028 Candidate.Conversions.resize(NumArgs + 1);
2029
Douglas Gregor88a35142008-12-22 05:46:06 +00002030 if (Method->isStatic() || !Object)
2031 // The implicit object argument is ignored.
2032 Candidate.IgnoreObjectArgument = true;
2033 else {
2034 // Determine the implicit conversion sequence for the object
2035 // parameter.
2036 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2037 if (Candidate.Conversions[0].ConversionKind
2038 == ImplicitConversionSequence::BadConversion) {
2039 Candidate.Viable = false;
2040 return;
2041 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002042 }
2043
2044 // Determine the implicit conversion sequences for each of the
2045 // arguments.
2046 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2047 if (ArgIdx < NumArgsInProto) {
2048 // (C++ 13.3.2p3): for F to be a viable function, there shall
2049 // exist for each argument an implicit conversion sequence
2050 // (13.3.3.1) that converts that argument to the corresponding
2051 // parameter of F.
2052 QualType ParamType = Proto->getArgType(ArgIdx);
2053 Candidate.Conversions[ArgIdx + 1]
2054 = TryCopyInitialization(Args[ArgIdx], ParamType,
2055 SuppressUserConversions);
2056 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2057 == ImplicitConversionSequence::BadConversion) {
2058 Candidate.Viable = false;
2059 break;
2060 }
2061 } else {
2062 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2063 // argument for which there is no corresponding parameter is
2064 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2065 Candidate.Conversions[ArgIdx + 1].ConversionKind
2066 = ImplicitConversionSequence::EllipsisConversion;
2067 }
2068 }
2069}
2070
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002071/// AddConversionCandidate - Add a C++ conversion function as a
2072/// candidate in the candidate set (C++ [over.match.conv],
2073/// C++ [over.match.copy]). From is the expression we're converting from,
2074/// and ToType is the type that we're eventually trying to convert to
2075/// (which may or may not be the same type as the type that the
2076/// conversion function produces).
2077void
2078Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2079 Expr *From, QualType ToType,
2080 OverloadCandidateSet& CandidateSet) {
2081 // Add this candidate
2082 CandidateSet.push_back(OverloadCandidate());
2083 OverloadCandidate& Candidate = CandidateSet.back();
2084 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002085 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002086 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002087 Candidate.FinalConversion.setAsIdentityConversion();
2088 Candidate.FinalConversion.FromTypePtr
2089 = Conversion->getConversionType().getAsOpaquePtr();
2090 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2091
Douglas Gregor96176b32008-11-18 23:14:02 +00002092 // Determine the implicit conversion sequence for the implicit
2093 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002094 Candidate.Viable = true;
2095 Candidate.Conversions.resize(1);
Douglas Gregor96176b32008-11-18 23:14:02 +00002096 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002097
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002098 if (Candidate.Conversions[0].ConversionKind
2099 == ImplicitConversionSequence::BadConversion) {
2100 Candidate.Viable = false;
2101 return;
2102 }
2103
2104 // To determine what the conversion from the result of calling the
2105 // conversion function to the type we're eventually trying to
2106 // convert to (ToType), we need to synthesize a call to the
2107 // conversion function and attempt copy initialization from it. This
2108 // makes sure that we get the right semantics with respect to
2109 // lvalues/rvalues and the type. Fortunately, we can allocate this
2110 // call on the stack and we don't need its arguments to be
2111 // well-formed.
2112 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2113 SourceLocation());
2114 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002115 &ConversionRef, false);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002116 CallExpr Call(&ConversionFn, 0, 0,
2117 Conversion->getConversionType().getNonReferenceType(),
2118 SourceLocation());
2119 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2120 switch (ICS.ConversionKind) {
2121 case ImplicitConversionSequence::StandardConversion:
2122 Candidate.FinalConversion = ICS.Standard;
2123 break;
2124
2125 case ImplicitConversionSequence::BadConversion:
2126 Candidate.Viable = false;
2127 break;
2128
2129 default:
2130 assert(false &&
2131 "Can only end up with a standard conversion sequence or failure");
2132 }
2133}
2134
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002135/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2136/// converts the given @c Object to a function pointer via the
2137/// conversion function @c Conversion, and then attempts to call it
2138/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2139/// the type of function that we'll eventually be calling.
2140void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
2141 const FunctionTypeProto *Proto,
2142 Expr *Object, Expr **Args, unsigned NumArgs,
2143 OverloadCandidateSet& CandidateSet) {
2144 CandidateSet.push_back(OverloadCandidate());
2145 OverloadCandidate& Candidate = CandidateSet.back();
2146 Candidate.Function = 0;
2147 Candidate.Surrogate = Conversion;
2148 Candidate.Viable = true;
2149 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002150 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002151 Candidate.Conversions.resize(NumArgs + 1);
2152
2153 // Determine the implicit conversion sequence for the implicit
2154 // object parameter.
2155 ImplicitConversionSequence ObjectInit
2156 = TryObjectArgumentInitialization(Object, Conversion);
2157 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2158 Candidate.Viable = false;
2159 return;
2160 }
2161
2162 // The first conversion is actually a user-defined conversion whose
2163 // first conversion is ObjectInit's standard conversion (which is
2164 // effectively a reference binding). Record it as such.
2165 Candidate.Conversions[0].ConversionKind
2166 = ImplicitConversionSequence::UserDefinedConversion;
2167 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2168 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2169 Candidate.Conversions[0].UserDefined.After
2170 = Candidate.Conversions[0].UserDefined.Before;
2171 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2172
2173 // Find the
2174 unsigned NumArgsInProto = Proto->getNumArgs();
2175
2176 // (C++ 13.3.2p2): A candidate function having fewer than m
2177 // parameters is viable only if it has an ellipsis in its parameter
2178 // list (8.3.5).
2179 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2180 Candidate.Viable = false;
2181 return;
2182 }
2183
2184 // Function types don't have any default arguments, so just check if
2185 // we have enough arguments.
2186 if (NumArgs < NumArgsInProto) {
2187 // Not enough arguments.
2188 Candidate.Viable = false;
2189 return;
2190 }
2191
2192 // Determine the implicit conversion sequences for each of the
2193 // arguments.
2194 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2195 if (ArgIdx < NumArgsInProto) {
2196 // (C++ 13.3.2p3): for F to be a viable function, there shall
2197 // exist for each argument an implicit conversion sequence
2198 // (13.3.3.1) that converts that argument to the corresponding
2199 // parameter of F.
2200 QualType ParamType = Proto->getArgType(ArgIdx);
2201 Candidate.Conversions[ArgIdx + 1]
2202 = TryCopyInitialization(Args[ArgIdx], ParamType,
2203 /*SuppressUserConversions=*/false);
2204 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2205 == ImplicitConversionSequence::BadConversion) {
2206 Candidate.Viable = false;
2207 break;
2208 }
2209 } else {
2210 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2211 // argument for which there is no corresponding parameter is
2212 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2213 Candidate.Conversions[ArgIdx + 1].ConversionKind
2214 = ImplicitConversionSequence::EllipsisConversion;
2215 }
2216 }
2217}
2218
Douglas Gregor447b69e2008-11-19 03:25:36 +00002219/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2220/// an acceptable non-member overloaded operator for a call whose
2221/// arguments have types T1 (and, if non-empty, T2). This routine
2222/// implements the check in C++ [over.match.oper]p3b2 concerning
2223/// enumeration types.
2224static bool
2225IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2226 QualType T1, QualType T2,
2227 ASTContext &Context) {
2228 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2229 return true;
2230
2231 const FunctionTypeProto *Proto = Fn->getType()->getAsFunctionTypeProto();
2232 if (Proto->getNumArgs() < 1)
2233 return false;
2234
2235 if (T1->isEnumeralType()) {
2236 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
2237 if (Context.getCanonicalType(T1).getUnqualifiedType()
2238 == Context.getCanonicalType(ArgType).getUnqualifiedType())
2239 return true;
2240 }
2241
2242 if (Proto->getNumArgs() < 2)
2243 return false;
2244
2245 if (!T2.isNull() && T2->isEnumeralType()) {
2246 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
2247 if (Context.getCanonicalType(T2).getUnqualifiedType()
2248 == Context.getCanonicalType(ArgType).getUnqualifiedType())
2249 return true;
2250 }
2251
2252 return false;
2253}
2254
Douglas Gregor96176b32008-11-18 23:14:02 +00002255/// AddOperatorCandidates - Add the overloaded operator candidates for
2256/// the operator Op that was used in an operator expression such as "x
2257/// Op y". S is the scope in which the expression occurred (used for
2258/// name lookup of the operator), Args/NumArgs provides the operator
2259/// arguments, and CandidateSet will store the added overload
2260/// candidates. (C++ [over.match.oper]).
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002261bool Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
2262 SourceLocation OpLoc,
Douglas Gregor96176b32008-11-18 23:14:02 +00002263 Expr **Args, unsigned NumArgs,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002264 OverloadCandidateSet& CandidateSet,
2265 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002266 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2267
2268 // C++ [over.match.oper]p3:
2269 // For a unary operator @ with an operand of a type whose
2270 // cv-unqualified version is T1, and for a binary operator @ with
2271 // a left operand of a type whose cv-unqualified version is T1 and
2272 // a right operand of a type whose cv-unqualified version is T2,
2273 // three sets of candidate functions, designated member
2274 // candidates, non-member candidates and built-in candidates, are
2275 // constructed as follows:
2276 QualType T1 = Args[0]->getType();
2277 QualType T2;
2278 if (NumArgs > 1)
2279 T2 = Args[1]->getType();
2280
2281 // -- If T1 is a class type, the set of member candidates is the
2282 // result of the qualified lookup of T1::operator@
2283 // (13.3.1.1.1); otherwise, the set of member candidates is
2284 // empty.
2285 if (const RecordType *T1Rec = T1->getAsRecordType()) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002286 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00002287 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002288 Oper != OperEnd; ++Oper)
2289 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2290 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor96176b32008-11-18 23:14:02 +00002291 /*SuppressUserConversions=*/false);
Douglas Gregor96176b32008-11-18 23:14:02 +00002292 }
2293
2294 // -- The set of non-member candidates is the result of the
2295 // unqualified lookup of operator@ in the context of the
2296 // expression according to the usual rules for name lookup in
2297 // unqualified function calls (3.4.2) except that all member
2298 // functions are ignored. However, if no operand has a class
2299 // type, only those non-member functions in the lookup set
2300 // that have a first parameter of type T1 or “reference to
2301 // (possibly cv-qualified) T1”, when T1 is an enumeration
2302 // type, or (if there is a right operand) a second parameter
2303 // of type T2 or “reference to (possibly cv-qualified) T2”,
2304 // when T2 is an enumeration type, are candidate functions.
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002305 LookupResult Operators = LookupName(S, OpName, LookupOperatorName);
2306
2307 if (Operators.isAmbiguous())
2308 return DiagnoseAmbiguousLookup(Operators, OpName, OpLoc, OpRange);
2309 else if (Operators) {
2310 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2311 Op != OpEnd; ++Op) {
2312 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op))
2313 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
2314 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2315 /*SuppressUserConversions=*/false);
Douglas Gregor96176b32008-11-18 23:14:02 +00002316 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002317 }
2318
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002319 // Since the set of non-member candidates corresponds to
2320 // *unqualified* lookup of the operator name, we also perform
2321 // argument-dependent lookup (C++ [basic.lookup.argdep]).
2322 AddArgumentDependentLookupCandidates(OpName, Args, NumArgs, CandidateSet);
2323
Douglas Gregor96176b32008-11-18 23:14:02 +00002324 // Add builtin overload candidates (C++ [over.built]).
Douglas Gregor74253732008-11-19 15:42:04 +00002325 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002326
2327 return false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002328}
2329
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002330/// AddBuiltinCandidate - Add a candidate for a built-in
2331/// operator. ResultTy and ParamTys are the result and parameter types
2332/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002333/// arguments being passed to the candidate. IsAssignmentOperator
2334/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002335/// operator. NumContextualBoolArguments is the number of arguments
2336/// (at the beginning of the argument list) that will be contextually
2337/// converted to bool.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002338void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2339 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002340 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002341 bool IsAssignmentOperator,
2342 unsigned NumContextualBoolArguments) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002343 // Add this candidate
2344 CandidateSet.push_back(OverloadCandidate());
2345 OverloadCandidate& Candidate = CandidateSet.back();
2346 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00002347 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002348 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002349 Candidate.BuiltinTypes.ResultTy = ResultTy;
2350 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2351 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2352
2353 // Determine the implicit conversion sequences for each of the
2354 // arguments.
2355 Candidate.Viable = true;
2356 Candidate.Conversions.resize(NumArgs);
2357 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002358 // C++ [over.match.oper]p4:
2359 // For the built-in assignment operators, conversions of the
2360 // left operand are restricted as follows:
2361 // -- no temporaries are introduced to hold the left operand, and
2362 // -- no user-defined conversions are applied to the left
2363 // operand to achieve a type match with the left-most
2364 // parameter of a built-in candidate.
2365 //
2366 // We block these conversions by turning off user-defined
2367 // conversions, since that is the only way that initialization of
2368 // a reference to a non-class type can occur from something that
2369 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002370 if (ArgIdx < NumContextualBoolArguments) {
2371 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2372 "Contextual conversion to bool requires bool type");
2373 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2374 } else {
2375 Candidate.Conversions[ArgIdx]
2376 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2377 ArgIdx == 0 && IsAssignmentOperator);
2378 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002379 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002380 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002381 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002382 break;
2383 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002384 }
2385}
2386
2387/// BuiltinCandidateTypeSet - A set of types that will be used for the
2388/// candidate operator functions for built-in operators (C++
2389/// [over.built]). The types are separated into pointer types and
2390/// enumeration types.
2391class BuiltinCandidateTypeSet {
2392 /// TypeSet - A set of types.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002393 typedef llvm::SmallPtrSet<void*, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002394
2395 /// PointerTypes - The set of pointer types that will be used in the
2396 /// built-in candidates.
2397 TypeSet PointerTypes;
2398
2399 /// EnumerationTypes - The set of enumeration types that will be
2400 /// used in the built-in candidates.
2401 TypeSet EnumerationTypes;
2402
2403 /// Context - The AST context in which we will build the type sets.
2404 ASTContext &Context;
2405
2406 bool AddWithMoreQualifiedTypeVariants(QualType Ty);
2407
2408public:
2409 /// iterator - Iterates through the types that are part of the set.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002410 class iterator {
2411 TypeSet::iterator Base;
2412
2413 public:
2414 typedef QualType value_type;
2415 typedef QualType reference;
2416 typedef QualType pointer;
2417 typedef std::ptrdiff_t difference_type;
2418 typedef std::input_iterator_tag iterator_category;
2419
2420 iterator(TypeSet::iterator B) : Base(B) { }
2421
2422 iterator& operator++() {
2423 ++Base;
2424 return *this;
2425 }
2426
2427 iterator operator++(int) {
2428 iterator tmp(*this);
2429 ++(*this);
2430 return tmp;
2431 }
2432
2433 reference operator*() const {
2434 return QualType::getFromOpaquePtr(*Base);
2435 }
2436
2437 pointer operator->() const {
2438 return **this;
2439 }
2440
2441 friend bool operator==(iterator LHS, iterator RHS) {
2442 return LHS.Base == RHS.Base;
2443 }
2444
2445 friend bool operator!=(iterator LHS, iterator RHS) {
2446 return LHS.Base != RHS.Base;
2447 }
2448 };
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002449
2450 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2451
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002452 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2453 bool AllowExplicitConversions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002454
2455 /// pointer_begin - First pointer type found;
2456 iterator pointer_begin() { return PointerTypes.begin(); }
2457
2458 /// pointer_end - Last pointer type found;
2459 iterator pointer_end() { return PointerTypes.end(); }
2460
2461 /// enumeration_begin - First enumeration type found;
2462 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2463
2464 /// enumeration_end - Last enumeration type found;
2465 iterator enumeration_end() { return EnumerationTypes.end(); }
2466};
2467
2468/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2469/// the set of pointer types along with any more-qualified variants of
2470/// that type. For example, if @p Ty is "int const *", this routine
2471/// will add "int const *", "int const volatile *", "int const
2472/// restrict *", and "int const volatile restrict *" to the set of
2473/// pointer types. Returns true if the add of @p Ty itself succeeded,
2474/// false otherwise.
2475bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) {
2476 // Insert this type.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002477 if (!PointerTypes.insert(Ty.getAsOpaquePtr()))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002478 return false;
2479
2480 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2481 QualType PointeeTy = PointerTy->getPointeeType();
2482 // FIXME: Optimize this so that we don't keep trying to add the same types.
2483
2484 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
2485 // with all pointer conversions that don't cast away constness?
2486 if (!PointeeTy.isConstQualified())
2487 AddWithMoreQualifiedTypeVariants
2488 (Context.getPointerType(PointeeTy.withConst()));
2489 if (!PointeeTy.isVolatileQualified())
2490 AddWithMoreQualifiedTypeVariants
2491 (Context.getPointerType(PointeeTy.withVolatile()));
2492 if (!PointeeTy.isRestrictQualified())
2493 AddWithMoreQualifiedTypeVariants
2494 (Context.getPointerType(PointeeTy.withRestrict()));
2495 }
2496
2497 return true;
2498}
2499
2500/// AddTypesConvertedFrom - Add each of the types to which the type @p
2501/// Ty can be implicit converted to the given set of @p Types. We're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002502/// primarily interested in pointer types and enumeration types.
2503/// AllowUserConversions is true if we should look at the conversion
2504/// functions of a class type, and AllowExplicitConversions if we
2505/// should also include the explicit conversion functions of a class
2506/// type.
2507void
2508BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2509 bool AllowUserConversions,
2510 bool AllowExplicitConversions) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002511 // Only deal with canonical types.
2512 Ty = Context.getCanonicalType(Ty);
2513
2514 // Look through reference types; they aren't part of the type of an
2515 // expression for the purposes of conversions.
2516 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2517 Ty = RefTy->getPointeeType();
2518
2519 // We don't care about qualifiers on the type.
2520 Ty = Ty.getUnqualifiedType();
2521
2522 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2523 QualType PointeeTy = PointerTy->getPointeeType();
2524
2525 // Insert our type, and its more-qualified variants, into the set
2526 // of types.
2527 if (!AddWithMoreQualifiedTypeVariants(Ty))
2528 return;
2529
2530 // Add 'cv void*' to our set of types.
2531 if (!Ty->isVoidType()) {
2532 QualType QualVoid
2533 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2534 AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2535 }
2536
2537 // If this is a pointer to a class type, add pointers to its bases
2538 // (with the same level of cv-qualification as the original
2539 // derived class, of course).
2540 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2541 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2542 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2543 Base != ClassDecl->bases_end(); ++Base) {
2544 QualType BaseTy = Context.getCanonicalType(Base->getType());
2545 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2546
2547 // Add the pointer type, recursively, so that we get all of
2548 // the indirect base classes, too.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002549 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002550 }
2551 }
2552 } else if (Ty->isEnumeralType()) {
Douglas Gregorbf3af052008-11-13 20:12:29 +00002553 EnumerationTypes.insert(Ty.getAsOpaquePtr());
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002554 } else if (AllowUserConversions) {
2555 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2556 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2557 // FIXME: Visit conversion functions in the base classes, too.
2558 OverloadedFunctionDecl *Conversions
2559 = ClassDecl->getConversionFunctions();
2560 for (OverloadedFunctionDecl::function_iterator Func
2561 = Conversions->function_begin();
2562 Func != Conversions->function_end(); ++Func) {
2563 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002564 if (AllowExplicitConversions || !Conv->isExplicit())
2565 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002566 }
2567 }
2568 }
2569}
2570
Douglas Gregor74253732008-11-19 15:42:04 +00002571/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2572/// operator overloads to the candidate set (C++ [over.built]), based
2573/// on the operator @p Op and the arguments given. For example, if the
2574/// operator is a binary '+', this routine might add "int
2575/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002576void
Douglas Gregor74253732008-11-19 15:42:04 +00002577Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2578 Expr **Args, unsigned NumArgs,
2579 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002580 // The set of "promoted arithmetic types", which are the arithmetic
2581 // types are that preserved by promotion (C++ [over.built]p2). Note
2582 // that the first few of these types are the promoted integral
2583 // types; these types need to be first.
2584 // FIXME: What about complex?
2585 const unsigned FirstIntegralType = 0;
2586 const unsigned LastIntegralType = 13;
2587 const unsigned FirstPromotedIntegralType = 7,
2588 LastPromotedIntegralType = 13;
2589 const unsigned FirstPromotedArithmeticType = 7,
2590 LastPromotedArithmeticType = 16;
2591 const unsigned NumArithmeticTypes = 16;
2592 QualType ArithmeticTypes[NumArithmeticTypes] = {
2593 Context.BoolTy, Context.CharTy, Context.WCharTy,
2594 Context.SignedCharTy, Context.ShortTy,
2595 Context.UnsignedCharTy, Context.UnsignedShortTy,
2596 Context.IntTy, Context.LongTy, Context.LongLongTy,
2597 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2598 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2599 };
2600
2601 // Find all of the types that the arguments can convert to, but only
2602 // if the operator we're looking at has built-in operator candidates
2603 // that make use of these types.
2604 BuiltinCandidateTypeSet CandidateTypes(Context);
2605 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2606 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00002607 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002608 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00002609 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
2610 (Op == OO_Star && NumArgs == 1)) {
2611 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002612 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2613 true,
2614 (Op == OO_Exclaim ||
2615 Op == OO_AmpAmp ||
2616 Op == OO_PipePipe));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002617 }
2618
2619 bool isComparison = false;
2620 switch (Op) {
2621 case OO_None:
2622 case NUM_OVERLOADED_OPERATORS:
2623 assert(false && "Expected an overloaded operator");
2624 break;
2625
Douglas Gregor74253732008-11-19 15:42:04 +00002626 case OO_Star: // '*' is either unary or binary
2627 if (NumArgs == 1)
2628 goto UnaryStar;
2629 else
2630 goto BinaryStar;
2631 break;
2632
2633 case OO_Plus: // '+' is either unary or binary
2634 if (NumArgs == 1)
2635 goto UnaryPlus;
2636 else
2637 goto BinaryPlus;
2638 break;
2639
2640 case OO_Minus: // '-' is either unary or binary
2641 if (NumArgs == 1)
2642 goto UnaryMinus;
2643 else
2644 goto BinaryMinus;
2645 break;
2646
2647 case OO_Amp: // '&' is either unary or binary
2648 if (NumArgs == 1)
2649 goto UnaryAmp;
2650 else
2651 goto BinaryAmp;
2652
2653 case OO_PlusPlus:
2654 case OO_MinusMinus:
2655 // C++ [over.built]p3:
2656 //
2657 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2658 // is either volatile or empty, there exist candidate operator
2659 // functions of the form
2660 //
2661 // VQ T& operator++(VQ T&);
2662 // T operator++(VQ T&, int);
2663 //
2664 // C++ [over.built]p4:
2665 //
2666 // For every pair (T, VQ), where T is an arithmetic type other
2667 // than bool, and VQ is either volatile or empty, there exist
2668 // candidate operator functions of the form
2669 //
2670 // VQ T& operator--(VQ T&);
2671 // T operator--(VQ T&, int);
2672 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2673 Arith < NumArithmeticTypes; ++Arith) {
2674 QualType ArithTy = ArithmeticTypes[Arith];
2675 QualType ParamTypes[2]
2676 = { Context.getReferenceType(ArithTy), Context.IntTy };
2677
2678 // Non-volatile version.
2679 if (NumArgs == 1)
2680 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2681 else
2682 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2683
2684 // Volatile version
2685 ParamTypes[0] = Context.getReferenceType(ArithTy.withVolatile());
2686 if (NumArgs == 1)
2687 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2688 else
2689 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2690 }
2691
2692 // C++ [over.built]p5:
2693 //
2694 // For every pair (T, VQ), where T is a cv-qualified or
2695 // cv-unqualified object type, and VQ is either volatile or
2696 // empty, there exist candidate operator functions of the form
2697 //
2698 // T*VQ& operator++(T*VQ&);
2699 // T*VQ& operator--(T*VQ&);
2700 // T* operator++(T*VQ&, int);
2701 // T* operator--(T*VQ&, int);
2702 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2703 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2704 // Skip pointer types that aren't pointers to object types.
Douglas Gregorcb7de522008-11-26 23:31:11 +00002705 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00002706 continue;
2707
2708 QualType ParamTypes[2] = {
2709 Context.getReferenceType(*Ptr), Context.IntTy
2710 };
2711
2712 // Without volatile
2713 if (NumArgs == 1)
2714 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2715 else
2716 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2717
2718 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2719 // With volatile
2720 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2721 if (NumArgs == 1)
2722 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2723 else
2724 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2725 }
2726 }
2727 break;
2728
2729 UnaryStar:
2730 // C++ [over.built]p6:
2731 // For every cv-qualified or cv-unqualified object type T, there
2732 // exist candidate operator functions of the form
2733 //
2734 // T& operator*(T*);
2735 //
2736 // C++ [over.built]p7:
2737 // For every function type T, there exist candidate operator
2738 // functions of the form
2739 // T& operator*(T*);
2740 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2741 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2742 QualType ParamTy = *Ptr;
2743 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
2744 AddBuiltinCandidate(Context.getReferenceType(PointeeTy),
2745 &ParamTy, Args, 1, CandidateSet);
2746 }
2747 break;
2748
2749 UnaryPlus:
2750 // C++ [over.built]p8:
2751 // For every type T, there exist candidate operator functions of
2752 // the form
2753 //
2754 // T* operator+(T*);
2755 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2756 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2757 QualType ParamTy = *Ptr;
2758 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2759 }
2760
2761 // Fall through
2762
2763 UnaryMinus:
2764 // C++ [over.built]p9:
2765 // For every promoted arithmetic type T, there exist candidate
2766 // operator functions of the form
2767 //
2768 // T operator+(T);
2769 // T operator-(T);
2770 for (unsigned Arith = FirstPromotedArithmeticType;
2771 Arith < LastPromotedArithmeticType; ++Arith) {
2772 QualType ArithTy = ArithmeticTypes[Arith];
2773 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2774 }
2775 break;
2776
2777 case OO_Tilde:
2778 // C++ [over.built]p10:
2779 // For every promoted integral type T, there exist candidate
2780 // operator functions of the form
2781 //
2782 // T operator~(T);
2783 for (unsigned Int = FirstPromotedIntegralType;
2784 Int < LastPromotedIntegralType; ++Int) {
2785 QualType IntTy = ArithmeticTypes[Int];
2786 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2787 }
2788 break;
2789
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002790 case OO_New:
2791 case OO_Delete:
2792 case OO_Array_New:
2793 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002794 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00002795 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002796 break;
2797
2798 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00002799 UnaryAmp:
2800 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002801 // C++ [over.match.oper]p3:
2802 // -- For the operator ',', the unary operator '&', or the
2803 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002804 break;
2805
2806 case OO_Less:
2807 case OO_Greater:
2808 case OO_LessEqual:
2809 case OO_GreaterEqual:
2810 case OO_EqualEqual:
2811 case OO_ExclaimEqual:
2812 // C++ [over.built]p15:
2813 //
2814 // For every pointer or enumeration type T, there exist
2815 // candidate operator functions of the form
2816 //
2817 // bool operator<(T, T);
2818 // bool operator>(T, T);
2819 // bool operator<=(T, T);
2820 // bool operator>=(T, T);
2821 // bool operator==(T, T);
2822 // bool operator!=(T, T);
2823 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2824 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2825 QualType ParamTypes[2] = { *Ptr, *Ptr };
2826 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2827 }
2828 for (BuiltinCandidateTypeSet::iterator Enum
2829 = CandidateTypes.enumeration_begin();
2830 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2831 QualType ParamTypes[2] = { *Enum, *Enum };
2832 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2833 }
2834
2835 // Fall through.
2836 isComparison = true;
2837
Douglas Gregor74253732008-11-19 15:42:04 +00002838 BinaryPlus:
2839 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002840 if (!isComparison) {
2841 // We didn't fall through, so we must have OO_Plus or OO_Minus.
2842
2843 // C++ [over.built]p13:
2844 //
2845 // For every cv-qualified or cv-unqualified object type T
2846 // there exist candidate operator functions of the form
2847 //
2848 // T* operator+(T*, ptrdiff_t);
2849 // T& operator[](T*, ptrdiff_t); [BELOW]
2850 // T* operator-(T*, ptrdiff_t);
2851 // T* operator+(ptrdiff_t, T*);
2852 // T& operator[](ptrdiff_t, T*); [BELOW]
2853 //
2854 // C++ [over.built]p14:
2855 //
2856 // For every T, where T is a pointer to object type, there
2857 // exist candidate operator functions of the form
2858 //
2859 // ptrdiff_t operator-(T, T);
2860 for (BuiltinCandidateTypeSet::iterator Ptr
2861 = CandidateTypes.pointer_begin();
2862 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2863 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2864
2865 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
2866 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2867
2868 if (Op == OO_Plus) {
2869 // T* operator+(ptrdiff_t, T*);
2870 ParamTypes[0] = ParamTypes[1];
2871 ParamTypes[1] = *Ptr;
2872 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2873 } else {
2874 // ptrdiff_t operator-(T, T);
2875 ParamTypes[1] = *Ptr;
2876 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
2877 Args, 2, CandidateSet);
2878 }
2879 }
2880 }
2881 // Fall through
2882
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002883 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00002884 BinaryStar:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002885 // C++ [over.built]p12:
2886 //
2887 // For every pair of promoted arithmetic types L and R, there
2888 // exist candidate operator functions of the form
2889 //
2890 // LR operator*(L, R);
2891 // LR operator/(L, R);
2892 // LR operator+(L, R);
2893 // LR operator-(L, R);
2894 // bool operator<(L, R);
2895 // bool operator>(L, R);
2896 // bool operator<=(L, R);
2897 // bool operator>=(L, R);
2898 // bool operator==(L, R);
2899 // bool operator!=(L, R);
2900 //
2901 // where LR is the result of the usual arithmetic conversions
2902 // between types L and R.
2903 for (unsigned Left = FirstPromotedArithmeticType;
2904 Left < LastPromotedArithmeticType; ++Left) {
2905 for (unsigned Right = FirstPromotedArithmeticType;
2906 Right < LastPromotedArithmeticType; ++Right) {
2907 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2908 QualType Result
2909 = isComparison? Context.BoolTy
2910 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2911 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2912 }
2913 }
2914 break;
2915
2916 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00002917 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002918 case OO_Caret:
2919 case OO_Pipe:
2920 case OO_LessLess:
2921 case OO_GreaterGreater:
2922 // C++ [over.built]p17:
2923 //
2924 // For every pair of promoted integral types L and R, there
2925 // exist candidate operator functions of the form
2926 //
2927 // LR operator%(L, R);
2928 // LR operator&(L, R);
2929 // LR operator^(L, R);
2930 // LR operator|(L, R);
2931 // L operator<<(L, R);
2932 // L operator>>(L, R);
2933 //
2934 // where LR is the result of the usual arithmetic conversions
2935 // between types L and R.
2936 for (unsigned Left = FirstPromotedIntegralType;
2937 Left < LastPromotedIntegralType; ++Left) {
2938 for (unsigned Right = FirstPromotedIntegralType;
2939 Right < LastPromotedIntegralType; ++Right) {
2940 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2941 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
2942 ? LandR[0]
2943 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2944 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2945 }
2946 }
2947 break;
2948
2949 case OO_Equal:
2950 // C++ [over.built]p20:
2951 //
2952 // For every pair (T, VQ), where T is an enumeration or
2953 // (FIXME:) pointer to member type and VQ is either volatile or
2954 // empty, there exist candidate operator functions of the form
2955 //
2956 // VQ T& operator=(VQ T&, T);
2957 for (BuiltinCandidateTypeSet::iterator Enum
2958 = CandidateTypes.enumeration_begin();
2959 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2960 QualType ParamTypes[2];
2961
2962 // T& operator=(T&, T)
2963 ParamTypes[0] = Context.getReferenceType(*Enum);
2964 ParamTypes[1] = *Enum;
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002965 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002966 /*IsAssignmentOperator=*/false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002967
Douglas Gregor74253732008-11-19 15:42:04 +00002968 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
2969 // volatile T& operator=(volatile T&, T)
2970 ParamTypes[0] = Context.getReferenceType((*Enum).withVolatile());
2971 ParamTypes[1] = *Enum;
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002972 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002973 /*IsAssignmentOperator=*/false);
Douglas Gregor74253732008-11-19 15:42:04 +00002974 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002975 }
2976 // Fall through.
2977
2978 case OO_PlusEqual:
2979 case OO_MinusEqual:
2980 // C++ [over.built]p19:
2981 //
2982 // For every pair (T, VQ), where T is any type and VQ is either
2983 // volatile or empty, there exist candidate operator functions
2984 // of the form
2985 //
2986 // T*VQ& operator=(T*VQ&, T*);
2987 //
2988 // C++ [over.built]p21:
2989 //
2990 // For every pair (T, VQ), where T is a cv-qualified or
2991 // cv-unqualified object type and VQ is either volatile or
2992 // empty, there exist candidate operator functions of the form
2993 //
2994 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
2995 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
2996 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2997 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2998 QualType ParamTypes[2];
2999 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3000
3001 // non-volatile version
3002 ParamTypes[0] = Context.getReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003003 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3004 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003005
Douglas Gregor74253732008-11-19 15:42:04 +00003006 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3007 // volatile version
3008 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003009 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3010 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00003011 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003012 }
3013 // Fall through.
3014
3015 case OO_StarEqual:
3016 case OO_SlashEqual:
3017 // C++ [over.built]p18:
3018 //
3019 // For every triple (L, VQ, R), where L is an arithmetic type,
3020 // VQ is either volatile or empty, and R is a promoted
3021 // arithmetic type, there exist candidate operator functions of
3022 // the form
3023 //
3024 // VQ L& operator=(VQ L&, R);
3025 // VQ L& operator*=(VQ L&, R);
3026 // VQ L& operator/=(VQ L&, R);
3027 // VQ L& operator+=(VQ L&, R);
3028 // VQ L& operator-=(VQ L&, R);
3029 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3030 for (unsigned Right = FirstPromotedArithmeticType;
3031 Right < LastPromotedArithmeticType; ++Right) {
3032 QualType ParamTypes[2];
3033 ParamTypes[1] = ArithmeticTypes[Right];
3034
3035 // Add this built-in operator as a candidate (VQ is empty).
3036 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003037 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3038 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003039
3040 // Add this built-in operator as a candidate (VQ is 'volatile').
3041 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
3042 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003043 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3044 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003045 }
3046 }
3047 break;
3048
3049 case OO_PercentEqual:
3050 case OO_LessLessEqual:
3051 case OO_GreaterGreaterEqual:
3052 case OO_AmpEqual:
3053 case OO_CaretEqual:
3054 case OO_PipeEqual:
3055 // C++ [over.built]p22:
3056 //
3057 // For every triple (L, VQ, R), where L is an integral type, VQ
3058 // is either volatile or empty, and R is a promoted integral
3059 // type, there exist candidate operator functions of the form
3060 //
3061 // VQ L& operator%=(VQ L&, R);
3062 // VQ L& operator<<=(VQ L&, R);
3063 // VQ L& operator>>=(VQ L&, R);
3064 // VQ L& operator&=(VQ L&, R);
3065 // VQ L& operator^=(VQ L&, R);
3066 // VQ L& operator|=(VQ L&, R);
3067 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3068 for (unsigned Right = FirstPromotedIntegralType;
3069 Right < LastPromotedIntegralType; ++Right) {
3070 QualType ParamTypes[2];
3071 ParamTypes[1] = ArithmeticTypes[Right];
3072
3073 // Add this built-in operator as a candidate (VQ is empty).
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003074 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
3075 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3076
3077 // Add this built-in operator as a candidate (VQ is 'volatile').
3078 ParamTypes[0] = ArithmeticTypes[Left];
3079 ParamTypes[0].addVolatile();
3080 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
3081 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3082 }
3083 }
3084 break;
3085
Douglas Gregor74253732008-11-19 15:42:04 +00003086 case OO_Exclaim: {
3087 // C++ [over.operator]p23:
3088 //
3089 // There also exist candidate operator functions of the form
3090 //
3091 // bool operator!(bool);
3092 // bool operator&&(bool, bool); [BELOW]
3093 // bool operator||(bool, bool); [BELOW]
3094 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003095 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3096 /*IsAssignmentOperator=*/false,
3097 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00003098 break;
3099 }
3100
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003101 case OO_AmpAmp:
3102 case OO_PipePipe: {
3103 // C++ [over.operator]p23:
3104 //
3105 // There also exist candidate operator functions of the form
3106 //
Douglas Gregor74253732008-11-19 15:42:04 +00003107 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003108 // bool operator&&(bool, bool);
3109 // bool operator||(bool, bool);
3110 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003111 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3112 /*IsAssignmentOperator=*/false,
3113 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003114 break;
3115 }
3116
3117 case OO_Subscript:
3118 // C++ [over.built]p13:
3119 //
3120 // For every cv-qualified or cv-unqualified object type T there
3121 // exist candidate operator functions of the form
3122 //
3123 // T* operator+(T*, ptrdiff_t); [ABOVE]
3124 // T& operator[](T*, ptrdiff_t);
3125 // T* operator-(T*, ptrdiff_t); [ABOVE]
3126 // T* operator+(ptrdiff_t, T*); [ABOVE]
3127 // T& operator[](ptrdiff_t, T*);
3128 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3129 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3130 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3131 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
3132 QualType ResultTy = Context.getReferenceType(PointeeType);
3133
3134 // T& operator[](T*, ptrdiff_t)
3135 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3136
3137 // T& operator[](ptrdiff_t, T*);
3138 ParamTypes[0] = ParamTypes[1];
3139 ParamTypes[1] = *Ptr;
3140 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3141 }
3142 break;
3143
3144 case OO_ArrowStar:
3145 // FIXME: No support for pointer-to-members yet.
3146 break;
3147 }
3148}
3149
Douglas Gregorfa047642009-02-04 00:32:51 +00003150/// \brief Add function candidates found via argument-dependent lookup
3151/// to the set of overloading candidates.
3152///
3153/// This routine performs argument-dependent name lookup based on the
3154/// given function name (which may also be an operator name) and adds
3155/// all of the overload candidates found by ADL to the overload
3156/// candidate set (C++ [basic.lookup.argdep]).
3157void
3158Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3159 Expr **Args, unsigned NumArgs,
3160 OverloadCandidateSet& CandidateSet) {
3161 // Find all of the associated namespaces and classes based on the
3162 // arguments we have.
3163 AssociatedNamespaceSet AssociatedNamespaces;
3164 AssociatedClassSet AssociatedClasses;
3165 FindAssociatedClassesAndNamespaces(Args, NumArgs,
3166 AssociatedNamespaces, AssociatedClasses);
3167
3168 // C++ [basic.lookup.argdep]p3:
3169 //
3170 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3171 // and let Y be the lookup set produced by argument dependent
3172 // lookup (defined as follows). If X contains [...] then Y is
3173 // empty. Otherwise Y is the set of declarations found in the
3174 // namespaces associated with the argument types as described
3175 // below. The set of declarations found by the lookup of the name
3176 // is the union of X and Y.
3177 //
3178 // Here, we compute Y and add its members to the overloaded
3179 // candidate set.
3180 llvm::SmallPtrSet<FunctionDecl *, 16> KnownCandidates;
3181 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
3182 NSEnd = AssociatedNamespaces.end();
3183 NS != NSEnd; ++NS) {
3184 // When considering an associated namespace, the lookup is the
3185 // same as the lookup performed when the associated namespace is
3186 // used as a qualifier (3.4.3.2) except that:
3187 //
3188 // -- Any using-directives in the associated namespace are
3189 // ignored.
3190 //
3191 // -- FIXME: Any namespace-scope friend functions declared in
3192 // associated classes are visible within their respective
3193 // namespaces even if they are not visible during an ordinary
3194 // lookup (11.4).
3195 DeclContext::lookup_iterator I, E;
3196 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
3197 FunctionDecl *Func = dyn_cast<FunctionDecl>(*I);
3198 if (!Func)
3199 break;
3200
3201 if (KnownCandidates.empty()) {
3202 // Record all of the function candidates that we've already
3203 // added to the overload set, so that we don't add those same
3204 // candidates a second time.
3205 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3206 CandEnd = CandidateSet.end();
3207 Cand != CandEnd; ++Cand)
3208 KnownCandidates.insert(Cand->Function);
3209 }
3210
3211 // If we haven't seen this function before, add it as a
3212 // candidate.
3213 if (KnownCandidates.insert(Func))
3214 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
3215 }
3216 }
3217}
3218
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003219/// isBetterOverloadCandidate - Determines whether the first overload
3220/// candidate is a better candidate than the second (C++ 13.3.3p1).
3221bool
3222Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3223 const OverloadCandidate& Cand2)
3224{
3225 // Define viable functions to be better candidates than non-viable
3226 // functions.
3227 if (!Cand2.Viable)
3228 return Cand1.Viable;
3229 else if (!Cand1.Viable)
3230 return false;
3231
Douglas Gregor88a35142008-12-22 05:46:06 +00003232 // C++ [over.match.best]p1:
3233 //
3234 // -- if F is a static member function, ICS1(F) is defined such
3235 // that ICS1(F) is neither better nor worse than ICS1(G) for
3236 // any function G, and, symmetrically, ICS1(G) is neither
3237 // better nor worse than ICS1(F).
3238 unsigned StartArg = 0;
3239 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3240 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003241
3242 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
3243 // function than another viable function F2 if for all arguments i,
3244 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
3245 // then...
3246 unsigned NumArgs = Cand1.Conversions.size();
3247 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3248 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003249 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003250 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3251 Cand2.Conversions[ArgIdx])) {
3252 case ImplicitConversionSequence::Better:
3253 // Cand1 has a better conversion sequence.
3254 HasBetterConversion = true;
3255 break;
3256
3257 case ImplicitConversionSequence::Worse:
3258 // Cand1 can't be better than Cand2.
3259 return false;
3260
3261 case ImplicitConversionSequence::Indistinguishable:
3262 // Do nothing.
3263 break;
3264 }
3265 }
3266
3267 if (HasBetterConversion)
3268 return true;
3269
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003270 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
3271 // implemented, but they require template support.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003272
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003273 // C++ [over.match.best]p1b4:
3274 //
3275 // -- the context is an initialization by user-defined conversion
3276 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3277 // from the return type of F1 to the destination type (i.e.,
3278 // the type of the entity being initialized) is a better
3279 // conversion sequence than the standard conversion sequence
3280 // from the return type of F2 to the destination type.
Douglas Gregor447b69e2008-11-19 03:25:36 +00003281 if (Cand1.Function && Cand2.Function &&
3282 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003283 isa<CXXConversionDecl>(Cand2.Function)) {
3284 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3285 Cand2.FinalConversion)) {
3286 case ImplicitConversionSequence::Better:
3287 // Cand1 has a better conversion sequence.
3288 return true;
3289
3290 case ImplicitConversionSequence::Worse:
3291 // Cand1 can't be better than Cand2.
3292 return false;
3293
3294 case ImplicitConversionSequence::Indistinguishable:
3295 // Do nothing
3296 break;
3297 }
3298 }
3299
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003300 return false;
3301}
3302
3303/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
3304/// within an overload candidate set. If overloading is successful,
3305/// the result will be OR_Success and Best will be set to point to the
3306/// best viable function within the candidate set. Otherwise, one of
3307/// several kinds of errors will be returned; see
3308/// Sema::OverloadingResult.
3309Sema::OverloadingResult
3310Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
3311 OverloadCandidateSet::iterator& Best)
3312{
3313 // Find the best viable function.
3314 Best = CandidateSet.end();
3315 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3316 Cand != CandidateSet.end(); ++Cand) {
3317 if (Cand->Viable) {
3318 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3319 Best = Cand;
3320 }
3321 }
3322
3323 // If we didn't find any viable functions, abort.
3324 if (Best == CandidateSet.end())
3325 return OR_No_Viable_Function;
3326
3327 // Make sure that this function is better than every other viable
3328 // function. If not, we have an ambiguity.
3329 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3330 Cand != CandidateSet.end(); ++Cand) {
3331 if (Cand->Viable &&
3332 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003333 !isBetterOverloadCandidate(*Best, *Cand)) {
3334 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003335 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003336 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003337 }
3338
3339 // Best is the best viable function.
3340 return OR_Success;
3341}
3342
3343/// PrintOverloadCandidates - When overload resolution fails, prints
3344/// diagnostic messages containing the candidates in the candidate
3345/// set. If OnlyViable is true, only viable candidates will be printed.
3346void
3347Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3348 bool OnlyViable)
3349{
3350 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3351 LastCand = CandidateSet.end();
3352 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003353 if (Cand->Viable || !OnlyViable) {
3354 if (Cand->Function) {
3355 // Normal function
3356 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003357 } else if (Cand->IsSurrogate) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003358 // Desugar the type of the surrogate down to a function type,
3359 // retaining as many typedefs as possible while still showing
3360 // the function type (and, therefore, its parameter types).
3361 QualType FnType = Cand->Surrogate->getConversionType();
3362 bool isReference = false;
3363 bool isPointer = false;
3364 if (const ReferenceType *FnTypeRef = FnType->getAsReferenceType()) {
3365 FnType = FnTypeRef->getPointeeType();
3366 isReference = true;
3367 }
3368 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
3369 FnType = FnTypePtr->getPointeeType();
3370 isPointer = true;
3371 }
3372 // Desugar down to a function type.
3373 FnType = QualType(FnType->getAsFunctionType(), 0);
3374 // Reconstruct the pointer/reference as appropriate.
3375 if (isPointer) FnType = Context.getPointerType(FnType);
3376 if (isReference) FnType = Context.getReferenceType(FnType);
3377
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003378 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003379 << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003380 } else {
3381 // FIXME: We need to get the identifier in here
3382 // FIXME: Do we want the error message to point at the
3383 // operator? (built-ins won't have a location)
3384 QualType FnType
3385 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3386 Cand->BuiltinTypes.ParamTypes,
3387 Cand->Conversions.size(),
3388 false, 0);
3389
Chris Lattnerd1625842008-11-24 06:25:27 +00003390 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003391 }
3392 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003393 }
3394}
3395
Douglas Gregor904eed32008-11-10 20:40:00 +00003396/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3397/// an overloaded function (C++ [over.over]), where @p From is an
3398/// expression with overloaded function type and @p ToType is the type
3399/// we're trying to resolve to. For example:
3400///
3401/// @code
3402/// int f(double);
3403/// int f(int);
3404///
3405/// int (*pfd)(double) = f; // selects f(double)
3406/// @endcode
3407///
3408/// This routine returns the resulting FunctionDecl if it could be
3409/// resolved, and NULL otherwise. When @p Complain is true, this
3410/// routine will emit diagnostics if there is an error.
3411FunctionDecl *
3412Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
3413 bool Complain) {
3414 QualType FunctionType = ToType;
3415 if (const PointerLikeType *ToTypePtr = ToType->getAsPointerLikeType())
3416 FunctionType = ToTypePtr->getPointeeType();
3417
3418 // We only look at pointers or references to functions.
3419 if (!FunctionType->isFunctionType())
3420 return 0;
3421
3422 // Find the actual overloaded function declaration.
3423 OverloadedFunctionDecl *Ovl = 0;
3424
3425 // C++ [over.over]p1:
3426 // [...] [Note: any redundant set of parentheses surrounding the
3427 // overloaded function name is ignored (5.1). ]
3428 Expr *OvlExpr = From->IgnoreParens();
3429
3430 // C++ [over.over]p1:
3431 // [...] The overloaded function name can be preceded by the &
3432 // operator.
3433 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3434 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3435 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3436 }
3437
3438 // Try to dig out the overloaded function.
3439 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
3440 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
3441
3442 // If there's no overloaded function declaration, we're done.
3443 if (!Ovl)
3444 return 0;
3445
3446 // Look through all of the overloaded functions, searching for one
3447 // whose type matches exactly.
3448 // FIXME: When templates or using declarations come along, we'll actually
3449 // have to deal with duplicates, partial ordering, etc. For now, we
3450 // can just do a simple search.
3451 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
3452 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
3453 Fun != Ovl->function_end(); ++Fun) {
3454 // C++ [over.over]p3:
3455 // Non-member functions and static member functions match
3456 // targets of type “pointer-to-function”or
3457 // “reference-to-function.”
3458 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun))
3459 if (!Method->isStatic())
3460 continue;
3461
3462 if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
3463 return *Fun;
3464 }
3465
3466 return 0;
3467}
3468
Douglas Gregorf6b89692008-11-26 05:54:23 +00003469/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00003470/// (which eventually refers to the declaration Func) and the call
3471/// arguments Args/NumArgs, attempt to resolve the function call down
3472/// to a specific function. If overload resolution succeeds, returns
3473/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00003474/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00003475/// arguments and Fn, and returns NULL.
Douglas Gregorfa047642009-02-04 00:32:51 +00003476FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor17330012009-02-04 15:01:18 +00003477 DeclarationName UnqualifiedName,
Douglas Gregor0a396682008-11-26 06:01:48 +00003478 SourceLocation LParenLoc,
3479 Expr **Args, unsigned NumArgs,
3480 SourceLocation *CommaLocs,
Douglas Gregorfa047642009-02-04 00:32:51 +00003481 SourceLocation RParenLoc,
Douglas Gregor17330012009-02-04 15:01:18 +00003482 bool &ArgumentDependentLookup) {
Douglas Gregorf6b89692008-11-26 05:54:23 +00003483 OverloadCandidateSet CandidateSet;
Douglas Gregor17330012009-02-04 15:01:18 +00003484
3485 // Add the functions denoted by Callee to the set of candidate
3486 // functions. While we're doing so, track whether argument-dependent
3487 // lookup still applies, per:
3488 //
3489 // C++0x [basic.lookup.argdep]p3:
3490 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3491 // and let Y be the lookup set produced by argument dependent
3492 // lookup (defined as follows). If X contains
3493 //
3494 // -- a declaration of a class member, or
3495 //
3496 // -- a block-scope function declaration that is not a
3497 // using-declaration, or
3498 //
3499 // -- a declaration that is neither a function or a function
3500 // template
3501 //
3502 // then Y is empty.
Douglas Gregorfa047642009-02-04 00:32:51 +00003503 if (OverloadedFunctionDecl *Ovl
Douglas Gregor17330012009-02-04 15:01:18 +00003504 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
3505 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3506 FuncEnd = Ovl->function_end();
3507 Func != FuncEnd; ++Func) {
3508 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
3509
3510 if ((*Func)->getDeclContext()->isRecord() ||
3511 (*Func)->getDeclContext()->isFunctionOrMethod())
3512 ArgumentDependentLookup = false;
3513 }
3514 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
3515 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
3516
3517 if (Func->getDeclContext()->isRecord() ||
3518 Func->getDeclContext()->isFunctionOrMethod())
3519 ArgumentDependentLookup = false;
3520 }
3521
3522 if (Callee)
3523 UnqualifiedName = Callee->getDeclName();
3524
Douglas Gregorfa047642009-02-04 00:32:51 +00003525 if (ArgumentDependentLookup)
Douglas Gregor17330012009-02-04 15:01:18 +00003526 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregorfa047642009-02-04 00:32:51 +00003527 CandidateSet);
3528
Douglas Gregorf6b89692008-11-26 05:54:23 +00003529 OverloadCandidateSet::iterator Best;
3530 switch (BestViableFunction(CandidateSet, Best)) {
Douglas Gregor0a396682008-11-26 06:01:48 +00003531 case OR_Success:
3532 return Best->Function;
Douglas Gregorf6b89692008-11-26 05:54:23 +00003533
3534 case OR_No_Viable_Function:
3535 Diag(Fn->getSourceRange().getBegin(),
3536 diag::err_ovl_no_viable_function_in_call)
Douglas Gregor17330012009-02-04 15:01:18 +00003537 << UnqualifiedName << (unsigned)CandidateSet.size()
Douglas Gregorf6b89692008-11-26 05:54:23 +00003538 << Fn->getSourceRange();
3539 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3540 break;
3541
3542 case OR_Ambiguous:
3543 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor17330012009-02-04 15:01:18 +00003544 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00003545 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3546 break;
3547 }
3548
3549 // Overload resolution failed. Destroy all of the subexpressions and
3550 // return NULL.
3551 Fn->Destroy(Context);
3552 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3553 Args[Arg]->Destroy(Context);
3554 return 0;
3555}
3556
Douglas Gregor88a35142008-12-22 05:46:06 +00003557/// BuildCallToMemberFunction - Build a call to a member
3558/// function. MemExpr is the expression that refers to the member
3559/// function (and includes the object parameter), Args/NumArgs are the
3560/// arguments to the function call (not including the object
3561/// parameter). The caller needs to validate that the member
3562/// expression refers to a member function or an overloaded member
3563/// function.
3564Sema::ExprResult
3565Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
3566 SourceLocation LParenLoc, Expr **Args,
3567 unsigned NumArgs, SourceLocation *CommaLocs,
3568 SourceLocation RParenLoc) {
3569 // Dig out the member expression. This holds both the object
3570 // argument and the member function we're referring to.
3571 MemberExpr *MemExpr = 0;
3572 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
3573 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
3574 else
3575 MemExpr = dyn_cast<MemberExpr>(MemExprE);
3576 assert(MemExpr && "Building member call without member expression");
3577
3578 // Extract the object argument.
3579 Expr *ObjectArg = MemExpr->getBase();
3580 if (MemExpr->isArrow())
3581 ObjectArg = new UnaryOperator(ObjectArg, UnaryOperator::Deref,
3582 ObjectArg->getType()->getAsPointerType()->getPointeeType(),
3583 SourceLocation());
3584 CXXMethodDecl *Method = 0;
3585 if (OverloadedFunctionDecl *Ovl
3586 = dyn_cast<OverloadedFunctionDecl>(MemExpr->getMemberDecl())) {
3587 // Add overload candidates
3588 OverloadCandidateSet CandidateSet;
3589 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3590 FuncEnd = Ovl->function_end();
3591 Func != FuncEnd; ++Func) {
3592 assert(isa<CXXMethodDecl>(*Func) && "Function is not a method");
3593 Method = cast<CXXMethodDecl>(*Func);
3594 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
3595 /*SuppressUserConversions=*/false);
3596 }
3597
3598 OverloadCandidateSet::iterator Best;
3599 switch (BestViableFunction(CandidateSet, Best)) {
3600 case OR_Success:
3601 Method = cast<CXXMethodDecl>(Best->Function);
3602 break;
3603
3604 case OR_No_Viable_Function:
3605 Diag(MemExpr->getSourceRange().getBegin(),
3606 diag::err_ovl_no_viable_member_function_in_call)
3607 << Ovl->getDeclName() << (unsigned)CandidateSet.size()
3608 << MemExprE->getSourceRange();
3609 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3610 // FIXME: Leaking incoming expressions!
3611 return true;
3612
3613 case OR_Ambiguous:
3614 Diag(MemExpr->getSourceRange().getBegin(),
3615 diag::err_ovl_ambiguous_member_call)
3616 << Ovl->getDeclName() << MemExprE->getSourceRange();
3617 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3618 // FIXME: Leaking incoming expressions!
3619 return true;
3620 }
3621
3622 FixOverloadedFunctionReference(MemExpr, Method);
3623 } else {
3624 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
3625 }
3626
3627 assert(Method && "Member call to something that isn't a method?");
3628 llvm::OwningPtr<CXXMemberCallExpr>
3629 TheCall(new CXXMemberCallExpr(MemExpr, Args, NumArgs,
3630 Method->getResultType().getNonReferenceType(),
3631 RParenLoc));
3632
3633 // Convert the object argument (for a non-static member function call).
3634 if (!Method->isStatic() &&
3635 PerformObjectArgumentInitialization(ObjectArg, Method))
3636 return true;
3637 MemExpr->setBase(ObjectArg);
3638
3639 // Convert the rest of the arguments
3640 const FunctionTypeProto *Proto = cast<FunctionTypeProto>(Method->getType());
3641 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
3642 RParenLoc))
3643 return true;
3644
Sebastian Redl0eb23302009-01-19 00:08:26 +00003645 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregor88a35142008-12-22 05:46:06 +00003646}
3647
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003648/// BuildCallToObjectOfClassType - Build a call to an object of class
3649/// type (C++ [over.call.object]), which can end up invoking an
3650/// overloaded function call operator (@c operator()) or performing a
3651/// user-defined conversion on the object argument.
Douglas Gregor88a35142008-12-22 05:46:06 +00003652Sema::ExprResult
Douglas Gregor5c37de72008-12-06 00:22:45 +00003653Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
3654 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003655 Expr **Args, unsigned NumArgs,
3656 SourceLocation *CommaLocs,
3657 SourceLocation RParenLoc) {
3658 assert(Object->getType()->isRecordType() && "Requires object type argument");
3659 const RecordType *Record = Object->getType()->getAsRecordType();
3660
3661 // C++ [over.call.object]p1:
3662 // If the primary-expression E in the function call syntax
3663 // evaluates to a class object of type “cv T”, then the set of
3664 // candidate functions includes at least the function call
3665 // operators of T. The function call operators of T are obtained by
3666 // ordinary lookup of the name operator() in the context of
3667 // (E).operator().
3668 OverloadCandidateSet CandidateSet;
Douglas Gregor44b43212008-12-11 16:49:14 +00003669 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003670 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00003671 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003672 Oper != OperEnd; ++Oper)
3673 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
3674 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003675
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003676 // C++ [over.call.object]p2:
3677 // In addition, for each conversion function declared in T of the
3678 // form
3679 //
3680 // operator conversion-type-id () cv-qualifier;
3681 //
3682 // where cv-qualifier is the same cv-qualification as, or a
3683 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00003684 // denotes the type "pointer to function of (P1,...,Pn) returning
3685 // R", or the type "reference to pointer to function of
3686 // (P1,...,Pn) returning R", or the type "reference to function
3687 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003688 // is also considered as a candidate function. Similarly,
3689 // surrogate call functions are added to the set of candidate
3690 // functions for each conversion function declared in an
3691 // accessible base class provided the function is not hidden
3692 // within T by another intervening declaration.
3693 //
3694 // FIXME: Look in base classes for more conversion operators!
3695 OverloadedFunctionDecl *Conversions
3696 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor621b3932008-11-21 02:54:28 +00003697 for (OverloadedFunctionDecl::function_iterator
3698 Func = Conversions->function_begin(),
3699 FuncEnd = Conversions->function_end();
3700 Func != FuncEnd; ++Func) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003701 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
3702
3703 // Strip the reference type (if any) and then the pointer type (if
3704 // any) to get down to what might be a function type.
3705 QualType ConvType = Conv->getConversionType().getNonReferenceType();
3706 if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
3707 ConvType = ConvPtrType->getPointeeType();
3708
3709 if (const FunctionTypeProto *Proto = ConvType->getAsFunctionTypeProto())
3710 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
3711 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003712
3713 // Perform overload resolution.
3714 OverloadCandidateSet::iterator Best;
3715 switch (BestViableFunction(CandidateSet, Best)) {
3716 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003717 // Overload resolution succeeded; we'll build the appropriate call
3718 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003719 break;
3720
3721 case OR_No_Viable_Function:
Sebastian Redle4c452c2008-11-22 13:44:36 +00003722 Diag(Object->getSourceRange().getBegin(),
3723 diag::err_ovl_no_viable_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00003724 << Object->getType() << (unsigned)CandidateSet.size()
Sebastian Redle4c452c2008-11-22 13:44:36 +00003725 << Object->getSourceRange();
3726 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003727 break;
3728
3729 case OR_Ambiguous:
3730 Diag(Object->getSourceRange().getBegin(),
3731 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00003732 << Object->getType() << Object->getSourceRange();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003733 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3734 break;
3735 }
3736
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003737 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003738 // We had an error; delete all of the subexpressions and return
3739 // the error.
3740 delete Object;
3741 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3742 delete Args[ArgIdx];
3743 return true;
3744 }
3745
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003746 if (Best->Function == 0) {
3747 // Since there is no function declaration, this is one of the
3748 // surrogate candidates. Dig out the conversion function.
3749 CXXConversionDecl *Conv
3750 = cast<CXXConversionDecl>(
3751 Best->Conversions[0].UserDefined.ConversionFunction);
3752
3753 // We selected one of the surrogate functions that converts the
3754 // object parameter to a function pointer. Perform the conversion
3755 // on the object argument, then let ActOnCallExpr finish the job.
3756 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl0eb23302009-01-19 00:08:26 +00003757 ImpCastExprToType(Object,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003758 Conv->getConversionType().getNonReferenceType(),
3759 Conv->getConversionType()->isReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003760 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
3761 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
3762 CommaLocs, RParenLoc).release();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003763 }
3764
3765 // We found an overloaded operator(). Build a CXXOperatorCallExpr
3766 // that calls this method, using Object for the implicit object
3767 // parameter and passing along the remaining arguments.
3768 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003769 const FunctionTypeProto *Proto = Method->getType()->getAsFunctionTypeProto();
3770
3771 unsigned NumArgsInProto = Proto->getNumArgs();
3772 unsigned NumArgsToCheck = NumArgs;
3773
3774 // Build the full argument list for the method call (the
3775 // implicit object parameter is placed at the beginning of the
3776 // list).
3777 Expr **MethodArgs;
3778 if (NumArgs < NumArgsInProto) {
3779 NumArgsToCheck = NumArgsInProto;
3780 MethodArgs = new Expr*[NumArgsInProto + 1];
3781 } else {
3782 MethodArgs = new Expr*[NumArgs + 1];
3783 }
3784 MethodArgs[0] = Object;
3785 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3786 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
3787
3788 Expr *NewFn = new DeclRefExpr(Method, Method->getType(),
3789 SourceLocation());
3790 UsualUnaryConversions(NewFn);
3791
3792 // Once we've built TheCall, all of the expressions are properly
3793 // owned.
3794 QualType ResultTy = Method->getResultType().getNonReferenceType();
3795 llvm::OwningPtr<CXXOperatorCallExpr>
3796 TheCall(new CXXOperatorCallExpr(NewFn, MethodArgs, NumArgs + 1,
3797 ResultTy, RParenLoc));
3798 delete [] MethodArgs;
3799
Douglas Gregor518fda12009-01-13 05:10:00 +00003800 // We may have default arguments. If so, we need to allocate more
3801 // slots in the call for them.
3802 if (NumArgs < NumArgsInProto)
3803 TheCall->setNumArgs(NumArgsInProto + 1);
3804 else if (NumArgs > NumArgsInProto)
3805 NumArgsToCheck = NumArgsInProto;
3806
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003807 // Initialize the implicit object parameter.
Douglas Gregor518fda12009-01-13 05:10:00 +00003808 if (PerformObjectArgumentInitialization(Object, Method))
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003809 return true;
3810 TheCall->setArg(0, Object);
3811
3812 // Check the argument types.
3813 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003814 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00003815 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003816 Arg = Args[i];
Douglas Gregor518fda12009-01-13 05:10:00 +00003817
3818 // Pass the argument.
3819 QualType ProtoArgType = Proto->getArgType(i);
3820 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3821 return true;
3822 } else {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003823 Arg = new CXXDefaultArgExpr(Method->getParamDecl(i));
Douglas Gregor518fda12009-01-13 05:10:00 +00003824 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003825
3826 TheCall->setArg(i + 1, Arg);
3827 }
3828
3829 // If this is a variadic call, handle args passed through "...".
3830 if (Proto->isVariadic()) {
3831 // Promote the arguments (C99 6.5.2.2p7).
3832 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3833 Expr *Arg = Args[i];
Anders Carlsson906fed02009-01-13 05:48:52 +00003834
Anders Carlssondce5e2c2009-01-16 16:48:51 +00003835 DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003836 TheCall->setArg(i + 1, Arg);
3837 }
3838 }
3839
Sebastian Redl0eb23302009-01-19 00:08:26 +00003840 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003841}
3842
Douglas Gregor8ba10742008-11-20 16:27:02 +00003843/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
3844/// (if one exists), where @c Base is an expression of class type and
3845/// @c Member is the name of the member we're trying to find.
3846Action::ExprResult
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003847Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
Douglas Gregor8ba10742008-11-20 16:27:02 +00003848 SourceLocation MemberLoc,
3849 IdentifierInfo &Member) {
3850 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
3851
3852 // C++ [over.ref]p1:
3853 //
3854 // [...] An expression x->m is interpreted as (x.operator->())->m
3855 // for a class object x of type T if T::operator->() exists and if
3856 // the operator is selected as the best match function by the
3857 // overload resolution mechanism (13.3).
3858 // FIXME: look in base classes.
3859 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
3860 OverloadCandidateSet CandidateSet;
3861 const RecordType *BaseRecord = Base->getType()->getAsRecordType();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003862
3863 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00003864 for (llvm::tie(Oper, OperEnd) = BaseRecord->getDecl()->lookup(OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003865 Oper != OperEnd; ++Oper)
3866 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00003867 /*SuppressUserConversions=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003868
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003869 llvm::OwningPtr<Expr> BasePtr(Base);
3870
Douglas Gregor8ba10742008-11-20 16:27:02 +00003871 // Perform overload resolution.
3872 OverloadCandidateSet::iterator Best;
3873 switch (BestViableFunction(CandidateSet, Best)) {
3874 case OR_Success:
3875 // Overload resolution succeeded; we'll build the call below.
3876 break;
3877
3878 case OR_No_Viable_Function:
3879 if (CandidateSet.empty())
3880 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattnerd1625842008-11-24 06:25:27 +00003881 << BasePtr->getType() << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003882 else
3883 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Sebastian Redle4c452c2008-11-22 13:44:36 +00003884 << "operator->" << (unsigned)CandidateSet.size()
3885 << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003886 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003887 return true;
3888
3889 case OR_Ambiguous:
3890 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Chris Lattnerd1625842008-11-24 06:25:27 +00003891 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003892 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003893 return true;
3894 }
3895
3896 // Convert the object parameter.
3897 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003898 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregor8ba10742008-11-20 16:27:02 +00003899 return true;
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003900
3901 // No concerns about early exits now.
3902 BasePtr.take();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003903
3904 // Build the operator call.
3905 Expr *FnExpr = new DeclRefExpr(Method, Method->getType(), SourceLocation());
3906 UsualUnaryConversions(FnExpr);
3907 Base = new CXXOperatorCallExpr(FnExpr, &Base, 1,
3908 Method->getResultType().getNonReferenceType(),
3909 OpLoc);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003910 return ActOnMemberReferenceExpr(S, ExprArg(*this, Base), OpLoc, tok::arrow,
3911 MemberLoc, Member).release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003912}
3913
Douglas Gregor904eed32008-11-10 20:40:00 +00003914/// FixOverloadedFunctionReference - E is an expression that refers to
3915/// a C++ overloaded function (possibly with some parentheses and
3916/// perhaps a '&' around it). We have resolved the overloaded function
3917/// to the function declaration Fn, so patch up the expression E to
3918/// refer (possibly indirectly) to Fn.
3919void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
3920 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
3921 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
3922 E->setType(PE->getSubExpr()->getType());
3923 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
3924 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
3925 "Can only take the address of an overloaded function");
3926 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
3927 E->setType(Context.getPointerType(E->getType()));
3928 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
3929 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
3930 "Expected overloaded function");
3931 DR->setDecl(Fn);
3932 E->setType(Fn->getType());
Douglas Gregor88a35142008-12-22 05:46:06 +00003933 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
3934 MemExpr->setMemberDecl(Fn);
3935 E->setType(Fn->getType());
Douglas Gregor904eed32008-11-10 20:40:00 +00003936 } else {
3937 assert(false && "Invalid reference to overloaded function");
3938 }
3939}
3940
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003941} // end namespace clang