blob: b2130e42f886ccf565f1da2d3d28db088fb42189 [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 Gregor8e9bebd2008-10-21 16:13:35 +0000364ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +0000365Sema::TryImplicitConversion(Expr* From, QualType ToType,
366 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000367{
368 ImplicitConversionSequence ICS;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000369 if (IsStandardConversion(From, ToType, ICS.Standard))
370 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000371 else if (!SuppressUserConversions &&
372 IsUserDefinedConversion(From, ToType, ICS.UserDefined)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000373 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000374 // C++ [over.ics.user]p4:
375 // A conversion of an expression of class type to the same class
376 // type is given Exact Match rank, and a conversion of an
377 // expression of class type to a base class of that type is
378 // given Conversion rank, in spite of the fact that a copy
379 // constructor (i.e., a user-defined conversion function) is
380 // called for those cases.
381 if (CXXConstructorDecl *Constructor
382 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
383 if (Constructor->isCopyConstructor(Context)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000384 // Turn this into a "standard" conversion sequence, so that it
385 // gets ranked with standard conversion sequences.
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000386 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
387 ICS.Standard.setAsIdentityConversion();
388 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
389 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000390 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000391 if (IsDerivedFrom(From->getType().getUnqualifiedType(),
392 ToType.getUnqualifiedType()))
393 ICS.Standard.Second = ICK_Derived_To_Base;
394 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000395 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000396 } else
Douglas Gregor60d62c22008-10-31 16:23:19 +0000397 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000398
399 return ICS;
400}
401
402/// IsStandardConversion - Determines whether there is a standard
403/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
404/// expression From to the type ToType. Standard conversion sequences
405/// only consider non-class types; for conversions that involve class
406/// types, use TryImplicitConversion. If a conversion exists, SCS will
407/// contain the standard conversion sequence required to perform this
408/// conversion and this routine will return true. Otherwise, this
409/// routine will return false and the value of SCS is unspecified.
410bool
411Sema::IsStandardConversion(Expr* From, QualType ToType,
412 StandardConversionSequence &SCS)
413{
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000414 QualType FromType = From->getType();
415
Douglas Gregor60d62c22008-10-31 16:23:19 +0000416 // There are no standard conversions for class types, so abort early.
417 if (FromType->isRecordType() || ToType->isRecordType())
418 return false;
419
420 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000421 SCS.setAsIdentityConversion();
Douglas Gregor60d62c22008-10-31 16:23:19 +0000422 SCS.Deprecated = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000423 SCS.IncompatibleObjC = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000424 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000425 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000426
427 // The first conversion can be an lvalue-to-rvalue conversion,
428 // array-to-pointer conversion, or function-to-pointer conversion
429 // (C++ 4p1).
430
431 // Lvalue-to-rvalue conversion (C++ 4.1):
432 // An lvalue (3.10) of a non-function, non-array type T can be
433 // converted to an rvalue.
434 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
435 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000436 !FromType->isFunctionType() && !FromType->isArrayType() &&
437 !FromType->isOverloadType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000438 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000439
440 // If T is a non-class type, the type of the rvalue is the
441 // cv-unqualified version of T. Otherwise, the type of the rvalue
442 // is T (C++ 4.1p1).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000443 FromType = FromType.getUnqualifiedType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000444 }
445 // Array-to-pointer conversion (C++ 4.2)
446 else if (FromType->isArrayType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000447 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000448
449 // An lvalue or rvalue of type "array of N T" or "array of unknown
450 // bound of T" can be converted to an rvalue of type "pointer to
451 // T" (C++ 4.2p1).
452 FromType = Context.getArrayDecayedType(FromType);
453
454 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
455 // This conversion is deprecated. (C++ D.4).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000456 SCS.Deprecated = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000457
458 // For the purpose of ranking in overload resolution
459 // (13.3.3.1.1), this conversion is considered an
460 // array-to-pointer conversion followed by a qualification
461 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000462 SCS.Second = ICK_Identity;
463 SCS.Third = ICK_Qualification;
464 SCS.ToTypePtr = ToType.getAsOpaquePtr();
465 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000466 }
467 }
468 // Function-to-pointer conversion (C++ 4.3).
469 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000470 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000471
472 // An lvalue of function type T can be converted to an rvalue of
473 // type "pointer to T." The result is a pointer to the
474 // function. (C++ 4.3p1).
475 FromType = Context.getPointerType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000476 }
Douglas Gregor904eed32008-11-10 20:40:00 +0000477 // Address of overloaded function (C++ [over.over]).
478 else if (FunctionDecl *Fn
479 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
480 SCS.First = ICK_Function_To_Pointer;
481
482 // We were able to resolve the address of the overloaded function,
483 // so we can convert to the type of that function.
484 FromType = Fn->getType();
485 if (ToType->isReferenceType())
486 FromType = Context.getReferenceType(FromType);
487 else
488 FromType = Context.getPointerType(FromType);
489 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000490 // We don't require any conversions for the first step.
491 else {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000492 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000493 }
494
495 // The second conversion can be an integral promotion, floating
496 // point promotion, integral conversion, floating point conversion,
497 // floating-integral conversion, pointer conversion,
498 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor45920e82008-12-19 17:40:08 +0000499 bool IncompatibleObjC = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000500 if (Context.getCanonicalType(FromType).getUnqualifiedType() ==
501 Context.getCanonicalType(ToType).getUnqualifiedType()) {
502 // The unqualified versions of the types are the same: there's no
503 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000504 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000505 }
506 // Integral promotion (C++ 4.5).
507 else if (IsIntegralPromotion(From, FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000508 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000509 FromType = ToType.getUnqualifiedType();
510 }
511 // Floating point promotion (C++ 4.6).
512 else if (IsFloatingPointPromotion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000513 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000514 FromType = ToType.getUnqualifiedType();
515 }
516 // Integral conversions (C++ 4.7).
Sebastian Redl07779722008-10-31 14:43:28 +0000517 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000518 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000519 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000520 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000521 FromType = ToType.getUnqualifiedType();
522 }
523 // Floating point conversions (C++ 4.8).
524 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000525 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000526 FromType = ToType.getUnqualifiedType();
527 }
528 // Floating-integral conversions (C++ 4.9).
Sebastian Redl07779722008-10-31 14:43:28 +0000529 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000530 else if ((FromType->isFloatingType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000531 ToType->isIntegralType() && !ToType->isBooleanType() &&
532 !ToType->isEnumeralType()) ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000533 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
534 ToType->isFloatingType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000535 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000536 FromType = ToType.getUnqualifiedType();
537 }
538 // Pointer conversions (C++ 4.10).
Douglas Gregor45920e82008-12-19 17:40:08 +0000539 else if (IsPointerConversion(From, FromType, ToType, FromType,
540 IncompatibleObjC)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000541 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000542 SCS.IncompatibleObjC = IncompatibleObjC;
Sebastian Redl07779722008-10-31 14:43:28 +0000543 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000544 // FIXME: Pointer to member conversions (4.11).
545 // Boolean conversions (C++ 4.12).
546 // FIXME: pointer-to-member type
547 else if (ToType->isBooleanType() &&
548 (FromType->isArithmeticType() ||
549 FromType->isEnumeralType() ||
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000550 FromType->isPointerType() ||
551 FromType->isBlockPointerType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000552 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000553 FromType = Context.BoolTy;
554 } else {
555 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000556 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000557 }
558
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000559 QualType CanonFrom;
560 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000561 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000562 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000563 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000564 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000565 CanonFrom = Context.getCanonicalType(FromType);
566 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000567 } else {
568 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000569 SCS.Third = ICK_Identity;
570
571 // C++ [over.best.ics]p6:
572 // [...] Any difference in top-level cv-qualification is
573 // subsumed by the initialization itself and does not constitute
574 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000575 CanonFrom = Context.getCanonicalType(FromType);
576 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000577 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000578 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
579 FromType = ToType;
580 CanonFrom = CanonTo;
581 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000582 }
583
584 // If we have not converted the argument type to the parameter type,
585 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000586 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000587 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000588
Douglas Gregor60d62c22008-10-31 16:23:19 +0000589 SCS.ToTypePtr = FromType.getAsOpaquePtr();
590 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000591}
592
593/// IsIntegralPromotion - Determines whether the conversion from the
594/// expression From (whose potentially-adjusted type is FromType) to
595/// ToType is an integral promotion (C++ 4.5). If so, returns true and
596/// sets PromotedType to the promoted type.
597bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
598{
599 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000600 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000601 if (!To) {
602 return false;
603 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000604
605 // An rvalue of type char, signed char, unsigned char, short int, or
606 // unsigned short int can be converted to an rvalue of type int if
607 // int can represent all the values of the source type; otherwise,
608 // the source rvalue can be converted to an rvalue of type unsigned
609 // int (C++ 4.5p1).
Sebastian Redl07779722008-10-31 14:43:28 +0000610 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000611 if (// We can promote any signed, promotable integer type to an int
612 (FromType->isSignedIntegerType() ||
613 // We can promote any unsigned integer type whose size is
614 // less than int to an int.
615 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000616 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000617 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000618 }
619
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000620 return To->getKind() == BuiltinType::UInt;
621 }
622
623 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
624 // can be converted to an rvalue of the first of the following types
625 // that can represent all the values of its underlying type: int,
626 // unsigned int, long, or unsigned long (C++ 4.5p2).
627 if ((FromType->isEnumeralType() || FromType->isWideCharType())
628 && ToType->isIntegerType()) {
629 // Determine whether the type we're converting from is signed or
630 // unsigned.
631 bool FromIsSigned;
632 uint64_t FromSize = Context.getTypeSize(FromType);
633 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
634 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
635 FromIsSigned = UnderlyingType->isSignedIntegerType();
636 } else {
637 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
638 FromIsSigned = true;
639 }
640
641 // The types we'll try to promote to, in the appropriate
642 // order. Try each of these types.
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000643 QualType PromoteTypes[6] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000644 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000645 Context.LongTy, Context.UnsignedLongTy ,
646 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000647 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000648 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000649 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
650 if (FromSize < ToSize ||
651 (FromSize == ToSize &&
652 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
653 // We found the type that we can promote to. If this is the
654 // type we wanted, we have a promotion. Otherwise, no
655 // promotion.
Sebastian Redl07779722008-10-31 14:43:28 +0000656 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000657 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
658 }
659 }
660 }
661
662 // An rvalue for an integral bit-field (9.6) can be converted to an
663 // rvalue of type int if int can represent all the values of the
664 // bit-field; otherwise, it can be converted to unsigned int if
665 // unsigned int can represent all the values of the bit-field. If
666 // the bit-field is larger yet, no integral promotion applies to
667 // it. If the bit-field has an enumerated type, it is treated as any
668 // other value of that type for promotion purposes (C++ 4.5p3).
669 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) {
670 using llvm::APSInt;
Douglas Gregor86f19402008-12-20 23:49:58 +0000671 if (FieldDecl *MemberDecl = dyn_cast<FieldDecl>(MemRef->getMemberDecl())) {
672 APSInt BitWidth;
673 if (MemberDecl->isBitField() &&
674 FromType->isIntegralType() && !FromType->isEnumeralType() &&
675 From->isIntegerConstantExpr(BitWidth, Context)) {
676 APSInt ToSize(Context.getTypeSize(ToType));
677
678 // Are we promoting to an int from a bitfield that fits in an int?
679 if (BitWidth < ToSize ||
680 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
681 return To->getKind() == BuiltinType::Int;
682 }
683
684 // Are we promoting to an unsigned int from an unsigned bitfield
685 // that fits into an unsigned int?
686 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
687 return To->getKind() == BuiltinType::UInt;
688 }
689
690 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000691 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000692 }
693 }
694
695 // An rvalue of type bool can be converted to an rvalue of type int,
696 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000697 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000698 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000699 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000700
701 return false;
702}
703
704/// IsFloatingPointPromotion - Determines whether the conversion from
705/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
706/// returns true and sets PromotedType to the promoted type.
707bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
708{
709 /// An rvalue of type float can be converted to an rvalue of type
710 /// double. (C++ 4.6p1).
711 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
712 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType())
713 if (FromBuiltin->getKind() == BuiltinType::Float &&
714 ToBuiltin->getKind() == BuiltinType::Double)
715 return true;
716
717 return false;
718}
719
Douglas Gregorcb7de522008-11-26 23:31:11 +0000720/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
721/// the pointer type FromPtr to a pointer to type ToPointee, with the
722/// same type qualifiers as FromPtr has on its pointee type. ToType,
723/// if non-empty, will be a pointer to ToType that may or may not have
724/// the right set of qualifiers on its pointee.
725static QualType
726BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
727 QualType ToPointee, QualType ToType,
728 ASTContext &Context) {
729 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
730 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
731 unsigned Quals = CanonFromPointee.getCVRQualifiers();
732
733 // Exact qualifier match -> return the pointer type we're converting to.
734 if (CanonToPointee.getCVRQualifiers() == Quals) {
735 // ToType is exactly what we need. Return it.
736 if (ToType.getTypePtr())
737 return ToType;
738
739 // Build a pointer to ToPointee. It has the right qualifiers
740 // already.
741 return Context.getPointerType(ToPointee);
742 }
743
744 // Just build a canonical type that has the right qualifiers.
745 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
746}
747
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000748/// IsPointerConversion - Determines whether the conversion of the
749/// expression From, which has the (possibly adjusted) type FromType,
750/// can be converted to the type ToType via a pointer conversion (C++
751/// 4.10). If so, returns true and places the converted type (that
752/// might differ from ToType in its cv-qualifiers at some level) into
753/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000754///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000755/// This routine also supports conversions to and from block pointers
756/// and conversions with Objective-C's 'id', 'id<protocols...>', and
757/// pointers to interfaces. FIXME: Once we've determined the
758/// appropriate overloading rules for Objective-C, we may want to
759/// split the Objective-C checks into a different routine; however,
760/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000761/// conversions, so for now they live here. IncompatibleObjC will be
762/// set if the conversion is an allowed Objective-C conversion that
763/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000764bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000765 QualType& ConvertedType,
766 bool &IncompatibleObjC)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000767{
Douglas Gregor45920e82008-12-19 17:40:08 +0000768 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +0000769 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
770 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +0000771
Douglas Gregor27b09ac2008-12-22 20:51:52 +0000772 // Conversion from a null pointer constant to any Objective-C pointer type.
773 if (Context.isObjCObjectPointerType(ToType) &&
774 From->isNullPointerConstant(Context)) {
775 ConvertedType = ToType;
776 return true;
777 }
778
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000779 // Blocks: Block pointers can be converted to void*.
780 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
781 ToType->getAsPointerType()->getPointeeType()->isVoidType()) {
782 ConvertedType = ToType;
783 return true;
784 }
785 // Blocks: A null pointer constant can be converted to a block
786 // pointer type.
787 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
788 ConvertedType = ToType;
789 return true;
790 }
791
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000792 const PointerType* ToTypePtr = ToType->getAsPointerType();
793 if (!ToTypePtr)
794 return false;
795
796 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
797 if (From->isNullPointerConstant(Context)) {
798 ConvertedType = ToType;
799 return true;
800 }
Sebastian Redl07779722008-10-31 14:43:28 +0000801
Douglas Gregorcb7de522008-11-26 23:31:11 +0000802 // Beyond this point, both types need to be pointers.
803 const PointerType *FromTypePtr = FromType->getAsPointerType();
804 if (!FromTypePtr)
805 return false;
806
807 QualType FromPointeeType = FromTypePtr->getPointeeType();
808 QualType ToPointeeType = ToTypePtr->getPointeeType();
809
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000810 // An rvalue of type "pointer to cv T," where T is an object type,
811 // can be converted to an rvalue of type "pointer to cv void" (C++
812 // 4.10p2).
Douglas Gregorc7887512008-12-19 19:13:09 +0000813 if (FromPointeeType->isIncompleteOrObjectType() &&
814 ToPointeeType->isVoidType()) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000815 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
816 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000817 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000818 return true;
819 }
820
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000821 // C++ [conv.ptr]p3:
822 //
823 // An rvalue of type "pointer to cv D," where D is a class type,
824 // can be converted to an rvalue of type "pointer to cv B," where
825 // B is a base class (clause 10) of D. If B is an inaccessible
826 // (clause 11) or ambiguous (10.2) base class of D, a program that
827 // necessitates this conversion is ill-formed. The result of the
828 // conversion is a pointer to the base class sub-object of the
829 // derived class object. The null pointer value is converted to
830 // the null pointer value of the destination type.
831 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000832 // Note that we do not check for ambiguity or inaccessibility
833 // here. That is handled by CheckPointerConversion.
Douglas Gregorcb7de522008-11-26 23:31:11 +0000834 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
835 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000836 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
837 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000838 ToType, Context);
839 return true;
840 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000841
Douglas Gregorc7887512008-12-19 19:13:09 +0000842 return false;
843}
844
845/// isObjCPointerConversion - Determines whether this is an
846/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
847/// with the same arguments and return values.
848bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
849 QualType& ConvertedType,
850 bool &IncompatibleObjC) {
851 if (!getLangOptions().ObjC1)
852 return false;
853
854 // Conversions with Objective-C's id<...>.
855 if ((FromType->isObjCQualifiedIdType() || ToType->isObjCQualifiedIdType()) &&
856 ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) {
857 ConvertedType = ToType;
858 return true;
859 }
860
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000861 // Beyond this point, both types need to be pointers or block pointers.
862 QualType ToPointeeType;
Douglas Gregorc7887512008-12-19 19:13:09 +0000863 const PointerType* ToTypePtr = ToType->getAsPointerType();
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000864 if (ToTypePtr)
865 ToPointeeType = ToTypePtr->getPointeeType();
866 else if (const BlockPointerType *ToBlockPtr = ToType->getAsBlockPointerType())
867 ToPointeeType = ToBlockPtr->getPointeeType();
868 else
Douglas Gregorc7887512008-12-19 19:13:09 +0000869 return false;
870
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000871 QualType FromPointeeType;
Douglas Gregorc7887512008-12-19 19:13:09 +0000872 const PointerType *FromTypePtr = FromType->getAsPointerType();
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000873 if (FromTypePtr)
874 FromPointeeType = FromTypePtr->getPointeeType();
875 else if (const BlockPointerType *FromBlockPtr
876 = FromType->getAsBlockPointerType())
877 FromPointeeType = FromBlockPtr->getPointeeType();
878 else
Douglas Gregorc7887512008-12-19 19:13:09 +0000879 return false;
880
Douglas Gregorcb7de522008-11-26 23:31:11 +0000881 // Objective C++: We're able to convert from a pointer to an
882 // interface to a pointer to a different interface.
883 const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType();
884 const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType();
885 if (FromIface && ToIface &&
886 Context.canAssignObjCInterfaces(ToIface, FromIface)) {
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000887 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +0000888 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000889 ToType, Context);
890 return true;
891 }
892
Douglas Gregor45920e82008-12-19 17:40:08 +0000893 if (FromIface && ToIface &&
894 Context.canAssignObjCInterfaces(FromIface, ToIface)) {
895 // Okay: this is some kind of implicit downcast of Objective-C
896 // interfaces, which is permitted. However, we're going to
897 // complain about it.
898 IncompatibleObjC = true;
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000899 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor45920e82008-12-19 17:40:08 +0000900 ToPointeeType,
901 ToType, Context);
902 return true;
903 }
904
Douglas Gregorcb7de522008-11-26 23:31:11 +0000905 // Objective C++: We're able to convert between "id" and a pointer
906 // to any interface (in both directions).
907 if ((FromIface && Context.isObjCIdType(ToPointeeType))
908 || (ToIface && Context.isObjCIdType(FromPointeeType))) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000909 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
910 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000911 ToType, Context);
912 return true;
913 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000914
Douglas Gregordda78892008-12-18 23:43:31 +0000915 // Objective C++: Allow conversions between the Objective-C "id" and
916 // "Class", in either direction.
917 if ((Context.isObjCIdType(FromPointeeType) &&
918 Context.isObjCClassType(ToPointeeType)) ||
919 (Context.isObjCClassType(FromPointeeType) &&
920 Context.isObjCIdType(ToPointeeType))) {
921 ConvertedType = ToType;
922 return true;
923 }
924
Douglas Gregorc7887512008-12-19 19:13:09 +0000925 // If we have pointers to pointers, recursively check whether this
926 // is an Objective-C conversion.
927 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
928 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
929 IncompatibleObjC)) {
930 // We always complain about this conversion.
931 IncompatibleObjC = true;
932 ConvertedType = ToType;
933 return true;
934 }
935
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000936 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +0000937 // differences in the argument and result types are in Objective-C
938 // pointer conversions. If so, we permit the conversion (but
939 // complain about it).
940 const FunctionTypeProto *FromFunctionType
941 = FromPointeeType->getAsFunctionTypeProto();
942 const FunctionTypeProto *ToFunctionType
943 = ToPointeeType->getAsFunctionTypeProto();
944 if (FromFunctionType && ToFunctionType) {
945 // If the function types are exactly the same, this isn't an
946 // Objective-C pointer conversion.
947 if (Context.getCanonicalType(FromPointeeType)
948 == Context.getCanonicalType(ToPointeeType))
949 return false;
950
951 // Perform the quick checks that will tell us whether these
952 // function types are obviously different.
953 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
954 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
955 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
956 return false;
957
958 bool HasObjCConversion = false;
959 if (Context.getCanonicalType(FromFunctionType->getResultType())
960 == Context.getCanonicalType(ToFunctionType->getResultType())) {
961 // Okay, the types match exactly. Nothing to do.
962 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
963 ToFunctionType->getResultType(),
964 ConvertedType, IncompatibleObjC)) {
965 // Okay, we have an Objective-C pointer conversion.
966 HasObjCConversion = true;
967 } else {
968 // Function types are too different. Abort.
969 return false;
970 }
971
972 // Check argument types.
973 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
974 ArgIdx != NumArgs; ++ArgIdx) {
975 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
976 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
977 if (Context.getCanonicalType(FromArgType)
978 == Context.getCanonicalType(ToArgType)) {
979 // Okay, the types match exactly. Nothing to do.
980 } else if (isObjCPointerConversion(FromArgType, ToArgType,
981 ConvertedType, IncompatibleObjC)) {
982 // Okay, we have an Objective-C pointer conversion.
983 HasObjCConversion = true;
984 } else {
985 // Argument types are too different. Abort.
986 return false;
987 }
988 }
989
990 if (HasObjCConversion) {
991 // We had an Objective-C conversion. Allow this pointer
992 // conversion, but complain about it.
993 ConvertedType = ToType;
994 IncompatibleObjC = true;
995 return true;
996 }
997 }
998
999 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001000}
1001
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001002/// CheckPointerConversion - Check the pointer conversion from the
1003/// expression From to the type ToType. This routine checks for
1004/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
1005/// conversions for which IsPointerConversion has already returned
1006/// true. It returns true and produces a diagnostic if there was an
1007/// error, or returns false otherwise.
1008bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1009 QualType FromType = From->getType();
1010
1011 if (const PointerType *FromPtrType = FromType->getAsPointerType())
1012 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
Sebastian Redl07779722008-10-31 14:43:28 +00001013 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1014 /*DetectVirtual=*/false);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001015 QualType FromPointeeType = FromPtrType->getPointeeType(),
1016 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001017
1018 // Objective-C++ conversions are always okay.
1019 // FIXME: We should have a different class of conversions for
1020 // the Objective-C++ implicit conversions.
1021 if (Context.isObjCIdType(FromPointeeType) ||
1022 Context.isObjCIdType(ToPointeeType) ||
1023 Context.isObjCClassType(FromPointeeType) ||
1024 Context.isObjCClassType(ToPointeeType))
1025 return false;
1026
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001027 if (FromPointeeType->isRecordType() &&
1028 ToPointeeType->isRecordType()) {
1029 // We must have a derived-to-base conversion. Check an
1030 // ambiguous or inaccessible conversion.
Douglas Gregor0575d4a2008-10-24 16:17:19 +00001031 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1032 From->getExprLoc(),
1033 From->getSourceRange());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001034 }
1035 }
1036
1037 return false;
1038}
1039
Douglas Gregor98cd5992008-10-21 23:43:52 +00001040/// IsQualificationConversion - Determines whether the conversion from
1041/// an rvalue of type FromType to ToType is a qualification conversion
1042/// (C++ 4.4).
1043bool
1044Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1045{
1046 FromType = Context.getCanonicalType(FromType);
1047 ToType = Context.getCanonicalType(ToType);
1048
1049 // If FromType and ToType are the same type, this is not a
1050 // qualification conversion.
1051 if (FromType == ToType)
1052 return false;
1053
1054 // (C++ 4.4p4):
1055 // A conversion can add cv-qualifiers at levels other than the first
1056 // in multi-level pointers, subject to the following rules: [...]
1057 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001058 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001059 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001060 // Within each iteration of the loop, we check the qualifiers to
1061 // determine if this still looks like a qualification
1062 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001063 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001064 // until there are no more pointers or pointers-to-members left to
1065 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001066 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001067
1068 // -- for every j > 0, if const is in cv 1,j then const is in cv
1069 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001070 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001071 return false;
Douglas Gregor57373262008-10-22 14:17:15 +00001072
Douglas Gregor98cd5992008-10-21 23:43:52 +00001073 // -- if the cv 1,j and cv 2,j are different, then const is in
1074 // every cv for 0 < k < j.
1075 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001076 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001077 return false;
Douglas Gregor57373262008-10-22 14:17:15 +00001078
Douglas Gregor98cd5992008-10-21 23:43:52 +00001079 // Keep track of whether all prior cv-qualifiers in the "to" type
1080 // include const.
1081 PreviousToQualsIncludeConst
1082 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001083 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001084
1085 // We are left with FromType and ToType being the pointee types
1086 // after unwrapping the original FromType and ToType the same number
1087 // of types. If we unwrapped any pointers, and if FromType and
1088 // ToType have the same unqualified type (since we checked
1089 // qualifiers above), then this is a qualification conversion.
1090 return UnwrappedAnyPointer &&
1091 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1092}
1093
Douglas Gregor60d62c22008-10-31 16:23:19 +00001094/// IsUserDefinedConversion - Determines whether there is a
1095/// user-defined conversion sequence (C++ [over.ics.user]) that
1096/// converts expression From to the type ToType. If such a conversion
1097/// exists, User will contain the user-defined conversion sequence
1098/// that performs such a conversion and this routine will return
1099/// true. Otherwise, this routine returns false and User is
1100/// unspecified.
1101bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1102 UserDefinedConversionSequence& User)
1103{
1104 OverloadCandidateSet CandidateSet;
1105 if (const CXXRecordType *ToRecordType
1106 = dyn_cast_or_null<CXXRecordType>(ToType->getAsRecordType())) {
1107 // C++ [over.match.ctor]p1:
1108 // When objects of class type are direct-initialized (8.5), or
1109 // copy-initialized from an expression of the same or a
1110 // derived class type (8.5), overload resolution selects the
1111 // constructor. [...] For copy-initialization, the candidate
1112 // functions are all the converting constructors (12.3.1) of
1113 // that class. The argument list is the expression-list within
1114 // the parentheses of the initializer.
1115 CXXRecordDecl *ToRecordDecl = ToRecordType->getDecl();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001116 DeclarationName ConstructorName
1117 = Context.DeclarationNames.getCXXConstructorName(
1118 Context.getCanonicalType(ToType));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001119 DeclContext::lookup_iterator Con, ConEnd;
1120 for (llvm::tie(Con, ConEnd) = ToRecordDecl->lookup(Context, ConstructorName);
1121 Con != ConEnd; ++Con) {
1122 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001123 if (Constructor->isConvertingConstructor())
Douglas Gregor225c41e2008-11-03 19:09:14 +00001124 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1125 /*SuppressUserConversions=*/true);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001126 }
1127 }
1128
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001129 if (const CXXRecordType *FromRecordType
1130 = dyn_cast_or_null<CXXRecordType>(From->getType()->getAsRecordType())) {
1131 // Add all of the conversion functions as candidates.
1132 // FIXME: Look for conversions in base classes!
1133 CXXRecordDecl *FromRecordDecl = FromRecordType->getDecl();
1134 OverloadedFunctionDecl *Conversions
1135 = FromRecordDecl->getConversionFunctions();
1136 for (OverloadedFunctionDecl::function_iterator Func
1137 = Conversions->function_begin();
1138 Func != Conversions->function_end(); ++Func) {
1139 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1140 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1141 }
1142 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001143
1144 OverloadCandidateSet::iterator Best;
1145 switch (BestViableFunction(CandidateSet, Best)) {
1146 case OR_Success:
1147 // Record the standard conversion we used and the conversion function.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001148 if (CXXConstructorDecl *Constructor
1149 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1150 // C++ [over.ics.user]p1:
1151 // If the user-defined conversion is specified by a
1152 // constructor (12.3.1), the initial standard conversion
1153 // sequence converts the source type to the type required by
1154 // the argument of the constructor.
1155 //
1156 // FIXME: What about ellipsis conversions?
1157 QualType ThisType = Constructor->getThisType(Context);
1158 User.Before = Best->Conversions[0].Standard;
1159 User.ConversionFunction = Constructor;
1160 User.After.setAsIdentityConversion();
1161 User.After.FromTypePtr
1162 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
1163 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1164 return true;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001165 } else if (CXXConversionDecl *Conversion
1166 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1167 // C++ [over.ics.user]p1:
1168 //
1169 // [...] If the user-defined conversion is specified by a
1170 // conversion function (12.3.2), the initial standard
1171 // conversion sequence converts the source type to the
1172 // implicit object parameter of the conversion function.
1173 User.Before = Best->Conversions[0].Standard;
1174 User.ConversionFunction = Conversion;
1175
1176 // C++ [over.ics.user]p2:
1177 // The second standard conversion sequence converts the
1178 // result of the user-defined conversion to the target type
1179 // for the sequence. Since an implicit conversion sequence
1180 // is an initialization, the special rules for
1181 // initialization by user-defined conversion apply when
1182 // selecting the best user-defined conversion for a
1183 // user-defined conversion sequence (see 13.3.3 and
1184 // 13.3.3.1).
1185 User.After = Best->FinalConversion;
1186 return true;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001187 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001188 assert(false && "Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001189 return false;
1190 }
1191
1192 case OR_No_Viable_Function:
1193 // No conversion here! We're done.
1194 return false;
1195
1196 case OR_Ambiguous:
1197 // FIXME: See C++ [over.best.ics]p10 for the handling of
1198 // ambiguous conversion sequences.
1199 return false;
1200 }
1201
1202 return false;
1203}
1204
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001205/// CompareImplicitConversionSequences - Compare two implicit
1206/// conversion sequences to determine whether one is better than the
1207/// other or if they are indistinguishable (C++ 13.3.3.2).
1208ImplicitConversionSequence::CompareKind
1209Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1210 const ImplicitConversionSequence& ICS2)
1211{
1212 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1213 // conversion sequences (as defined in 13.3.3.1)
1214 // -- a standard conversion sequence (13.3.3.1.1) is a better
1215 // conversion sequence than a user-defined conversion sequence or
1216 // an ellipsis conversion sequence, and
1217 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1218 // conversion sequence than an ellipsis conversion sequence
1219 // (13.3.3.1.3).
1220 //
1221 if (ICS1.ConversionKind < ICS2.ConversionKind)
1222 return ImplicitConversionSequence::Better;
1223 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1224 return ImplicitConversionSequence::Worse;
1225
1226 // Two implicit conversion sequences of the same form are
1227 // indistinguishable conversion sequences unless one of the
1228 // following rules apply: (C++ 13.3.3.2p3):
1229 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1230 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1231 else if (ICS1.ConversionKind ==
1232 ImplicitConversionSequence::UserDefinedConversion) {
1233 // User-defined conversion sequence U1 is a better conversion
1234 // sequence than another user-defined conversion sequence U2 if
1235 // they contain the same user-defined conversion function or
1236 // constructor and if the second standard conversion sequence of
1237 // U1 is better than the second standard conversion sequence of
1238 // U2 (C++ 13.3.3.2p3).
1239 if (ICS1.UserDefined.ConversionFunction ==
1240 ICS2.UserDefined.ConversionFunction)
1241 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1242 ICS2.UserDefined.After);
1243 }
1244
1245 return ImplicitConversionSequence::Indistinguishable;
1246}
1247
1248/// CompareStandardConversionSequences - Compare two standard
1249/// conversion sequences to determine whether one is better than the
1250/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1251ImplicitConversionSequence::CompareKind
1252Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1253 const StandardConversionSequence& SCS2)
1254{
1255 // Standard conversion sequence S1 is a better conversion sequence
1256 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1257
1258 // -- S1 is a proper subsequence of S2 (comparing the conversion
1259 // sequences in the canonical form defined by 13.3.3.1.1,
1260 // excluding any Lvalue Transformation; the identity conversion
1261 // sequence is considered to be a subsequence of any
1262 // non-identity conversion sequence) or, if not that,
1263 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1264 // Neither is a proper subsequence of the other. Do nothing.
1265 ;
1266 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1267 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1268 (SCS1.Second == ICK_Identity &&
1269 SCS1.Third == ICK_Identity))
1270 // SCS1 is a proper subsequence of SCS2.
1271 return ImplicitConversionSequence::Better;
1272 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1273 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1274 (SCS2.Second == ICK_Identity &&
1275 SCS2.Third == ICK_Identity))
1276 // SCS2 is a proper subsequence of SCS1.
1277 return ImplicitConversionSequence::Worse;
1278
1279 // -- the rank of S1 is better than the rank of S2 (by the rules
1280 // defined below), or, if not that,
1281 ImplicitConversionRank Rank1 = SCS1.getRank();
1282 ImplicitConversionRank Rank2 = SCS2.getRank();
1283 if (Rank1 < Rank2)
1284 return ImplicitConversionSequence::Better;
1285 else if (Rank2 < Rank1)
1286 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001287
Douglas Gregor57373262008-10-22 14:17:15 +00001288 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1289 // are indistinguishable unless one of the following rules
1290 // applies:
1291
1292 // A conversion that is not a conversion of a pointer, or
1293 // pointer to member, to bool is better than another conversion
1294 // that is such a conversion.
1295 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1296 return SCS2.isPointerConversionToBool()
1297 ? ImplicitConversionSequence::Better
1298 : ImplicitConversionSequence::Worse;
1299
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001300 // C++ [over.ics.rank]p4b2:
1301 //
1302 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001303 // conversion of B* to A* is better than conversion of B* to
1304 // void*, and conversion of A* to void* is better than conversion
1305 // of B* to void*.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001306 bool SCS1ConvertsToVoid
1307 = SCS1.isPointerConversionToVoidPointer(Context);
1308 bool SCS2ConvertsToVoid
1309 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001310 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1311 // Exactly one of the conversion sequences is a conversion to
1312 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001313 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1314 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001315 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1316 // Neither conversion sequence converts to a void pointer; compare
1317 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001318 if (ImplicitConversionSequence::CompareKind DerivedCK
1319 = CompareDerivedToBaseConversions(SCS1, SCS2))
1320 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001321 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1322 // Both conversion sequences are conversions to void
1323 // pointers. Compare the source types to determine if there's an
1324 // inheritance relationship in their sources.
1325 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1326 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1327
1328 // Adjust the types we're converting from via the array-to-pointer
1329 // conversion, if we need to.
1330 if (SCS1.First == ICK_Array_To_Pointer)
1331 FromType1 = Context.getArrayDecayedType(FromType1);
1332 if (SCS2.First == ICK_Array_To_Pointer)
1333 FromType2 = Context.getArrayDecayedType(FromType2);
1334
1335 QualType FromPointee1
1336 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1337 QualType FromPointee2
1338 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1339
1340 if (IsDerivedFrom(FromPointee2, FromPointee1))
1341 return ImplicitConversionSequence::Better;
1342 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1343 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001344
1345 // Objective-C++: If one interface is more specific than the
1346 // other, it is the better one.
1347 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1348 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1349 if (FromIface1 && FromIface1) {
1350 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1351 return ImplicitConversionSequence::Better;
1352 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1353 return ImplicitConversionSequence::Worse;
1354 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001355 }
Douglas Gregor57373262008-10-22 14:17:15 +00001356
1357 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1358 // bullet 3).
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001359 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001360 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001361 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001362
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001363 // C++ [over.ics.rank]p3b4:
1364 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1365 // which the references refer are the same type except for
1366 // top-level cv-qualifiers, and the type to which the reference
1367 // initialized by S2 refers is more cv-qualified than the type
1368 // to which the reference initialized by S1 refers.
1369 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1370 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1371 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1372 T1 = Context.getCanonicalType(T1);
1373 T2 = Context.getCanonicalType(T2);
1374 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1375 if (T2.isMoreQualifiedThan(T1))
1376 return ImplicitConversionSequence::Better;
1377 else if (T1.isMoreQualifiedThan(T2))
1378 return ImplicitConversionSequence::Worse;
1379 }
1380 }
Douglas Gregor57373262008-10-22 14:17:15 +00001381
1382 return ImplicitConversionSequence::Indistinguishable;
1383}
1384
1385/// CompareQualificationConversions - Compares two standard conversion
1386/// sequences to determine whether they can be ranked based on their
1387/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1388ImplicitConversionSequence::CompareKind
1389Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1390 const StandardConversionSequence& SCS2)
1391{
Douglas Gregorba7e2102008-10-22 15:04:37 +00001392 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001393 // -- S1 and S2 differ only in their qualification conversion and
1394 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1395 // cv-qualification signature of type T1 is a proper subset of
1396 // the cv-qualification signature of type T2, and S1 is not the
1397 // deprecated string literal array-to-pointer conversion (4.2).
1398 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1399 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1400 return ImplicitConversionSequence::Indistinguishable;
1401
1402 // FIXME: the example in the standard doesn't use a qualification
1403 // conversion (!)
1404 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1405 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1406 T1 = Context.getCanonicalType(T1);
1407 T2 = Context.getCanonicalType(T2);
1408
1409 // If the types are the same, we won't learn anything by unwrapped
1410 // them.
1411 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1412 return ImplicitConversionSequence::Indistinguishable;
1413
1414 ImplicitConversionSequence::CompareKind Result
1415 = ImplicitConversionSequence::Indistinguishable;
1416 while (UnwrapSimilarPointerTypes(T1, T2)) {
1417 // Within each iteration of the loop, we check the qualifiers to
1418 // determine if this still looks like a qualification
1419 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001420 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001421 // until there are no more pointers or pointers-to-members left
1422 // to unwrap. This essentially mimics what
1423 // IsQualificationConversion does, but here we're checking for a
1424 // strict subset of qualifiers.
1425 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1426 // The qualifiers are the same, so this doesn't tell us anything
1427 // about how the sequences rank.
1428 ;
1429 else if (T2.isMoreQualifiedThan(T1)) {
1430 // T1 has fewer qualifiers, so it could be the better sequence.
1431 if (Result == ImplicitConversionSequence::Worse)
1432 // Neither has qualifiers that are a subset of the other's
1433 // qualifiers.
1434 return ImplicitConversionSequence::Indistinguishable;
1435
1436 Result = ImplicitConversionSequence::Better;
1437 } else if (T1.isMoreQualifiedThan(T2)) {
1438 // T2 has fewer qualifiers, so it could be the better sequence.
1439 if (Result == ImplicitConversionSequence::Better)
1440 // Neither has qualifiers that are a subset of the other's
1441 // qualifiers.
1442 return ImplicitConversionSequence::Indistinguishable;
1443
1444 Result = ImplicitConversionSequence::Worse;
1445 } else {
1446 // Qualifiers are disjoint.
1447 return ImplicitConversionSequence::Indistinguishable;
1448 }
1449
1450 // If the types after this point are equivalent, we're done.
1451 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1452 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001453 }
1454
Douglas Gregor57373262008-10-22 14:17:15 +00001455 // Check that the winning standard conversion sequence isn't using
1456 // the deprecated string literal array to pointer conversion.
1457 switch (Result) {
1458 case ImplicitConversionSequence::Better:
1459 if (SCS1.Deprecated)
1460 Result = ImplicitConversionSequence::Indistinguishable;
1461 break;
1462
1463 case ImplicitConversionSequence::Indistinguishable:
1464 break;
1465
1466 case ImplicitConversionSequence::Worse:
1467 if (SCS2.Deprecated)
1468 Result = ImplicitConversionSequence::Indistinguishable;
1469 break;
1470 }
1471
1472 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001473}
1474
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001475/// CompareDerivedToBaseConversions - Compares two standard conversion
1476/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00001477/// various kinds of derived-to-base conversions (C++
1478/// [over.ics.rank]p4b3). As part of these checks, we also look at
1479/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001480ImplicitConversionSequence::CompareKind
1481Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1482 const StandardConversionSequence& SCS2) {
1483 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1484 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1485 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1486 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1487
1488 // Adjust the types we're converting from via the array-to-pointer
1489 // conversion, if we need to.
1490 if (SCS1.First == ICK_Array_To_Pointer)
1491 FromType1 = Context.getArrayDecayedType(FromType1);
1492 if (SCS2.First == ICK_Array_To_Pointer)
1493 FromType2 = Context.getArrayDecayedType(FromType2);
1494
1495 // Canonicalize all of the types.
1496 FromType1 = Context.getCanonicalType(FromType1);
1497 ToType1 = Context.getCanonicalType(ToType1);
1498 FromType2 = Context.getCanonicalType(FromType2);
1499 ToType2 = Context.getCanonicalType(ToType2);
1500
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001501 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001502 //
1503 // If class B is derived directly or indirectly from class A and
1504 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001505 //
1506 // For Objective-C, we let A, B, and C also be Objective-C
1507 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001508
1509 // Compare based on pointer conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001510 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00001511 SCS2.Second == ICK_Pointer_Conversion &&
1512 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1513 FromType1->isPointerType() && FromType2->isPointerType() &&
1514 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001515 QualType FromPointee1
1516 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1517 QualType ToPointee1
1518 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1519 QualType FromPointee2
1520 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1521 QualType ToPointee2
1522 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001523
1524 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1525 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1526 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1527 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1528
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001529 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001530 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1531 if (IsDerivedFrom(ToPointee1, ToPointee2))
1532 return ImplicitConversionSequence::Better;
1533 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1534 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001535
1536 if (ToIface1 && ToIface2) {
1537 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1538 return ImplicitConversionSequence::Better;
1539 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1540 return ImplicitConversionSequence::Worse;
1541 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001542 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001543
1544 // -- conversion of B* to A* is better than conversion of C* to A*,
1545 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1546 if (IsDerivedFrom(FromPointee2, FromPointee1))
1547 return ImplicitConversionSequence::Better;
1548 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1549 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001550
1551 if (FromIface1 && FromIface2) {
1552 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1553 return ImplicitConversionSequence::Better;
1554 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1555 return ImplicitConversionSequence::Worse;
1556 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001557 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001558 }
1559
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001560 // Compare based on reference bindings.
1561 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1562 SCS1.Second == ICK_Derived_To_Base) {
1563 // -- binding of an expression of type C to a reference of type
1564 // B& is better than binding an expression of type C to a
1565 // reference of type A&,
1566 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1567 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1568 if (IsDerivedFrom(ToType1, ToType2))
1569 return ImplicitConversionSequence::Better;
1570 else if (IsDerivedFrom(ToType2, ToType1))
1571 return ImplicitConversionSequence::Worse;
1572 }
1573
Douglas Gregor225c41e2008-11-03 19:09:14 +00001574 // -- binding of an expression of type B to a reference of type
1575 // A& is better than binding an expression of type C to a
1576 // reference of type A&,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001577 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1578 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1579 if (IsDerivedFrom(FromType2, FromType1))
1580 return ImplicitConversionSequence::Better;
1581 else if (IsDerivedFrom(FromType1, FromType2))
1582 return ImplicitConversionSequence::Worse;
1583 }
1584 }
1585
1586
1587 // FIXME: conversion of A::* to B::* is better than conversion of
1588 // A::* to C::*,
1589
1590 // FIXME: conversion of B::* to C::* is better than conversion of
1591 // A::* to C::*, and
1592
Douglas Gregor225c41e2008-11-03 19:09:14 +00001593 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1594 SCS1.Second == ICK_Derived_To_Base) {
1595 // -- conversion of C to B is better than conversion of C to A,
1596 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1597 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1598 if (IsDerivedFrom(ToType1, ToType2))
1599 return ImplicitConversionSequence::Better;
1600 else if (IsDerivedFrom(ToType2, ToType1))
1601 return ImplicitConversionSequence::Worse;
1602 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001603
Douglas Gregor225c41e2008-11-03 19:09:14 +00001604 // -- conversion of B to A is better than conversion of C to A.
1605 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1606 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1607 if (IsDerivedFrom(FromType2, FromType1))
1608 return ImplicitConversionSequence::Better;
1609 else if (IsDerivedFrom(FromType1, FromType2))
1610 return ImplicitConversionSequence::Worse;
1611 }
1612 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001613
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001614 return ImplicitConversionSequence::Indistinguishable;
1615}
1616
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001617/// TryCopyInitialization - Try to copy-initialize a value of type
1618/// ToType from the expression From. Return the implicit conversion
1619/// sequence required to pass this argument, which may be a bad
1620/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00001621/// a parameter of this type). If @p SuppressUserConversions, then we
1622/// do not permit any user-defined conversion sequences.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001623ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +00001624Sema::TryCopyInitialization(Expr *From, QualType ToType,
1625 bool SuppressUserConversions) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001626 if (!getLangOptions().CPlusPlus) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001627 // In C, copy initialization is the same as performing an assignment.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001628 AssignConvertType ConvTy =
1629 CheckSingleAssignmentConstraints(ToType, From);
1630 ImplicitConversionSequence ICS;
1631 if (getLangOptions().NoExtensions? ConvTy != Compatible
1632 : ConvTy == Incompatible)
1633 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1634 else
1635 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1636 return ICS;
1637 } else if (ToType->isReferenceType()) {
1638 ImplicitConversionSequence ICS;
Douglas Gregor225c41e2008-11-03 19:09:14 +00001639 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001640 return ICS;
1641 } else {
Douglas Gregor225c41e2008-11-03 19:09:14 +00001642 return TryImplicitConversion(From, ToType, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001643 }
1644}
1645
1646/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1647/// type ToType. Returns true (and emits a diagnostic) if there was
1648/// an error, returns false if the initialization succeeded.
1649bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1650 const char* Flavor) {
1651 if (!getLangOptions().CPlusPlus) {
1652 // In C, argument passing is the same as performing an assignment.
1653 QualType FromType = From->getType();
1654 AssignConvertType ConvTy =
1655 CheckSingleAssignmentConstraints(ToType, From);
1656
1657 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1658 FromType, From, Flavor);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001659 }
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001660
1661 if (ToType->isReferenceType())
1662 return CheckReferenceInit(From, ToType);
1663
Douglas Gregor45920e82008-12-19 17:40:08 +00001664 if (!PerformImplicitConversion(From, ToType, Flavor))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001665 return false;
1666
1667 return Diag(From->getSourceRange().getBegin(),
1668 diag::err_typecheck_convert_incompatible)
1669 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001670}
1671
Douglas Gregor96176b32008-11-18 23:14:02 +00001672/// TryObjectArgumentInitialization - Try to initialize the object
1673/// parameter of the given member function (@c Method) from the
1674/// expression @p From.
1675ImplicitConversionSequence
1676Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1677 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1678 unsigned MethodQuals = Method->getTypeQualifiers();
1679 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1680
1681 // Set up the conversion sequence as a "bad" conversion, to allow us
1682 // to exit early.
1683 ImplicitConversionSequence ICS;
1684 ICS.Standard.setAsIdentityConversion();
1685 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1686
1687 // We need to have an object of class type.
1688 QualType FromType = From->getType();
1689 if (!FromType->isRecordType())
1690 return ICS;
1691
1692 // The implicit object parmeter is has the type "reference to cv X",
1693 // where X is the class of which the function is a member
1694 // (C++ [over.match.funcs]p4). However, when finding an implicit
1695 // conversion sequence for the argument, we are not allowed to
1696 // create temporaries or perform user-defined conversions
1697 // (C++ [over.match.funcs]p5). We perform a simplified version of
1698 // reference binding here, that allows class rvalues to bind to
1699 // non-constant references.
1700
1701 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1702 // with the implicit object parameter (C++ [over.match.funcs]p5).
1703 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1704 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1705 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1706 return ICS;
1707
1708 // Check that we have either the same type or a derived type. It
1709 // affects the conversion rank.
1710 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1711 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1712 ICS.Standard.Second = ICK_Identity;
1713 else if (IsDerivedFrom(FromType, ClassType))
1714 ICS.Standard.Second = ICK_Derived_To_Base;
1715 else
1716 return ICS;
1717
1718 // Success. Mark this as a reference binding.
1719 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1720 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1721 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1722 ICS.Standard.ReferenceBinding = true;
1723 ICS.Standard.DirectBinding = true;
1724 return ICS;
1725}
1726
1727/// PerformObjectArgumentInitialization - Perform initialization of
1728/// the implicit object parameter for the given Method with the given
1729/// expression.
1730bool
1731Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
1732 QualType ImplicitParamType
1733 = Method->getThisType(Context)->getAsPointerType()->getPointeeType();
1734 ImplicitConversionSequence ICS
1735 = TryObjectArgumentInitialization(From, Method);
1736 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
1737 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001738 diag::err_implicit_object_parameter_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00001739 << ImplicitParamType << From->getType() << From->getSourceRange();
Douglas Gregor96176b32008-11-18 23:14:02 +00001740
1741 if (ICS.Standard.Second == ICK_Derived_To_Base &&
1742 CheckDerivedToBaseConversion(From->getType(), ImplicitParamType,
1743 From->getSourceRange().getBegin(),
1744 From->getSourceRange()))
1745 return true;
1746
1747 ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true);
1748 return false;
1749}
1750
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001751/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00001752/// candidate functions, using the given function call arguments. If
1753/// @p SuppressUserConversions, then don't allow user-defined
1754/// conversions via constructors or conversion operators.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001755void
1756Sema::AddOverloadCandidate(FunctionDecl *Function,
1757 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00001758 OverloadCandidateSet& CandidateSet,
1759 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001760{
1761 const FunctionTypeProto* Proto
1762 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType());
1763 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001764 assert(!isa<CXXConversionDecl>(Function) &&
1765 "Use AddConversionCandidate for conversion functions");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001766
Douglas Gregor88a35142008-12-22 05:46:06 +00001767 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
1768 // If we get here, it's because we're calling a member function
1769 // that is named without a member access expression (e.g.,
1770 // "this->f") that was either written explicitly or created
1771 // implicitly. This can happen with a qualified call to a member
1772 // function, e.g., X::f(). We use a NULL object as the implied
1773 // object argument (C++ [over.call.func]p3).
1774 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
1775 SuppressUserConversions);
1776 return;
1777 }
1778
1779
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001780 // Add this candidate
1781 CandidateSet.push_back(OverloadCandidate());
1782 OverloadCandidate& Candidate = CandidateSet.back();
1783 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00001784 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001785 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00001786 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001787
1788 unsigned NumArgsInProto = Proto->getNumArgs();
1789
1790 // (C++ 13.3.2p2): A candidate function having fewer than m
1791 // parameters is viable only if it has an ellipsis in its parameter
1792 // list (8.3.5).
1793 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1794 Candidate.Viable = false;
1795 return;
1796 }
1797
1798 // (C++ 13.3.2p2): A candidate function having more than m parameters
1799 // is viable only if the (m+1)st parameter has a default argument
1800 // (8.3.6). For the purposes of overload resolution, the
1801 // parameter list is truncated on the right, so that there are
1802 // exactly m parameters.
1803 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
1804 if (NumArgs < MinRequiredArgs) {
1805 // Not enough arguments.
1806 Candidate.Viable = false;
1807 return;
1808 }
1809
1810 // Determine the implicit conversion sequences for each of the
1811 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001812 Candidate.Conversions.resize(NumArgs);
1813 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1814 if (ArgIdx < NumArgsInProto) {
1815 // (C++ 13.3.2p3): for F to be a viable function, there shall
1816 // exist for each argument an implicit conversion sequence
1817 // (13.3.3.1) that converts that argument to the corresponding
1818 // parameter of F.
1819 QualType ParamType = Proto->getArgType(ArgIdx);
1820 Candidate.Conversions[ArgIdx]
Douglas Gregor225c41e2008-11-03 19:09:14 +00001821 = TryCopyInitialization(Args[ArgIdx], ParamType,
1822 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001823 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00001824 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001825 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001826 break;
1827 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001828 } else {
1829 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1830 // argument for which there is no corresponding parameter is
1831 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1832 Candidate.Conversions[ArgIdx].ConversionKind
1833 = ImplicitConversionSequence::EllipsisConversion;
1834 }
1835 }
1836}
1837
Douglas Gregor96176b32008-11-18 23:14:02 +00001838/// AddMethodCandidate - Adds the given C++ member function to the set
1839/// of candidate functions, using the given function call arguments
1840/// and the object argument (@c Object). For example, in a call
1841/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
1842/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
1843/// allow user-defined conversions via constructors or conversion
1844/// operators.
1845void
1846Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
1847 Expr **Args, unsigned NumArgs,
1848 OverloadCandidateSet& CandidateSet,
1849 bool SuppressUserConversions)
1850{
1851 const FunctionTypeProto* Proto
1852 = dyn_cast<FunctionTypeProto>(Method->getType()->getAsFunctionType());
1853 assert(Proto && "Methods without a prototype cannot be overloaded");
1854 assert(!isa<CXXConversionDecl>(Method) &&
1855 "Use AddConversionCandidate for conversion functions");
1856
1857 // Add this candidate
1858 CandidateSet.push_back(OverloadCandidate());
1859 OverloadCandidate& Candidate = CandidateSet.back();
1860 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001861 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00001862 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001863
1864 unsigned NumArgsInProto = Proto->getNumArgs();
1865
1866 // (C++ 13.3.2p2): A candidate function having fewer than m
1867 // parameters is viable only if it has an ellipsis in its parameter
1868 // list (8.3.5).
1869 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1870 Candidate.Viable = false;
1871 return;
1872 }
1873
1874 // (C++ 13.3.2p2): A candidate function having more than m parameters
1875 // is viable only if the (m+1)st parameter has a default argument
1876 // (8.3.6). For the purposes of overload resolution, the
1877 // parameter list is truncated on the right, so that there are
1878 // exactly m parameters.
1879 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
1880 if (NumArgs < MinRequiredArgs) {
1881 // Not enough arguments.
1882 Candidate.Viable = false;
1883 return;
1884 }
1885
1886 Candidate.Viable = true;
1887 Candidate.Conversions.resize(NumArgs + 1);
1888
Douglas Gregor88a35142008-12-22 05:46:06 +00001889 if (Method->isStatic() || !Object)
1890 // The implicit object argument is ignored.
1891 Candidate.IgnoreObjectArgument = true;
1892 else {
1893 // Determine the implicit conversion sequence for the object
1894 // parameter.
1895 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
1896 if (Candidate.Conversions[0].ConversionKind
1897 == ImplicitConversionSequence::BadConversion) {
1898 Candidate.Viable = false;
1899 return;
1900 }
Douglas Gregor96176b32008-11-18 23:14:02 +00001901 }
1902
1903 // Determine the implicit conversion sequences for each of the
1904 // arguments.
1905 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1906 if (ArgIdx < NumArgsInProto) {
1907 // (C++ 13.3.2p3): for F to be a viable function, there shall
1908 // exist for each argument an implicit conversion sequence
1909 // (13.3.3.1) that converts that argument to the corresponding
1910 // parameter of F.
1911 QualType ParamType = Proto->getArgType(ArgIdx);
1912 Candidate.Conversions[ArgIdx + 1]
1913 = TryCopyInitialization(Args[ArgIdx], ParamType,
1914 SuppressUserConversions);
1915 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
1916 == ImplicitConversionSequence::BadConversion) {
1917 Candidate.Viable = false;
1918 break;
1919 }
1920 } else {
1921 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1922 // argument for which there is no corresponding parameter is
1923 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1924 Candidate.Conversions[ArgIdx + 1].ConversionKind
1925 = ImplicitConversionSequence::EllipsisConversion;
1926 }
1927 }
1928}
1929
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001930/// AddConversionCandidate - Add a C++ conversion function as a
1931/// candidate in the candidate set (C++ [over.match.conv],
1932/// C++ [over.match.copy]). From is the expression we're converting from,
1933/// and ToType is the type that we're eventually trying to convert to
1934/// (which may or may not be the same type as the type that the
1935/// conversion function produces).
1936void
1937Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
1938 Expr *From, QualType ToType,
1939 OverloadCandidateSet& CandidateSet) {
1940 // Add this candidate
1941 CandidateSet.push_back(OverloadCandidate());
1942 OverloadCandidate& Candidate = CandidateSet.back();
1943 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001944 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00001945 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001946 Candidate.FinalConversion.setAsIdentityConversion();
1947 Candidate.FinalConversion.FromTypePtr
1948 = Conversion->getConversionType().getAsOpaquePtr();
1949 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
1950
Douglas Gregor96176b32008-11-18 23:14:02 +00001951 // Determine the implicit conversion sequence for the implicit
1952 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001953 Candidate.Viable = true;
1954 Candidate.Conversions.resize(1);
Douglas Gregor96176b32008-11-18 23:14:02 +00001955 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001956
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001957 if (Candidate.Conversions[0].ConversionKind
1958 == ImplicitConversionSequence::BadConversion) {
1959 Candidate.Viable = false;
1960 return;
1961 }
1962
1963 // To determine what the conversion from the result of calling the
1964 // conversion function to the type we're eventually trying to
1965 // convert to (ToType), we need to synthesize a call to the
1966 // conversion function and attempt copy initialization from it. This
1967 // makes sure that we get the right semantics with respect to
1968 // lvalues/rvalues and the type. Fortunately, we can allocate this
1969 // call on the stack and we don't need its arguments to be
1970 // well-formed.
1971 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
1972 SourceLocation());
1973 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001974 &ConversionRef, false);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001975 CallExpr Call(&ConversionFn, 0, 0,
1976 Conversion->getConversionType().getNonReferenceType(),
1977 SourceLocation());
1978 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
1979 switch (ICS.ConversionKind) {
1980 case ImplicitConversionSequence::StandardConversion:
1981 Candidate.FinalConversion = ICS.Standard;
1982 break;
1983
1984 case ImplicitConversionSequence::BadConversion:
1985 Candidate.Viable = false;
1986 break;
1987
1988 default:
1989 assert(false &&
1990 "Can only end up with a standard conversion sequence or failure");
1991 }
1992}
1993
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001994/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
1995/// converts the given @c Object to a function pointer via the
1996/// conversion function @c Conversion, and then attempts to call it
1997/// with the given arguments (C++ [over.call.object]p2-4). Proto is
1998/// the type of function that we'll eventually be calling.
1999void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
2000 const FunctionTypeProto *Proto,
2001 Expr *Object, Expr **Args, unsigned NumArgs,
2002 OverloadCandidateSet& CandidateSet) {
2003 CandidateSet.push_back(OverloadCandidate());
2004 OverloadCandidate& Candidate = CandidateSet.back();
2005 Candidate.Function = 0;
2006 Candidate.Surrogate = Conversion;
2007 Candidate.Viable = true;
2008 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002009 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002010 Candidate.Conversions.resize(NumArgs + 1);
2011
2012 // Determine the implicit conversion sequence for the implicit
2013 // object parameter.
2014 ImplicitConversionSequence ObjectInit
2015 = TryObjectArgumentInitialization(Object, Conversion);
2016 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2017 Candidate.Viable = false;
2018 return;
2019 }
2020
2021 // The first conversion is actually a user-defined conversion whose
2022 // first conversion is ObjectInit's standard conversion (which is
2023 // effectively a reference binding). Record it as such.
2024 Candidate.Conversions[0].ConversionKind
2025 = ImplicitConversionSequence::UserDefinedConversion;
2026 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2027 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2028 Candidate.Conversions[0].UserDefined.After
2029 = Candidate.Conversions[0].UserDefined.Before;
2030 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2031
2032 // Find the
2033 unsigned NumArgsInProto = Proto->getNumArgs();
2034
2035 // (C++ 13.3.2p2): A candidate function having fewer than m
2036 // parameters is viable only if it has an ellipsis in its parameter
2037 // list (8.3.5).
2038 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2039 Candidate.Viable = false;
2040 return;
2041 }
2042
2043 // Function types don't have any default arguments, so just check if
2044 // we have enough arguments.
2045 if (NumArgs < NumArgsInProto) {
2046 // Not enough arguments.
2047 Candidate.Viable = false;
2048 return;
2049 }
2050
2051 // Determine the implicit conversion sequences for each of the
2052 // arguments.
2053 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2054 if (ArgIdx < NumArgsInProto) {
2055 // (C++ 13.3.2p3): for F to be a viable function, there shall
2056 // exist for each argument an implicit conversion sequence
2057 // (13.3.3.1) that converts that argument to the corresponding
2058 // parameter of F.
2059 QualType ParamType = Proto->getArgType(ArgIdx);
2060 Candidate.Conversions[ArgIdx + 1]
2061 = TryCopyInitialization(Args[ArgIdx], ParamType,
2062 /*SuppressUserConversions=*/false);
2063 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2064 == ImplicitConversionSequence::BadConversion) {
2065 Candidate.Viable = false;
2066 break;
2067 }
2068 } else {
2069 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2070 // argument for which there is no corresponding parameter is
2071 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2072 Candidate.Conversions[ArgIdx + 1].ConversionKind
2073 = ImplicitConversionSequence::EllipsisConversion;
2074 }
2075 }
2076}
2077
Douglas Gregor447b69e2008-11-19 03:25:36 +00002078/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2079/// an acceptable non-member overloaded operator for a call whose
2080/// arguments have types T1 (and, if non-empty, T2). This routine
2081/// implements the check in C++ [over.match.oper]p3b2 concerning
2082/// enumeration types.
2083static bool
2084IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2085 QualType T1, QualType T2,
2086 ASTContext &Context) {
2087 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2088 return true;
2089
2090 const FunctionTypeProto *Proto = Fn->getType()->getAsFunctionTypeProto();
2091 if (Proto->getNumArgs() < 1)
2092 return false;
2093
2094 if (T1->isEnumeralType()) {
2095 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
2096 if (Context.getCanonicalType(T1).getUnqualifiedType()
2097 == Context.getCanonicalType(ArgType).getUnqualifiedType())
2098 return true;
2099 }
2100
2101 if (Proto->getNumArgs() < 2)
2102 return false;
2103
2104 if (!T2.isNull() && T2->isEnumeralType()) {
2105 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
2106 if (Context.getCanonicalType(T2).getUnqualifiedType()
2107 == Context.getCanonicalType(ArgType).getUnqualifiedType())
2108 return true;
2109 }
2110
2111 return false;
2112}
2113
Douglas Gregor96176b32008-11-18 23:14:02 +00002114/// AddOperatorCandidates - Add the overloaded operator candidates for
2115/// the operator Op that was used in an operator expression such as "x
2116/// Op y". S is the scope in which the expression occurred (used for
2117/// name lookup of the operator), Args/NumArgs provides the operator
2118/// arguments, and CandidateSet will store the added overload
2119/// candidates. (C++ [over.match.oper]).
2120void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
2121 Expr **Args, unsigned NumArgs,
2122 OverloadCandidateSet& CandidateSet) {
2123 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2124
2125 // C++ [over.match.oper]p3:
2126 // For a unary operator @ with an operand of a type whose
2127 // cv-unqualified version is T1, and for a binary operator @ with
2128 // a left operand of a type whose cv-unqualified version is T1 and
2129 // a right operand of a type whose cv-unqualified version is T2,
2130 // three sets of candidate functions, designated member
2131 // candidates, non-member candidates and built-in candidates, are
2132 // constructed as follows:
2133 QualType T1 = Args[0]->getType();
2134 QualType T2;
2135 if (NumArgs > 1)
2136 T2 = Args[1]->getType();
2137
2138 // -- If T1 is a class type, the set of member candidates is the
2139 // result of the qualified lookup of T1::operator@
2140 // (13.3.1.1.1); otherwise, the set of member candidates is
2141 // empty.
2142 if (const RecordType *T1Rec = T1->getAsRecordType()) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002143 DeclContext::lookup_const_iterator Oper, OperEnd;
2144 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(Context, OpName);
2145 Oper != OperEnd; ++Oper)
2146 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2147 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor96176b32008-11-18 23:14:02 +00002148 /*SuppressUserConversions=*/false);
Douglas Gregor96176b32008-11-18 23:14:02 +00002149 }
2150
2151 // -- The set of non-member candidates is the result of the
2152 // unqualified lookup of operator@ in the context of the
2153 // expression according to the usual rules for name lookup in
2154 // unqualified function calls (3.4.2) except that all member
2155 // functions are ignored. However, if no operand has a class
2156 // type, only those non-member functions in the lookup set
2157 // that have a first parameter of type T1 or “reference to
2158 // (possibly cv-qualified) T1”, when T1 is an enumeration
2159 // type, or (if there is a right operand) a second parameter
2160 // of type T2 or “reference to (possibly cv-qualified) T2”,
2161 // when T2 is an enumeration type, are candidate functions.
2162 {
2163 NamedDecl *NonMemberOps = 0;
2164 for (IdentifierResolver::iterator I
2165 = IdResolver.begin(OpName, CurContext, true/*LookInParentCtx*/);
2166 I != IdResolver.end(); ++I) {
2167 // We don't need to check the identifier namespace, because
2168 // operator names can only be ordinary identifiers.
2169
2170 // Ignore member functions.
2171 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(*I)) {
2172 if (SD->getDeclContext()->isCXXRecord())
2173 continue;
2174 }
2175
2176 // We found something with this name. We're done.
2177 NonMemberOps = *I;
2178 break;
2179 }
2180
Douglas Gregor447b69e2008-11-19 03:25:36 +00002181 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NonMemberOps)) {
2182 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
2183 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2184 /*SuppressUserConversions=*/false);
2185 } else if (OverloadedFunctionDecl *Ovl
2186 = dyn_cast_or_null<OverloadedFunctionDecl>(NonMemberOps)) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002187 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
2188 FEnd = Ovl->function_end();
Douglas Gregor447b69e2008-11-19 03:25:36 +00002189 F != FEnd; ++F) {
2190 if (IsAcceptableNonMemberOperatorCandidate(*F, T1, T2, Context))
2191 AddOverloadCandidate(*F, Args, NumArgs, CandidateSet,
2192 /*SuppressUserConversions=*/false);
2193 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002194 }
2195 }
2196
2197 // Add builtin overload candidates (C++ [over.built]).
Douglas Gregor74253732008-11-19 15:42:04 +00002198 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
Douglas Gregor96176b32008-11-18 23:14:02 +00002199}
2200
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002201/// AddBuiltinCandidate - Add a candidate for a built-in
2202/// operator. ResultTy and ParamTys are the result and parameter types
2203/// of the built-in candidate, respectively. Args and NumArgs are the
2204/// arguments being passed to the candidate.
2205void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2206 Expr **Args, unsigned NumArgs,
2207 OverloadCandidateSet& CandidateSet) {
2208 // Add this candidate
2209 CandidateSet.push_back(OverloadCandidate());
2210 OverloadCandidate& Candidate = CandidateSet.back();
2211 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00002212 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002213 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002214 Candidate.BuiltinTypes.ResultTy = ResultTy;
2215 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2216 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2217
2218 // Determine the implicit conversion sequences for each of the
2219 // arguments.
2220 Candidate.Viable = true;
2221 Candidate.Conversions.resize(NumArgs);
2222 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2223 Candidate.Conversions[ArgIdx]
2224 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx], false);
2225 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002226 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002227 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002228 break;
2229 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002230 }
2231}
2232
2233/// BuiltinCandidateTypeSet - A set of types that will be used for the
2234/// candidate operator functions for built-in operators (C++
2235/// [over.built]). The types are separated into pointer types and
2236/// enumeration types.
2237class BuiltinCandidateTypeSet {
2238 /// TypeSet - A set of types.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002239 typedef llvm::SmallPtrSet<void*, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002240
2241 /// PointerTypes - The set of pointer types that will be used in the
2242 /// built-in candidates.
2243 TypeSet PointerTypes;
2244
2245 /// EnumerationTypes - The set of enumeration types that will be
2246 /// used in the built-in candidates.
2247 TypeSet EnumerationTypes;
2248
2249 /// Context - The AST context in which we will build the type sets.
2250 ASTContext &Context;
2251
2252 bool AddWithMoreQualifiedTypeVariants(QualType Ty);
2253
2254public:
2255 /// iterator - Iterates through the types that are part of the set.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002256 class iterator {
2257 TypeSet::iterator Base;
2258
2259 public:
2260 typedef QualType value_type;
2261 typedef QualType reference;
2262 typedef QualType pointer;
2263 typedef std::ptrdiff_t difference_type;
2264 typedef std::input_iterator_tag iterator_category;
2265
2266 iterator(TypeSet::iterator B) : Base(B) { }
2267
2268 iterator& operator++() {
2269 ++Base;
2270 return *this;
2271 }
2272
2273 iterator operator++(int) {
2274 iterator tmp(*this);
2275 ++(*this);
2276 return tmp;
2277 }
2278
2279 reference operator*() const {
2280 return QualType::getFromOpaquePtr(*Base);
2281 }
2282
2283 pointer operator->() const {
2284 return **this;
2285 }
2286
2287 friend bool operator==(iterator LHS, iterator RHS) {
2288 return LHS.Base == RHS.Base;
2289 }
2290
2291 friend bool operator!=(iterator LHS, iterator RHS) {
2292 return LHS.Base != RHS.Base;
2293 }
2294 };
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002295
2296 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2297
2298 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions = true);
2299
2300 /// pointer_begin - First pointer type found;
2301 iterator pointer_begin() { return PointerTypes.begin(); }
2302
2303 /// pointer_end - Last pointer type found;
2304 iterator pointer_end() { return PointerTypes.end(); }
2305
2306 /// enumeration_begin - First enumeration type found;
2307 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2308
2309 /// enumeration_end - Last enumeration type found;
2310 iterator enumeration_end() { return EnumerationTypes.end(); }
2311};
2312
2313/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2314/// the set of pointer types along with any more-qualified variants of
2315/// that type. For example, if @p Ty is "int const *", this routine
2316/// will add "int const *", "int const volatile *", "int const
2317/// restrict *", and "int const volatile restrict *" to the set of
2318/// pointer types. Returns true if the add of @p Ty itself succeeded,
2319/// false otherwise.
2320bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) {
2321 // Insert this type.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002322 if (!PointerTypes.insert(Ty.getAsOpaquePtr()))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002323 return false;
2324
2325 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2326 QualType PointeeTy = PointerTy->getPointeeType();
2327 // FIXME: Optimize this so that we don't keep trying to add the same types.
2328
2329 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
2330 // with all pointer conversions that don't cast away constness?
2331 if (!PointeeTy.isConstQualified())
2332 AddWithMoreQualifiedTypeVariants
2333 (Context.getPointerType(PointeeTy.withConst()));
2334 if (!PointeeTy.isVolatileQualified())
2335 AddWithMoreQualifiedTypeVariants
2336 (Context.getPointerType(PointeeTy.withVolatile()));
2337 if (!PointeeTy.isRestrictQualified())
2338 AddWithMoreQualifiedTypeVariants
2339 (Context.getPointerType(PointeeTy.withRestrict()));
2340 }
2341
2342 return true;
2343}
2344
2345/// AddTypesConvertedFrom - Add each of the types to which the type @p
2346/// Ty can be implicit converted to the given set of @p Types. We're
2347/// primarily interested in pointer types, enumeration types,
2348void BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2349 bool AllowUserConversions) {
2350 // Only deal with canonical types.
2351 Ty = Context.getCanonicalType(Ty);
2352
2353 // Look through reference types; they aren't part of the type of an
2354 // expression for the purposes of conversions.
2355 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2356 Ty = RefTy->getPointeeType();
2357
2358 // We don't care about qualifiers on the type.
2359 Ty = Ty.getUnqualifiedType();
2360
2361 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2362 QualType PointeeTy = PointerTy->getPointeeType();
2363
2364 // Insert our type, and its more-qualified variants, into the set
2365 // of types.
2366 if (!AddWithMoreQualifiedTypeVariants(Ty))
2367 return;
2368
2369 // Add 'cv void*' to our set of types.
2370 if (!Ty->isVoidType()) {
2371 QualType QualVoid
2372 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2373 AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2374 }
2375
2376 // If this is a pointer to a class type, add pointers to its bases
2377 // (with the same level of cv-qualification as the original
2378 // derived class, of course).
2379 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2380 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2381 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2382 Base != ClassDecl->bases_end(); ++Base) {
2383 QualType BaseTy = Context.getCanonicalType(Base->getType());
2384 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2385
2386 // Add the pointer type, recursively, so that we get all of
2387 // the indirect base classes, too.
2388 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false);
2389 }
2390 }
2391 } else if (Ty->isEnumeralType()) {
Douglas Gregorbf3af052008-11-13 20:12:29 +00002392 EnumerationTypes.insert(Ty.getAsOpaquePtr());
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002393 } else if (AllowUserConversions) {
2394 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2395 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2396 // FIXME: Visit conversion functions in the base classes, too.
2397 OverloadedFunctionDecl *Conversions
2398 = ClassDecl->getConversionFunctions();
2399 for (OverloadedFunctionDecl::function_iterator Func
2400 = Conversions->function_begin();
2401 Func != Conversions->function_end(); ++Func) {
2402 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
2403 AddTypesConvertedFrom(Conv->getConversionType(), false);
2404 }
2405 }
2406 }
2407}
2408
Douglas Gregor74253732008-11-19 15:42:04 +00002409/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2410/// operator overloads to the candidate set (C++ [over.built]), based
2411/// on the operator @p Op and the arguments given. For example, if the
2412/// operator is a binary '+', this routine might add "int
2413/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002414void
Douglas Gregor74253732008-11-19 15:42:04 +00002415Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2416 Expr **Args, unsigned NumArgs,
2417 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002418 // The set of "promoted arithmetic types", which are the arithmetic
2419 // types are that preserved by promotion (C++ [over.built]p2). Note
2420 // that the first few of these types are the promoted integral
2421 // types; these types need to be first.
2422 // FIXME: What about complex?
2423 const unsigned FirstIntegralType = 0;
2424 const unsigned LastIntegralType = 13;
2425 const unsigned FirstPromotedIntegralType = 7,
2426 LastPromotedIntegralType = 13;
2427 const unsigned FirstPromotedArithmeticType = 7,
2428 LastPromotedArithmeticType = 16;
2429 const unsigned NumArithmeticTypes = 16;
2430 QualType ArithmeticTypes[NumArithmeticTypes] = {
2431 Context.BoolTy, Context.CharTy, Context.WCharTy,
2432 Context.SignedCharTy, Context.ShortTy,
2433 Context.UnsignedCharTy, Context.UnsignedShortTy,
2434 Context.IntTy, Context.LongTy, Context.LongLongTy,
2435 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2436 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2437 };
2438
2439 // Find all of the types that the arguments can convert to, but only
2440 // if the operator we're looking at has built-in operator candidates
2441 // that make use of these types.
2442 BuiltinCandidateTypeSet CandidateTypes(Context);
2443 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2444 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00002445 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002446 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00002447 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
2448 (Op == OO_Star && NumArgs == 1)) {
2449 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002450 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType());
2451 }
2452
2453 bool isComparison = false;
2454 switch (Op) {
2455 case OO_None:
2456 case NUM_OVERLOADED_OPERATORS:
2457 assert(false && "Expected an overloaded operator");
2458 break;
2459
Douglas Gregor74253732008-11-19 15:42:04 +00002460 case OO_Star: // '*' is either unary or binary
2461 if (NumArgs == 1)
2462 goto UnaryStar;
2463 else
2464 goto BinaryStar;
2465 break;
2466
2467 case OO_Plus: // '+' is either unary or binary
2468 if (NumArgs == 1)
2469 goto UnaryPlus;
2470 else
2471 goto BinaryPlus;
2472 break;
2473
2474 case OO_Minus: // '-' is either unary or binary
2475 if (NumArgs == 1)
2476 goto UnaryMinus;
2477 else
2478 goto BinaryMinus;
2479 break;
2480
2481 case OO_Amp: // '&' is either unary or binary
2482 if (NumArgs == 1)
2483 goto UnaryAmp;
2484 else
2485 goto BinaryAmp;
2486
2487 case OO_PlusPlus:
2488 case OO_MinusMinus:
2489 // C++ [over.built]p3:
2490 //
2491 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2492 // is either volatile or empty, there exist candidate operator
2493 // functions of the form
2494 //
2495 // VQ T& operator++(VQ T&);
2496 // T operator++(VQ T&, int);
2497 //
2498 // C++ [over.built]p4:
2499 //
2500 // For every pair (T, VQ), where T is an arithmetic type other
2501 // than bool, and VQ is either volatile or empty, there exist
2502 // candidate operator functions of the form
2503 //
2504 // VQ T& operator--(VQ T&);
2505 // T operator--(VQ T&, int);
2506 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2507 Arith < NumArithmeticTypes; ++Arith) {
2508 QualType ArithTy = ArithmeticTypes[Arith];
2509 QualType ParamTypes[2]
2510 = { Context.getReferenceType(ArithTy), Context.IntTy };
2511
2512 // Non-volatile version.
2513 if (NumArgs == 1)
2514 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2515 else
2516 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2517
2518 // Volatile version
2519 ParamTypes[0] = Context.getReferenceType(ArithTy.withVolatile());
2520 if (NumArgs == 1)
2521 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2522 else
2523 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2524 }
2525
2526 // C++ [over.built]p5:
2527 //
2528 // For every pair (T, VQ), where T is a cv-qualified or
2529 // cv-unqualified object type, and VQ is either volatile or
2530 // empty, there exist candidate operator functions of the form
2531 //
2532 // T*VQ& operator++(T*VQ&);
2533 // T*VQ& operator--(T*VQ&);
2534 // T* operator++(T*VQ&, int);
2535 // T* operator--(T*VQ&, int);
2536 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2537 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2538 // Skip pointer types that aren't pointers to object types.
Douglas Gregorcb7de522008-11-26 23:31:11 +00002539 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00002540 continue;
2541
2542 QualType ParamTypes[2] = {
2543 Context.getReferenceType(*Ptr), Context.IntTy
2544 };
2545
2546 // Without volatile
2547 if (NumArgs == 1)
2548 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2549 else
2550 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2551
2552 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2553 // With volatile
2554 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2555 if (NumArgs == 1)
2556 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2557 else
2558 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2559 }
2560 }
2561 break;
2562
2563 UnaryStar:
2564 // C++ [over.built]p6:
2565 // For every cv-qualified or cv-unqualified object type T, there
2566 // exist candidate operator functions of the form
2567 //
2568 // T& operator*(T*);
2569 //
2570 // C++ [over.built]p7:
2571 // For every function type T, there exist candidate operator
2572 // functions of the form
2573 // T& operator*(T*);
2574 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2575 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2576 QualType ParamTy = *Ptr;
2577 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
2578 AddBuiltinCandidate(Context.getReferenceType(PointeeTy),
2579 &ParamTy, Args, 1, CandidateSet);
2580 }
2581 break;
2582
2583 UnaryPlus:
2584 // C++ [over.built]p8:
2585 // For every type T, there exist candidate operator functions of
2586 // the form
2587 //
2588 // T* operator+(T*);
2589 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2590 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2591 QualType ParamTy = *Ptr;
2592 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2593 }
2594
2595 // Fall through
2596
2597 UnaryMinus:
2598 // C++ [over.built]p9:
2599 // For every promoted arithmetic type T, there exist candidate
2600 // operator functions of the form
2601 //
2602 // T operator+(T);
2603 // T operator-(T);
2604 for (unsigned Arith = FirstPromotedArithmeticType;
2605 Arith < LastPromotedArithmeticType; ++Arith) {
2606 QualType ArithTy = ArithmeticTypes[Arith];
2607 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2608 }
2609 break;
2610
2611 case OO_Tilde:
2612 // C++ [over.built]p10:
2613 // For every promoted integral type T, there exist candidate
2614 // operator functions of the form
2615 //
2616 // T operator~(T);
2617 for (unsigned Int = FirstPromotedIntegralType;
2618 Int < LastPromotedIntegralType; ++Int) {
2619 QualType IntTy = ArithmeticTypes[Int];
2620 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2621 }
2622 break;
2623
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002624 case OO_New:
2625 case OO_Delete:
2626 case OO_Array_New:
2627 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002628 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00002629 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002630 break;
2631
2632 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00002633 UnaryAmp:
2634 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002635 // C++ [over.match.oper]p3:
2636 // -- For the operator ',', the unary operator '&', or the
2637 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002638 break;
2639
2640 case OO_Less:
2641 case OO_Greater:
2642 case OO_LessEqual:
2643 case OO_GreaterEqual:
2644 case OO_EqualEqual:
2645 case OO_ExclaimEqual:
2646 // C++ [over.built]p15:
2647 //
2648 // For every pointer or enumeration type T, there exist
2649 // candidate operator functions of the form
2650 //
2651 // bool operator<(T, T);
2652 // bool operator>(T, T);
2653 // bool operator<=(T, T);
2654 // bool operator>=(T, T);
2655 // bool operator==(T, T);
2656 // bool operator!=(T, T);
2657 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2658 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2659 QualType ParamTypes[2] = { *Ptr, *Ptr };
2660 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2661 }
2662 for (BuiltinCandidateTypeSet::iterator Enum
2663 = CandidateTypes.enumeration_begin();
2664 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2665 QualType ParamTypes[2] = { *Enum, *Enum };
2666 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2667 }
2668
2669 // Fall through.
2670 isComparison = true;
2671
Douglas Gregor74253732008-11-19 15:42:04 +00002672 BinaryPlus:
2673 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002674 if (!isComparison) {
2675 // We didn't fall through, so we must have OO_Plus or OO_Minus.
2676
2677 // C++ [over.built]p13:
2678 //
2679 // For every cv-qualified or cv-unqualified object type T
2680 // there exist candidate operator functions of the form
2681 //
2682 // T* operator+(T*, ptrdiff_t);
2683 // T& operator[](T*, ptrdiff_t); [BELOW]
2684 // T* operator-(T*, ptrdiff_t);
2685 // T* operator+(ptrdiff_t, T*);
2686 // T& operator[](ptrdiff_t, T*); [BELOW]
2687 //
2688 // C++ [over.built]p14:
2689 //
2690 // For every T, where T is a pointer to object type, there
2691 // exist candidate operator functions of the form
2692 //
2693 // ptrdiff_t operator-(T, T);
2694 for (BuiltinCandidateTypeSet::iterator Ptr
2695 = CandidateTypes.pointer_begin();
2696 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2697 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2698
2699 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
2700 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2701
2702 if (Op == OO_Plus) {
2703 // T* operator+(ptrdiff_t, T*);
2704 ParamTypes[0] = ParamTypes[1];
2705 ParamTypes[1] = *Ptr;
2706 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2707 } else {
2708 // ptrdiff_t operator-(T, T);
2709 ParamTypes[1] = *Ptr;
2710 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
2711 Args, 2, CandidateSet);
2712 }
2713 }
2714 }
2715 // Fall through
2716
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002717 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00002718 BinaryStar:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002719 // C++ [over.built]p12:
2720 //
2721 // For every pair of promoted arithmetic types L and R, there
2722 // exist candidate operator functions of the form
2723 //
2724 // LR operator*(L, R);
2725 // LR operator/(L, R);
2726 // LR operator+(L, R);
2727 // LR operator-(L, R);
2728 // bool operator<(L, R);
2729 // bool operator>(L, R);
2730 // bool operator<=(L, R);
2731 // bool operator>=(L, R);
2732 // bool operator==(L, R);
2733 // bool operator!=(L, R);
2734 //
2735 // where LR is the result of the usual arithmetic conversions
2736 // between types L and R.
2737 for (unsigned Left = FirstPromotedArithmeticType;
2738 Left < LastPromotedArithmeticType; ++Left) {
2739 for (unsigned Right = FirstPromotedArithmeticType;
2740 Right < LastPromotedArithmeticType; ++Right) {
2741 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2742 QualType Result
2743 = isComparison? Context.BoolTy
2744 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2745 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2746 }
2747 }
2748 break;
2749
2750 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00002751 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002752 case OO_Caret:
2753 case OO_Pipe:
2754 case OO_LessLess:
2755 case OO_GreaterGreater:
2756 // C++ [over.built]p17:
2757 //
2758 // For every pair of promoted integral types L and R, there
2759 // exist candidate operator functions of the form
2760 //
2761 // LR operator%(L, R);
2762 // LR operator&(L, R);
2763 // LR operator^(L, R);
2764 // LR operator|(L, R);
2765 // L operator<<(L, R);
2766 // L operator>>(L, R);
2767 //
2768 // where LR is the result of the usual arithmetic conversions
2769 // between types L and R.
2770 for (unsigned Left = FirstPromotedIntegralType;
2771 Left < LastPromotedIntegralType; ++Left) {
2772 for (unsigned Right = FirstPromotedIntegralType;
2773 Right < LastPromotedIntegralType; ++Right) {
2774 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2775 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
2776 ? LandR[0]
2777 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2778 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2779 }
2780 }
2781 break;
2782
2783 case OO_Equal:
2784 // C++ [over.built]p20:
2785 //
2786 // For every pair (T, VQ), where T is an enumeration or
2787 // (FIXME:) pointer to member type and VQ is either volatile or
2788 // empty, there exist candidate operator functions of the form
2789 //
2790 // VQ T& operator=(VQ T&, T);
2791 for (BuiltinCandidateTypeSet::iterator Enum
2792 = CandidateTypes.enumeration_begin();
2793 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2794 QualType ParamTypes[2];
2795
2796 // T& operator=(T&, T)
2797 ParamTypes[0] = Context.getReferenceType(*Enum);
2798 ParamTypes[1] = *Enum;
2799 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2800
Douglas Gregor74253732008-11-19 15:42:04 +00002801 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
2802 // volatile T& operator=(volatile T&, T)
2803 ParamTypes[0] = Context.getReferenceType((*Enum).withVolatile());
2804 ParamTypes[1] = *Enum;
2805 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2806 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002807 }
2808 // Fall through.
2809
2810 case OO_PlusEqual:
2811 case OO_MinusEqual:
2812 // C++ [over.built]p19:
2813 //
2814 // For every pair (T, VQ), where T is any type and VQ is either
2815 // volatile or empty, there exist candidate operator functions
2816 // of the form
2817 //
2818 // T*VQ& operator=(T*VQ&, T*);
2819 //
2820 // C++ [over.built]p21:
2821 //
2822 // For every pair (T, VQ), where T is a cv-qualified or
2823 // cv-unqualified object type and VQ is either volatile or
2824 // empty, there exist candidate operator functions of the form
2825 //
2826 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
2827 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
2828 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2829 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2830 QualType ParamTypes[2];
2831 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
2832
2833 // non-volatile version
2834 ParamTypes[0] = Context.getReferenceType(*Ptr);
2835 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2836
Douglas Gregor74253732008-11-19 15:42:04 +00002837 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2838 // volatile version
2839 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2840 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2841 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002842 }
2843 // Fall through.
2844
2845 case OO_StarEqual:
2846 case OO_SlashEqual:
2847 // C++ [over.built]p18:
2848 //
2849 // For every triple (L, VQ, R), where L is an arithmetic type,
2850 // VQ is either volatile or empty, and R is a promoted
2851 // arithmetic type, there exist candidate operator functions of
2852 // the form
2853 //
2854 // VQ L& operator=(VQ L&, R);
2855 // VQ L& operator*=(VQ L&, R);
2856 // VQ L& operator/=(VQ L&, R);
2857 // VQ L& operator+=(VQ L&, R);
2858 // VQ L& operator-=(VQ L&, R);
2859 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
2860 for (unsigned Right = FirstPromotedArithmeticType;
2861 Right < LastPromotedArithmeticType; ++Right) {
2862 QualType ParamTypes[2];
2863 ParamTypes[1] = ArithmeticTypes[Right];
2864
2865 // Add this built-in operator as a candidate (VQ is empty).
2866 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
2867 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2868
2869 // Add this built-in operator as a candidate (VQ is 'volatile').
2870 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
2871 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
2872 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2873 }
2874 }
2875 break;
2876
2877 case OO_PercentEqual:
2878 case OO_LessLessEqual:
2879 case OO_GreaterGreaterEqual:
2880 case OO_AmpEqual:
2881 case OO_CaretEqual:
2882 case OO_PipeEqual:
2883 // C++ [over.built]p22:
2884 //
2885 // For every triple (L, VQ, R), where L is an integral type, VQ
2886 // is either volatile or empty, and R is a promoted integral
2887 // type, there exist candidate operator functions of the form
2888 //
2889 // VQ L& operator%=(VQ L&, R);
2890 // VQ L& operator<<=(VQ L&, R);
2891 // VQ L& operator>>=(VQ L&, R);
2892 // VQ L& operator&=(VQ L&, R);
2893 // VQ L& operator^=(VQ L&, R);
2894 // VQ L& operator|=(VQ L&, R);
2895 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
2896 for (unsigned Right = FirstPromotedIntegralType;
2897 Right < LastPromotedIntegralType; ++Right) {
2898 QualType ParamTypes[2];
2899 ParamTypes[1] = ArithmeticTypes[Right];
2900
2901 // Add this built-in operator as a candidate (VQ is empty).
2902 // FIXME: We should be caching these declarations somewhere,
2903 // rather than re-building them every time.
2904 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
2905 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2906
2907 // Add this built-in operator as a candidate (VQ is 'volatile').
2908 ParamTypes[0] = ArithmeticTypes[Left];
2909 ParamTypes[0].addVolatile();
2910 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
2911 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2912 }
2913 }
2914 break;
2915
Douglas Gregor74253732008-11-19 15:42:04 +00002916 case OO_Exclaim: {
2917 // C++ [over.operator]p23:
2918 //
2919 // There also exist candidate operator functions of the form
2920 //
2921 // bool operator!(bool);
2922 // bool operator&&(bool, bool); [BELOW]
2923 // bool operator||(bool, bool); [BELOW]
2924 QualType ParamTy = Context.BoolTy;
2925 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2926 break;
2927 }
2928
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002929 case OO_AmpAmp:
2930 case OO_PipePipe: {
2931 // C++ [over.operator]p23:
2932 //
2933 // There also exist candidate operator functions of the form
2934 //
Douglas Gregor74253732008-11-19 15:42:04 +00002935 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002936 // bool operator&&(bool, bool);
2937 // bool operator||(bool, bool);
2938 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
2939 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2940 break;
2941 }
2942
2943 case OO_Subscript:
2944 // C++ [over.built]p13:
2945 //
2946 // For every cv-qualified or cv-unqualified object type T there
2947 // exist candidate operator functions of the form
2948 //
2949 // T* operator+(T*, ptrdiff_t); [ABOVE]
2950 // T& operator[](T*, ptrdiff_t);
2951 // T* operator-(T*, ptrdiff_t); [ABOVE]
2952 // T* operator+(ptrdiff_t, T*); [ABOVE]
2953 // T& operator[](ptrdiff_t, T*);
2954 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2955 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2956 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2957 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
2958 QualType ResultTy = Context.getReferenceType(PointeeType);
2959
2960 // T& operator[](T*, ptrdiff_t)
2961 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
2962
2963 // T& operator[](ptrdiff_t, T*);
2964 ParamTypes[0] = ParamTypes[1];
2965 ParamTypes[1] = *Ptr;
2966 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
2967 }
2968 break;
2969
2970 case OO_ArrowStar:
2971 // FIXME: No support for pointer-to-members yet.
2972 break;
2973 }
2974}
2975
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002976/// AddOverloadCandidates - Add all of the function overloads in Ovl
2977/// to the candidate set.
2978void
Douglas Gregor18fe5682008-11-03 20:45:27 +00002979Sema::AddOverloadCandidates(const OverloadedFunctionDecl *Ovl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002980 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002981 OverloadCandidateSet& CandidateSet,
2982 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002983{
Douglas Gregor18fe5682008-11-03 20:45:27 +00002984 for (OverloadedFunctionDecl::function_const_iterator Func
2985 = Ovl->function_begin();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002986 Func != Ovl->function_end(); ++Func)
Douglas Gregor225c41e2008-11-03 19:09:14 +00002987 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet,
2988 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002989}
2990
2991/// isBetterOverloadCandidate - Determines whether the first overload
2992/// candidate is a better candidate than the second (C++ 13.3.3p1).
2993bool
2994Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
2995 const OverloadCandidate& Cand2)
2996{
2997 // Define viable functions to be better candidates than non-viable
2998 // functions.
2999 if (!Cand2.Viable)
3000 return Cand1.Viable;
3001 else if (!Cand1.Viable)
3002 return false;
3003
Douglas Gregor88a35142008-12-22 05:46:06 +00003004 // C++ [over.match.best]p1:
3005 //
3006 // -- if F is a static member function, ICS1(F) is defined such
3007 // that ICS1(F) is neither better nor worse than ICS1(G) for
3008 // any function G, and, symmetrically, ICS1(G) is neither
3009 // better nor worse than ICS1(F).
3010 unsigned StartArg = 0;
3011 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3012 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003013
3014 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
3015 // function than another viable function F2 if for all arguments i,
3016 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
3017 // then...
3018 unsigned NumArgs = Cand1.Conversions.size();
3019 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3020 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003021 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003022 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3023 Cand2.Conversions[ArgIdx])) {
3024 case ImplicitConversionSequence::Better:
3025 // Cand1 has a better conversion sequence.
3026 HasBetterConversion = true;
3027 break;
3028
3029 case ImplicitConversionSequence::Worse:
3030 // Cand1 can't be better than Cand2.
3031 return false;
3032
3033 case ImplicitConversionSequence::Indistinguishable:
3034 // Do nothing.
3035 break;
3036 }
3037 }
3038
3039 if (HasBetterConversion)
3040 return true;
3041
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003042 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
3043 // implemented, but they require template support.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003044
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003045 // C++ [over.match.best]p1b4:
3046 //
3047 // -- the context is an initialization by user-defined conversion
3048 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3049 // from the return type of F1 to the destination type (i.e.,
3050 // the type of the entity being initialized) is a better
3051 // conversion sequence than the standard conversion sequence
3052 // from the return type of F2 to the destination type.
Douglas Gregor447b69e2008-11-19 03:25:36 +00003053 if (Cand1.Function && Cand2.Function &&
3054 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003055 isa<CXXConversionDecl>(Cand2.Function)) {
3056 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3057 Cand2.FinalConversion)) {
3058 case ImplicitConversionSequence::Better:
3059 // Cand1 has a better conversion sequence.
3060 return true;
3061
3062 case ImplicitConversionSequence::Worse:
3063 // Cand1 can't be better than Cand2.
3064 return false;
3065
3066 case ImplicitConversionSequence::Indistinguishable:
3067 // Do nothing
3068 break;
3069 }
3070 }
3071
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003072 return false;
3073}
3074
3075/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
3076/// within an overload candidate set. If overloading is successful,
3077/// the result will be OR_Success and Best will be set to point to the
3078/// best viable function within the candidate set. Otherwise, one of
3079/// several kinds of errors will be returned; see
3080/// Sema::OverloadingResult.
3081Sema::OverloadingResult
3082Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
3083 OverloadCandidateSet::iterator& Best)
3084{
3085 // Find the best viable function.
3086 Best = CandidateSet.end();
3087 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3088 Cand != CandidateSet.end(); ++Cand) {
3089 if (Cand->Viable) {
3090 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3091 Best = Cand;
3092 }
3093 }
3094
3095 // If we didn't find any viable functions, abort.
3096 if (Best == CandidateSet.end())
3097 return OR_No_Viable_Function;
3098
3099 // Make sure that this function is better than every other viable
3100 // function. If not, we have an ambiguity.
3101 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3102 Cand != CandidateSet.end(); ++Cand) {
3103 if (Cand->Viable &&
3104 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003105 !isBetterOverloadCandidate(*Best, *Cand)) {
3106 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003107 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003108 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003109 }
3110
3111 // Best is the best viable function.
3112 return OR_Success;
3113}
3114
3115/// PrintOverloadCandidates - When overload resolution fails, prints
3116/// diagnostic messages containing the candidates in the candidate
3117/// set. If OnlyViable is true, only viable candidates will be printed.
3118void
3119Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3120 bool OnlyViable)
3121{
3122 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3123 LastCand = CandidateSet.end();
3124 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003125 if (Cand->Viable || !OnlyViable) {
3126 if (Cand->Function) {
3127 // Normal function
3128 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003129 } else if (Cand->IsSurrogate) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003130 // Desugar the type of the surrogate down to a function type,
3131 // retaining as many typedefs as possible while still showing
3132 // the function type (and, therefore, its parameter types).
3133 QualType FnType = Cand->Surrogate->getConversionType();
3134 bool isReference = false;
3135 bool isPointer = false;
3136 if (const ReferenceType *FnTypeRef = FnType->getAsReferenceType()) {
3137 FnType = FnTypeRef->getPointeeType();
3138 isReference = true;
3139 }
3140 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
3141 FnType = FnTypePtr->getPointeeType();
3142 isPointer = true;
3143 }
3144 // Desugar down to a function type.
3145 FnType = QualType(FnType->getAsFunctionType(), 0);
3146 // Reconstruct the pointer/reference as appropriate.
3147 if (isPointer) FnType = Context.getPointerType(FnType);
3148 if (isReference) FnType = Context.getReferenceType(FnType);
3149
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003150 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003151 << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003152 } else {
3153 // FIXME: We need to get the identifier in here
3154 // FIXME: Do we want the error message to point at the
3155 // operator? (built-ins won't have a location)
3156 QualType FnType
3157 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3158 Cand->BuiltinTypes.ParamTypes,
3159 Cand->Conversions.size(),
3160 false, 0);
3161
Chris Lattnerd1625842008-11-24 06:25:27 +00003162 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003163 }
3164 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003165 }
3166}
3167
Douglas Gregor904eed32008-11-10 20:40:00 +00003168/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3169/// an overloaded function (C++ [over.over]), where @p From is an
3170/// expression with overloaded function type and @p ToType is the type
3171/// we're trying to resolve to. For example:
3172///
3173/// @code
3174/// int f(double);
3175/// int f(int);
3176///
3177/// int (*pfd)(double) = f; // selects f(double)
3178/// @endcode
3179///
3180/// This routine returns the resulting FunctionDecl if it could be
3181/// resolved, and NULL otherwise. When @p Complain is true, this
3182/// routine will emit diagnostics if there is an error.
3183FunctionDecl *
3184Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
3185 bool Complain) {
3186 QualType FunctionType = ToType;
3187 if (const PointerLikeType *ToTypePtr = ToType->getAsPointerLikeType())
3188 FunctionType = ToTypePtr->getPointeeType();
3189
3190 // We only look at pointers or references to functions.
3191 if (!FunctionType->isFunctionType())
3192 return 0;
3193
3194 // Find the actual overloaded function declaration.
3195 OverloadedFunctionDecl *Ovl = 0;
3196
3197 // C++ [over.over]p1:
3198 // [...] [Note: any redundant set of parentheses surrounding the
3199 // overloaded function name is ignored (5.1). ]
3200 Expr *OvlExpr = From->IgnoreParens();
3201
3202 // C++ [over.over]p1:
3203 // [...] The overloaded function name can be preceded by the &
3204 // operator.
3205 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3206 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3207 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3208 }
3209
3210 // Try to dig out the overloaded function.
3211 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
3212 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
3213
3214 // If there's no overloaded function declaration, we're done.
3215 if (!Ovl)
3216 return 0;
3217
3218 // Look through all of the overloaded functions, searching for one
3219 // whose type matches exactly.
3220 // FIXME: When templates or using declarations come along, we'll actually
3221 // have to deal with duplicates, partial ordering, etc. For now, we
3222 // can just do a simple search.
3223 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
3224 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
3225 Fun != Ovl->function_end(); ++Fun) {
3226 // C++ [over.over]p3:
3227 // Non-member functions and static member functions match
3228 // targets of type “pointer-to-function”or
3229 // “reference-to-function.”
3230 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun))
3231 if (!Method->isStatic())
3232 continue;
3233
3234 if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
3235 return *Fun;
3236 }
3237
3238 return 0;
3239}
3240
Douglas Gregorf6b89692008-11-26 05:54:23 +00003241/// ResolveOverloadedCallFn - Given the call expression that calls Fn
3242/// (which eventually refers to the set of overloaded functions in
3243/// Ovl) and the call arguments Args/NumArgs, attempt to resolve the
3244/// function call down to a specific function. If overload resolution
Douglas Gregor0a396682008-11-26 06:01:48 +00003245/// succeeds, returns the function declaration produced by overload
3246/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00003247/// arguments and Fn, and returns NULL.
Douglas Gregor0a396682008-11-26 06:01:48 +00003248FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, OverloadedFunctionDecl *Ovl,
3249 SourceLocation LParenLoc,
3250 Expr **Args, unsigned NumArgs,
3251 SourceLocation *CommaLocs,
3252 SourceLocation RParenLoc) {
Douglas Gregorf6b89692008-11-26 05:54:23 +00003253 OverloadCandidateSet CandidateSet;
3254 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet);
3255 OverloadCandidateSet::iterator Best;
3256 switch (BestViableFunction(CandidateSet, Best)) {
Douglas Gregor0a396682008-11-26 06:01:48 +00003257 case OR_Success:
3258 return Best->Function;
Douglas Gregorf6b89692008-11-26 05:54:23 +00003259
3260 case OR_No_Viable_Function:
3261 Diag(Fn->getSourceRange().getBegin(),
3262 diag::err_ovl_no_viable_function_in_call)
3263 << Ovl->getDeclName() << (unsigned)CandidateSet.size()
3264 << Fn->getSourceRange();
3265 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3266 break;
3267
3268 case OR_Ambiguous:
3269 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
3270 << Ovl->getDeclName() << Fn->getSourceRange();
3271 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3272 break;
3273 }
3274
3275 // Overload resolution failed. Destroy all of the subexpressions and
3276 // return NULL.
3277 Fn->Destroy(Context);
3278 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3279 Args[Arg]->Destroy(Context);
3280 return 0;
3281}
3282
Douglas Gregor88a35142008-12-22 05:46:06 +00003283/// BuildCallToMemberFunction - Build a call to a member
3284/// function. MemExpr is the expression that refers to the member
3285/// function (and includes the object parameter), Args/NumArgs are the
3286/// arguments to the function call (not including the object
3287/// parameter). The caller needs to validate that the member
3288/// expression refers to a member function or an overloaded member
3289/// function.
3290Sema::ExprResult
3291Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
3292 SourceLocation LParenLoc, Expr **Args,
3293 unsigned NumArgs, SourceLocation *CommaLocs,
3294 SourceLocation RParenLoc) {
3295 // Dig out the member expression. This holds both the object
3296 // argument and the member function we're referring to.
3297 MemberExpr *MemExpr = 0;
3298 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
3299 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
3300 else
3301 MemExpr = dyn_cast<MemberExpr>(MemExprE);
3302 assert(MemExpr && "Building member call without member expression");
3303
3304 // Extract the object argument.
3305 Expr *ObjectArg = MemExpr->getBase();
3306 if (MemExpr->isArrow())
3307 ObjectArg = new UnaryOperator(ObjectArg, UnaryOperator::Deref,
3308 ObjectArg->getType()->getAsPointerType()->getPointeeType(),
3309 SourceLocation());
3310 CXXMethodDecl *Method = 0;
3311 if (OverloadedFunctionDecl *Ovl
3312 = dyn_cast<OverloadedFunctionDecl>(MemExpr->getMemberDecl())) {
3313 // Add overload candidates
3314 OverloadCandidateSet CandidateSet;
3315 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3316 FuncEnd = Ovl->function_end();
3317 Func != FuncEnd; ++Func) {
3318 assert(isa<CXXMethodDecl>(*Func) && "Function is not a method");
3319 Method = cast<CXXMethodDecl>(*Func);
3320 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
3321 /*SuppressUserConversions=*/false);
3322 }
3323
3324 OverloadCandidateSet::iterator Best;
3325 switch (BestViableFunction(CandidateSet, Best)) {
3326 case OR_Success:
3327 Method = cast<CXXMethodDecl>(Best->Function);
3328 break;
3329
3330 case OR_No_Viable_Function:
3331 Diag(MemExpr->getSourceRange().getBegin(),
3332 diag::err_ovl_no_viable_member_function_in_call)
3333 << Ovl->getDeclName() << (unsigned)CandidateSet.size()
3334 << MemExprE->getSourceRange();
3335 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3336 // FIXME: Leaking incoming expressions!
3337 return true;
3338
3339 case OR_Ambiguous:
3340 Diag(MemExpr->getSourceRange().getBegin(),
3341 diag::err_ovl_ambiguous_member_call)
3342 << Ovl->getDeclName() << MemExprE->getSourceRange();
3343 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3344 // FIXME: Leaking incoming expressions!
3345 return true;
3346 }
3347
3348 FixOverloadedFunctionReference(MemExpr, Method);
3349 } else {
3350 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
3351 }
3352
3353 assert(Method && "Member call to something that isn't a method?");
3354 llvm::OwningPtr<CXXMemberCallExpr>
3355 TheCall(new CXXMemberCallExpr(MemExpr, Args, NumArgs,
3356 Method->getResultType().getNonReferenceType(),
3357 RParenLoc));
3358
3359 // Convert the object argument (for a non-static member function call).
3360 if (!Method->isStatic() &&
3361 PerformObjectArgumentInitialization(ObjectArg, Method))
3362 return true;
3363 MemExpr->setBase(ObjectArg);
3364
3365 // Convert the rest of the arguments
3366 const FunctionTypeProto *Proto = cast<FunctionTypeProto>(Method->getType());
3367 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
3368 RParenLoc))
3369 return true;
3370
3371 return CheckFunctionCall(Method, TheCall.take());
3372}
3373
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003374/// BuildCallToObjectOfClassType - Build a call to an object of class
3375/// type (C++ [over.call.object]), which can end up invoking an
3376/// overloaded function call operator (@c operator()) or performing a
3377/// user-defined conversion on the object argument.
Douglas Gregor88a35142008-12-22 05:46:06 +00003378Sema::ExprResult
Douglas Gregor5c37de72008-12-06 00:22:45 +00003379Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
3380 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003381 Expr **Args, unsigned NumArgs,
3382 SourceLocation *CommaLocs,
3383 SourceLocation RParenLoc) {
3384 assert(Object->getType()->isRecordType() && "Requires object type argument");
3385 const RecordType *Record = Object->getType()->getAsRecordType();
3386
3387 // C++ [over.call.object]p1:
3388 // If the primary-expression E in the function call syntax
3389 // evaluates to a class object of type “cv T”, then the set of
3390 // candidate functions includes at least the function call
3391 // operators of T. The function call operators of T are obtained by
3392 // ordinary lookup of the name operator() in the context of
3393 // (E).operator().
3394 OverloadCandidateSet CandidateSet;
Douglas Gregor44b43212008-12-11 16:49:14 +00003395 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003396 DeclContext::lookup_const_iterator Oper, OperEnd;
3397 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(Context, OpName);
3398 Oper != OperEnd; ++Oper)
3399 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
3400 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003401
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003402 // C++ [over.call.object]p2:
3403 // In addition, for each conversion function declared in T of the
3404 // form
3405 //
3406 // operator conversion-type-id () cv-qualifier;
3407 //
3408 // where cv-qualifier is the same cv-qualification as, or a
3409 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00003410 // denotes the type "pointer to function of (P1,...,Pn) returning
3411 // R", or the type "reference to pointer to function of
3412 // (P1,...,Pn) returning R", or the type "reference to function
3413 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003414 // is also considered as a candidate function. Similarly,
3415 // surrogate call functions are added to the set of candidate
3416 // functions for each conversion function declared in an
3417 // accessible base class provided the function is not hidden
3418 // within T by another intervening declaration.
3419 //
3420 // FIXME: Look in base classes for more conversion operators!
3421 OverloadedFunctionDecl *Conversions
3422 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor621b3932008-11-21 02:54:28 +00003423 for (OverloadedFunctionDecl::function_iterator
3424 Func = Conversions->function_begin(),
3425 FuncEnd = Conversions->function_end();
3426 Func != FuncEnd; ++Func) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003427 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
3428
3429 // Strip the reference type (if any) and then the pointer type (if
3430 // any) to get down to what might be a function type.
3431 QualType ConvType = Conv->getConversionType().getNonReferenceType();
3432 if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
3433 ConvType = ConvPtrType->getPointeeType();
3434
3435 if (const FunctionTypeProto *Proto = ConvType->getAsFunctionTypeProto())
3436 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
3437 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003438
3439 // Perform overload resolution.
3440 OverloadCandidateSet::iterator Best;
3441 switch (BestViableFunction(CandidateSet, Best)) {
3442 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003443 // Overload resolution succeeded; we'll build the appropriate call
3444 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003445 break;
3446
3447 case OR_No_Viable_Function:
Sebastian Redle4c452c2008-11-22 13:44:36 +00003448 Diag(Object->getSourceRange().getBegin(),
3449 diag::err_ovl_no_viable_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00003450 << Object->getType() << (unsigned)CandidateSet.size()
Sebastian Redle4c452c2008-11-22 13:44:36 +00003451 << Object->getSourceRange();
3452 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003453 break;
3454
3455 case OR_Ambiguous:
3456 Diag(Object->getSourceRange().getBegin(),
3457 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00003458 << Object->getType() << Object->getSourceRange();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003459 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3460 break;
3461 }
3462
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003463 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003464 // We had an error; delete all of the subexpressions and return
3465 // the error.
3466 delete Object;
3467 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3468 delete Args[ArgIdx];
3469 return true;
3470 }
3471
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003472 if (Best->Function == 0) {
3473 // Since there is no function declaration, this is one of the
3474 // surrogate candidates. Dig out the conversion function.
3475 CXXConversionDecl *Conv
3476 = cast<CXXConversionDecl>(
3477 Best->Conversions[0].UserDefined.ConversionFunction);
3478
3479 // We selected one of the surrogate functions that converts the
3480 // object parameter to a function pointer. Perform the conversion
3481 // on the object argument, then let ActOnCallExpr finish the job.
3482 // FIXME: Represent the user-defined conversion in the AST!
3483 ImpCastExprToType(Object,
3484 Conv->getConversionType().getNonReferenceType(),
3485 Conv->getConversionType()->isReferenceType());
Douglas Gregor5c37de72008-12-06 00:22:45 +00003486 return ActOnCallExpr(S, (ExprTy*)Object, LParenLoc, (ExprTy**)Args, NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003487 CommaLocs, RParenLoc);
3488 }
3489
3490 // We found an overloaded operator(). Build a CXXOperatorCallExpr
3491 // that calls this method, using Object for the implicit object
3492 // parameter and passing along the remaining arguments.
3493 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003494 const FunctionTypeProto *Proto = Method->getType()->getAsFunctionTypeProto();
3495
3496 unsigned NumArgsInProto = Proto->getNumArgs();
3497 unsigned NumArgsToCheck = NumArgs;
3498
3499 // Build the full argument list for the method call (the
3500 // implicit object parameter is placed at the beginning of the
3501 // list).
3502 Expr **MethodArgs;
3503 if (NumArgs < NumArgsInProto) {
3504 NumArgsToCheck = NumArgsInProto;
3505 MethodArgs = new Expr*[NumArgsInProto + 1];
3506 } else {
3507 MethodArgs = new Expr*[NumArgs + 1];
3508 }
3509 MethodArgs[0] = Object;
3510 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3511 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
3512
3513 Expr *NewFn = new DeclRefExpr(Method, Method->getType(),
3514 SourceLocation());
3515 UsualUnaryConversions(NewFn);
3516
3517 // Once we've built TheCall, all of the expressions are properly
3518 // owned.
3519 QualType ResultTy = Method->getResultType().getNonReferenceType();
3520 llvm::OwningPtr<CXXOperatorCallExpr>
3521 TheCall(new CXXOperatorCallExpr(NewFn, MethodArgs, NumArgs + 1,
3522 ResultTy, RParenLoc));
3523 delete [] MethodArgs;
3524
3525 // Initialize the implicit object parameter.
3526 if (!PerformObjectArgumentInitialization(Object, Method))
3527 return true;
3528 TheCall->setArg(0, Object);
3529
3530 // Check the argument types.
3531 for (unsigned i = 0; i != NumArgsToCheck; i++) {
3532 QualType ProtoArgType = Proto->getArgType(i);
3533
3534 Expr *Arg;
3535 if (i < NumArgs)
3536 Arg = Args[i];
3537 else
3538 Arg = new CXXDefaultArgExpr(Method->getParamDecl(i));
3539 QualType ArgType = Arg->getType();
3540
3541 // Pass the argument.
3542 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3543 return true;
3544
3545 TheCall->setArg(i + 1, Arg);
3546 }
3547
3548 // If this is a variadic call, handle args passed through "...".
3549 if (Proto->isVariadic()) {
3550 // Promote the arguments (C99 6.5.2.2p7).
3551 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3552 Expr *Arg = Args[i];
3553 DefaultArgumentPromotion(Arg);
3554 TheCall->setArg(i + 1, Arg);
3555 }
3556 }
3557
3558 return CheckFunctionCall(Method, TheCall.take());
3559}
3560
Douglas Gregor8ba10742008-11-20 16:27:02 +00003561/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
3562/// (if one exists), where @c Base is an expression of class type and
3563/// @c Member is the name of the member we're trying to find.
3564Action::ExprResult
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003565Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
Douglas Gregor8ba10742008-11-20 16:27:02 +00003566 SourceLocation MemberLoc,
3567 IdentifierInfo &Member) {
3568 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
3569
3570 // C++ [over.ref]p1:
3571 //
3572 // [...] An expression x->m is interpreted as (x.operator->())->m
3573 // for a class object x of type T if T::operator->() exists and if
3574 // the operator is selected as the best match function by the
3575 // overload resolution mechanism (13.3).
3576 // FIXME: look in base classes.
3577 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
3578 OverloadCandidateSet CandidateSet;
3579 const RecordType *BaseRecord = Base->getType()->getAsRecordType();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003580
3581 DeclContext::lookup_const_iterator Oper, OperEnd;
3582 for (llvm::tie(Oper, OperEnd) = BaseRecord->getDecl()->lookup(Context, OpName);
3583 Oper != OperEnd; ++Oper)
3584 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00003585 /*SuppressUserConversions=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003586
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003587 llvm::OwningPtr<Expr> BasePtr(Base);
3588
Douglas Gregor8ba10742008-11-20 16:27:02 +00003589 // Perform overload resolution.
3590 OverloadCandidateSet::iterator Best;
3591 switch (BestViableFunction(CandidateSet, Best)) {
3592 case OR_Success:
3593 // Overload resolution succeeded; we'll build the call below.
3594 break;
3595
3596 case OR_No_Viable_Function:
3597 if (CandidateSet.empty())
3598 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattnerd1625842008-11-24 06:25:27 +00003599 << BasePtr->getType() << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003600 else
3601 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Sebastian Redle4c452c2008-11-22 13:44:36 +00003602 << "operator->" << (unsigned)CandidateSet.size()
3603 << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003604 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003605 return true;
3606
3607 case OR_Ambiguous:
3608 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Chris Lattnerd1625842008-11-24 06:25:27 +00003609 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003610 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003611 return true;
3612 }
3613
3614 // Convert the object parameter.
3615 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003616 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregor8ba10742008-11-20 16:27:02 +00003617 return true;
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003618
3619 // No concerns about early exits now.
3620 BasePtr.take();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003621
3622 // Build the operator call.
3623 Expr *FnExpr = new DeclRefExpr(Method, Method->getType(), SourceLocation());
3624 UsualUnaryConversions(FnExpr);
3625 Base = new CXXOperatorCallExpr(FnExpr, &Base, 1,
3626 Method->getResultType().getNonReferenceType(),
3627 OpLoc);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003628 return ActOnMemberReferenceExpr(S, Base, OpLoc, tok::arrow, MemberLoc, Member);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003629}
3630
Douglas Gregor904eed32008-11-10 20:40:00 +00003631/// FixOverloadedFunctionReference - E is an expression that refers to
3632/// a C++ overloaded function (possibly with some parentheses and
3633/// perhaps a '&' around it). We have resolved the overloaded function
3634/// to the function declaration Fn, so patch up the expression E to
3635/// refer (possibly indirectly) to Fn.
3636void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
3637 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
3638 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
3639 E->setType(PE->getSubExpr()->getType());
3640 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
3641 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
3642 "Can only take the address of an overloaded function");
3643 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
3644 E->setType(Context.getPointerType(E->getType()));
3645 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
3646 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
3647 "Expected overloaded function");
3648 DR->setDecl(Fn);
3649 E->setType(Fn->getType());
Douglas Gregor88a35142008-12-22 05:46:06 +00003650 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
3651 MemExpr->setMemberDecl(Fn);
3652 E->setType(Fn->getType());
Douglas Gregor904eed32008-11-10 20:40:00 +00003653 } else {
3654 assert(false && "Invalid reference to overloaded function");
3655 }
3656}
3657
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003658} // end namespace clang