blob: 0f9f0cf9c6aa9df99282b28908eb45bd828a65f7 [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,
369 bool AllowExplict)
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 Gregor225c41e2008-11-03 19:09:14 +0000374 else if (!SuppressUserConversions &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000375 IsUserDefinedConversion(From, ToType, ICS.UserDefined, AllowExplict)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000376 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000377 // C++ [over.ics.user]p4:
378 // A conversion of an expression of class type to the same class
379 // type is given Exact Match rank, and a conversion of an
380 // expression of class type to a base class of that type is
381 // given Conversion rank, in spite of the fact that a copy
382 // constructor (i.e., a user-defined conversion function) is
383 // called for those cases.
384 if (CXXConstructorDecl *Constructor
385 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
386 if (Constructor->isCopyConstructor(Context)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000387 // Turn this into a "standard" conversion sequence, so that it
388 // gets ranked with standard conversion sequences.
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000389 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
390 ICS.Standard.setAsIdentityConversion();
391 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
392 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000393 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000394 if (IsDerivedFrom(From->getType().getUnqualifiedType(),
395 ToType.getUnqualifiedType()))
396 ICS.Standard.Second = ICK_Derived_To_Base;
397 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000398 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000399 } else
Douglas Gregor60d62c22008-10-31 16:23:19 +0000400 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000401
402 return ICS;
403}
404
405/// IsStandardConversion - Determines whether there is a standard
406/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
407/// expression From to the type ToType. Standard conversion sequences
408/// only consider non-class types; for conversions that involve class
409/// types, use TryImplicitConversion. If a conversion exists, SCS will
410/// contain the standard conversion sequence required to perform this
411/// conversion and this routine will return true. Otherwise, this
412/// routine will return false and the value of SCS is unspecified.
413bool
414Sema::IsStandardConversion(Expr* From, QualType ToType,
415 StandardConversionSequence &SCS)
416{
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000417 QualType FromType = From->getType();
418
Douglas Gregor60d62c22008-10-31 16:23:19 +0000419 // There are no standard conversions for class types, so abort early.
420 if (FromType->isRecordType() || ToType->isRecordType())
421 return false;
422
423 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000424 SCS.setAsIdentityConversion();
Douglas Gregor60d62c22008-10-31 16:23:19 +0000425 SCS.Deprecated = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000426 SCS.IncompatibleObjC = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000427 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000428 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000429
430 // The first conversion can be an lvalue-to-rvalue conversion,
431 // array-to-pointer conversion, or function-to-pointer conversion
432 // (C++ 4p1).
433
434 // Lvalue-to-rvalue conversion (C++ 4.1):
435 // An lvalue (3.10) of a non-function, non-array type T can be
436 // converted to an rvalue.
437 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
438 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000439 !FromType->isFunctionType() && !FromType->isArrayType() &&
440 !FromType->isOverloadType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000441 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000442
443 // If T is a non-class type, the type of the rvalue is the
444 // cv-unqualified version of T. Otherwise, the type of the rvalue
445 // is T (C++ 4.1p1).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000446 FromType = FromType.getUnqualifiedType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000447 }
448 // Array-to-pointer conversion (C++ 4.2)
449 else if (FromType->isArrayType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000450 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000451
452 // An lvalue or rvalue of type "array of N T" or "array of unknown
453 // bound of T" can be converted to an rvalue of type "pointer to
454 // T" (C++ 4.2p1).
455 FromType = Context.getArrayDecayedType(FromType);
456
457 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
458 // This conversion is deprecated. (C++ D.4).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000459 SCS.Deprecated = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000460
461 // For the purpose of ranking in overload resolution
462 // (13.3.3.1.1), this conversion is considered an
463 // array-to-pointer conversion followed by a qualification
464 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000465 SCS.Second = ICK_Identity;
466 SCS.Third = ICK_Qualification;
467 SCS.ToTypePtr = ToType.getAsOpaquePtr();
468 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000469 }
470 }
471 // Function-to-pointer conversion (C++ 4.3).
472 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000473 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000474
475 // An lvalue of function type T can be converted to an rvalue of
476 // type "pointer to T." The result is a pointer to the
477 // function. (C++ 4.3p1).
478 FromType = Context.getPointerType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000479 }
Douglas Gregor904eed32008-11-10 20:40:00 +0000480 // Address of overloaded function (C++ [over.over]).
481 else if (FunctionDecl *Fn
482 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
483 SCS.First = ICK_Function_To_Pointer;
484
485 // We were able to resolve the address of the overloaded function,
486 // so we can convert to the type of that function.
487 FromType = Fn->getType();
488 if (ToType->isReferenceType())
489 FromType = Context.getReferenceType(FromType);
490 else
491 FromType = Context.getPointerType(FromType);
492 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000493 // We don't require any conversions for the first step.
494 else {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000495 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000496 }
497
498 // The second conversion can be an integral promotion, floating
499 // point promotion, integral conversion, floating point conversion,
500 // floating-integral conversion, pointer conversion,
501 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor45920e82008-12-19 17:40:08 +0000502 bool IncompatibleObjC = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000503 if (Context.getCanonicalType(FromType).getUnqualifiedType() ==
504 Context.getCanonicalType(ToType).getUnqualifiedType()) {
505 // The unqualified versions of the types are the same: there's no
506 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000507 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000508 }
509 // Integral promotion (C++ 4.5).
510 else if (IsIntegralPromotion(From, FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000511 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000512 FromType = ToType.getUnqualifiedType();
513 }
514 // Floating point promotion (C++ 4.6).
515 else if (IsFloatingPointPromotion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000516 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000517 FromType = ToType.getUnqualifiedType();
518 }
519 // Integral conversions (C++ 4.7).
Sebastian Redl07779722008-10-31 14:43:28 +0000520 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000521 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000522 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000523 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000524 FromType = ToType.getUnqualifiedType();
525 }
526 // Floating point conversions (C++ 4.8).
527 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000528 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000529 FromType = ToType.getUnqualifiedType();
530 }
531 // Floating-integral conversions (C++ 4.9).
Sebastian Redl07779722008-10-31 14:43:28 +0000532 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000533 else if ((FromType->isFloatingType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000534 ToType->isIntegralType() && !ToType->isBooleanType() &&
535 !ToType->isEnumeralType()) ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000536 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
537 ToType->isFloatingType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000538 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000539 FromType = ToType.getUnqualifiedType();
540 }
541 // Pointer conversions (C++ 4.10).
Douglas Gregor45920e82008-12-19 17:40:08 +0000542 else if (IsPointerConversion(From, FromType, ToType, FromType,
543 IncompatibleObjC)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000544 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000545 SCS.IncompatibleObjC = IncompatibleObjC;
Sebastian Redl07779722008-10-31 14:43:28 +0000546 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000547 // Pointer to member conversions (4.11).
548 else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
549 SCS.Second = ICK_Pointer_Member;
550 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000551 // Boolean conversions (C++ 4.12).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000552 else if (ToType->isBooleanType() &&
553 (FromType->isArithmeticType() ||
554 FromType->isEnumeralType() ||
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000555 FromType->isPointerType() ||
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000556 FromType->isBlockPointerType() ||
557 FromType->isMemberPointerType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000558 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000559 FromType = Context.BoolTy;
560 } else {
561 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000562 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000563 }
564
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000565 QualType CanonFrom;
566 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000567 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000568 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000569 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000570 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000571 CanonFrom = Context.getCanonicalType(FromType);
572 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000573 } else {
574 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000575 SCS.Third = ICK_Identity;
576
577 // C++ [over.best.ics]p6:
578 // [...] Any difference in top-level cv-qualification is
579 // subsumed by the initialization itself and does not constitute
580 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000581 CanonFrom = Context.getCanonicalType(FromType);
582 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000583 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000584 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
585 FromType = ToType;
586 CanonFrom = CanonTo;
587 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000588 }
589
590 // If we have not converted the argument type to the parameter type,
591 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000592 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000593 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000594
Douglas Gregor60d62c22008-10-31 16:23:19 +0000595 SCS.ToTypePtr = FromType.getAsOpaquePtr();
596 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000597}
598
599/// IsIntegralPromotion - Determines whether the conversion from the
600/// expression From (whose potentially-adjusted type is FromType) to
601/// ToType is an integral promotion (C++ 4.5). If so, returns true and
602/// sets PromotedType to the promoted type.
603bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
604{
605 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000606 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000607 if (!To) {
608 return false;
609 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000610
611 // An rvalue of type char, signed char, unsigned char, short int, or
612 // unsigned short int can be converted to an rvalue of type int if
613 // int can represent all the values of the source type; otherwise,
614 // the source rvalue can be converted to an rvalue of type unsigned
615 // int (C++ 4.5p1).
Sebastian Redl07779722008-10-31 14:43:28 +0000616 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000617 if (// We can promote any signed, promotable integer type to an int
618 (FromType->isSignedIntegerType() ||
619 // We can promote any unsigned integer type whose size is
620 // less than int to an int.
621 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000622 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000623 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000624 }
625
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000626 return To->getKind() == BuiltinType::UInt;
627 }
628
629 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
630 // can be converted to an rvalue of the first of the following types
631 // that can represent all the values of its underlying type: int,
632 // unsigned int, long, or unsigned long (C++ 4.5p2).
633 if ((FromType->isEnumeralType() || FromType->isWideCharType())
634 && ToType->isIntegerType()) {
635 // Determine whether the type we're converting from is signed or
636 // unsigned.
637 bool FromIsSigned;
638 uint64_t FromSize = Context.getTypeSize(FromType);
639 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
640 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
641 FromIsSigned = UnderlyingType->isSignedIntegerType();
642 } else {
643 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
644 FromIsSigned = true;
645 }
646
647 // The types we'll try to promote to, in the appropriate
648 // order. Try each of these types.
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000649 QualType PromoteTypes[6] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000650 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000651 Context.LongTy, Context.UnsignedLongTy ,
652 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000653 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000654 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000655 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
656 if (FromSize < ToSize ||
657 (FromSize == ToSize &&
658 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
659 // We found the type that we can promote to. If this is the
660 // type we wanted, we have a promotion. Otherwise, no
661 // promotion.
Sebastian Redl07779722008-10-31 14:43:28 +0000662 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000663 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
664 }
665 }
666 }
667
668 // An rvalue for an integral bit-field (9.6) can be converted to an
669 // rvalue of type int if int can represent all the values of the
670 // bit-field; otherwise, it can be converted to unsigned int if
671 // unsigned int can represent all the values of the bit-field. If
672 // the bit-field is larger yet, no integral promotion applies to
673 // it. If the bit-field has an enumerated type, it is treated as any
674 // other value of that type for promotion purposes (C++ 4.5p3).
675 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) {
676 using llvm::APSInt;
Douglas Gregor86f19402008-12-20 23:49:58 +0000677 if (FieldDecl *MemberDecl = dyn_cast<FieldDecl>(MemRef->getMemberDecl())) {
678 APSInt BitWidth;
679 if (MemberDecl->isBitField() &&
680 FromType->isIntegralType() && !FromType->isEnumeralType() &&
681 From->isIntegerConstantExpr(BitWidth, Context)) {
682 APSInt ToSize(Context.getTypeSize(ToType));
683
684 // Are we promoting to an int from a bitfield that fits in an int?
685 if (BitWidth < ToSize ||
686 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
687 return To->getKind() == BuiltinType::Int;
688 }
689
690 // Are we promoting to an unsigned int from an unsigned bitfield
691 // that fits into an unsigned int?
692 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
693 return To->getKind() == BuiltinType::UInt;
694 }
695
696 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000697 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000698 }
699 }
700
701 // An rvalue of type bool can be converted to an rvalue of type int,
702 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000703 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000704 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000705 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000706
707 return false;
708}
709
710/// IsFloatingPointPromotion - Determines whether the conversion from
711/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
712/// returns true and sets PromotedType to the promoted type.
713bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
714{
715 /// An rvalue of type float can be converted to an rvalue of type
716 /// double. (C++ 4.6p1).
717 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
718 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType())
719 if (FromBuiltin->getKind() == BuiltinType::Float &&
720 ToBuiltin->getKind() == BuiltinType::Double)
721 return true;
722
723 return false;
724}
725
Douglas Gregorcb7de522008-11-26 23:31:11 +0000726/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
727/// the pointer type FromPtr to a pointer to type ToPointee, with the
728/// same type qualifiers as FromPtr has on its pointee type. ToType,
729/// if non-empty, will be a pointer to ToType that may or may not have
730/// the right set of qualifiers on its pointee.
731static QualType
732BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
733 QualType ToPointee, QualType ToType,
734 ASTContext &Context) {
735 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
736 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
737 unsigned Quals = CanonFromPointee.getCVRQualifiers();
738
739 // Exact qualifier match -> return the pointer type we're converting to.
740 if (CanonToPointee.getCVRQualifiers() == Quals) {
741 // ToType is exactly what we need. Return it.
742 if (ToType.getTypePtr())
743 return ToType;
744
745 // Build a pointer to ToPointee. It has the right qualifiers
746 // already.
747 return Context.getPointerType(ToPointee);
748 }
749
750 // Just build a canonical type that has the right qualifiers.
751 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
752}
753
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000754/// IsPointerConversion - Determines whether the conversion of the
755/// expression From, which has the (possibly adjusted) type FromType,
756/// can be converted to the type ToType via a pointer conversion (C++
757/// 4.10). If so, returns true and places the converted type (that
758/// might differ from ToType in its cv-qualifiers at some level) into
759/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000760///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000761/// This routine also supports conversions to and from block pointers
762/// and conversions with Objective-C's 'id', 'id<protocols...>', and
763/// pointers to interfaces. FIXME: Once we've determined the
764/// appropriate overloading rules for Objective-C, we may want to
765/// split the Objective-C checks into a different routine; however,
766/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000767/// conversions, so for now they live here. IncompatibleObjC will be
768/// set if the conversion is an allowed Objective-C conversion that
769/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000770bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000771 QualType& ConvertedType,
772 bool &IncompatibleObjC)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000773{
Douglas Gregor45920e82008-12-19 17:40:08 +0000774 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +0000775 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
776 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +0000777
Douglas Gregor27b09ac2008-12-22 20:51:52 +0000778 // Conversion from a null pointer constant to any Objective-C pointer type.
779 if (Context.isObjCObjectPointerType(ToType) &&
780 From->isNullPointerConstant(Context)) {
781 ConvertedType = ToType;
782 return true;
783 }
784
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000785 // Blocks: Block pointers can be converted to void*.
786 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
787 ToType->getAsPointerType()->getPointeeType()->isVoidType()) {
788 ConvertedType = ToType;
789 return true;
790 }
791 // Blocks: A null pointer constant can be converted to a block
792 // pointer type.
793 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
794 ConvertedType = ToType;
795 return true;
796 }
797
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000798 const PointerType* ToTypePtr = ToType->getAsPointerType();
799 if (!ToTypePtr)
800 return false;
801
802 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
803 if (From->isNullPointerConstant(Context)) {
804 ConvertedType = ToType;
805 return true;
806 }
Sebastian Redl07779722008-10-31 14:43:28 +0000807
Douglas Gregorcb7de522008-11-26 23:31:11 +0000808 // Beyond this point, both types need to be pointers.
809 const PointerType *FromTypePtr = FromType->getAsPointerType();
810 if (!FromTypePtr)
811 return false;
812
813 QualType FromPointeeType = FromTypePtr->getPointeeType();
814 QualType ToPointeeType = ToTypePtr->getPointeeType();
815
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000816 // An rvalue of type "pointer to cv T," where T is an object type,
817 // can be converted to an rvalue of type "pointer to cv void" (C++
818 // 4.10p2).
Douglas Gregorc7887512008-12-19 19:13:09 +0000819 if (FromPointeeType->isIncompleteOrObjectType() &&
820 ToPointeeType->isVoidType()) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000821 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
822 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000823 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000824 return true;
825 }
826
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000827 // C++ [conv.ptr]p3:
828 //
829 // An rvalue of type "pointer to cv D," where D is a class type,
830 // can be converted to an rvalue of type "pointer to cv B," where
831 // B is a base class (clause 10) of D. If B is an inaccessible
832 // (clause 11) or ambiguous (10.2) base class of D, a program that
833 // necessitates this conversion is ill-formed. The result of the
834 // conversion is a pointer to the base class sub-object of the
835 // derived class object. The null pointer value is converted to
836 // the null pointer value of the destination type.
837 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000838 // Note that we do not check for ambiguity or inaccessibility
839 // here. That is handled by CheckPointerConversion.
Douglas Gregorcb7de522008-11-26 23:31:11 +0000840 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
841 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000842 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
843 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000844 ToType, Context);
845 return true;
846 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000847
Douglas Gregorc7887512008-12-19 19:13:09 +0000848 return false;
849}
850
851/// isObjCPointerConversion - Determines whether this is an
852/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
853/// with the same arguments and return values.
854bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
855 QualType& ConvertedType,
856 bool &IncompatibleObjC) {
857 if (!getLangOptions().ObjC1)
858 return false;
859
860 // Conversions with Objective-C's id<...>.
861 if ((FromType->isObjCQualifiedIdType() || ToType->isObjCQualifiedIdType()) &&
862 ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) {
863 ConvertedType = ToType;
864 return true;
865 }
866
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000867 // Beyond this point, both types need to be pointers or block pointers.
868 QualType ToPointeeType;
Douglas Gregorc7887512008-12-19 19:13:09 +0000869 const PointerType* ToTypePtr = ToType->getAsPointerType();
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000870 if (ToTypePtr)
871 ToPointeeType = ToTypePtr->getPointeeType();
872 else if (const BlockPointerType *ToBlockPtr = ToType->getAsBlockPointerType())
873 ToPointeeType = ToBlockPtr->getPointeeType();
874 else
Douglas Gregorc7887512008-12-19 19:13:09 +0000875 return false;
876
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000877 QualType FromPointeeType;
Douglas Gregorc7887512008-12-19 19:13:09 +0000878 const PointerType *FromTypePtr = FromType->getAsPointerType();
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000879 if (FromTypePtr)
880 FromPointeeType = FromTypePtr->getPointeeType();
881 else if (const BlockPointerType *FromBlockPtr
882 = FromType->getAsBlockPointerType())
883 FromPointeeType = FromBlockPtr->getPointeeType();
884 else
Douglas Gregorc7887512008-12-19 19:13:09 +0000885 return false;
886
Douglas Gregorcb7de522008-11-26 23:31:11 +0000887 // Objective C++: We're able to convert from a pointer to an
888 // interface to a pointer to a different interface.
889 const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType();
890 const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType();
891 if (FromIface && ToIface &&
892 Context.canAssignObjCInterfaces(ToIface, FromIface)) {
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000893 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +0000894 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000895 ToType, Context);
896 return true;
897 }
898
Douglas Gregor45920e82008-12-19 17:40:08 +0000899 if (FromIface && ToIface &&
900 Context.canAssignObjCInterfaces(FromIface, ToIface)) {
901 // Okay: this is some kind of implicit downcast of Objective-C
902 // interfaces, which is permitted. However, we're going to
903 // complain about it.
904 IncompatibleObjC = true;
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000905 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor45920e82008-12-19 17:40:08 +0000906 ToPointeeType,
907 ToType, Context);
908 return true;
909 }
910
Douglas Gregorcb7de522008-11-26 23:31:11 +0000911 // Objective C++: We're able to convert between "id" and a pointer
912 // to any interface (in both directions).
913 if ((FromIface && Context.isObjCIdType(ToPointeeType))
914 || (ToIface && Context.isObjCIdType(FromPointeeType))) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000915 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
916 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000917 ToType, Context);
918 return true;
919 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000920
Douglas Gregordda78892008-12-18 23:43:31 +0000921 // Objective C++: Allow conversions between the Objective-C "id" and
922 // "Class", in either direction.
923 if ((Context.isObjCIdType(FromPointeeType) &&
924 Context.isObjCClassType(ToPointeeType)) ||
925 (Context.isObjCClassType(FromPointeeType) &&
926 Context.isObjCIdType(ToPointeeType))) {
927 ConvertedType = ToType;
928 return true;
929 }
930
Douglas Gregorc7887512008-12-19 19:13:09 +0000931 // If we have pointers to pointers, recursively check whether this
932 // is an Objective-C conversion.
933 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
934 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
935 IncompatibleObjC)) {
936 // We always complain about this conversion.
937 IncompatibleObjC = true;
938 ConvertedType = ToType;
939 return true;
940 }
941
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000942 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +0000943 // differences in the argument and result types are in Objective-C
944 // pointer conversions. If so, we permit the conversion (but
945 // complain about it).
946 const FunctionTypeProto *FromFunctionType
947 = FromPointeeType->getAsFunctionTypeProto();
948 const FunctionTypeProto *ToFunctionType
949 = ToPointeeType->getAsFunctionTypeProto();
950 if (FromFunctionType && ToFunctionType) {
951 // If the function types are exactly the same, this isn't an
952 // Objective-C pointer conversion.
953 if (Context.getCanonicalType(FromPointeeType)
954 == Context.getCanonicalType(ToPointeeType))
955 return false;
956
957 // Perform the quick checks that will tell us whether these
958 // function types are obviously different.
959 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
960 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
961 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
962 return false;
963
964 bool HasObjCConversion = false;
965 if (Context.getCanonicalType(FromFunctionType->getResultType())
966 == Context.getCanonicalType(ToFunctionType->getResultType())) {
967 // Okay, the types match exactly. Nothing to do.
968 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
969 ToFunctionType->getResultType(),
970 ConvertedType, IncompatibleObjC)) {
971 // Okay, we have an Objective-C pointer conversion.
972 HasObjCConversion = true;
973 } else {
974 // Function types are too different. Abort.
975 return false;
976 }
977
978 // Check argument types.
979 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
980 ArgIdx != NumArgs; ++ArgIdx) {
981 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
982 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
983 if (Context.getCanonicalType(FromArgType)
984 == Context.getCanonicalType(ToArgType)) {
985 // Okay, the types match exactly. Nothing to do.
986 } else if (isObjCPointerConversion(FromArgType, ToArgType,
987 ConvertedType, IncompatibleObjC)) {
988 // Okay, we have an Objective-C pointer conversion.
989 HasObjCConversion = true;
990 } else {
991 // Argument types are too different. Abort.
992 return false;
993 }
994 }
995
996 if (HasObjCConversion) {
997 // We had an Objective-C conversion. Allow this pointer
998 // conversion, but complain about it.
999 ConvertedType = ToType;
1000 IncompatibleObjC = true;
1001 return true;
1002 }
1003 }
1004
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001005 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001006}
1007
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001008/// CheckPointerConversion - Check the pointer conversion from the
1009/// expression From to the type ToType. This routine checks for
1010/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
1011/// conversions for which IsPointerConversion has already returned
1012/// true. It returns true and produces a diagnostic if there was an
1013/// error, or returns false otherwise.
1014bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1015 QualType FromType = From->getType();
1016
1017 if (const PointerType *FromPtrType = FromType->getAsPointerType())
1018 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001019 QualType FromPointeeType = FromPtrType->getPointeeType(),
1020 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001021
1022 // Objective-C++ conversions are always okay.
1023 // FIXME: We should have a different class of conversions for
1024 // the Objective-C++ implicit conversions.
1025 if (Context.isObjCIdType(FromPointeeType) ||
1026 Context.isObjCIdType(ToPointeeType) ||
1027 Context.isObjCClassType(FromPointeeType) ||
1028 Context.isObjCClassType(ToPointeeType))
1029 return false;
1030
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001031 if (FromPointeeType->isRecordType() &&
1032 ToPointeeType->isRecordType()) {
1033 // We must have a derived-to-base conversion. Check an
1034 // ambiguous or inaccessible conversion.
Douglas Gregor0575d4a2008-10-24 16:17:19 +00001035 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1036 From->getExprLoc(),
1037 From->getSourceRange());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001038 }
1039 }
1040
1041 return false;
1042}
1043
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001044/// IsMemberPointerConversion - Determines whether the conversion of the
1045/// expression From, which has the (possibly adjusted) type FromType, can be
1046/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1047/// If so, returns true and places the converted type (that might differ from
1048/// ToType in its cv-qualifiers at some level) into ConvertedType.
1049bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1050 QualType ToType, QualType &ConvertedType)
1051{
1052 const MemberPointerType *ToTypePtr = ToType->getAsMemberPointerType();
1053 if (!ToTypePtr)
1054 return false;
1055
1056 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1057 if (From->isNullPointerConstant(Context)) {
1058 ConvertedType = ToType;
1059 return true;
1060 }
1061
1062 // Otherwise, both types have to be member pointers.
1063 const MemberPointerType *FromTypePtr = FromType->getAsMemberPointerType();
1064 if (!FromTypePtr)
1065 return false;
1066
1067 // A pointer to member of B can be converted to a pointer to member of D,
1068 // where D is derived from B (C++ 4.11p2).
1069 QualType FromClass(FromTypePtr->getClass(), 0);
1070 QualType ToClass(ToTypePtr->getClass(), 0);
1071 // FIXME: What happens when these are dependent? Is this function even called?
1072
1073 if (IsDerivedFrom(ToClass, FromClass)) {
1074 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1075 ToClass.getTypePtr());
1076 return true;
1077 }
1078
1079 return false;
1080}
1081
1082/// CheckMemberPointerConversion - Check the member pointer conversion from the
1083/// expression From to the type ToType. This routine checks for ambiguous or
1084/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1085/// for which IsMemberPointerConversion has already returned true. It returns
1086/// true and produces a diagnostic if there was an error, or returns false
1087/// otherwise.
1088bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType) {
1089 QualType FromType = From->getType();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001090 const MemberPointerType *FromPtrType = FromType->getAsMemberPointerType();
1091 if (!FromPtrType)
1092 return false;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001093
Sebastian Redl21593ac2009-01-28 18:33:18 +00001094 const MemberPointerType *ToPtrType = ToType->getAsMemberPointerType();
1095 assert(ToPtrType && "No member pointer cast has a target type "
1096 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001097
Sebastian Redl21593ac2009-01-28 18:33:18 +00001098 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1099 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001100
Sebastian Redl21593ac2009-01-28 18:33:18 +00001101 // FIXME: What about dependent types?
1102 assert(FromClass->isRecordType() && "Pointer into non-class.");
1103 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001104
Sebastian Redl21593ac2009-01-28 18:33:18 +00001105 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1106 /*DetectVirtual=*/true);
1107 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1108 assert(DerivationOkay &&
1109 "Should not have been called if derivation isn't OK.");
1110 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001111
Sebastian Redl21593ac2009-01-28 18:33:18 +00001112 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1113 getUnqualifiedType())) {
1114 // Derivation is ambiguous. Redo the check to find the exact paths.
1115 Paths.clear();
1116 Paths.setRecordingPaths(true);
1117 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1118 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1119 (void)StillOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001120
Sebastian Redl21593ac2009-01-28 18:33:18 +00001121 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1122 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1123 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1124 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001125 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001126
1127 if (const CXXRecordType *VBase = Paths.getDetectedVirtual()) {
1128 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1129 << FromClass << ToClass << QualType(VBase, 0)
1130 << From->getSourceRange();
1131 return true;
1132 }
1133
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001134 return false;
1135}
1136
Douglas Gregor98cd5992008-10-21 23:43:52 +00001137/// IsQualificationConversion - Determines whether the conversion from
1138/// an rvalue of type FromType to ToType is a qualification conversion
1139/// (C++ 4.4).
1140bool
1141Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1142{
1143 FromType = Context.getCanonicalType(FromType);
1144 ToType = Context.getCanonicalType(ToType);
1145
1146 // If FromType and ToType are the same type, this is not a
1147 // qualification conversion.
1148 if (FromType == ToType)
1149 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001150
Douglas Gregor98cd5992008-10-21 23:43:52 +00001151 // (C++ 4.4p4):
1152 // A conversion can add cv-qualifiers at levels other than the first
1153 // in multi-level pointers, subject to the following rules: [...]
1154 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001155 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001156 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001157 // Within each iteration of the loop, we check the qualifiers to
1158 // determine if this still looks like a qualification
1159 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001160 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001161 // until there are no more pointers or pointers-to-members left to
1162 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001163 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001164
1165 // -- for every j > 0, if const is in cv 1,j then const is in cv
1166 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001167 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001168 return false;
Douglas Gregor57373262008-10-22 14:17:15 +00001169
Douglas Gregor98cd5992008-10-21 23:43:52 +00001170 // -- if the cv 1,j and cv 2,j are different, then const is in
1171 // every cv for 0 < k < j.
1172 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001173 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001174 return false;
Douglas Gregor57373262008-10-22 14:17:15 +00001175
Douglas Gregor98cd5992008-10-21 23:43:52 +00001176 // Keep track of whether all prior cv-qualifiers in the "to" type
1177 // include const.
1178 PreviousToQualsIncludeConst
1179 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001180 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001181
1182 // We are left with FromType and ToType being the pointee types
1183 // after unwrapping the original FromType and ToType the same number
1184 // of types. If we unwrapped any pointers, and if FromType and
1185 // ToType have the same unqualified type (since we checked
1186 // qualifiers above), then this is a qualification conversion.
1187 return UnwrappedAnyPointer &&
1188 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1189}
1190
Douglas Gregor60d62c22008-10-31 16:23:19 +00001191/// IsUserDefinedConversion - Determines whether there is a
1192/// user-defined conversion sequence (C++ [over.ics.user]) that
1193/// converts expression From to the type ToType. If such a conversion
1194/// exists, User will contain the user-defined conversion sequence
1195/// that performs such a conversion and this routine will return
1196/// true. Otherwise, this routine returns false and User is
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001197/// unspecified. AllowExplicit is true if the conversion should
1198/// consider C++0x "explicit" conversion functions as well as
1199/// non-explicit conversion functions (C++0x [class.conv.fct]p2).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001200bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001201 UserDefinedConversionSequence& User,
1202 bool AllowExplicit)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001203{
1204 OverloadCandidateSet CandidateSet;
1205 if (const CXXRecordType *ToRecordType
1206 = dyn_cast_or_null<CXXRecordType>(ToType->getAsRecordType())) {
1207 // C++ [over.match.ctor]p1:
1208 // When objects of class type are direct-initialized (8.5), or
1209 // copy-initialized from an expression of the same or a
1210 // derived class type (8.5), overload resolution selects the
1211 // constructor. [...] For copy-initialization, the candidate
1212 // functions are all the converting constructors (12.3.1) of
1213 // that class. The argument list is the expression-list within
1214 // the parentheses of the initializer.
1215 CXXRecordDecl *ToRecordDecl = ToRecordType->getDecl();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001216 DeclarationName ConstructorName
1217 = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregore63ef482009-01-13 00:11:19 +00001218 Context.getCanonicalType(ToType).getUnqualifiedType());
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001219 DeclContext::lookup_iterator Con, ConEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00001220 for (llvm::tie(Con, ConEnd) = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001221 Con != ConEnd; ++Con) {
1222 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001223 if (Constructor->isConvertingConstructor())
Douglas Gregor225c41e2008-11-03 19:09:14 +00001224 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1225 /*SuppressUserConversions=*/true);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001226 }
1227 }
1228
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001229 if (const CXXRecordType *FromRecordType
1230 = dyn_cast_or_null<CXXRecordType>(From->getType()->getAsRecordType())) {
1231 // Add all of the conversion functions as candidates.
1232 // FIXME: Look for conversions in base classes!
1233 CXXRecordDecl *FromRecordDecl = FromRecordType->getDecl();
1234 OverloadedFunctionDecl *Conversions
1235 = FromRecordDecl->getConversionFunctions();
1236 for (OverloadedFunctionDecl::function_iterator Func
1237 = Conversions->function_begin();
1238 Func != Conversions->function_end(); ++Func) {
1239 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001240 if (AllowExplicit || !Conv->isExplicit())
1241 AddConversionCandidate(Conv, From, ToType, CandidateSet);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001242 }
1243 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001244
1245 OverloadCandidateSet::iterator Best;
1246 switch (BestViableFunction(CandidateSet, Best)) {
1247 case OR_Success:
1248 // Record the standard conversion we used and the conversion function.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001249 if (CXXConstructorDecl *Constructor
1250 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1251 // C++ [over.ics.user]p1:
1252 // If the user-defined conversion is specified by a
1253 // constructor (12.3.1), the initial standard conversion
1254 // sequence converts the source type to the type required by
1255 // the argument of the constructor.
1256 //
1257 // FIXME: What about ellipsis conversions?
1258 QualType ThisType = Constructor->getThisType(Context);
1259 User.Before = Best->Conversions[0].Standard;
1260 User.ConversionFunction = Constructor;
1261 User.After.setAsIdentityConversion();
1262 User.After.FromTypePtr
1263 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
1264 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1265 return true;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001266 } else if (CXXConversionDecl *Conversion
1267 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1268 // C++ [over.ics.user]p1:
1269 //
1270 // [...] If the user-defined conversion is specified by a
1271 // conversion function (12.3.2), the initial standard
1272 // conversion sequence converts the source type to the
1273 // implicit object parameter of the conversion function.
1274 User.Before = Best->Conversions[0].Standard;
1275 User.ConversionFunction = Conversion;
1276
1277 // C++ [over.ics.user]p2:
1278 // The second standard conversion sequence converts the
1279 // result of the user-defined conversion to the target type
1280 // for the sequence. Since an implicit conversion sequence
1281 // is an initialization, the special rules for
1282 // initialization by user-defined conversion apply when
1283 // selecting the best user-defined conversion for a
1284 // user-defined conversion sequence (see 13.3.3 and
1285 // 13.3.3.1).
1286 User.After = Best->FinalConversion;
1287 return true;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001288 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001289 assert(false && "Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001290 return false;
1291 }
1292
1293 case OR_No_Viable_Function:
1294 // No conversion here! We're done.
1295 return false;
1296
1297 case OR_Ambiguous:
1298 // FIXME: See C++ [over.best.ics]p10 for the handling of
1299 // ambiguous conversion sequences.
1300 return false;
1301 }
1302
1303 return false;
1304}
1305
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001306/// CompareImplicitConversionSequences - Compare two implicit
1307/// conversion sequences to determine whether one is better than the
1308/// other or if they are indistinguishable (C++ 13.3.3.2).
1309ImplicitConversionSequence::CompareKind
1310Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1311 const ImplicitConversionSequence& ICS2)
1312{
1313 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1314 // conversion sequences (as defined in 13.3.3.1)
1315 // -- a standard conversion sequence (13.3.3.1.1) is a better
1316 // conversion sequence than a user-defined conversion sequence or
1317 // an ellipsis conversion sequence, and
1318 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1319 // conversion sequence than an ellipsis conversion sequence
1320 // (13.3.3.1.3).
1321 //
1322 if (ICS1.ConversionKind < ICS2.ConversionKind)
1323 return ImplicitConversionSequence::Better;
1324 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1325 return ImplicitConversionSequence::Worse;
1326
1327 // Two implicit conversion sequences of the same form are
1328 // indistinguishable conversion sequences unless one of the
1329 // following rules apply: (C++ 13.3.3.2p3):
1330 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1331 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1332 else if (ICS1.ConversionKind ==
1333 ImplicitConversionSequence::UserDefinedConversion) {
1334 // User-defined conversion sequence U1 is a better conversion
1335 // sequence than another user-defined conversion sequence U2 if
1336 // they contain the same user-defined conversion function or
1337 // constructor and if the second standard conversion sequence of
1338 // U1 is better than the second standard conversion sequence of
1339 // U2 (C++ 13.3.3.2p3).
1340 if (ICS1.UserDefined.ConversionFunction ==
1341 ICS2.UserDefined.ConversionFunction)
1342 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1343 ICS2.UserDefined.After);
1344 }
1345
1346 return ImplicitConversionSequence::Indistinguishable;
1347}
1348
1349/// CompareStandardConversionSequences - Compare two standard
1350/// conversion sequences to determine whether one is better than the
1351/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1352ImplicitConversionSequence::CompareKind
1353Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1354 const StandardConversionSequence& SCS2)
1355{
1356 // Standard conversion sequence S1 is a better conversion sequence
1357 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1358
1359 // -- S1 is a proper subsequence of S2 (comparing the conversion
1360 // sequences in the canonical form defined by 13.3.3.1.1,
1361 // excluding any Lvalue Transformation; the identity conversion
1362 // sequence is considered to be a subsequence of any
1363 // non-identity conversion sequence) or, if not that,
1364 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1365 // Neither is a proper subsequence of the other. Do nothing.
1366 ;
1367 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1368 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1369 (SCS1.Second == ICK_Identity &&
1370 SCS1.Third == ICK_Identity))
1371 // SCS1 is a proper subsequence of SCS2.
1372 return ImplicitConversionSequence::Better;
1373 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1374 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1375 (SCS2.Second == ICK_Identity &&
1376 SCS2.Third == ICK_Identity))
1377 // SCS2 is a proper subsequence of SCS1.
1378 return ImplicitConversionSequence::Worse;
1379
1380 // -- the rank of S1 is better than the rank of S2 (by the rules
1381 // defined below), or, if not that,
1382 ImplicitConversionRank Rank1 = SCS1.getRank();
1383 ImplicitConversionRank Rank2 = SCS2.getRank();
1384 if (Rank1 < Rank2)
1385 return ImplicitConversionSequence::Better;
1386 else if (Rank2 < Rank1)
1387 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001388
Douglas Gregor57373262008-10-22 14:17:15 +00001389 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1390 // are indistinguishable unless one of the following rules
1391 // applies:
1392
1393 // A conversion that is not a conversion of a pointer, or
1394 // pointer to member, to bool is better than another conversion
1395 // that is such a conversion.
1396 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1397 return SCS2.isPointerConversionToBool()
1398 ? ImplicitConversionSequence::Better
1399 : ImplicitConversionSequence::Worse;
1400
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001401 // C++ [over.ics.rank]p4b2:
1402 //
1403 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001404 // conversion of B* to A* is better than conversion of B* to
1405 // void*, and conversion of A* to void* is better than conversion
1406 // of B* to void*.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001407 bool SCS1ConvertsToVoid
1408 = SCS1.isPointerConversionToVoidPointer(Context);
1409 bool SCS2ConvertsToVoid
1410 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001411 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1412 // Exactly one of the conversion sequences is a conversion to
1413 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001414 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1415 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001416 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1417 // Neither conversion sequence converts to a void pointer; compare
1418 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001419 if (ImplicitConversionSequence::CompareKind DerivedCK
1420 = CompareDerivedToBaseConversions(SCS1, SCS2))
1421 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001422 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1423 // Both conversion sequences are conversions to void
1424 // pointers. Compare the source types to determine if there's an
1425 // inheritance relationship in their sources.
1426 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1427 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1428
1429 // Adjust the types we're converting from via the array-to-pointer
1430 // conversion, if we need to.
1431 if (SCS1.First == ICK_Array_To_Pointer)
1432 FromType1 = Context.getArrayDecayedType(FromType1);
1433 if (SCS2.First == ICK_Array_To_Pointer)
1434 FromType2 = Context.getArrayDecayedType(FromType2);
1435
1436 QualType FromPointee1
1437 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1438 QualType FromPointee2
1439 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1440
1441 if (IsDerivedFrom(FromPointee2, FromPointee1))
1442 return ImplicitConversionSequence::Better;
1443 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1444 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001445
1446 // Objective-C++: If one interface is more specific than the
1447 // other, it is the better one.
1448 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1449 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1450 if (FromIface1 && FromIface1) {
1451 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1452 return ImplicitConversionSequence::Better;
1453 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1454 return ImplicitConversionSequence::Worse;
1455 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001456 }
Douglas Gregor57373262008-10-22 14:17:15 +00001457
1458 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1459 // bullet 3).
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001460 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001461 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001462 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001463
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001464 // C++ [over.ics.rank]p3b4:
1465 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1466 // which the references refer are the same type except for
1467 // top-level cv-qualifiers, and the type to which the reference
1468 // initialized by S2 refers is more cv-qualified than the type
1469 // to which the reference initialized by S1 refers.
1470 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1471 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1472 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1473 T1 = Context.getCanonicalType(T1);
1474 T2 = Context.getCanonicalType(T2);
1475 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1476 if (T2.isMoreQualifiedThan(T1))
1477 return ImplicitConversionSequence::Better;
1478 else if (T1.isMoreQualifiedThan(T2))
1479 return ImplicitConversionSequence::Worse;
1480 }
1481 }
Douglas Gregor57373262008-10-22 14:17:15 +00001482
1483 return ImplicitConversionSequence::Indistinguishable;
1484}
1485
1486/// CompareQualificationConversions - Compares two standard conversion
1487/// sequences to determine whether they can be ranked based on their
1488/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1489ImplicitConversionSequence::CompareKind
1490Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1491 const StandardConversionSequence& SCS2)
1492{
Douglas Gregorba7e2102008-10-22 15:04:37 +00001493 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001494 // -- S1 and S2 differ only in their qualification conversion and
1495 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1496 // cv-qualification signature of type T1 is a proper subset of
1497 // the cv-qualification signature of type T2, and S1 is not the
1498 // deprecated string literal array-to-pointer conversion (4.2).
1499 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1500 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1501 return ImplicitConversionSequence::Indistinguishable;
1502
1503 // FIXME: the example in the standard doesn't use a qualification
1504 // conversion (!)
1505 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1506 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1507 T1 = Context.getCanonicalType(T1);
1508 T2 = Context.getCanonicalType(T2);
1509
1510 // If the types are the same, we won't learn anything by unwrapped
1511 // them.
1512 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1513 return ImplicitConversionSequence::Indistinguishable;
1514
1515 ImplicitConversionSequence::CompareKind Result
1516 = ImplicitConversionSequence::Indistinguishable;
1517 while (UnwrapSimilarPointerTypes(T1, T2)) {
1518 // Within each iteration of the loop, we check the qualifiers to
1519 // determine if this still looks like a qualification
1520 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001521 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001522 // until there are no more pointers or pointers-to-members left
1523 // to unwrap. This essentially mimics what
1524 // IsQualificationConversion does, but here we're checking for a
1525 // strict subset of qualifiers.
1526 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1527 // The qualifiers are the same, so this doesn't tell us anything
1528 // about how the sequences rank.
1529 ;
1530 else if (T2.isMoreQualifiedThan(T1)) {
1531 // T1 has fewer qualifiers, so it could be the better sequence.
1532 if (Result == ImplicitConversionSequence::Worse)
1533 // Neither has qualifiers that are a subset of the other's
1534 // qualifiers.
1535 return ImplicitConversionSequence::Indistinguishable;
1536
1537 Result = ImplicitConversionSequence::Better;
1538 } else if (T1.isMoreQualifiedThan(T2)) {
1539 // T2 has fewer qualifiers, so it could be the better sequence.
1540 if (Result == ImplicitConversionSequence::Better)
1541 // Neither has qualifiers that are a subset of the other's
1542 // qualifiers.
1543 return ImplicitConversionSequence::Indistinguishable;
1544
1545 Result = ImplicitConversionSequence::Worse;
1546 } else {
1547 // Qualifiers are disjoint.
1548 return ImplicitConversionSequence::Indistinguishable;
1549 }
1550
1551 // If the types after this point are equivalent, we're done.
1552 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1553 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001554 }
1555
Douglas Gregor57373262008-10-22 14:17:15 +00001556 // Check that the winning standard conversion sequence isn't using
1557 // the deprecated string literal array to pointer conversion.
1558 switch (Result) {
1559 case ImplicitConversionSequence::Better:
1560 if (SCS1.Deprecated)
1561 Result = ImplicitConversionSequence::Indistinguishable;
1562 break;
1563
1564 case ImplicitConversionSequence::Indistinguishable:
1565 break;
1566
1567 case ImplicitConversionSequence::Worse:
1568 if (SCS2.Deprecated)
1569 Result = ImplicitConversionSequence::Indistinguishable;
1570 break;
1571 }
1572
1573 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001574}
1575
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001576/// CompareDerivedToBaseConversions - Compares two standard conversion
1577/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00001578/// various kinds of derived-to-base conversions (C++
1579/// [over.ics.rank]p4b3). As part of these checks, we also look at
1580/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001581ImplicitConversionSequence::CompareKind
1582Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1583 const StandardConversionSequence& SCS2) {
1584 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1585 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1586 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1587 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1588
1589 // Adjust the types we're converting from via the array-to-pointer
1590 // conversion, if we need to.
1591 if (SCS1.First == ICK_Array_To_Pointer)
1592 FromType1 = Context.getArrayDecayedType(FromType1);
1593 if (SCS2.First == ICK_Array_To_Pointer)
1594 FromType2 = Context.getArrayDecayedType(FromType2);
1595
1596 // Canonicalize all of the types.
1597 FromType1 = Context.getCanonicalType(FromType1);
1598 ToType1 = Context.getCanonicalType(ToType1);
1599 FromType2 = Context.getCanonicalType(FromType2);
1600 ToType2 = Context.getCanonicalType(ToType2);
1601
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001602 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001603 //
1604 // If class B is derived directly or indirectly from class A and
1605 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001606 //
1607 // For Objective-C, we let A, B, and C also be Objective-C
1608 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001609
1610 // Compare based on pointer conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001611 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00001612 SCS2.Second == ICK_Pointer_Conversion &&
1613 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1614 FromType1->isPointerType() && FromType2->isPointerType() &&
1615 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001616 QualType FromPointee1
1617 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1618 QualType ToPointee1
1619 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1620 QualType FromPointee2
1621 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1622 QualType ToPointee2
1623 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001624
1625 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1626 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1627 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1628 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1629
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001630 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001631 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1632 if (IsDerivedFrom(ToPointee1, ToPointee2))
1633 return ImplicitConversionSequence::Better;
1634 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1635 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001636
1637 if (ToIface1 && ToIface2) {
1638 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1639 return ImplicitConversionSequence::Better;
1640 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1641 return ImplicitConversionSequence::Worse;
1642 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001643 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001644
1645 // -- conversion of B* to A* is better than conversion of C* to A*,
1646 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1647 if (IsDerivedFrom(FromPointee2, FromPointee1))
1648 return ImplicitConversionSequence::Better;
1649 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1650 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001651
1652 if (FromIface1 && FromIface2) {
1653 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1654 return ImplicitConversionSequence::Better;
1655 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1656 return ImplicitConversionSequence::Worse;
1657 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001658 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001659 }
1660
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001661 // Compare based on reference bindings.
1662 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1663 SCS1.Second == ICK_Derived_To_Base) {
1664 // -- binding of an expression of type C to a reference of type
1665 // B& is better than binding an expression of type C to a
1666 // reference of type A&,
1667 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1668 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1669 if (IsDerivedFrom(ToType1, ToType2))
1670 return ImplicitConversionSequence::Better;
1671 else if (IsDerivedFrom(ToType2, ToType1))
1672 return ImplicitConversionSequence::Worse;
1673 }
1674
Douglas Gregor225c41e2008-11-03 19:09:14 +00001675 // -- binding of an expression of type B to a reference of type
1676 // A& is better than binding an expression of type C to a
1677 // reference of type A&,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001678 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1679 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1680 if (IsDerivedFrom(FromType2, FromType1))
1681 return ImplicitConversionSequence::Better;
1682 else if (IsDerivedFrom(FromType1, FromType2))
1683 return ImplicitConversionSequence::Worse;
1684 }
1685 }
1686
1687
1688 // FIXME: conversion of A::* to B::* is better than conversion of
1689 // A::* to C::*,
1690
1691 // FIXME: conversion of B::* to C::* is better than conversion of
1692 // A::* to C::*, and
1693
Douglas Gregor225c41e2008-11-03 19:09:14 +00001694 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1695 SCS1.Second == ICK_Derived_To_Base) {
1696 // -- conversion of C to B is better than conversion of C to A,
1697 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1698 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1699 if (IsDerivedFrom(ToType1, ToType2))
1700 return ImplicitConversionSequence::Better;
1701 else if (IsDerivedFrom(ToType2, ToType1))
1702 return ImplicitConversionSequence::Worse;
1703 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001704
Douglas Gregor225c41e2008-11-03 19:09:14 +00001705 // -- conversion of B to A is better than conversion of C to A.
1706 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1707 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1708 if (IsDerivedFrom(FromType2, FromType1))
1709 return ImplicitConversionSequence::Better;
1710 else if (IsDerivedFrom(FromType1, FromType2))
1711 return ImplicitConversionSequence::Worse;
1712 }
1713 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001714
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001715 return ImplicitConversionSequence::Indistinguishable;
1716}
1717
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001718/// TryCopyInitialization - Try to copy-initialize a value of type
1719/// ToType from the expression From. Return the implicit conversion
1720/// sequence required to pass this argument, which may be a bad
1721/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00001722/// a parameter of this type). If @p SuppressUserConversions, then we
1723/// do not permit any user-defined conversion sequences.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001724ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +00001725Sema::TryCopyInitialization(Expr *From, QualType ToType,
1726 bool SuppressUserConversions) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001727 if (!getLangOptions().CPlusPlus) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001728 // In C, copy initialization is the same as performing an assignment.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001729 AssignConvertType ConvTy =
1730 CheckSingleAssignmentConstraints(ToType, From);
1731 ImplicitConversionSequence ICS;
1732 if (getLangOptions().NoExtensions? ConvTy != Compatible
1733 : ConvTy == Incompatible)
1734 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1735 else
1736 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1737 return ICS;
1738 } else if (ToType->isReferenceType()) {
1739 ImplicitConversionSequence ICS;
Douglas Gregor225c41e2008-11-03 19:09:14 +00001740 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001741 return ICS;
1742 } else {
Douglas Gregor225c41e2008-11-03 19:09:14 +00001743 return TryImplicitConversion(From, ToType, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001744 }
1745}
1746
1747/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1748/// type ToType. Returns true (and emits a diagnostic) if there was
1749/// an error, returns false if the initialization succeeded.
1750bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1751 const char* Flavor) {
1752 if (!getLangOptions().CPlusPlus) {
1753 // In C, argument passing is the same as performing an assignment.
1754 QualType FromType = From->getType();
1755 AssignConvertType ConvTy =
1756 CheckSingleAssignmentConstraints(ToType, From);
1757
1758 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1759 FromType, From, Flavor);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001760 }
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001761
1762 if (ToType->isReferenceType())
1763 return CheckReferenceInit(From, ToType);
1764
Douglas Gregor45920e82008-12-19 17:40:08 +00001765 if (!PerformImplicitConversion(From, ToType, Flavor))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001766 return false;
1767
1768 return Diag(From->getSourceRange().getBegin(),
1769 diag::err_typecheck_convert_incompatible)
1770 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001771}
1772
Douglas Gregor96176b32008-11-18 23:14:02 +00001773/// TryObjectArgumentInitialization - Try to initialize the object
1774/// parameter of the given member function (@c Method) from the
1775/// expression @p From.
1776ImplicitConversionSequence
1777Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1778 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1779 unsigned MethodQuals = Method->getTypeQualifiers();
1780 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1781
1782 // Set up the conversion sequence as a "bad" conversion, to allow us
1783 // to exit early.
1784 ImplicitConversionSequence ICS;
1785 ICS.Standard.setAsIdentityConversion();
1786 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1787
1788 // We need to have an object of class type.
1789 QualType FromType = From->getType();
1790 if (!FromType->isRecordType())
1791 return ICS;
1792
1793 // The implicit object parmeter is has the type "reference to cv X",
1794 // where X is the class of which the function is a member
1795 // (C++ [over.match.funcs]p4). However, when finding an implicit
1796 // conversion sequence for the argument, we are not allowed to
1797 // create temporaries or perform user-defined conversions
1798 // (C++ [over.match.funcs]p5). We perform a simplified version of
1799 // reference binding here, that allows class rvalues to bind to
1800 // non-constant references.
1801
1802 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1803 // with the implicit object parameter (C++ [over.match.funcs]p5).
1804 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1805 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1806 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1807 return ICS;
1808
1809 // Check that we have either the same type or a derived type. It
1810 // affects the conversion rank.
1811 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1812 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1813 ICS.Standard.Second = ICK_Identity;
1814 else if (IsDerivedFrom(FromType, ClassType))
1815 ICS.Standard.Second = ICK_Derived_To_Base;
1816 else
1817 return ICS;
1818
1819 // Success. Mark this as a reference binding.
1820 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1821 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1822 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1823 ICS.Standard.ReferenceBinding = true;
1824 ICS.Standard.DirectBinding = true;
1825 return ICS;
1826}
1827
1828/// PerformObjectArgumentInitialization - Perform initialization of
1829/// the implicit object parameter for the given Method with the given
1830/// expression.
1831bool
1832Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
1833 QualType ImplicitParamType
1834 = Method->getThisType(Context)->getAsPointerType()->getPointeeType();
1835 ImplicitConversionSequence ICS
1836 = TryObjectArgumentInitialization(From, Method);
1837 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
1838 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001839 diag::err_implicit_object_parameter_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00001840 << ImplicitParamType << From->getType() << From->getSourceRange();
Douglas Gregor96176b32008-11-18 23:14:02 +00001841
1842 if (ICS.Standard.Second == ICK_Derived_To_Base &&
1843 CheckDerivedToBaseConversion(From->getType(), ImplicitParamType,
1844 From->getSourceRange().getBegin(),
1845 From->getSourceRange()))
1846 return true;
1847
1848 ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true);
1849 return false;
1850}
1851
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001852/// TryContextuallyConvertToBool - Attempt to contextually convert the
1853/// expression From to bool (C++0x [conv]p3).
1854ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
1855 return TryImplicitConversion(From, Context.BoolTy, false, true);
1856}
1857
1858/// PerformContextuallyConvertToBool - Perform a contextual conversion
1859/// of the expression From to bool (C++0x [conv]p3).
1860bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
1861 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
1862 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
1863 return false;
1864
1865 return Diag(From->getSourceRange().getBegin(),
1866 diag::err_typecheck_bool_condition)
1867 << From->getType() << From->getSourceRange();
1868}
1869
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001870/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00001871/// candidate functions, using the given function call arguments. If
1872/// @p SuppressUserConversions, then don't allow user-defined
1873/// conversions via constructors or conversion operators.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001874void
1875Sema::AddOverloadCandidate(FunctionDecl *Function,
1876 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00001877 OverloadCandidateSet& CandidateSet,
1878 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001879{
1880 const FunctionTypeProto* Proto
1881 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType());
1882 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001883 assert(!isa<CXXConversionDecl>(Function) &&
1884 "Use AddConversionCandidate for conversion functions");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001885
Douglas Gregor88a35142008-12-22 05:46:06 +00001886 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
1887 // If we get here, it's because we're calling a member function
1888 // that is named without a member access expression (e.g.,
1889 // "this->f") that was either written explicitly or created
1890 // implicitly. This can happen with a qualified call to a member
1891 // function, e.g., X::f(). We use a NULL object as the implied
1892 // object argument (C++ [over.call.func]p3).
1893 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
1894 SuppressUserConversions);
1895 return;
1896 }
1897
1898
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001899 // Add this candidate
1900 CandidateSet.push_back(OverloadCandidate());
1901 OverloadCandidate& Candidate = CandidateSet.back();
1902 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00001903 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001904 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00001905 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001906
1907 unsigned NumArgsInProto = Proto->getNumArgs();
1908
1909 // (C++ 13.3.2p2): A candidate function having fewer than m
1910 // parameters is viable only if it has an ellipsis in its parameter
1911 // list (8.3.5).
1912 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1913 Candidate.Viable = false;
1914 return;
1915 }
1916
1917 // (C++ 13.3.2p2): A candidate function having more than m parameters
1918 // is viable only if the (m+1)st parameter has a default argument
1919 // (8.3.6). For the purposes of overload resolution, the
1920 // parameter list is truncated on the right, so that there are
1921 // exactly m parameters.
1922 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
1923 if (NumArgs < MinRequiredArgs) {
1924 // Not enough arguments.
1925 Candidate.Viable = false;
1926 return;
1927 }
1928
1929 // Determine the implicit conversion sequences for each of the
1930 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001931 Candidate.Conversions.resize(NumArgs);
1932 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1933 if (ArgIdx < NumArgsInProto) {
1934 // (C++ 13.3.2p3): for F to be a viable function, there shall
1935 // exist for each argument an implicit conversion sequence
1936 // (13.3.3.1) that converts that argument to the corresponding
1937 // parameter of F.
1938 QualType ParamType = Proto->getArgType(ArgIdx);
1939 Candidate.Conversions[ArgIdx]
Douglas Gregor225c41e2008-11-03 19:09:14 +00001940 = TryCopyInitialization(Args[ArgIdx], ParamType,
1941 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001942 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00001943 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001944 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001945 break;
1946 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001947 } else {
1948 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1949 // argument for which there is no corresponding parameter is
1950 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1951 Candidate.Conversions[ArgIdx].ConversionKind
1952 = ImplicitConversionSequence::EllipsisConversion;
1953 }
1954 }
1955}
1956
Douglas Gregor96176b32008-11-18 23:14:02 +00001957/// AddMethodCandidate - Adds the given C++ member function to the set
1958/// of candidate functions, using the given function call arguments
1959/// and the object argument (@c Object). For example, in a call
1960/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
1961/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
1962/// allow user-defined conversions via constructors or conversion
1963/// operators.
1964void
1965Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
1966 Expr **Args, unsigned NumArgs,
1967 OverloadCandidateSet& CandidateSet,
1968 bool SuppressUserConversions)
1969{
1970 const FunctionTypeProto* Proto
1971 = dyn_cast<FunctionTypeProto>(Method->getType()->getAsFunctionType());
1972 assert(Proto && "Methods without a prototype cannot be overloaded");
1973 assert(!isa<CXXConversionDecl>(Method) &&
1974 "Use AddConversionCandidate for conversion functions");
1975
1976 // Add this candidate
1977 CandidateSet.push_back(OverloadCandidate());
1978 OverloadCandidate& Candidate = CandidateSet.back();
1979 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001980 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00001981 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001982
1983 unsigned NumArgsInProto = Proto->getNumArgs();
1984
1985 // (C++ 13.3.2p2): A candidate function having fewer than m
1986 // parameters is viable only if it has an ellipsis in its parameter
1987 // list (8.3.5).
1988 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1989 Candidate.Viable = false;
1990 return;
1991 }
1992
1993 // (C++ 13.3.2p2): A candidate function having more than m parameters
1994 // is viable only if the (m+1)st parameter has a default argument
1995 // (8.3.6). For the purposes of overload resolution, the
1996 // parameter list is truncated on the right, so that there are
1997 // exactly m parameters.
1998 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
1999 if (NumArgs < MinRequiredArgs) {
2000 // Not enough arguments.
2001 Candidate.Viable = false;
2002 return;
2003 }
2004
2005 Candidate.Viable = true;
2006 Candidate.Conversions.resize(NumArgs + 1);
2007
Douglas Gregor88a35142008-12-22 05:46:06 +00002008 if (Method->isStatic() || !Object)
2009 // The implicit object argument is ignored.
2010 Candidate.IgnoreObjectArgument = true;
2011 else {
2012 // Determine the implicit conversion sequence for the object
2013 // parameter.
2014 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2015 if (Candidate.Conversions[0].ConversionKind
2016 == ImplicitConversionSequence::BadConversion) {
2017 Candidate.Viable = false;
2018 return;
2019 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002020 }
2021
2022 // Determine the implicit conversion sequences for each of the
2023 // arguments.
2024 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2025 if (ArgIdx < NumArgsInProto) {
2026 // (C++ 13.3.2p3): for F to be a viable function, there shall
2027 // exist for each argument an implicit conversion sequence
2028 // (13.3.3.1) that converts that argument to the corresponding
2029 // parameter of F.
2030 QualType ParamType = Proto->getArgType(ArgIdx);
2031 Candidate.Conversions[ArgIdx + 1]
2032 = TryCopyInitialization(Args[ArgIdx], ParamType,
2033 SuppressUserConversions);
2034 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2035 == ImplicitConversionSequence::BadConversion) {
2036 Candidate.Viable = false;
2037 break;
2038 }
2039 } else {
2040 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2041 // argument for which there is no corresponding parameter is
2042 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2043 Candidate.Conversions[ArgIdx + 1].ConversionKind
2044 = ImplicitConversionSequence::EllipsisConversion;
2045 }
2046 }
2047}
2048
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002049/// AddConversionCandidate - Add a C++ conversion function as a
2050/// candidate in the candidate set (C++ [over.match.conv],
2051/// C++ [over.match.copy]). From is the expression we're converting from,
2052/// and ToType is the type that we're eventually trying to convert to
2053/// (which may or may not be the same type as the type that the
2054/// conversion function produces).
2055void
2056Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2057 Expr *From, QualType ToType,
2058 OverloadCandidateSet& CandidateSet) {
2059 // Add this candidate
2060 CandidateSet.push_back(OverloadCandidate());
2061 OverloadCandidate& Candidate = CandidateSet.back();
2062 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002063 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002064 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002065 Candidate.FinalConversion.setAsIdentityConversion();
2066 Candidate.FinalConversion.FromTypePtr
2067 = Conversion->getConversionType().getAsOpaquePtr();
2068 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2069
Douglas Gregor96176b32008-11-18 23:14:02 +00002070 // Determine the implicit conversion sequence for the implicit
2071 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002072 Candidate.Viable = true;
2073 Candidate.Conversions.resize(1);
Douglas Gregor96176b32008-11-18 23:14:02 +00002074 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002075
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002076 if (Candidate.Conversions[0].ConversionKind
2077 == ImplicitConversionSequence::BadConversion) {
2078 Candidate.Viable = false;
2079 return;
2080 }
2081
2082 // To determine what the conversion from the result of calling the
2083 // conversion function to the type we're eventually trying to
2084 // convert to (ToType), we need to synthesize a call to the
2085 // conversion function and attempt copy initialization from it. This
2086 // makes sure that we get the right semantics with respect to
2087 // lvalues/rvalues and the type. Fortunately, we can allocate this
2088 // call on the stack and we don't need its arguments to be
2089 // well-formed.
2090 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2091 SourceLocation());
2092 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002093 &ConversionRef, false);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002094 CallExpr Call(&ConversionFn, 0, 0,
2095 Conversion->getConversionType().getNonReferenceType(),
2096 SourceLocation());
2097 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2098 switch (ICS.ConversionKind) {
2099 case ImplicitConversionSequence::StandardConversion:
2100 Candidate.FinalConversion = ICS.Standard;
2101 break;
2102
2103 case ImplicitConversionSequence::BadConversion:
2104 Candidate.Viable = false;
2105 break;
2106
2107 default:
2108 assert(false &&
2109 "Can only end up with a standard conversion sequence or failure");
2110 }
2111}
2112
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002113/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2114/// converts the given @c Object to a function pointer via the
2115/// conversion function @c Conversion, and then attempts to call it
2116/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2117/// the type of function that we'll eventually be calling.
2118void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
2119 const FunctionTypeProto *Proto,
2120 Expr *Object, Expr **Args, unsigned NumArgs,
2121 OverloadCandidateSet& CandidateSet) {
2122 CandidateSet.push_back(OverloadCandidate());
2123 OverloadCandidate& Candidate = CandidateSet.back();
2124 Candidate.Function = 0;
2125 Candidate.Surrogate = Conversion;
2126 Candidate.Viable = true;
2127 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002128 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002129 Candidate.Conversions.resize(NumArgs + 1);
2130
2131 // Determine the implicit conversion sequence for the implicit
2132 // object parameter.
2133 ImplicitConversionSequence ObjectInit
2134 = TryObjectArgumentInitialization(Object, Conversion);
2135 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2136 Candidate.Viable = false;
2137 return;
2138 }
2139
2140 // The first conversion is actually a user-defined conversion whose
2141 // first conversion is ObjectInit's standard conversion (which is
2142 // effectively a reference binding). Record it as such.
2143 Candidate.Conversions[0].ConversionKind
2144 = ImplicitConversionSequence::UserDefinedConversion;
2145 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2146 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2147 Candidate.Conversions[0].UserDefined.After
2148 = Candidate.Conversions[0].UserDefined.Before;
2149 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2150
2151 // Find the
2152 unsigned NumArgsInProto = Proto->getNumArgs();
2153
2154 // (C++ 13.3.2p2): A candidate function having fewer than m
2155 // parameters is viable only if it has an ellipsis in its parameter
2156 // list (8.3.5).
2157 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2158 Candidate.Viable = false;
2159 return;
2160 }
2161
2162 // Function types don't have any default arguments, so just check if
2163 // we have enough arguments.
2164 if (NumArgs < NumArgsInProto) {
2165 // Not enough arguments.
2166 Candidate.Viable = false;
2167 return;
2168 }
2169
2170 // Determine the implicit conversion sequences for each of the
2171 // arguments.
2172 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2173 if (ArgIdx < NumArgsInProto) {
2174 // (C++ 13.3.2p3): for F to be a viable function, there shall
2175 // exist for each argument an implicit conversion sequence
2176 // (13.3.3.1) that converts that argument to the corresponding
2177 // parameter of F.
2178 QualType ParamType = Proto->getArgType(ArgIdx);
2179 Candidate.Conversions[ArgIdx + 1]
2180 = TryCopyInitialization(Args[ArgIdx], ParamType,
2181 /*SuppressUserConversions=*/false);
2182 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2183 == ImplicitConversionSequence::BadConversion) {
2184 Candidate.Viable = false;
2185 break;
2186 }
2187 } else {
2188 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2189 // argument for which there is no corresponding parameter is
2190 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2191 Candidate.Conversions[ArgIdx + 1].ConversionKind
2192 = ImplicitConversionSequence::EllipsisConversion;
2193 }
2194 }
2195}
2196
Douglas Gregor447b69e2008-11-19 03:25:36 +00002197/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2198/// an acceptable non-member overloaded operator for a call whose
2199/// arguments have types T1 (and, if non-empty, T2). This routine
2200/// implements the check in C++ [over.match.oper]p3b2 concerning
2201/// enumeration types.
2202static bool
2203IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2204 QualType T1, QualType T2,
2205 ASTContext &Context) {
2206 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2207 return true;
2208
2209 const FunctionTypeProto *Proto = Fn->getType()->getAsFunctionTypeProto();
2210 if (Proto->getNumArgs() < 1)
2211 return false;
2212
2213 if (T1->isEnumeralType()) {
2214 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
2215 if (Context.getCanonicalType(T1).getUnqualifiedType()
2216 == Context.getCanonicalType(ArgType).getUnqualifiedType())
2217 return true;
2218 }
2219
2220 if (Proto->getNumArgs() < 2)
2221 return false;
2222
2223 if (!T2.isNull() && T2->isEnumeralType()) {
2224 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
2225 if (Context.getCanonicalType(T2).getUnqualifiedType()
2226 == Context.getCanonicalType(ArgType).getUnqualifiedType())
2227 return true;
2228 }
2229
2230 return false;
2231}
2232
Douglas Gregor96176b32008-11-18 23:14:02 +00002233/// AddOperatorCandidates - Add the overloaded operator candidates for
2234/// the operator Op that was used in an operator expression such as "x
2235/// Op y". S is the scope in which the expression occurred (used for
2236/// name lookup of the operator), Args/NumArgs provides the operator
2237/// arguments, and CandidateSet will store the added overload
2238/// candidates. (C++ [over.match.oper]).
2239void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
2240 Expr **Args, unsigned NumArgs,
2241 OverloadCandidateSet& CandidateSet) {
2242 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2243
2244 // C++ [over.match.oper]p3:
2245 // For a unary operator @ with an operand of a type whose
2246 // cv-unqualified version is T1, and for a binary operator @ with
2247 // a left operand of a type whose cv-unqualified version is T1 and
2248 // a right operand of a type whose cv-unqualified version is T2,
2249 // three sets of candidate functions, designated member
2250 // candidates, non-member candidates and built-in candidates, are
2251 // constructed as follows:
2252 QualType T1 = Args[0]->getType();
2253 QualType T2;
2254 if (NumArgs > 1)
2255 T2 = Args[1]->getType();
2256
2257 // -- If T1 is a class type, the set of member candidates is the
2258 // result of the qualified lookup of T1::operator@
2259 // (13.3.1.1.1); otherwise, the set of member candidates is
2260 // empty.
2261 if (const RecordType *T1Rec = T1->getAsRecordType()) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002262 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00002263 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002264 Oper != OperEnd; ++Oper)
2265 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2266 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor96176b32008-11-18 23:14:02 +00002267 /*SuppressUserConversions=*/false);
Douglas Gregor96176b32008-11-18 23:14:02 +00002268 }
2269
2270 // -- The set of non-member candidates is the result of the
2271 // unqualified lookup of operator@ in the context of the
2272 // expression according to the usual rules for name lookup in
2273 // unqualified function calls (3.4.2) except that all member
2274 // functions are ignored. However, if no operand has a class
2275 // type, only those non-member functions in the lookup set
2276 // that have a first parameter of type T1 or “reference to
2277 // (possibly cv-qualified) T1”, when T1 is an enumeration
2278 // type, or (if there is a right operand) a second parameter
2279 // of type T2 or “reference to (possibly cv-qualified) T2”,
2280 // when T2 is an enumeration type, are candidate functions.
2281 {
Douglas Gregor6ed40e32008-12-23 21:05:05 +00002282 IdentifierResolver::iterator
2283 I = IdResolver.begin(OpName, CurContext, true/*LookInParentCtx*/),
2284 IEnd = IdResolver.end();
2285 for (; I != IEnd; ++I) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002286 // We don't need to check the identifier namespace, because
2287 // operator names can only be ordinary identifiers.
2288
2289 // Ignore member functions.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002290 if ((*I)->getDeclContext()->isRecord())
2291 continue;
Douglas Gregor96176b32008-11-18 23:14:02 +00002292
2293 // We found something with this name. We're done.
Douglas Gregor96176b32008-11-18 23:14:02 +00002294 break;
2295 }
2296
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002297 if (I != IEnd) {
2298 Decl *FirstDecl = *I;
Douglas Gregor6ed40e32008-12-23 21:05:05 +00002299 for (; I != IEnd; ++I) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002300 if (FirstDecl->getDeclContext() != (*I)->getDeclContext())
Douglas Gregor6ed40e32008-12-23 21:05:05 +00002301 break;
2302
2303 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I))
2304 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
2305 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2306 /*SuppressUserConversions=*/false);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002307 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002308 }
2309 }
2310
2311 // Add builtin overload candidates (C++ [over.built]).
Douglas Gregor74253732008-11-19 15:42:04 +00002312 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
Douglas Gregor96176b32008-11-18 23:14:02 +00002313}
2314
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002315/// AddBuiltinCandidate - Add a candidate for a built-in
2316/// operator. ResultTy and ParamTys are the result and parameter types
2317/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002318/// arguments being passed to the candidate. IsAssignmentOperator
2319/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002320/// operator. NumContextualBoolArguments is the number of arguments
2321/// (at the beginning of the argument list) that will be contextually
2322/// converted to bool.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002323void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2324 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002325 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002326 bool IsAssignmentOperator,
2327 unsigned NumContextualBoolArguments) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002328 // Add this candidate
2329 CandidateSet.push_back(OverloadCandidate());
2330 OverloadCandidate& Candidate = CandidateSet.back();
2331 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00002332 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002333 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002334 Candidate.BuiltinTypes.ResultTy = ResultTy;
2335 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2336 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2337
2338 // Determine the implicit conversion sequences for each of the
2339 // arguments.
2340 Candidate.Viable = true;
2341 Candidate.Conversions.resize(NumArgs);
2342 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002343 // C++ [over.match.oper]p4:
2344 // For the built-in assignment operators, conversions of the
2345 // left operand are restricted as follows:
2346 // -- no temporaries are introduced to hold the left operand, and
2347 // -- no user-defined conversions are applied to the left
2348 // operand to achieve a type match with the left-most
2349 // parameter of a built-in candidate.
2350 //
2351 // We block these conversions by turning off user-defined
2352 // conversions, since that is the only way that initialization of
2353 // a reference to a non-class type can occur from something that
2354 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002355 if (ArgIdx < NumContextualBoolArguments) {
2356 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2357 "Contextual conversion to bool requires bool type");
2358 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2359 } else {
2360 Candidate.Conversions[ArgIdx]
2361 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2362 ArgIdx == 0 && IsAssignmentOperator);
2363 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002364 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002365 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002366 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002367 break;
2368 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002369 }
2370}
2371
2372/// BuiltinCandidateTypeSet - A set of types that will be used for the
2373/// candidate operator functions for built-in operators (C++
2374/// [over.built]). The types are separated into pointer types and
2375/// enumeration types.
2376class BuiltinCandidateTypeSet {
2377 /// TypeSet - A set of types.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002378 typedef llvm::SmallPtrSet<void*, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002379
2380 /// PointerTypes - The set of pointer types that will be used in the
2381 /// built-in candidates.
2382 TypeSet PointerTypes;
2383
2384 /// EnumerationTypes - The set of enumeration types that will be
2385 /// used in the built-in candidates.
2386 TypeSet EnumerationTypes;
2387
2388 /// Context - The AST context in which we will build the type sets.
2389 ASTContext &Context;
2390
2391 bool AddWithMoreQualifiedTypeVariants(QualType Ty);
2392
2393public:
2394 /// iterator - Iterates through the types that are part of the set.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002395 class iterator {
2396 TypeSet::iterator Base;
2397
2398 public:
2399 typedef QualType value_type;
2400 typedef QualType reference;
2401 typedef QualType pointer;
2402 typedef std::ptrdiff_t difference_type;
2403 typedef std::input_iterator_tag iterator_category;
2404
2405 iterator(TypeSet::iterator B) : Base(B) { }
2406
2407 iterator& operator++() {
2408 ++Base;
2409 return *this;
2410 }
2411
2412 iterator operator++(int) {
2413 iterator tmp(*this);
2414 ++(*this);
2415 return tmp;
2416 }
2417
2418 reference operator*() const {
2419 return QualType::getFromOpaquePtr(*Base);
2420 }
2421
2422 pointer operator->() const {
2423 return **this;
2424 }
2425
2426 friend bool operator==(iterator LHS, iterator RHS) {
2427 return LHS.Base == RHS.Base;
2428 }
2429
2430 friend bool operator!=(iterator LHS, iterator RHS) {
2431 return LHS.Base != RHS.Base;
2432 }
2433 };
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002434
2435 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2436
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002437 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2438 bool AllowExplicitConversions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002439
2440 /// pointer_begin - First pointer type found;
2441 iterator pointer_begin() { return PointerTypes.begin(); }
2442
2443 /// pointer_end - Last pointer type found;
2444 iterator pointer_end() { return PointerTypes.end(); }
2445
2446 /// enumeration_begin - First enumeration type found;
2447 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2448
2449 /// enumeration_end - Last enumeration type found;
2450 iterator enumeration_end() { return EnumerationTypes.end(); }
2451};
2452
2453/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2454/// the set of pointer types along with any more-qualified variants of
2455/// that type. For example, if @p Ty is "int const *", this routine
2456/// will add "int const *", "int const volatile *", "int const
2457/// restrict *", and "int const volatile restrict *" to the set of
2458/// pointer types. Returns true if the add of @p Ty itself succeeded,
2459/// false otherwise.
2460bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) {
2461 // Insert this type.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002462 if (!PointerTypes.insert(Ty.getAsOpaquePtr()))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002463 return false;
2464
2465 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2466 QualType PointeeTy = PointerTy->getPointeeType();
2467 // FIXME: Optimize this so that we don't keep trying to add the same types.
2468
2469 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
2470 // with all pointer conversions that don't cast away constness?
2471 if (!PointeeTy.isConstQualified())
2472 AddWithMoreQualifiedTypeVariants
2473 (Context.getPointerType(PointeeTy.withConst()));
2474 if (!PointeeTy.isVolatileQualified())
2475 AddWithMoreQualifiedTypeVariants
2476 (Context.getPointerType(PointeeTy.withVolatile()));
2477 if (!PointeeTy.isRestrictQualified())
2478 AddWithMoreQualifiedTypeVariants
2479 (Context.getPointerType(PointeeTy.withRestrict()));
2480 }
2481
2482 return true;
2483}
2484
2485/// AddTypesConvertedFrom - Add each of the types to which the type @p
2486/// Ty can be implicit converted to the given set of @p Types. We're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002487/// primarily interested in pointer types and enumeration types.
2488/// AllowUserConversions is true if we should look at the conversion
2489/// functions of a class type, and AllowExplicitConversions if we
2490/// should also include the explicit conversion functions of a class
2491/// type.
2492void
2493BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2494 bool AllowUserConversions,
2495 bool AllowExplicitConversions) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002496 // Only deal with canonical types.
2497 Ty = Context.getCanonicalType(Ty);
2498
2499 // Look through reference types; they aren't part of the type of an
2500 // expression for the purposes of conversions.
2501 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2502 Ty = RefTy->getPointeeType();
2503
2504 // We don't care about qualifiers on the type.
2505 Ty = Ty.getUnqualifiedType();
2506
2507 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2508 QualType PointeeTy = PointerTy->getPointeeType();
2509
2510 // Insert our type, and its more-qualified variants, into the set
2511 // of types.
2512 if (!AddWithMoreQualifiedTypeVariants(Ty))
2513 return;
2514
2515 // Add 'cv void*' to our set of types.
2516 if (!Ty->isVoidType()) {
2517 QualType QualVoid
2518 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2519 AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2520 }
2521
2522 // If this is a pointer to a class type, add pointers to its bases
2523 // (with the same level of cv-qualification as the original
2524 // derived class, of course).
2525 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2526 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2527 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2528 Base != ClassDecl->bases_end(); ++Base) {
2529 QualType BaseTy = Context.getCanonicalType(Base->getType());
2530 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2531
2532 // Add the pointer type, recursively, so that we get all of
2533 // the indirect base classes, too.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002534 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002535 }
2536 }
2537 } else if (Ty->isEnumeralType()) {
Douglas Gregorbf3af052008-11-13 20:12:29 +00002538 EnumerationTypes.insert(Ty.getAsOpaquePtr());
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002539 } else if (AllowUserConversions) {
2540 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2541 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2542 // FIXME: Visit conversion functions in the base classes, too.
2543 OverloadedFunctionDecl *Conversions
2544 = ClassDecl->getConversionFunctions();
2545 for (OverloadedFunctionDecl::function_iterator Func
2546 = Conversions->function_begin();
2547 Func != Conversions->function_end(); ++Func) {
2548 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002549 if (AllowExplicitConversions || !Conv->isExplicit())
2550 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002551 }
2552 }
2553 }
2554}
2555
Douglas Gregor74253732008-11-19 15:42:04 +00002556/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2557/// operator overloads to the candidate set (C++ [over.built]), based
2558/// on the operator @p Op and the arguments given. For example, if the
2559/// operator is a binary '+', this routine might add "int
2560/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002561void
Douglas Gregor74253732008-11-19 15:42:04 +00002562Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2563 Expr **Args, unsigned NumArgs,
2564 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002565 // The set of "promoted arithmetic types", which are the arithmetic
2566 // types are that preserved by promotion (C++ [over.built]p2). Note
2567 // that the first few of these types are the promoted integral
2568 // types; these types need to be first.
2569 // FIXME: What about complex?
2570 const unsigned FirstIntegralType = 0;
2571 const unsigned LastIntegralType = 13;
2572 const unsigned FirstPromotedIntegralType = 7,
2573 LastPromotedIntegralType = 13;
2574 const unsigned FirstPromotedArithmeticType = 7,
2575 LastPromotedArithmeticType = 16;
2576 const unsigned NumArithmeticTypes = 16;
2577 QualType ArithmeticTypes[NumArithmeticTypes] = {
2578 Context.BoolTy, Context.CharTy, Context.WCharTy,
2579 Context.SignedCharTy, Context.ShortTy,
2580 Context.UnsignedCharTy, Context.UnsignedShortTy,
2581 Context.IntTy, Context.LongTy, Context.LongLongTy,
2582 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2583 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2584 };
2585
2586 // Find all of the types that the arguments can convert to, but only
2587 // if the operator we're looking at has built-in operator candidates
2588 // that make use of these types.
2589 BuiltinCandidateTypeSet CandidateTypes(Context);
2590 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2591 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00002592 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002593 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00002594 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
2595 (Op == OO_Star && NumArgs == 1)) {
2596 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002597 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2598 true,
2599 (Op == OO_Exclaim ||
2600 Op == OO_AmpAmp ||
2601 Op == OO_PipePipe));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002602 }
2603
2604 bool isComparison = false;
2605 switch (Op) {
2606 case OO_None:
2607 case NUM_OVERLOADED_OPERATORS:
2608 assert(false && "Expected an overloaded operator");
2609 break;
2610
Douglas Gregor74253732008-11-19 15:42:04 +00002611 case OO_Star: // '*' is either unary or binary
2612 if (NumArgs == 1)
2613 goto UnaryStar;
2614 else
2615 goto BinaryStar;
2616 break;
2617
2618 case OO_Plus: // '+' is either unary or binary
2619 if (NumArgs == 1)
2620 goto UnaryPlus;
2621 else
2622 goto BinaryPlus;
2623 break;
2624
2625 case OO_Minus: // '-' is either unary or binary
2626 if (NumArgs == 1)
2627 goto UnaryMinus;
2628 else
2629 goto BinaryMinus;
2630 break;
2631
2632 case OO_Amp: // '&' is either unary or binary
2633 if (NumArgs == 1)
2634 goto UnaryAmp;
2635 else
2636 goto BinaryAmp;
2637
2638 case OO_PlusPlus:
2639 case OO_MinusMinus:
2640 // C++ [over.built]p3:
2641 //
2642 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2643 // is either volatile or empty, there exist candidate operator
2644 // functions of the form
2645 //
2646 // VQ T& operator++(VQ T&);
2647 // T operator++(VQ T&, int);
2648 //
2649 // C++ [over.built]p4:
2650 //
2651 // For every pair (T, VQ), where T is an arithmetic type other
2652 // than bool, and VQ is either volatile or empty, there exist
2653 // candidate operator functions of the form
2654 //
2655 // VQ T& operator--(VQ T&);
2656 // T operator--(VQ T&, int);
2657 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2658 Arith < NumArithmeticTypes; ++Arith) {
2659 QualType ArithTy = ArithmeticTypes[Arith];
2660 QualType ParamTypes[2]
2661 = { Context.getReferenceType(ArithTy), Context.IntTy };
2662
2663 // Non-volatile version.
2664 if (NumArgs == 1)
2665 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2666 else
2667 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2668
2669 // Volatile version
2670 ParamTypes[0] = Context.getReferenceType(ArithTy.withVolatile());
2671 if (NumArgs == 1)
2672 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2673 else
2674 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2675 }
2676
2677 // C++ [over.built]p5:
2678 //
2679 // For every pair (T, VQ), where T is a cv-qualified or
2680 // cv-unqualified object type, and VQ is either volatile or
2681 // empty, there exist candidate operator functions of the form
2682 //
2683 // T*VQ& operator++(T*VQ&);
2684 // T*VQ& operator--(T*VQ&);
2685 // T* operator++(T*VQ&, int);
2686 // T* operator--(T*VQ&, int);
2687 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2688 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2689 // Skip pointer types that aren't pointers to object types.
Douglas Gregorcb7de522008-11-26 23:31:11 +00002690 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00002691 continue;
2692
2693 QualType ParamTypes[2] = {
2694 Context.getReferenceType(*Ptr), Context.IntTy
2695 };
2696
2697 // Without volatile
2698 if (NumArgs == 1)
2699 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2700 else
2701 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2702
2703 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2704 // With volatile
2705 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2706 if (NumArgs == 1)
2707 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2708 else
2709 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2710 }
2711 }
2712 break;
2713
2714 UnaryStar:
2715 // C++ [over.built]p6:
2716 // For every cv-qualified or cv-unqualified object type T, there
2717 // exist candidate operator functions of the form
2718 //
2719 // T& operator*(T*);
2720 //
2721 // C++ [over.built]p7:
2722 // For every function type T, there exist candidate operator
2723 // functions of the form
2724 // T& operator*(T*);
2725 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2726 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2727 QualType ParamTy = *Ptr;
2728 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
2729 AddBuiltinCandidate(Context.getReferenceType(PointeeTy),
2730 &ParamTy, Args, 1, CandidateSet);
2731 }
2732 break;
2733
2734 UnaryPlus:
2735 // C++ [over.built]p8:
2736 // For every type T, there exist candidate operator functions of
2737 // the form
2738 //
2739 // T* operator+(T*);
2740 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2741 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2742 QualType ParamTy = *Ptr;
2743 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2744 }
2745
2746 // Fall through
2747
2748 UnaryMinus:
2749 // C++ [over.built]p9:
2750 // For every promoted arithmetic type T, there exist candidate
2751 // operator functions of the form
2752 //
2753 // T operator+(T);
2754 // T operator-(T);
2755 for (unsigned Arith = FirstPromotedArithmeticType;
2756 Arith < LastPromotedArithmeticType; ++Arith) {
2757 QualType ArithTy = ArithmeticTypes[Arith];
2758 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2759 }
2760 break;
2761
2762 case OO_Tilde:
2763 // C++ [over.built]p10:
2764 // For every promoted integral type T, there exist candidate
2765 // operator functions of the form
2766 //
2767 // T operator~(T);
2768 for (unsigned Int = FirstPromotedIntegralType;
2769 Int < LastPromotedIntegralType; ++Int) {
2770 QualType IntTy = ArithmeticTypes[Int];
2771 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2772 }
2773 break;
2774
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002775 case OO_New:
2776 case OO_Delete:
2777 case OO_Array_New:
2778 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002779 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00002780 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002781 break;
2782
2783 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00002784 UnaryAmp:
2785 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002786 // C++ [over.match.oper]p3:
2787 // -- For the operator ',', the unary operator '&', or the
2788 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002789 break;
2790
2791 case OO_Less:
2792 case OO_Greater:
2793 case OO_LessEqual:
2794 case OO_GreaterEqual:
2795 case OO_EqualEqual:
2796 case OO_ExclaimEqual:
2797 // C++ [over.built]p15:
2798 //
2799 // For every pointer or enumeration type T, there exist
2800 // candidate operator functions of the form
2801 //
2802 // bool operator<(T, T);
2803 // bool operator>(T, T);
2804 // bool operator<=(T, T);
2805 // bool operator>=(T, T);
2806 // bool operator==(T, T);
2807 // bool operator!=(T, T);
2808 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2809 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2810 QualType ParamTypes[2] = { *Ptr, *Ptr };
2811 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2812 }
2813 for (BuiltinCandidateTypeSet::iterator Enum
2814 = CandidateTypes.enumeration_begin();
2815 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2816 QualType ParamTypes[2] = { *Enum, *Enum };
2817 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2818 }
2819
2820 // Fall through.
2821 isComparison = true;
2822
Douglas Gregor74253732008-11-19 15:42:04 +00002823 BinaryPlus:
2824 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002825 if (!isComparison) {
2826 // We didn't fall through, so we must have OO_Plus or OO_Minus.
2827
2828 // C++ [over.built]p13:
2829 //
2830 // For every cv-qualified or cv-unqualified object type T
2831 // there exist candidate operator functions of the form
2832 //
2833 // T* operator+(T*, ptrdiff_t);
2834 // T& operator[](T*, ptrdiff_t); [BELOW]
2835 // T* operator-(T*, ptrdiff_t);
2836 // T* operator+(ptrdiff_t, T*);
2837 // T& operator[](ptrdiff_t, T*); [BELOW]
2838 //
2839 // C++ [over.built]p14:
2840 //
2841 // For every T, where T is a pointer to object type, there
2842 // exist candidate operator functions of the form
2843 //
2844 // ptrdiff_t operator-(T, T);
2845 for (BuiltinCandidateTypeSet::iterator Ptr
2846 = CandidateTypes.pointer_begin();
2847 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2848 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2849
2850 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
2851 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2852
2853 if (Op == OO_Plus) {
2854 // T* operator+(ptrdiff_t, T*);
2855 ParamTypes[0] = ParamTypes[1];
2856 ParamTypes[1] = *Ptr;
2857 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2858 } else {
2859 // ptrdiff_t operator-(T, T);
2860 ParamTypes[1] = *Ptr;
2861 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
2862 Args, 2, CandidateSet);
2863 }
2864 }
2865 }
2866 // Fall through
2867
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002868 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00002869 BinaryStar:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002870 // C++ [over.built]p12:
2871 //
2872 // For every pair of promoted arithmetic types L and R, there
2873 // exist candidate operator functions of the form
2874 //
2875 // LR operator*(L, R);
2876 // LR operator/(L, R);
2877 // LR operator+(L, R);
2878 // LR operator-(L, R);
2879 // bool operator<(L, R);
2880 // bool operator>(L, R);
2881 // bool operator<=(L, R);
2882 // bool operator>=(L, R);
2883 // bool operator==(L, R);
2884 // bool operator!=(L, R);
2885 //
2886 // where LR is the result of the usual arithmetic conversions
2887 // between types L and R.
2888 for (unsigned Left = FirstPromotedArithmeticType;
2889 Left < LastPromotedArithmeticType; ++Left) {
2890 for (unsigned Right = FirstPromotedArithmeticType;
2891 Right < LastPromotedArithmeticType; ++Right) {
2892 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2893 QualType Result
2894 = isComparison? Context.BoolTy
2895 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2896 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2897 }
2898 }
2899 break;
2900
2901 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00002902 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002903 case OO_Caret:
2904 case OO_Pipe:
2905 case OO_LessLess:
2906 case OO_GreaterGreater:
2907 // C++ [over.built]p17:
2908 //
2909 // For every pair of promoted integral types L and R, there
2910 // exist candidate operator functions of the form
2911 //
2912 // LR operator%(L, R);
2913 // LR operator&(L, R);
2914 // LR operator^(L, R);
2915 // LR operator|(L, R);
2916 // L operator<<(L, R);
2917 // L operator>>(L, R);
2918 //
2919 // where LR is the result of the usual arithmetic conversions
2920 // between types L and R.
2921 for (unsigned Left = FirstPromotedIntegralType;
2922 Left < LastPromotedIntegralType; ++Left) {
2923 for (unsigned Right = FirstPromotedIntegralType;
2924 Right < LastPromotedIntegralType; ++Right) {
2925 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2926 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
2927 ? LandR[0]
2928 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2929 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2930 }
2931 }
2932 break;
2933
2934 case OO_Equal:
2935 // C++ [over.built]p20:
2936 //
2937 // For every pair (T, VQ), where T is an enumeration or
2938 // (FIXME:) pointer to member type and VQ is either volatile or
2939 // empty, there exist candidate operator functions of the form
2940 //
2941 // VQ T& operator=(VQ T&, T);
2942 for (BuiltinCandidateTypeSet::iterator Enum
2943 = CandidateTypes.enumeration_begin();
2944 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2945 QualType ParamTypes[2];
2946
2947 // T& operator=(T&, T)
2948 ParamTypes[0] = Context.getReferenceType(*Enum);
2949 ParamTypes[1] = *Enum;
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002950 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002951 /*IsAssignmentOperator=*/false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002952
Douglas Gregor74253732008-11-19 15:42:04 +00002953 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
2954 // volatile T& operator=(volatile T&, T)
2955 ParamTypes[0] = Context.getReferenceType((*Enum).withVolatile());
2956 ParamTypes[1] = *Enum;
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002957 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002958 /*IsAssignmentOperator=*/false);
Douglas Gregor74253732008-11-19 15:42:04 +00002959 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002960 }
2961 // Fall through.
2962
2963 case OO_PlusEqual:
2964 case OO_MinusEqual:
2965 // C++ [over.built]p19:
2966 //
2967 // For every pair (T, VQ), where T is any type and VQ is either
2968 // volatile or empty, there exist candidate operator functions
2969 // of the form
2970 //
2971 // T*VQ& operator=(T*VQ&, T*);
2972 //
2973 // C++ [over.built]p21:
2974 //
2975 // For every pair (T, VQ), where T is a cv-qualified or
2976 // cv-unqualified object type and VQ is either volatile or
2977 // empty, there exist candidate operator functions of the form
2978 //
2979 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
2980 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
2981 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2982 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2983 QualType ParamTypes[2];
2984 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
2985
2986 // non-volatile version
2987 ParamTypes[0] = Context.getReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002988 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2989 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002990
Douglas Gregor74253732008-11-19 15:42:04 +00002991 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2992 // volatile version
2993 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002994 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2995 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00002996 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002997 }
2998 // Fall through.
2999
3000 case OO_StarEqual:
3001 case OO_SlashEqual:
3002 // C++ [over.built]p18:
3003 //
3004 // For every triple (L, VQ, R), where L is an arithmetic type,
3005 // VQ is either volatile or empty, and R is a promoted
3006 // arithmetic type, there exist candidate operator functions of
3007 // the form
3008 //
3009 // VQ L& operator=(VQ L&, R);
3010 // VQ L& operator*=(VQ L&, R);
3011 // VQ L& operator/=(VQ L&, R);
3012 // VQ L& operator+=(VQ L&, R);
3013 // VQ L& operator-=(VQ L&, R);
3014 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3015 for (unsigned Right = FirstPromotedArithmeticType;
3016 Right < LastPromotedArithmeticType; ++Right) {
3017 QualType ParamTypes[2];
3018 ParamTypes[1] = ArithmeticTypes[Right];
3019
3020 // Add this built-in operator as a candidate (VQ is empty).
3021 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003022 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3023 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003024
3025 // Add this built-in operator as a candidate (VQ is 'volatile').
3026 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
3027 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003028 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3029 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003030 }
3031 }
3032 break;
3033
3034 case OO_PercentEqual:
3035 case OO_LessLessEqual:
3036 case OO_GreaterGreaterEqual:
3037 case OO_AmpEqual:
3038 case OO_CaretEqual:
3039 case OO_PipeEqual:
3040 // C++ [over.built]p22:
3041 //
3042 // For every triple (L, VQ, R), where L is an integral type, VQ
3043 // is either volatile or empty, and R is a promoted integral
3044 // type, there exist candidate operator functions of the form
3045 //
3046 // VQ L& operator%=(VQ L&, R);
3047 // VQ L& operator<<=(VQ L&, R);
3048 // VQ L& operator>>=(VQ L&, R);
3049 // VQ L& operator&=(VQ L&, R);
3050 // VQ L& operator^=(VQ L&, R);
3051 // VQ L& operator|=(VQ L&, R);
3052 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3053 for (unsigned Right = FirstPromotedIntegralType;
3054 Right < LastPromotedIntegralType; ++Right) {
3055 QualType ParamTypes[2];
3056 ParamTypes[1] = ArithmeticTypes[Right];
3057
3058 // Add this built-in operator as a candidate (VQ is empty).
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003059 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
3060 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3061
3062 // Add this built-in operator as a candidate (VQ is 'volatile').
3063 ParamTypes[0] = ArithmeticTypes[Left];
3064 ParamTypes[0].addVolatile();
3065 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
3066 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3067 }
3068 }
3069 break;
3070
Douglas Gregor74253732008-11-19 15:42:04 +00003071 case OO_Exclaim: {
3072 // C++ [over.operator]p23:
3073 //
3074 // There also exist candidate operator functions of the form
3075 //
3076 // bool operator!(bool);
3077 // bool operator&&(bool, bool); [BELOW]
3078 // bool operator||(bool, bool); [BELOW]
3079 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003080 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3081 /*IsAssignmentOperator=*/false,
3082 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00003083 break;
3084 }
3085
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003086 case OO_AmpAmp:
3087 case OO_PipePipe: {
3088 // C++ [over.operator]p23:
3089 //
3090 // There also exist candidate operator functions of the form
3091 //
Douglas Gregor74253732008-11-19 15:42:04 +00003092 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003093 // bool operator&&(bool, bool);
3094 // bool operator||(bool, bool);
3095 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003096 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3097 /*IsAssignmentOperator=*/false,
3098 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003099 break;
3100 }
3101
3102 case OO_Subscript:
3103 // C++ [over.built]p13:
3104 //
3105 // For every cv-qualified or cv-unqualified object type T there
3106 // exist candidate operator functions of the form
3107 //
3108 // T* operator+(T*, ptrdiff_t); [ABOVE]
3109 // T& operator[](T*, ptrdiff_t);
3110 // T* operator-(T*, ptrdiff_t); [ABOVE]
3111 // T* operator+(ptrdiff_t, T*); [ABOVE]
3112 // T& operator[](ptrdiff_t, T*);
3113 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3114 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3115 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3116 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
3117 QualType ResultTy = Context.getReferenceType(PointeeType);
3118
3119 // T& operator[](T*, ptrdiff_t)
3120 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3121
3122 // T& operator[](ptrdiff_t, T*);
3123 ParamTypes[0] = ParamTypes[1];
3124 ParamTypes[1] = *Ptr;
3125 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3126 }
3127 break;
3128
3129 case OO_ArrowStar:
3130 // FIXME: No support for pointer-to-members yet.
3131 break;
3132 }
3133}
3134
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003135/// AddOverloadCandidates - Add all of the function overloads in Ovl
3136/// to the candidate set.
3137void
Douglas Gregor18fe5682008-11-03 20:45:27 +00003138Sema::AddOverloadCandidates(const OverloadedFunctionDecl *Ovl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003139 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00003140 OverloadCandidateSet& CandidateSet,
3141 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003142{
Douglas Gregor18fe5682008-11-03 20:45:27 +00003143 for (OverloadedFunctionDecl::function_const_iterator Func
3144 = Ovl->function_begin();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003145 Func != Ovl->function_end(); ++Func)
Douglas Gregor225c41e2008-11-03 19:09:14 +00003146 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet,
3147 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003148}
3149
3150/// isBetterOverloadCandidate - Determines whether the first overload
3151/// candidate is a better candidate than the second (C++ 13.3.3p1).
3152bool
3153Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3154 const OverloadCandidate& Cand2)
3155{
3156 // Define viable functions to be better candidates than non-viable
3157 // functions.
3158 if (!Cand2.Viable)
3159 return Cand1.Viable;
3160 else if (!Cand1.Viable)
3161 return false;
3162
Douglas Gregor88a35142008-12-22 05:46:06 +00003163 // C++ [over.match.best]p1:
3164 //
3165 // -- if F is a static member function, ICS1(F) is defined such
3166 // that ICS1(F) is neither better nor worse than ICS1(G) for
3167 // any function G, and, symmetrically, ICS1(G) is neither
3168 // better nor worse than ICS1(F).
3169 unsigned StartArg = 0;
3170 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3171 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003172
3173 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
3174 // function than another viable function F2 if for all arguments i,
3175 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
3176 // then...
3177 unsigned NumArgs = Cand1.Conversions.size();
3178 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3179 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003180 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003181 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3182 Cand2.Conversions[ArgIdx])) {
3183 case ImplicitConversionSequence::Better:
3184 // Cand1 has a better conversion sequence.
3185 HasBetterConversion = true;
3186 break;
3187
3188 case ImplicitConversionSequence::Worse:
3189 // Cand1 can't be better than Cand2.
3190 return false;
3191
3192 case ImplicitConversionSequence::Indistinguishable:
3193 // Do nothing.
3194 break;
3195 }
3196 }
3197
3198 if (HasBetterConversion)
3199 return true;
3200
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003201 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
3202 // implemented, but they require template support.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003203
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003204 // C++ [over.match.best]p1b4:
3205 //
3206 // -- the context is an initialization by user-defined conversion
3207 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3208 // from the return type of F1 to the destination type (i.e.,
3209 // the type of the entity being initialized) is a better
3210 // conversion sequence than the standard conversion sequence
3211 // from the return type of F2 to the destination type.
Douglas Gregor447b69e2008-11-19 03:25:36 +00003212 if (Cand1.Function && Cand2.Function &&
3213 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003214 isa<CXXConversionDecl>(Cand2.Function)) {
3215 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3216 Cand2.FinalConversion)) {
3217 case ImplicitConversionSequence::Better:
3218 // Cand1 has a better conversion sequence.
3219 return true;
3220
3221 case ImplicitConversionSequence::Worse:
3222 // Cand1 can't be better than Cand2.
3223 return false;
3224
3225 case ImplicitConversionSequence::Indistinguishable:
3226 // Do nothing
3227 break;
3228 }
3229 }
3230
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003231 return false;
3232}
3233
3234/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
3235/// within an overload candidate set. If overloading is successful,
3236/// the result will be OR_Success and Best will be set to point to the
3237/// best viable function within the candidate set. Otherwise, one of
3238/// several kinds of errors will be returned; see
3239/// Sema::OverloadingResult.
3240Sema::OverloadingResult
3241Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
3242 OverloadCandidateSet::iterator& Best)
3243{
3244 // Find the best viable function.
3245 Best = CandidateSet.end();
3246 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3247 Cand != CandidateSet.end(); ++Cand) {
3248 if (Cand->Viable) {
3249 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3250 Best = Cand;
3251 }
3252 }
3253
3254 // If we didn't find any viable functions, abort.
3255 if (Best == CandidateSet.end())
3256 return OR_No_Viable_Function;
3257
3258 // Make sure that this function is better than every other viable
3259 // function. If not, we have an ambiguity.
3260 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3261 Cand != CandidateSet.end(); ++Cand) {
3262 if (Cand->Viable &&
3263 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003264 !isBetterOverloadCandidate(*Best, *Cand)) {
3265 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003266 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003267 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003268 }
3269
3270 // Best is the best viable function.
3271 return OR_Success;
3272}
3273
3274/// PrintOverloadCandidates - When overload resolution fails, prints
3275/// diagnostic messages containing the candidates in the candidate
3276/// set. If OnlyViable is true, only viable candidates will be printed.
3277void
3278Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3279 bool OnlyViable)
3280{
3281 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3282 LastCand = CandidateSet.end();
3283 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003284 if (Cand->Viable || !OnlyViable) {
3285 if (Cand->Function) {
3286 // Normal function
3287 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003288 } else if (Cand->IsSurrogate) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003289 // Desugar the type of the surrogate down to a function type,
3290 // retaining as many typedefs as possible while still showing
3291 // the function type (and, therefore, its parameter types).
3292 QualType FnType = Cand->Surrogate->getConversionType();
3293 bool isReference = false;
3294 bool isPointer = false;
3295 if (const ReferenceType *FnTypeRef = FnType->getAsReferenceType()) {
3296 FnType = FnTypeRef->getPointeeType();
3297 isReference = true;
3298 }
3299 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
3300 FnType = FnTypePtr->getPointeeType();
3301 isPointer = true;
3302 }
3303 // Desugar down to a function type.
3304 FnType = QualType(FnType->getAsFunctionType(), 0);
3305 // Reconstruct the pointer/reference as appropriate.
3306 if (isPointer) FnType = Context.getPointerType(FnType);
3307 if (isReference) FnType = Context.getReferenceType(FnType);
3308
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003309 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003310 << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003311 } else {
3312 // FIXME: We need to get the identifier in here
3313 // FIXME: Do we want the error message to point at the
3314 // operator? (built-ins won't have a location)
3315 QualType FnType
3316 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3317 Cand->BuiltinTypes.ParamTypes,
3318 Cand->Conversions.size(),
3319 false, 0);
3320
Chris Lattnerd1625842008-11-24 06:25:27 +00003321 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003322 }
3323 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003324 }
3325}
3326
Douglas Gregor904eed32008-11-10 20:40:00 +00003327/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3328/// an overloaded function (C++ [over.over]), where @p From is an
3329/// expression with overloaded function type and @p ToType is the type
3330/// we're trying to resolve to. For example:
3331///
3332/// @code
3333/// int f(double);
3334/// int f(int);
3335///
3336/// int (*pfd)(double) = f; // selects f(double)
3337/// @endcode
3338///
3339/// This routine returns the resulting FunctionDecl if it could be
3340/// resolved, and NULL otherwise. When @p Complain is true, this
3341/// routine will emit diagnostics if there is an error.
3342FunctionDecl *
3343Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
3344 bool Complain) {
3345 QualType FunctionType = ToType;
3346 if (const PointerLikeType *ToTypePtr = ToType->getAsPointerLikeType())
3347 FunctionType = ToTypePtr->getPointeeType();
3348
3349 // We only look at pointers or references to functions.
3350 if (!FunctionType->isFunctionType())
3351 return 0;
3352
3353 // Find the actual overloaded function declaration.
3354 OverloadedFunctionDecl *Ovl = 0;
3355
3356 // C++ [over.over]p1:
3357 // [...] [Note: any redundant set of parentheses surrounding the
3358 // overloaded function name is ignored (5.1). ]
3359 Expr *OvlExpr = From->IgnoreParens();
3360
3361 // C++ [over.over]p1:
3362 // [...] The overloaded function name can be preceded by the &
3363 // operator.
3364 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3365 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3366 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3367 }
3368
3369 // Try to dig out the overloaded function.
3370 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
3371 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
3372
3373 // If there's no overloaded function declaration, we're done.
3374 if (!Ovl)
3375 return 0;
3376
3377 // Look through all of the overloaded functions, searching for one
3378 // whose type matches exactly.
3379 // FIXME: When templates or using declarations come along, we'll actually
3380 // have to deal with duplicates, partial ordering, etc. For now, we
3381 // can just do a simple search.
3382 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
3383 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
3384 Fun != Ovl->function_end(); ++Fun) {
3385 // C++ [over.over]p3:
3386 // Non-member functions and static member functions match
3387 // targets of type “pointer-to-function”or
3388 // “reference-to-function.”
3389 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun))
3390 if (!Method->isStatic())
3391 continue;
3392
3393 if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
3394 return *Fun;
3395 }
3396
3397 return 0;
3398}
3399
Douglas Gregorf6b89692008-11-26 05:54:23 +00003400/// ResolveOverloadedCallFn - Given the call expression that calls Fn
3401/// (which eventually refers to the set of overloaded functions in
3402/// Ovl) and the call arguments Args/NumArgs, attempt to resolve the
3403/// function call down to a specific function. If overload resolution
Douglas Gregor0a396682008-11-26 06:01:48 +00003404/// succeeds, returns the function declaration produced by overload
3405/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00003406/// arguments and Fn, and returns NULL.
Douglas Gregor0a396682008-11-26 06:01:48 +00003407FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, OverloadedFunctionDecl *Ovl,
3408 SourceLocation LParenLoc,
3409 Expr **Args, unsigned NumArgs,
3410 SourceLocation *CommaLocs,
3411 SourceLocation RParenLoc) {
Douglas Gregorf6b89692008-11-26 05:54:23 +00003412 OverloadCandidateSet CandidateSet;
3413 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet);
3414 OverloadCandidateSet::iterator Best;
3415 switch (BestViableFunction(CandidateSet, Best)) {
Douglas Gregor0a396682008-11-26 06:01:48 +00003416 case OR_Success:
3417 return Best->Function;
Douglas Gregorf6b89692008-11-26 05:54:23 +00003418
3419 case OR_No_Viable_Function:
3420 Diag(Fn->getSourceRange().getBegin(),
3421 diag::err_ovl_no_viable_function_in_call)
3422 << Ovl->getDeclName() << (unsigned)CandidateSet.size()
3423 << Fn->getSourceRange();
3424 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3425 break;
3426
3427 case OR_Ambiguous:
3428 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
3429 << Ovl->getDeclName() << Fn->getSourceRange();
3430 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3431 break;
3432 }
3433
3434 // Overload resolution failed. Destroy all of the subexpressions and
3435 // return NULL.
3436 Fn->Destroy(Context);
3437 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3438 Args[Arg]->Destroy(Context);
3439 return 0;
3440}
3441
Douglas Gregor88a35142008-12-22 05:46:06 +00003442/// BuildCallToMemberFunction - Build a call to a member
3443/// function. MemExpr is the expression that refers to the member
3444/// function (and includes the object parameter), Args/NumArgs are the
3445/// arguments to the function call (not including the object
3446/// parameter). The caller needs to validate that the member
3447/// expression refers to a member function or an overloaded member
3448/// function.
3449Sema::ExprResult
3450Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
3451 SourceLocation LParenLoc, Expr **Args,
3452 unsigned NumArgs, SourceLocation *CommaLocs,
3453 SourceLocation RParenLoc) {
3454 // Dig out the member expression. This holds both the object
3455 // argument and the member function we're referring to.
3456 MemberExpr *MemExpr = 0;
3457 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
3458 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
3459 else
3460 MemExpr = dyn_cast<MemberExpr>(MemExprE);
3461 assert(MemExpr && "Building member call without member expression");
3462
3463 // Extract the object argument.
3464 Expr *ObjectArg = MemExpr->getBase();
3465 if (MemExpr->isArrow())
3466 ObjectArg = new UnaryOperator(ObjectArg, UnaryOperator::Deref,
3467 ObjectArg->getType()->getAsPointerType()->getPointeeType(),
3468 SourceLocation());
3469 CXXMethodDecl *Method = 0;
3470 if (OverloadedFunctionDecl *Ovl
3471 = dyn_cast<OverloadedFunctionDecl>(MemExpr->getMemberDecl())) {
3472 // Add overload candidates
3473 OverloadCandidateSet CandidateSet;
3474 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3475 FuncEnd = Ovl->function_end();
3476 Func != FuncEnd; ++Func) {
3477 assert(isa<CXXMethodDecl>(*Func) && "Function is not a method");
3478 Method = cast<CXXMethodDecl>(*Func);
3479 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
3480 /*SuppressUserConversions=*/false);
3481 }
3482
3483 OverloadCandidateSet::iterator Best;
3484 switch (BestViableFunction(CandidateSet, Best)) {
3485 case OR_Success:
3486 Method = cast<CXXMethodDecl>(Best->Function);
3487 break;
3488
3489 case OR_No_Viable_Function:
3490 Diag(MemExpr->getSourceRange().getBegin(),
3491 diag::err_ovl_no_viable_member_function_in_call)
3492 << Ovl->getDeclName() << (unsigned)CandidateSet.size()
3493 << MemExprE->getSourceRange();
3494 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3495 // FIXME: Leaking incoming expressions!
3496 return true;
3497
3498 case OR_Ambiguous:
3499 Diag(MemExpr->getSourceRange().getBegin(),
3500 diag::err_ovl_ambiguous_member_call)
3501 << Ovl->getDeclName() << MemExprE->getSourceRange();
3502 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3503 // FIXME: Leaking incoming expressions!
3504 return true;
3505 }
3506
3507 FixOverloadedFunctionReference(MemExpr, Method);
3508 } else {
3509 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
3510 }
3511
3512 assert(Method && "Member call to something that isn't a method?");
3513 llvm::OwningPtr<CXXMemberCallExpr>
3514 TheCall(new CXXMemberCallExpr(MemExpr, Args, NumArgs,
3515 Method->getResultType().getNonReferenceType(),
3516 RParenLoc));
3517
3518 // Convert the object argument (for a non-static member function call).
3519 if (!Method->isStatic() &&
3520 PerformObjectArgumentInitialization(ObjectArg, Method))
3521 return true;
3522 MemExpr->setBase(ObjectArg);
3523
3524 // Convert the rest of the arguments
3525 const FunctionTypeProto *Proto = cast<FunctionTypeProto>(Method->getType());
3526 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
3527 RParenLoc))
3528 return true;
3529
Sebastian Redl0eb23302009-01-19 00:08:26 +00003530 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregor88a35142008-12-22 05:46:06 +00003531}
3532
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003533/// BuildCallToObjectOfClassType - Build a call to an object of class
3534/// type (C++ [over.call.object]), which can end up invoking an
3535/// overloaded function call operator (@c operator()) or performing a
3536/// user-defined conversion on the object argument.
Douglas Gregor88a35142008-12-22 05:46:06 +00003537Sema::ExprResult
Douglas Gregor5c37de72008-12-06 00:22:45 +00003538Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
3539 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003540 Expr **Args, unsigned NumArgs,
3541 SourceLocation *CommaLocs,
3542 SourceLocation RParenLoc) {
3543 assert(Object->getType()->isRecordType() && "Requires object type argument");
3544 const RecordType *Record = Object->getType()->getAsRecordType();
3545
3546 // C++ [over.call.object]p1:
3547 // If the primary-expression E in the function call syntax
3548 // evaluates to a class object of type “cv T”, then the set of
3549 // candidate functions includes at least the function call
3550 // operators of T. The function call operators of T are obtained by
3551 // ordinary lookup of the name operator() in the context of
3552 // (E).operator().
3553 OverloadCandidateSet CandidateSet;
Douglas Gregor44b43212008-12-11 16:49:14 +00003554 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003555 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00003556 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003557 Oper != OperEnd; ++Oper)
3558 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
3559 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003560
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003561 // C++ [over.call.object]p2:
3562 // In addition, for each conversion function declared in T of the
3563 // form
3564 //
3565 // operator conversion-type-id () cv-qualifier;
3566 //
3567 // where cv-qualifier is the same cv-qualification as, or a
3568 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00003569 // denotes the type "pointer to function of (P1,...,Pn) returning
3570 // R", or the type "reference to pointer to function of
3571 // (P1,...,Pn) returning R", or the type "reference to function
3572 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003573 // is also considered as a candidate function. Similarly,
3574 // surrogate call functions are added to the set of candidate
3575 // functions for each conversion function declared in an
3576 // accessible base class provided the function is not hidden
3577 // within T by another intervening declaration.
3578 //
3579 // FIXME: Look in base classes for more conversion operators!
3580 OverloadedFunctionDecl *Conversions
3581 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor621b3932008-11-21 02:54:28 +00003582 for (OverloadedFunctionDecl::function_iterator
3583 Func = Conversions->function_begin(),
3584 FuncEnd = Conversions->function_end();
3585 Func != FuncEnd; ++Func) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003586 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
3587
3588 // Strip the reference type (if any) and then the pointer type (if
3589 // any) to get down to what might be a function type.
3590 QualType ConvType = Conv->getConversionType().getNonReferenceType();
3591 if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
3592 ConvType = ConvPtrType->getPointeeType();
3593
3594 if (const FunctionTypeProto *Proto = ConvType->getAsFunctionTypeProto())
3595 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
3596 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003597
3598 // Perform overload resolution.
3599 OverloadCandidateSet::iterator Best;
3600 switch (BestViableFunction(CandidateSet, Best)) {
3601 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003602 // Overload resolution succeeded; we'll build the appropriate call
3603 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003604 break;
3605
3606 case OR_No_Viable_Function:
Sebastian Redle4c452c2008-11-22 13:44:36 +00003607 Diag(Object->getSourceRange().getBegin(),
3608 diag::err_ovl_no_viable_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00003609 << Object->getType() << (unsigned)CandidateSet.size()
Sebastian Redle4c452c2008-11-22 13:44:36 +00003610 << Object->getSourceRange();
3611 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003612 break;
3613
3614 case OR_Ambiguous:
3615 Diag(Object->getSourceRange().getBegin(),
3616 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00003617 << Object->getType() << Object->getSourceRange();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003618 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3619 break;
3620 }
3621
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003622 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003623 // We had an error; delete all of the subexpressions and return
3624 // the error.
3625 delete Object;
3626 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3627 delete Args[ArgIdx];
3628 return true;
3629 }
3630
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003631 if (Best->Function == 0) {
3632 // Since there is no function declaration, this is one of the
3633 // surrogate candidates. Dig out the conversion function.
3634 CXXConversionDecl *Conv
3635 = cast<CXXConversionDecl>(
3636 Best->Conversions[0].UserDefined.ConversionFunction);
3637
3638 // We selected one of the surrogate functions that converts the
3639 // object parameter to a function pointer. Perform the conversion
3640 // on the object argument, then let ActOnCallExpr finish the job.
3641 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl0eb23302009-01-19 00:08:26 +00003642 ImpCastExprToType(Object,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003643 Conv->getConversionType().getNonReferenceType(),
3644 Conv->getConversionType()->isReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003645 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
3646 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
3647 CommaLocs, RParenLoc).release();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003648 }
3649
3650 // We found an overloaded operator(). Build a CXXOperatorCallExpr
3651 // that calls this method, using Object for the implicit object
3652 // parameter and passing along the remaining arguments.
3653 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003654 const FunctionTypeProto *Proto = Method->getType()->getAsFunctionTypeProto();
3655
3656 unsigned NumArgsInProto = Proto->getNumArgs();
3657 unsigned NumArgsToCheck = NumArgs;
3658
3659 // Build the full argument list for the method call (the
3660 // implicit object parameter is placed at the beginning of the
3661 // list).
3662 Expr **MethodArgs;
3663 if (NumArgs < NumArgsInProto) {
3664 NumArgsToCheck = NumArgsInProto;
3665 MethodArgs = new Expr*[NumArgsInProto + 1];
3666 } else {
3667 MethodArgs = new Expr*[NumArgs + 1];
3668 }
3669 MethodArgs[0] = Object;
3670 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3671 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
3672
3673 Expr *NewFn = new DeclRefExpr(Method, Method->getType(),
3674 SourceLocation());
3675 UsualUnaryConversions(NewFn);
3676
3677 // Once we've built TheCall, all of the expressions are properly
3678 // owned.
3679 QualType ResultTy = Method->getResultType().getNonReferenceType();
3680 llvm::OwningPtr<CXXOperatorCallExpr>
3681 TheCall(new CXXOperatorCallExpr(NewFn, MethodArgs, NumArgs + 1,
3682 ResultTy, RParenLoc));
3683 delete [] MethodArgs;
3684
Douglas Gregor518fda12009-01-13 05:10:00 +00003685 // We may have default arguments. If so, we need to allocate more
3686 // slots in the call for them.
3687 if (NumArgs < NumArgsInProto)
3688 TheCall->setNumArgs(NumArgsInProto + 1);
3689 else if (NumArgs > NumArgsInProto)
3690 NumArgsToCheck = NumArgsInProto;
3691
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003692 // Initialize the implicit object parameter.
Douglas Gregor518fda12009-01-13 05:10:00 +00003693 if (PerformObjectArgumentInitialization(Object, Method))
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003694 return true;
3695 TheCall->setArg(0, Object);
3696
3697 // Check the argument types.
3698 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003699 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00003700 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003701 Arg = Args[i];
Douglas Gregor518fda12009-01-13 05:10:00 +00003702
3703 // Pass the argument.
3704 QualType ProtoArgType = Proto->getArgType(i);
3705 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3706 return true;
3707 } else {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003708 Arg = new CXXDefaultArgExpr(Method->getParamDecl(i));
Douglas Gregor518fda12009-01-13 05:10:00 +00003709 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003710
3711 TheCall->setArg(i + 1, Arg);
3712 }
3713
3714 // If this is a variadic call, handle args passed through "...".
3715 if (Proto->isVariadic()) {
3716 // Promote the arguments (C99 6.5.2.2p7).
3717 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3718 Expr *Arg = Args[i];
Anders Carlsson906fed02009-01-13 05:48:52 +00003719
Anders Carlssondce5e2c2009-01-16 16:48:51 +00003720 DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003721 TheCall->setArg(i + 1, Arg);
3722 }
3723 }
3724
Sebastian Redl0eb23302009-01-19 00:08:26 +00003725 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003726}
3727
Douglas Gregor8ba10742008-11-20 16:27:02 +00003728/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
3729/// (if one exists), where @c Base is an expression of class type and
3730/// @c Member is the name of the member we're trying to find.
3731Action::ExprResult
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003732Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
Douglas Gregor8ba10742008-11-20 16:27:02 +00003733 SourceLocation MemberLoc,
3734 IdentifierInfo &Member) {
3735 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
3736
3737 // C++ [over.ref]p1:
3738 //
3739 // [...] An expression x->m is interpreted as (x.operator->())->m
3740 // for a class object x of type T if T::operator->() exists and if
3741 // the operator is selected as the best match function by the
3742 // overload resolution mechanism (13.3).
3743 // FIXME: look in base classes.
3744 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
3745 OverloadCandidateSet CandidateSet;
3746 const RecordType *BaseRecord = Base->getType()->getAsRecordType();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003747
3748 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00003749 for (llvm::tie(Oper, OperEnd) = BaseRecord->getDecl()->lookup(OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003750 Oper != OperEnd; ++Oper)
3751 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00003752 /*SuppressUserConversions=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003753
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003754 llvm::OwningPtr<Expr> BasePtr(Base);
3755
Douglas Gregor8ba10742008-11-20 16:27:02 +00003756 // Perform overload resolution.
3757 OverloadCandidateSet::iterator Best;
3758 switch (BestViableFunction(CandidateSet, Best)) {
3759 case OR_Success:
3760 // Overload resolution succeeded; we'll build the call below.
3761 break;
3762
3763 case OR_No_Viable_Function:
3764 if (CandidateSet.empty())
3765 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattnerd1625842008-11-24 06:25:27 +00003766 << BasePtr->getType() << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003767 else
3768 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Sebastian Redle4c452c2008-11-22 13:44:36 +00003769 << "operator->" << (unsigned)CandidateSet.size()
3770 << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003771 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003772 return true;
3773
3774 case OR_Ambiguous:
3775 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Chris Lattnerd1625842008-11-24 06:25:27 +00003776 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003777 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003778 return true;
3779 }
3780
3781 // Convert the object parameter.
3782 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003783 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregor8ba10742008-11-20 16:27:02 +00003784 return true;
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003785
3786 // No concerns about early exits now.
3787 BasePtr.take();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003788
3789 // Build the operator call.
3790 Expr *FnExpr = new DeclRefExpr(Method, Method->getType(), SourceLocation());
3791 UsualUnaryConversions(FnExpr);
3792 Base = new CXXOperatorCallExpr(FnExpr, &Base, 1,
3793 Method->getResultType().getNonReferenceType(),
3794 OpLoc);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003795 return ActOnMemberReferenceExpr(S, ExprArg(*this, Base), OpLoc, tok::arrow,
3796 MemberLoc, Member).release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003797}
3798
Douglas Gregor904eed32008-11-10 20:40:00 +00003799/// FixOverloadedFunctionReference - E is an expression that refers to
3800/// a C++ overloaded function (possibly with some parentheses and
3801/// perhaps a '&' around it). We have resolved the overloaded function
3802/// to the function declaration Fn, so patch up the expression E to
3803/// refer (possibly indirectly) to Fn.
3804void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
3805 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
3806 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
3807 E->setType(PE->getSubExpr()->getType());
3808 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
3809 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
3810 "Can only take the address of an overloaded function");
3811 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
3812 E->setType(Context.getPointerType(E->getType()));
3813 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
3814 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
3815 "Expected overloaded function");
3816 DR->setDecl(Fn);
3817 E->setType(Fn->getType());
Douglas Gregor88a35142008-12-22 05:46:06 +00003818 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
3819 MemExpr->setMemberDecl(Fn);
3820 E->setType(Fn->getType());
Douglas Gregor904eed32008-11-10 20:40:00 +00003821 } else {
3822 assert(false && "Invalid reference to overloaded function");
3823 }
3824}
3825
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003826} // end namespace clang