blob: 170ef1b59c1977e5aa47d32bba7b0afe8162639e [file] [log] [blame]
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor94b1dd22008-10-24 04:54:22 +000015#include "SemaInherit.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000020#include "clang/AST/ExprCXX.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000022#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000023#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000024#include "llvm/Support/Compiler.h"
25#include <algorithm>
26
27namespace clang {
28
29/// GetConversionCategory - Retrieve the implicit conversion
30/// category corresponding to the given implicit conversion kind.
31ImplicitConversionCategory
32GetConversionCategory(ImplicitConversionKind Kind) {
33 static const ImplicitConversionCategory
34 Category[(int)ICK_Num_Conversion_Kinds] = {
35 ICC_Identity,
36 ICC_Lvalue_Transformation,
37 ICC_Lvalue_Transformation,
38 ICC_Lvalue_Transformation,
39 ICC_Qualification_Adjustment,
40 ICC_Promotion,
41 ICC_Promotion,
42 ICC_Conversion,
43 ICC_Conversion,
44 ICC_Conversion,
45 ICC_Conversion,
46 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000047 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000048 ICC_Conversion
49 };
50 return Category[(int)Kind];
51}
52
53/// GetConversionRank - Retrieve the implicit conversion rank
54/// corresponding to the given implicit conversion kind.
55ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
56 static const ImplicitConversionRank
57 Rank[(int)ICK_Num_Conversion_Kinds] = {
58 ICR_Exact_Match,
59 ICR_Exact_Match,
60 ICR_Exact_Match,
61 ICR_Exact_Match,
62 ICR_Exact_Match,
63 ICR_Promotion,
64 ICR_Promotion,
65 ICR_Conversion,
66 ICR_Conversion,
67 ICR_Conversion,
68 ICR_Conversion,
69 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000070 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000071 ICR_Conversion
72 };
73 return Rank[(int)Kind];
74}
75
76/// GetImplicitConversionName - Return the name of this kind of
77/// implicit conversion.
78const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
79 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
80 "No conversion",
81 "Lvalue-to-rvalue",
82 "Array-to-pointer",
83 "Function-to-pointer",
84 "Qualification",
85 "Integral promotion",
86 "Floating point promotion",
87 "Integral conversion",
88 "Floating conversion",
89 "Floating-integral conversion",
90 "Pointer conversion",
91 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +000092 "Boolean conversion",
93 "Derived-to-base conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000094 };
95 return Name[Kind];
96}
97
Douglas Gregor60d62c22008-10-31 16:23:19 +000098/// StandardConversionSequence - Set the standard conversion
99/// sequence to the identity conversion.
100void StandardConversionSequence::setAsIdentityConversion() {
101 First = ICK_Identity;
102 Second = ICK_Identity;
103 Third = ICK_Identity;
104 Deprecated = false;
105 ReferenceBinding = false;
106 DirectBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000107 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000108}
109
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000110/// getRank - Retrieve the rank of this standard conversion sequence
111/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
112/// implicit conversions.
113ImplicitConversionRank StandardConversionSequence::getRank() const {
114 ImplicitConversionRank Rank = ICR_Exact_Match;
115 if (GetConversionRank(First) > Rank)
116 Rank = GetConversionRank(First);
117 if (GetConversionRank(Second) > Rank)
118 Rank = GetConversionRank(Second);
119 if (GetConversionRank(Third) > Rank)
120 Rank = GetConversionRank(Third);
121 return Rank;
122}
123
124/// isPointerConversionToBool - Determines whether this conversion is
125/// a conversion of a pointer or pointer-to-member to bool. This is
126/// used as part of the ranking of standard conversion sequences
127/// (C++ 13.3.3.2p4).
128bool StandardConversionSequence::isPointerConversionToBool() const
129{
130 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
131 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
132
133 // Note that FromType has not necessarily been transformed by the
134 // array-to-pointer or function-to-pointer implicit conversions, so
135 // check for their presence as well as checking whether FromType is
136 // a pointer.
137 if (ToType->isBooleanType() &&
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000138 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000139 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
140 return true;
141
142 return false;
143}
144
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000145/// isPointerConversionToVoidPointer - Determines whether this
146/// conversion is a conversion of a pointer to a void pointer. This is
147/// used as part of the ranking of standard conversion sequences (C++
148/// 13.3.3.2p4).
149bool
150StandardConversionSequence::
151isPointerConversionToVoidPointer(ASTContext& Context) const
152{
153 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
154 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
155
156 // Note that FromType has not necessarily been transformed by the
157 // array-to-pointer implicit conversion, so check for its presence
158 // and redo the conversion to get a pointer.
159 if (First == ICK_Array_To_Pointer)
160 FromType = Context.getArrayDecayedType(FromType);
161
162 if (Second == ICK_Pointer_Conversion)
163 if (const PointerType* ToPtrType = ToType->getAsPointerType())
164 return ToPtrType->getPointeeType()->isVoidType();
165
166 return false;
167}
168
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000169/// DebugPrint - Print this standard conversion sequence to standard
170/// error. Useful for debugging overloading issues.
171void StandardConversionSequence::DebugPrint() const {
172 bool PrintedSomething = false;
173 if (First != ICK_Identity) {
174 fprintf(stderr, "%s", GetImplicitConversionName(First));
175 PrintedSomething = true;
176 }
177
178 if (Second != ICK_Identity) {
179 if (PrintedSomething) {
180 fprintf(stderr, " -> ");
181 }
182 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregor225c41e2008-11-03 19:09:14 +0000183
184 if (CopyConstructor) {
185 fprintf(stderr, " (by copy constructor)");
186 } else if (DirectBinding) {
187 fprintf(stderr, " (direct reference binding)");
188 } else if (ReferenceBinding) {
189 fprintf(stderr, " (reference binding)");
190 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000191 PrintedSomething = true;
192 }
193
194 if (Third != ICK_Identity) {
195 if (PrintedSomething) {
196 fprintf(stderr, " -> ");
197 }
198 fprintf(stderr, "%s", GetImplicitConversionName(Third));
199 PrintedSomething = true;
200 }
201
202 if (!PrintedSomething) {
203 fprintf(stderr, "No conversions required");
204 }
205}
206
207/// DebugPrint - Print this user-defined conversion sequence to standard
208/// error. Useful for debugging overloading issues.
209void UserDefinedConversionSequence::DebugPrint() const {
210 if (Before.First || Before.Second || Before.Third) {
211 Before.DebugPrint();
212 fprintf(stderr, " -> ");
213 }
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000214 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000215 if (After.First || After.Second || After.Third) {
216 fprintf(stderr, " -> ");
217 After.DebugPrint();
218 }
219}
220
221/// DebugPrint - Print this implicit conversion sequence to standard
222/// error. Useful for debugging overloading issues.
223void ImplicitConversionSequence::DebugPrint() const {
224 switch (ConversionKind) {
225 case StandardConversion:
226 fprintf(stderr, "Standard conversion: ");
227 Standard.DebugPrint();
228 break;
229 case UserDefinedConversion:
230 fprintf(stderr, "User-defined conversion: ");
231 UserDefined.DebugPrint();
232 break;
233 case EllipsisConversion:
234 fprintf(stderr, "Ellipsis conversion");
235 break;
236 case BadConversion:
237 fprintf(stderr, "Bad conversion");
238 break;
239 }
240
241 fprintf(stderr, "\n");
242}
243
244// IsOverload - Determine whether the given New declaration is an
245// overload of the Old declaration. This routine returns false if New
246// and Old cannot be overloaded, e.g., if they are functions with the
247// same signature (C++ 1.3.10) or if the Old declaration isn't a
248// function (or overload set). When it does return false and Old is an
249// OverloadedFunctionDecl, MatchedDecl will be set to point to the
250// FunctionDecl that New cannot be overloaded with.
251//
252// Example: Given the following input:
253//
254// void f(int, float); // #1
255// void f(int, int); // #2
256// int f(int, int); // #3
257//
258// When we process #1, there is no previous declaration of "f",
259// so IsOverload will not be used.
260//
261// When we process #2, Old is a FunctionDecl for #1. By comparing the
262// parameter types, we see that #1 and #2 are overloaded (since they
263// have different signatures), so this routine returns false;
264// MatchedDecl is unchanged.
265//
266// When we process #3, Old is an OverloadedFunctionDecl containing #1
267// and #2. We compare the signatures of #3 to #1 (they're overloaded,
268// so we do nothing) and then #3 to #2. Since the signatures of #3 and
269// #2 are identical (return types of functions are not part of the
270// signature), IsOverload returns false and MatchedDecl will be set to
271// point to the FunctionDecl for #2.
272bool
273Sema::IsOverload(FunctionDecl *New, Decl* OldD,
274 OverloadedFunctionDecl::function_iterator& MatchedDecl)
275{
276 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
277 // Is this new function an overload of every function in the
278 // overload set?
279 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
280 FuncEnd = Ovl->function_end();
281 for (; Func != FuncEnd; ++Func) {
282 if (!IsOverload(New, *Func, MatchedDecl)) {
283 MatchedDecl = Func;
284 return false;
285 }
286 }
287
288 // This function overloads every function in the overload set.
289 return true;
290 } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
291 // Is the function New an overload of the function Old?
292 QualType OldQType = Context.getCanonicalType(Old->getType());
293 QualType NewQType = Context.getCanonicalType(New->getType());
294
295 // Compare the signatures (C++ 1.3.10) of the two functions to
296 // determine whether they are overloads. If we find any mismatch
297 // in the signature, they are overloads.
298
299 // If either of these functions is a K&R-style function (no
300 // prototype), then we consider them to have matching signatures.
301 if (isa<FunctionTypeNoProto>(OldQType.getTypePtr()) ||
302 isa<FunctionTypeNoProto>(NewQType.getTypePtr()))
303 return false;
304
305 FunctionTypeProto* OldType = cast<FunctionTypeProto>(OldQType.getTypePtr());
306 FunctionTypeProto* NewType = cast<FunctionTypeProto>(NewQType.getTypePtr());
307
308 // The signature of a function includes the types of its
309 // parameters (C++ 1.3.10), which includes the presence or absence
310 // of the ellipsis; see C++ DR 357).
311 if (OldQType != NewQType &&
312 (OldType->getNumArgs() != NewType->getNumArgs() ||
313 OldType->isVariadic() != NewType->isVariadic() ||
314 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
315 NewType->arg_type_begin())))
316 return true;
317
318 // If the function is a class member, its signature includes the
319 // cv-qualifiers (if any) on the function itself.
320 //
321 // As part of this, also check whether one of the member functions
322 // is static, in which case they are not overloads (C++
323 // 13.1p2). While not part of the definition of the signature,
324 // this check is important to determine whether these functions
325 // can be overloaded.
326 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
327 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
328 if (OldMethod && NewMethod &&
329 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor1ca50c32008-11-21 15:36:28 +0000330 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000331 return true;
332
333 // The signatures match; this is not an overload.
334 return false;
335 } else {
336 // (C++ 13p1):
337 // Only function declarations can be overloaded; object and type
338 // declarations cannot be overloaded.
339 return false;
340 }
341}
342
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000343/// TryImplicitConversion - Attempt to perform an implicit conversion
344/// from the given expression (Expr) to the given type (ToType). This
345/// function returns an implicit conversion sequence that can be used
346/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000347///
348/// void f(float f);
349/// void g(int i) { f(i); }
350///
351/// this routine would produce an implicit conversion sequence to
352/// describe the initialization of f from i, which will be a standard
353/// conversion sequence containing an lvalue-to-rvalue conversion (C++
354/// 4.1) followed by a floating-integral conversion (C++ 4.9).
355//
356/// Note that this routine only determines how the conversion can be
357/// performed; it does not actually perform the conversion. As such,
358/// it will not produce any diagnostics if no conversion is available,
359/// but will instead return an implicit conversion sequence of kind
360/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000361///
362/// If @p SuppressUserConversions, then user-defined conversions are
363/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000364/// If @p AllowExplicit, then explicit user-defined conversions are
365/// permitted.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000366ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +0000367Sema::TryImplicitConversion(Expr* From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000368 bool SuppressUserConversions,
369 bool AllowExplict)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000370{
371 ImplicitConversionSequence ICS;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000372 if (IsStandardConversion(From, ToType, ICS.Standard))
373 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000374 else if (!SuppressUserConversions &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000375 IsUserDefinedConversion(From, ToType, ICS.UserDefined, AllowExplict)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000376 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000377 // C++ [over.ics.user]p4:
378 // A conversion of an expression of class type to the same class
379 // type is given Exact Match rank, and a conversion of an
380 // expression of class type to a base class of that type is
381 // given Conversion rank, in spite of the fact that a copy
382 // constructor (i.e., a user-defined conversion function) is
383 // called for those cases.
384 if (CXXConstructorDecl *Constructor
385 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
386 if (Constructor->isCopyConstructor(Context)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000387 // Turn this into a "standard" conversion sequence, so that it
388 // gets ranked with standard conversion sequences.
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000389 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
390 ICS.Standard.setAsIdentityConversion();
391 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
392 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000393 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000394 if (IsDerivedFrom(From->getType().getUnqualifiedType(),
395 ToType.getUnqualifiedType()))
396 ICS.Standard.Second = ICK_Derived_To_Base;
397 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000398 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000399 } else
Douglas Gregor60d62c22008-10-31 16:23:19 +0000400 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000401
402 return ICS;
403}
404
405/// IsStandardConversion - Determines whether there is a standard
406/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
407/// expression From to the type ToType. Standard conversion sequences
408/// only consider non-class types; for conversions that involve class
409/// types, use TryImplicitConversion. If a conversion exists, SCS will
410/// contain the standard conversion sequence required to perform this
411/// conversion and this routine will return true. Otherwise, this
412/// routine will return false and the value of SCS is unspecified.
413bool
414Sema::IsStandardConversion(Expr* From, QualType ToType,
415 StandardConversionSequence &SCS)
416{
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000417 QualType FromType = From->getType();
418
Douglas Gregor60d62c22008-10-31 16:23:19 +0000419 // There are no standard conversions for class types, so abort early.
420 if (FromType->isRecordType() || ToType->isRecordType())
421 return false;
422
423 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000424 SCS.setAsIdentityConversion();
Douglas Gregor60d62c22008-10-31 16:23:19 +0000425 SCS.Deprecated = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000426 SCS.IncompatibleObjC = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000427 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000428 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000429
430 // The first conversion can be an lvalue-to-rvalue conversion,
431 // array-to-pointer conversion, or function-to-pointer conversion
432 // (C++ 4p1).
433
434 // Lvalue-to-rvalue conversion (C++ 4.1):
435 // An lvalue (3.10) of a non-function, non-array type T can be
436 // converted to an rvalue.
437 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
438 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000439 !FromType->isFunctionType() && !FromType->isArrayType() &&
440 !FromType->isOverloadType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000441 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000442
443 // If T is a non-class type, the type of the rvalue is the
444 // cv-unqualified version of T. Otherwise, the type of the rvalue
445 // is T (C++ 4.1p1).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000446 FromType = FromType.getUnqualifiedType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000447 }
448 // Array-to-pointer conversion (C++ 4.2)
449 else if (FromType->isArrayType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000450 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000451
452 // An lvalue or rvalue of type "array of N T" or "array of unknown
453 // bound of T" can be converted to an rvalue of type "pointer to
454 // T" (C++ 4.2p1).
455 FromType = Context.getArrayDecayedType(FromType);
456
457 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
458 // This conversion is deprecated. (C++ D.4).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000459 SCS.Deprecated = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000460
461 // For the purpose of ranking in overload resolution
462 // (13.3.3.1.1), this conversion is considered an
463 // array-to-pointer conversion followed by a qualification
464 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000465 SCS.Second = ICK_Identity;
466 SCS.Third = ICK_Qualification;
467 SCS.ToTypePtr = ToType.getAsOpaquePtr();
468 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000469 }
470 }
471 // Function-to-pointer conversion (C++ 4.3).
472 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000473 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000474
475 // An lvalue of function type T can be converted to an rvalue of
476 // type "pointer to T." The result is a pointer to the
477 // function. (C++ 4.3p1).
478 FromType = Context.getPointerType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000479 }
Douglas Gregor904eed32008-11-10 20:40:00 +0000480 // Address of overloaded function (C++ [over.over]).
481 else if (FunctionDecl *Fn
482 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
483 SCS.First = ICK_Function_To_Pointer;
484
485 // We were able to resolve the address of the overloaded function,
486 // so we can convert to the type of that function.
487 FromType = Fn->getType();
488 if (ToType->isReferenceType())
489 FromType = Context.getReferenceType(FromType);
490 else
491 FromType = Context.getPointerType(FromType);
492 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000493 // We don't require any conversions for the first step.
494 else {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000495 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000496 }
497
498 // The second conversion can be an integral promotion, floating
499 // point promotion, integral conversion, floating point conversion,
500 // floating-integral conversion, pointer conversion,
501 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor45920e82008-12-19 17:40:08 +0000502 bool IncompatibleObjC = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000503 if (Context.getCanonicalType(FromType).getUnqualifiedType() ==
504 Context.getCanonicalType(ToType).getUnqualifiedType()) {
505 // The unqualified versions of the types are the same: there's no
506 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000507 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000508 }
509 // Integral promotion (C++ 4.5).
510 else if (IsIntegralPromotion(From, FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000511 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000512 FromType = ToType.getUnqualifiedType();
513 }
514 // Floating point promotion (C++ 4.6).
515 else if (IsFloatingPointPromotion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000516 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000517 FromType = ToType.getUnqualifiedType();
518 }
519 // Integral conversions (C++ 4.7).
Sebastian Redl07779722008-10-31 14:43:28 +0000520 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000521 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000522 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000523 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000524 FromType = ToType.getUnqualifiedType();
525 }
526 // Floating point conversions (C++ 4.8).
527 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000528 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000529 FromType = ToType.getUnqualifiedType();
530 }
531 // Floating-integral conversions (C++ 4.9).
Sebastian Redl07779722008-10-31 14:43:28 +0000532 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000533 else if ((FromType->isFloatingType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000534 ToType->isIntegralType() && !ToType->isBooleanType() &&
535 !ToType->isEnumeralType()) ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000536 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
537 ToType->isFloatingType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000538 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000539 FromType = ToType.getUnqualifiedType();
540 }
541 // Pointer conversions (C++ 4.10).
Douglas Gregor45920e82008-12-19 17:40:08 +0000542 else if (IsPointerConversion(From, FromType, ToType, FromType,
543 IncompatibleObjC)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000544 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000545 SCS.IncompatibleObjC = IncompatibleObjC;
Sebastian Redl07779722008-10-31 14:43:28 +0000546 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000547 // FIXME: Pointer to member conversions (4.11).
548 // Boolean conversions (C++ 4.12).
549 // FIXME: pointer-to-member type
550 else if (ToType->isBooleanType() &&
551 (FromType->isArithmeticType() ||
552 FromType->isEnumeralType() ||
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000553 FromType->isPointerType() ||
554 FromType->isBlockPointerType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000555 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000556 FromType = Context.BoolTy;
557 } else {
558 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000559 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000560 }
561
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000562 QualType CanonFrom;
563 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000564 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000565 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000566 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000567 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000568 CanonFrom = Context.getCanonicalType(FromType);
569 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000570 } else {
571 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000572 SCS.Third = ICK_Identity;
573
574 // C++ [over.best.ics]p6:
575 // [...] Any difference in top-level cv-qualification is
576 // subsumed by the initialization itself and does not constitute
577 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000578 CanonFrom = Context.getCanonicalType(FromType);
579 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000580 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000581 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
582 FromType = ToType;
583 CanonFrom = CanonTo;
584 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000585 }
586
587 // If we have not converted the argument type to the parameter type,
588 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000589 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000590 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000591
Douglas Gregor60d62c22008-10-31 16:23:19 +0000592 SCS.ToTypePtr = FromType.getAsOpaquePtr();
593 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000594}
595
596/// IsIntegralPromotion - Determines whether the conversion from the
597/// expression From (whose potentially-adjusted type is FromType) to
598/// ToType is an integral promotion (C++ 4.5). If so, returns true and
599/// sets PromotedType to the promoted type.
600bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
601{
602 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000603 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000604 if (!To) {
605 return false;
606 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000607
608 // An rvalue of type char, signed char, unsigned char, short int, or
609 // unsigned short int can be converted to an rvalue of type int if
610 // int can represent all the values of the source type; otherwise,
611 // the source rvalue can be converted to an rvalue of type unsigned
612 // int (C++ 4.5p1).
Sebastian Redl07779722008-10-31 14:43:28 +0000613 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000614 if (// We can promote any signed, promotable integer type to an int
615 (FromType->isSignedIntegerType() ||
616 // We can promote any unsigned integer type whose size is
617 // less than int to an int.
618 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000619 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000620 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000621 }
622
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000623 return To->getKind() == BuiltinType::UInt;
624 }
625
626 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
627 // can be converted to an rvalue of the first of the following types
628 // that can represent all the values of its underlying type: int,
629 // unsigned int, long, or unsigned long (C++ 4.5p2).
630 if ((FromType->isEnumeralType() || FromType->isWideCharType())
631 && ToType->isIntegerType()) {
632 // Determine whether the type we're converting from is signed or
633 // unsigned.
634 bool FromIsSigned;
635 uint64_t FromSize = Context.getTypeSize(FromType);
636 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
637 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
638 FromIsSigned = UnderlyingType->isSignedIntegerType();
639 } else {
640 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
641 FromIsSigned = true;
642 }
643
644 // The types we'll try to promote to, in the appropriate
645 // order. Try each of these types.
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000646 QualType PromoteTypes[6] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000647 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000648 Context.LongTy, Context.UnsignedLongTy ,
649 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000650 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000651 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000652 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
653 if (FromSize < ToSize ||
654 (FromSize == ToSize &&
655 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
656 // We found the type that we can promote to. If this is the
657 // type we wanted, we have a promotion. Otherwise, no
658 // promotion.
Sebastian Redl07779722008-10-31 14:43:28 +0000659 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000660 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
661 }
662 }
663 }
664
665 // An rvalue for an integral bit-field (9.6) can be converted to an
666 // rvalue of type int if int can represent all the values of the
667 // bit-field; otherwise, it can be converted to unsigned int if
668 // unsigned int can represent all the values of the bit-field. If
669 // the bit-field is larger yet, no integral promotion applies to
670 // it. If the bit-field has an enumerated type, it is treated as any
671 // other value of that type for promotion purposes (C++ 4.5p3).
672 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) {
673 using llvm::APSInt;
Douglas Gregor86f19402008-12-20 23:49:58 +0000674 if (FieldDecl *MemberDecl = dyn_cast<FieldDecl>(MemRef->getMemberDecl())) {
675 APSInt BitWidth;
676 if (MemberDecl->isBitField() &&
677 FromType->isIntegralType() && !FromType->isEnumeralType() &&
678 From->isIntegerConstantExpr(BitWidth, Context)) {
679 APSInt ToSize(Context.getTypeSize(ToType));
680
681 // Are we promoting to an int from a bitfield that fits in an int?
682 if (BitWidth < ToSize ||
683 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
684 return To->getKind() == BuiltinType::Int;
685 }
686
687 // Are we promoting to an unsigned int from an unsigned bitfield
688 // that fits into an unsigned int?
689 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
690 return To->getKind() == BuiltinType::UInt;
691 }
692
693 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000694 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000695 }
696 }
697
698 // An rvalue of type bool can be converted to an rvalue of type int,
699 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000700 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000701 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000702 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000703
704 return false;
705}
706
707/// IsFloatingPointPromotion - Determines whether the conversion from
708/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
709/// returns true and sets PromotedType to the promoted type.
710bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
711{
712 /// An rvalue of type float can be converted to an rvalue of type
713 /// double. (C++ 4.6p1).
714 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
715 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType())
716 if (FromBuiltin->getKind() == BuiltinType::Float &&
717 ToBuiltin->getKind() == BuiltinType::Double)
718 return true;
719
720 return false;
721}
722
Douglas Gregorcb7de522008-11-26 23:31:11 +0000723/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
724/// the pointer type FromPtr to a pointer to type ToPointee, with the
725/// same type qualifiers as FromPtr has on its pointee type. ToType,
726/// if non-empty, will be a pointer to ToType that may or may not have
727/// the right set of qualifiers on its pointee.
728static QualType
729BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
730 QualType ToPointee, QualType ToType,
731 ASTContext &Context) {
732 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
733 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
734 unsigned Quals = CanonFromPointee.getCVRQualifiers();
735
736 // Exact qualifier match -> return the pointer type we're converting to.
737 if (CanonToPointee.getCVRQualifiers() == Quals) {
738 // ToType is exactly what we need. Return it.
739 if (ToType.getTypePtr())
740 return ToType;
741
742 // Build a pointer to ToPointee. It has the right qualifiers
743 // already.
744 return Context.getPointerType(ToPointee);
745 }
746
747 // Just build a canonical type that has the right qualifiers.
748 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
749}
750
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000751/// IsPointerConversion - Determines whether the conversion of the
752/// expression From, which has the (possibly adjusted) type FromType,
753/// can be converted to the type ToType via a pointer conversion (C++
754/// 4.10). If so, returns true and places the converted type (that
755/// might differ from ToType in its cv-qualifiers at some level) into
756/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000757///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000758/// This routine also supports conversions to and from block pointers
759/// and conversions with Objective-C's 'id', 'id<protocols...>', and
760/// pointers to interfaces. FIXME: Once we've determined the
761/// appropriate overloading rules for Objective-C, we may want to
762/// split the Objective-C checks into a different routine; however,
763/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000764/// conversions, so for now they live here. IncompatibleObjC will be
765/// set if the conversion is an allowed Objective-C conversion that
766/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000767bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000768 QualType& ConvertedType,
769 bool &IncompatibleObjC)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000770{
Douglas Gregor45920e82008-12-19 17:40:08 +0000771 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +0000772 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
773 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +0000774
Douglas Gregor27b09ac2008-12-22 20:51:52 +0000775 // Conversion from a null pointer constant to any Objective-C pointer type.
776 if (Context.isObjCObjectPointerType(ToType) &&
777 From->isNullPointerConstant(Context)) {
778 ConvertedType = ToType;
779 return true;
780 }
781
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000782 // Blocks: Block pointers can be converted to void*.
783 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
784 ToType->getAsPointerType()->getPointeeType()->isVoidType()) {
785 ConvertedType = ToType;
786 return true;
787 }
788 // Blocks: A null pointer constant can be converted to a block
789 // pointer type.
790 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
791 ConvertedType = ToType;
792 return true;
793 }
794
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000795 const PointerType* ToTypePtr = ToType->getAsPointerType();
796 if (!ToTypePtr)
797 return false;
798
799 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
800 if (From->isNullPointerConstant(Context)) {
801 ConvertedType = ToType;
802 return true;
803 }
Sebastian Redl07779722008-10-31 14:43:28 +0000804
Douglas Gregorcb7de522008-11-26 23:31:11 +0000805 // Beyond this point, both types need to be pointers.
806 const PointerType *FromTypePtr = FromType->getAsPointerType();
807 if (!FromTypePtr)
808 return false;
809
810 QualType FromPointeeType = FromTypePtr->getPointeeType();
811 QualType ToPointeeType = ToTypePtr->getPointeeType();
812
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000813 // An rvalue of type "pointer to cv T," where T is an object type,
814 // can be converted to an rvalue of type "pointer to cv void" (C++
815 // 4.10p2).
Douglas Gregorc7887512008-12-19 19:13:09 +0000816 if (FromPointeeType->isIncompleteOrObjectType() &&
817 ToPointeeType->isVoidType()) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000818 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
819 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000820 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000821 return true;
822 }
823
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000824 // C++ [conv.ptr]p3:
825 //
826 // An rvalue of type "pointer to cv D," where D is a class type,
827 // can be converted to an rvalue of type "pointer to cv B," where
828 // B is a base class (clause 10) of D. If B is an inaccessible
829 // (clause 11) or ambiguous (10.2) base class of D, a program that
830 // necessitates this conversion is ill-formed. The result of the
831 // conversion is a pointer to the base class sub-object of the
832 // derived class object. The null pointer value is converted to
833 // the null pointer value of the destination type.
834 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000835 // Note that we do not check for ambiguity or inaccessibility
836 // here. That is handled by CheckPointerConversion.
Douglas Gregorcb7de522008-11-26 23:31:11 +0000837 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
838 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000839 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
840 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000841 ToType, Context);
842 return true;
843 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000844
Douglas Gregorc7887512008-12-19 19:13:09 +0000845 return false;
846}
847
848/// isObjCPointerConversion - Determines whether this is an
849/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
850/// with the same arguments and return values.
851bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
852 QualType& ConvertedType,
853 bool &IncompatibleObjC) {
854 if (!getLangOptions().ObjC1)
855 return false;
856
857 // Conversions with Objective-C's id<...>.
858 if ((FromType->isObjCQualifiedIdType() || ToType->isObjCQualifiedIdType()) &&
859 ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) {
860 ConvertedType = ToType;
861 return true;
862 }
863
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000864 // Beyond this point, both types need to be pointers or block pointers.
865 QualType ToPointeeType;
Douglas Gregorc7887512008-12-19 19:13:09 +0000866 const PointerType* ToTypePtr = ToType->getAsPointerType();
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000867 if (ToTypePtr)
868 ToPointeeType = ToTypePtr->getPointeeType();
869 else if (const BlockPointerType *ToBlockPtr = ToType->getAsBlockPointerType())
870 ToPointeeType = ToBlockPtr->getPointeeType();
871 else
Douglas Gregorc7887512008-12-19 19:13:09 +0000872 return false;
873
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000874 QualType FromPointeeType;
Douglas Gregorc7887512008-12-19 19:13:09 +0000875 const PointerType *FromTypePtr = FromType->getAsPointerType();
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000876 if (FromTypePtr)
877 FromPointeeType = FromTypePtr->getPointeeType();
878 else if (const BlockPointerType *FromBlockPtr
879 = FromType->getAsBlockPointerType())
880 FromPointeeType = FromBlockPtr->getPointeeType();
881 else
Douglas Gregorc7887512008-12-19 19:13:09 +0000882 return false;
883
Douglas Gregorcb7de522008-11-26 23:31:11 +0000884 // Objective C++: We're able to convert from a pointer to an
885 // interface to a pointer to a different interface.
886 const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType();
887 const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType();
888 if (FromIface && ToIface &&
889 Context.canAssignObjCInterfaces(ToIface, FromIface)) {
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000890 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +0000891 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000892 ToType, Context);
893 return true;
894 }
895
Douglas Gregor45920e82008-12-19 17:40:08 +0000896 if (FromIface && ToIface &&
897 Context.canAssignObjCInterfaces(FromIface, ToIface)) {
898 // Okay: this is some kind of implicit downcast of Objective-C
899 // interfaces, which is permitted. However, we're going to
900 // complain about it.
901 IncompatibleObjC = true;
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000902 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor45920e82008-12-19 17:40:08 +0000903 ToPointeeType,
904 ToType, Context);
905 return true;
906 }
907
Douglas Gregorcb7de522008-11-26 23:31:11 +0000908 // Objective C++: We're able to convert between "id" and a pointer
909 // to any interface (in both directions).
910 if ((FromIface && Context.isObjCIdType(ToPointeeType))
911 || (ToIface && Context.isObjCIdType(FromPointeeType))) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000912 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
913 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000914 ToType, Context);
915 return true;
916 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000917
Douglas Gregordda78892008-12-18 23:43:31 +0000918 // Objective C++: Allow conversions between the Objective-C "id" and
919 // "Class", in either direction.
920 if ((Context.isObjCIdType(FromPointeeType) &&
921 Context.isObjCClassType(ToPointeeType)) ||
922 (Context.isObjCClassType(FromPointeeType) &&
923 Context.isObjCIdType(ToPointeeType))) {
924 ConvertedType = ToType;
925 return true;
926 }
927
Douglas Gregorc7887512008-12-19 19:13:09 +0000928 // If we have pointers to pointers, recursively check whether this
929 // is an Objective-C conversion.
930 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
931 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
932 IncompatibleObjC)) {
933 // We always complain about this conversion.
934 IncompatibleObjC = true;
935 ConvertedType = ToType;
936 return true;
937 }
938
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000939 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +0000940 // differences in the argument and result types are in Objective-C
941 // pointer conversions. If so, we permit the conversion (but
942 // complain about it).
943 const FunctionTypeProto *FromFunctionType
944 = FromPointeeType->getAsFunctionTypeProto();
945 const FunctionTypeProto *ToFunctionType
946 = ToPointeeType->getAsFunctionTypeProto();
947 if (FromFunctionType && ToFunctionType) {
948 // If the function types are exactly the same, this isn't an
949 // Objective-C pointer conversion.
950 if (Context.getCanonicalType(FromPointeeType)
951 == Context.getCanonicalType(ToPointeeType))
952 return false;
953
954 // Perform the quick checks that will tell us whether these
955 // function types are obviously different.
956 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
957 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
958 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
959 return false;
960
961 bool HasObjCConversion = false;
962 if (Context.getCanonicalType(FromFunctionType->getResultType())
963 == Context.getCanonicalType(ToFunctionType->getResultType())) {
964 // Okay, the types match exactly. Nothing to do.
965 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
966 ToFunctionType->getResultType(),
967 ConvertedType, IncompatibleObjC)) {
968 // Okay, we have an Objective-C pointer conversion.
969 HasObjCConversion = true;
970 } else {
971 // Function types are too different. Abort.
972 return false;
973 }
974
975 // Check argument types.
976 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
977 ArgIdx != NumArgs; ++ArgIdx) {
978 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
979 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
980 if (Context.getCanonicalType(FromArgType)
981 == Context.getCanonicalType(ToArgType)) {
982 // Okay, the types match exactly. Nothing to do.
983 } else if (isObjCPointerConversion(FromArgType, ToArgType,
984 ConvertedType, IncompatibleObjC)) {
985 // Okay, we have an Objective-C pointer conversion.
986 HasObjCConversion = true;
987 } else {
988 // Argument types are too different. Abort.
989 return false;
990 }
991 }
992
993 if (HasObjCConversion) {
994 // We had an Objective-C conversion. Allow this pointer
995 // conversion, but complain about it.
996 ConvertedType = ToType;
997 IncompatibleObjC = true;
998 return true;
999 }
1000 }
1001
1002 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001003}
1004
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001005/// CheckPointerConversion - Check the pointer conversion from the
1006/// expression From to the type ToType. This routine checks for
1007/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
1008/// conversions for which IsPointerConversion has already returned
1009/// true. It returns true and produces a diagnostic if there was an
1010/// error, or returns false otherwise.
1011bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1012 QualType FromType = From->getType();
1013
1014 if (const PointerType *FromPtrType = FromType->getAsPointerType())
1015 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
Sebastian Redl07779722008-10-31 14:43:28 +00001016 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1017 /*DetectVirtual=*/false);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001018 QualType FromPointeeType = FromPtrType->getPointeeType(),
1019 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001020
1021 // Objective-C++ conversions are always okay.
1022 // FIXME: We should have a different class of conversions for
1023 // the Objective-C++ implicit conversions.
1024 if (Context.isObjCIdType(FromPointeeType) ||
1025 Context.isObjCIdType(ToPointeeType) ||
1026 Context.isObjCClassType(FromPointeeType) ||
1027 Context.isObjCClassType(ToPointeeType))
1028 return false;
1029
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001030 if (FromPointeeType->isRecordType() &&
1031 ToPointeeType->isRecordType()) {
1032 // We must have a derived-to-base conversion. Check an
1033 // ambiguous or inaccessible conversion.
Douglas Gregor0575d4a2008-10-24 16:17:19 +00001034 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1035 From->getExprLoc(),
1036 From->getSourceRange());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001037 }
1038 }
1039
1040 return false;
1041}
1042
Douglas Gregor98cd5992008-10-21 23:43:52 +00001043/// IsQualificationConversion - Determines whether the conversion from
1044/// an rvalue of type FromType to ToType is a qualification conversion
1045/// (C++ 4.4).
1046bool
1047Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1048{
1049 FromType = Context.getCanonicalType(FromType);
1050 ToType = Context.getCanonicalType(ToType);
1051
1052 // If FromType and ToType are the same type, this is not a
1053 // qualification conversion.
1054 if (FromType == ToType)
1055 return false;
1056
1057 // (C++ 4.4p4):
1058 // A conversion can add cv-qualifiers at levels other than the first
1059 // in multi-level pointers, subject to the following rules: [...]
1060 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001061 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001062 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001063 // Within each iteration of the loop, we check the qualifiers to
1064 // determine if this still looks like a qualification
1065 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001066 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001067 // until there are no more pointers or pointers-to-members left to
1068 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001069 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001070
1071 // -- for every j > 0, if const is in cv 1,j then const is in cv
1072 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001073 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001074 return false;
Douglas Gregor57373262008-10-22 14:17:15 +00001075
Douglas Gregor98cd5992008-10-21 23:43:52 +00001076 // -- if the cv 1,j and cv 2,j are different, then const is in
1077 // every cv for 0 < k < j.
1078 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001079 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001080 return false;
Douglas Gregor57373262008-10-22 14:17:15 +00001081
Douglas Gregor98cd5992008-10-21 23:43:52 +00001082 // Keep track of whether all prior cv-qualifiers in the "to" type
1083 // include const.
1084 PreviousToQualsIncludeConst
1085 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001086 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001087
1088 // We are left with FromType and ToType being the pointee types
1089 // after unwrapping the original FromType and ToType the same number
1090 // of types. If we unwrapped any pointers, and if FromType and
1091 // ToType have the same unqualified type (since we checked
1092 // qualifiers above), then this is a qualification conversion.
1093 return UnwrappedAnyPointer &&
1094 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1095}
1096
Douglas Gregor60d62c22008-10-31 16:23:19 +00001097/// IsUserDefinedConversion - Determines whether there is a
1098/// user-defined conversion sequence (C++ [over.ics.user]) that
1099/// converts expression From to the type ToType. If such a conversion
1100/// exists, User will contain the user-defined conversion sequence
1101/// that performs such a conversion and this routine will return
1102/// true. Otherwise, this routine returns false and User is
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001103/// unspecified. AllowExplicit is true if the conversion should
1104/// consider C++0x "explicit" conversion functions as well as
1105/// non-explicit conversion functions (C++0x [class.conv.fct]p2).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001106bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001107 UserDefinedConversionSequence& User,
1108 bool AllowExplicit)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001109{
1110 OverloadCandidateSet CandidateSet;
1111 if (const CXXRecordType *ToRecordType
1112 = dyn_cast_or_null<CXXRecordType>(ToType->getAsRecordType())) {
1113 // C++ [over.match.ctor]p1:
1114 // When objects of class type are direct-initialized (8.5), or
1115 // copy-initialized from an expression of the same or a
1116 // derived class type (8.5), overload resolution selects the
1117 // constructor. [...] For copy-initialization, the candidate
1118 // functions are all the converting constructors (12.3.1) of
1119 // that class. The argument list is the expression-list within
1120 // the parentheses of the initializer.
1121 CXXRecordDecl *ToRecordDecl = ToRecordType->getDecl();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001122 DeclarationName ConstructorName
1123 = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregore63ef482009-01-13 00:11:19 +00001124 Context.getCanonicalType(ToType).getUnqualifiedType());
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001125 DeclContext::lookup_iterator Con, ConEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00001126 for (llvm::tie(Con, ConEnd) = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001127 Con != ConEnd; ++Con) {
1128 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001129 if (Constructor->isConvertingConstructor())
Douglas Gregor225c41e2008-11-03 19:09:14 +00001130 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1131 /*SuppressUserConversions=*/true);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001132 }
1133 }
1134
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001135 if (const CXXRecordType *FromRecordType
1136 = dyn_cast_or_null<CXXRecordType>(From->getType()->getAsRecordType())) {
1137 // Add all of the conversion functions as candidates.
1138 // FIXME: Look for conversions in base classes!
1139 CXXRecordDecl *FromRecordDecl = FromRecordType->getDecl();
1140 OverloadedFunctionDecl *Conversions
1141 = FromRecordDecl->getConversionFunctions();
1142 for (OverloadedFunctionDecl::function_iterator Func
1143 = Conversions->function_begin();
1144 Func != Conversions->function_end(); ++Func) {
1145 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001146 if (AllowExplicit || !Conv->isExplicit())
1147 AddConversionCandidate(Conv, From, ToType, CandidateSet);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001148 }
1149 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001150
1151 OverloadCandidateSet::iterator Best;
1152 switch (BestViableFunction(CandidateSet, Best)) {
1153 case OR_Success:
1154 // Record the standard conversion we used and the conversion function.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001155 if (CXXConstructorDecl *Constructor
1156 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1157 // C++ [over.ics.user]p1:
1158 // If the user-defined conversion is specified by a
1159 // constructor (12.3.1), the initial standard conversion
1160 // sequence converts the source type to the type required by
1161 // the argument of the constructor.
1162 //
1163 // FIXME: What about ellipsis conversions?
1164 QualType ThisType = Constructor->getThisType(Context);
1165 User.Before = Best->Conversions[0].Standard;
1166 User.ConversionFunction = Constructor;
1167 User.After.setAsIdentityConversion();
1168 User.After.FromTypePtr
1169 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
1170 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1171 return true;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001172 } else if (CXXConversionDecl *Conversion
1173 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1174 // C++ [over.ics.user]p1:
1175 //
1176 // [...] If the user-defined conversion is specified by a
1177 // conversion function (12.3.2), the initial standard
1178 // conversion sequence converts the source type to the
1179 // implicit object parameter of the conversion function.
1180 User.Before = Best->Conversions[0].Standard;
1181 User.ConversionFunction = Conversion;
1182
1183 // C++ [over.ics.user]p2:
1184 // The second standard conversion sequence converts the
1185 // result of the user-defined conversion to the target type
1186 // for the sequence. Since an implicit conversion sequence
1187 // is an initialization, the special rules for
1188 // initialization by user-defined conversion apply when
1189 // selecting the best user-defined conversion for a
1190 // user-defined conversion sequence (see 13.3.3 and
1191 // 13.3.3.1).
1192 User.After = Best->FinalConversion;
1193 return true;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001194 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001195 assert(false && "Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001196 return false;
1197 }
1198
1199 case OR_No_Viable_Function:
1200 // No conversion here! We're done.
1201 return false;
1202
1203 case OR_Ambiguous:
1204 // FIXME: See C++ [over.best.ics]p10 for the handling of
1205 // ambiguous conversion sequences.
1206 return false;
1207 }
1208
1209 return false;
1210}
1211
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001212/// CompareImplicitConversionSequences - Compare two implicit
1213/// conversion sequences to determine whether one is better than the
1214/// other or if they are indistinguishable (C++ 13.3.3.2).
1215ImplicitConversionSequence::CompareKind
1216Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1217 const ImplicitConversionSequence& ICS2)
1218{
1219 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1220 // conversion sequences (as defined in 13.3.3.1)
1221 // -- a standard conversion sequence (13.3.3.1.1) is a better
1222 // conversion sequence than a user-defined conversion sequence or
1223 // an ellipsis conversion sequence, and
1224 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1225 // conversion sequence than an ellipsis conversion sequence
1226 // (13.3.3.1.3).
1227 //
1228 if (ICS1.ConversionKind < ICS2.ConversionKind)
1229 return ImplicitConversionSequence::Better;
1230 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1231 return ImplicitConversionSequence::Worse;
1232
1233 // Two implicit conversion sequences of the same form are
1234 // indistinguishable conversion sequences unless one of the
1235 // following rules apply: (C++ 13.3.3.2p3):
1236 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1237 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1238 else if (ICS1.ConversionKind ==
1239 ImplicitConversionSequence::UserDefinedConversion) {
1240 // User-defined conversion sequence U1 is a better conversion
1241 // sequence than another user-defined conversion sequence U2 if
1242 // they contain the same user-defined conversion function or
1243 // constructor and if the second standard conversion sequence of
1244 // U1 is better than the second standard conversion sequence of
1245 // U2 (C++ 13.3.3.2p3).
1246 if (ICS1.UserDefined.ConversionFunction ==
1247 ICS2.UserDefined.ConversionFunction)
1248 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1249 ICS2.UserDefined.After);
1250 }
1251
1252 return ImplicitConversionSequence::Indistinguishable;
1253}
1254
1255/// CompareStandardConversionSequences - Compare two standard
1256/// conversion sequences to determine whether one is better than the
1257/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1258ImplicitConversionSequence::CompareKind
1259Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1260 const StandardConversionSequence& SCS2)
1261{
1262 // Standard conversion sequence S1 is a better conversion sequence
1263 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1264
1265 // -- S1 is a proper subsequence of S2 (comparing the conversion
1266 // sequences in the canonical form defined by 13.3.3.1.1,
1267 // excluding any Lvalue Transformation; the identity conversion
1268 // sequence is considered to be a subsequence of any
1269 // non-identity conversion sequence) or, if not that,
1270 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1271 // Neither is a proper subsequence of the other. Do nothing.
1272 ;
1273 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1274 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1275 (SCS1.Second == ICK_Identity &&
1276 SCS1.Third == ICK_Identity))
1277 // SCS1 is a proper subsequence of SCS2.
1278 return ImplicitConversionSequence::Better;
1279 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1280 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1281 (SCS2.Second == ICK_Identity &&
1282 SCS2.Third == ICK_Identity))
1283 // SCS2 is a proper subsequence of SCS1.
1284 return ImplicitConversionSequence::Worse;
1285
1286 // -- the rank of S1 is better than the rank of S2 (by the rules
1287 // defined below), or, if not that,
1288 ImplicitConversionRank Rank1 = SCS1.getRank();
1289 ImplicitConversionRank Rank2 = SCS2.getRank();
1290 if (Rank1 < Rank2)
1291 return ImplicitConversionSequence::Better;
1292 else if (Rank2 < Rank1)
1293 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001294
Douglas Gregor57373262008-10-22 14:17:15 +00001295 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1296 // are indistinguishable unless one of the following rules
1297 // applies:
1298
1299 // A conversion that is not a conversion of a pointer, or
1300 // pointer to member, to bool is better than another conversion
1301 // that is such a conversion.
1302 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1303 return SCS2.isPointerConversionToBool()
1304 ? ImplicitConversionSequence::Better
1305 : ImplicitConversionSequence::Worse;
1306
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001307 // C++ [over.ics.rank]p4b2:
1308 //
1309 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001310 // conversion of B* to A* is better than conversion of B* to
1311 // void*, and conversion of A* to void* is better than conversion
1312 // of B* to void*.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001313 bool SCS1ConvertsToVoid
1314 = SCS1.isPointerConversionToVoidPointer(Context);
1315 bool SCS2ConvertsToVoid
1316 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001317 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1318 // Exactly one of the conversion sequences is a conversion to
1319 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001320 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1321 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001322 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1323 // Neither conversion sequence converts to a void pointer; compare
1324 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001325 if (ImplicitConversionSequence::CompareKind DerivedCK
1326 = CompareDerivedToBaseConversions(SCS1, SCS2))
1327 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001328 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1329 // Both conversion sequences are conversions to void
1330 // pointers. Compare the source types to determine if there's an
1331 // inheritance relationship in their sources.
1332 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1333 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1334
1335 // Adjust the types we're converting from via the array-to-pointer
1336 // conversion, if we need to.
1337 if (SCS1.First == ICK_Array_To_Pointer)
1338 FromType1 = Context.getArrayDecayedType(FromType1);
1339 if (SCS2.First == ICK_Array_To_Pointer)
1340 FromType2 = Context.getArrayDecayedType(FromType2);
1341
1342 QualType FromPointee1
1343 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1344 QualType FromPointee2
1345 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1346
1347 if (IsDerivedFrom(FromPointee2, FromPointee1))
1348 return ImplicitConversionSequence::Better;
1349 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1350 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001351
1352 // Objective-C++: If one interface is more specific than the
1353 // other, it is the better one.
1354 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1355 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1356 if (FromIface1 && FromIface1) {
1357 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1358 return ImplicitConversionSequence::Better;
1359 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1360 return ImplicitConversionSequence::Worse;
1361 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001362 }
Douglas Gregor57373262008-10-22 14:17:15 +00001363
1364 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1365 // bullet 3).
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001366 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001367 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001368 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001369
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001370 // C++ [over.ics.rank]p3b4:
1371 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1372 // which the references refer are the same type except for
1373 // top-level cv-qualifiers, and the type to which the reference
1374 // initialized by S2 refers is more cv-qualified than the type
1375 // to which the reference initialized by S1 refers.
1376 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1377 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1378 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1379 T1 = Context.getCanonicalType(T1);
1380 T2 = Context.getCanonicalType(T2);
1381 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1382 if (T2.isMoreQualifiedThan(T1))
1383 return ImplicitConversionSequence::Better;
1384 else if (T1.isMoreQualifiedThan(T2))
1385 return ImplicitConversionSequence::Worse;
1386 }
1387 }
Douglas Gregor57373262008-10-22 14:17:15 +00001388
1389 return ImplicitConversionSequence::Indistinguishable;
1390}
1391
1392/// CompareQualificationConversions - Compares two standard conversion
1393/// sequences to determine whether they can be ranked based on their
1394/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1395ImplicitConversionSequence::CompareKind
1396Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1397 const StandardConversionSequence& SCS2)
1398{
Douglas Gregorba7e2102008-10-22 15:04:37 +00001399 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001400 // -- S1 and S2 differ only in their qualification conversion and
1401 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1402 // cv-qualification signature of type T1 is a proper subset of
1403 // the cv-qualification signature of type T2, and S1 is not the
1404 // deprecated string literal array-to-pointer conversion (4.2).
1405 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1406 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1407 return ImplicitConversionSequence::Indistinguishable;
1408
1409 // FIXME: the example in the standard doesn't use a qualification
1410 // conversion (!)
1411 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1412 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1413 T1 = Context.getCanonicalType(T1);
1414 T2 = Context.getCanonicalType(T2);
1415
1416 // If the types are the same, we won't learn anything by unwrapped
1417 // them.
1418 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1419 return ImplicitConversionSequence::Indistinguishable;
1420
1421 ImplicitConversionSequence::CompareKind Result
1422 = ImplicitConversionSequence::Indistinguishable;
1423 while (UnwrapSimilarPointerTypes(T1, T2)) {
1424 // Within each iteration of the loop, we check the qualifiers to
1425 // determine if this still looks like a qualification
1426 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001427 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001428 // until there are no more pointers or pointers-to-members left
1429 // to unwrap. This essentially mimics what
1430 // IsQualificationConversion does, but here we're checking for a
1431 // strict subset of qualifiers.
1432 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1433 // The qualifiers are the same, so this doesn't tell us anything
1434 // about how the sequences rank.
1435 ;
1436 else if (T2.isMoreQualifiedThan(T1)) {
1437 // T1 has fewer qualifiers, so it could be the better sequence.
1438 if (Result == ImplicitConversionSequence::Worse)
1439 // Neither has qualifiers that are a subset of the other's
1440 // qualifiers.
1441 return ImplicitConversionSequence::Indistinguishable;
1442
1443 Result = ImplicitConversionSequence::Better;
1444 } else if (T1.isMoreQualifiedThan(T2)) {
1445 // T2 has fewer qualifiers, so it could be the better sequence.
1446 if (Result == ImplicitConversionSequence::Better)
1447 // Neither has qualifiers that are a subset of the other's
1448 // qualifiers.
1449 return ImplicitConversionSequence::Indistinguishable;
1450
1451 Result = ImplicitConversionSequence::Worse;
1452 } else {
1453 // Qualifiers are disjoint.
1454 return ImplicitConversionSequence::Indistinguishable;
1455 }
1456
1457 // If the types after this point are equivalent, we're done.
1458 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1459 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001460 }
1461
Douglas Gregor57373262008-10-22 14:17:15 +00001462 // Check that the winning standard conversion sequence isn't using
1463 // the deprecated string literal array to pointer conversion.
1464 switch (Result) {
1465 case ImplicitConversionSequence::Better:
1466 if (SCS1.Deprecated)
1467 Result = ImplicitConversionSequence::Indistinguishable;
1468 break;
1469
1470 case ImplicitConversionSequence::Indistinguishable:
1471 break;
1472
1473 case ImplicitConversionSequence::Worse:
1474 if (SCS2.Deprecated)
1475 Result = ImplicitConversionSequence::Indistinguishable;
1476 break;
1477 }
1478
1479 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001480}
1481
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001482/// CompareDerivedToBaseConversions - Compares two standard conversion
1483/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00001484/// various kinds of derived-to-base conversions (C++
1485/// [over.ics.rank]p4b3). As part of these checks, we also look at
1486/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001487ImplicitConversionSequence::CompareKind
1488Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1489 const StandardConversionSequence& SCS2) {
1490 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1491 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1492 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1493 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1494
1495 // Adjust the types we're converting from via the array-to-pointer
1496 // conversion, if we need to.
1497 if (SCS1.First == ICK_Array_To_Pointer)
1498 FromType1 = Context.getArrayDecayedType(FromType1);
1499 if (SCS2.First == ICK_Array_To_Pointer)
1500 FromType2 = Context.getArrayDecayedType(FromType2);
1501
1502 // Canonicalize all of the types.
1503 FromType1 = Context.getCanonicalType(FromType1);
1504 ToType1 = Context.getCanonicalType(ToType1);
1505 FromType2 = Context.getCanonicalType(FromType2);
1506 ToType2 = Context.getCanonicalType(ToType2);
1507
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001508 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001509 //
1510 // If class B is derived directly or indirectly from class A and
1511 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001512 //
1513 // For Objective-C, we let A, B, and C also be Objective-C
1514 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001515
1516 // Compare based on pointer conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001517 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00001518 SCS2.Second == ICK_Pointer_Conversion &&
1519 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1520 FromType1->isPointerType() && FromType2->isPointerType() &&
1521 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001522 QualType FromPointee1
1523 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1524 QualType ToPointee1
1525 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1526 QualType FromPointee2
1527 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1528 QualType ToPointee2
1529 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001530
1531 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1532 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1533 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1534 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1535
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001536 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001537 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1538 if (IsDerivedFrom(ToPointee1, ToPointee2))
1539 return ImplicitConversionSequence::Better;
1540 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1541 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001542
1543 if (ToIface1 && ToIface2) {
1544 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1545 return ImplicitConversionSequence::Better;
1546 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1547 return ImplicitConversionSequence::Worse;
1548 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001549 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001550
1551 // -- conversion of B* to A* is better than conversion of C* to A*,
1552 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1553 if (IsDerivedFrom(FromPointee2, FromPointee1))
1554 return ImplicitConversionSequence::Better;
1555 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1556 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001557
1558 if (FromIface1 && FromIface2) {
1559 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1560 return ImplicitConversionSequence::Better;
1561 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1562 return ImplicitConversionSequence::Worse;
1563 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001564 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001565 }
1566
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001567 // Compare based on reference bindings.
1568 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1569 SCS1.Second == ICK_Derived_To_Base) {
1570 // -- binding of an expression of type C to a reference of type
1571 // B& is better than binding an expression of type C to a
1572 // reference of type A&,
1573 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1574 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1575 if (IsDerivedFrom(ToType1, ToType2))
1576 return ImplicitConversionSequence::Better;
1577 else if (IsDerivedFrom(ToType2, ToType1))
1578 return ImplicitConversionSequence::Worse;
1579 }
1580
Douglas Gregor225c41e2008-11-03 19:09:14 +00001581 // -- binding of an expression of type B to a reference of type
1582 // A& is better than binding an expression of type C to a
1583 // reference of type A&,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001584 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1585 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1586 if (IsDerivedFrom(FromType2, FromType1))
1587 return ImplicitConversionSequence::Better;
1588 else if (IsDerivedFrom(FromType1, FromType2))
1589 return ImplicitConversionSequence::Worse;
1590 }
1591 }
1592
1593
1594 // FIXME: conversion of A::* to B::* is better than conversion of
1595 // A::* to C::*,
1596
1597 // FIXME: conversion of B::* to C::* is better than conversion of
1598 // A::* to C::*, and
1599
Douglas Gregor225c41e2008-11-03 19:09:14 +00001600 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1601 SCS1.Second == ICK_Derived_To_Base) {
1602 // -- conversion of C to B is better than conversion of C to A,
1603 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1604 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1605 if (IsDerivedFrom(ToType1, ToType2))
1606 return ImplicitConversionSequence::Better;
1607 else if (IsDerivedFrom(ToType2, ToType1))
1608 return ImplicitConversionSequence::Worse;
1609 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001610
Douglas Gregor225c41e2008-11-03 19:09:14 +00001611 // -- conversion of B to A is better than conversion of C to A.
1612 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1613 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1614 if (IsDerivedFrom(FromType2, FromType1))
1615 return ImplicitConversionSequence::Better;
1616 else if (IsDerivedFrom(FromType1, FromType2))
1617 return ImplicitConversionSequence::Worse;
1618 }
1619 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001620
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001621 return ImplicitConversionSequence::Indistinguishable;
1622}
1623
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001624/// TryCopyInitialization - Try to copy-initialize a value of type
1625/// ToType from the expression From. Return the implicit conversion
1626/// sequence required to pass this argument, which may be a bad
1627/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00001628/// a parameter of this type). If @p SuppressUserConversions, then we
1629/// do not permit any user-defined conversion sequences.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001630ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +00001631Sema::TryCopyInitialization(Expr *From, QualType ToType,
1632 bool SuppressUserConversions) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001633 if (!getLangOptions().CPlusPlus) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001634 // In C, copy initialization is the same as performing an assignment.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001635 AssignConvertType ConvTy =
1636 CheckSingleAssignmentConstraints(ToType, From);
1637 ImplicitConversionSequence ICS;
1638 if (getLangOptions().NoExtensions? ConvTy != Compatible
1639 : ConvTy == Incompatible)
1640 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1641 else
1642 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1643 return ICS;
1644 } else if (ToType->isReferenceType()) {
1645 ImplicitConversionSequence ICS;
Douglas Gregor225c41e2008-11-03 19:09:14 +00001646 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001647 return ICS;
1648 } else {
Douglas Gregor225c41e2008-11-03 19:09:14 +00001649 return TryImplicitConversion(From, ToType, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001650 }
1651}
1652
1653/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1654/// type ToType. Returns true (and emits a diagnostic) if there was
1655/// an error, returns false if the initialization succeeded.
1656bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1657 const char* Flavor) {
1658 if (!getLangOptions().CPlusPlus) {
1659 // In C, argument passing is the same as performing an assignment.
1660 QualType FromType = From->getType();
1661 AssignConvertType ConvTy =
1662 CheckSingleAssignmentConstraints(ToType, From);
1663
1664 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1665 FromType, From, Flavor);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001666 }
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001667
1668 if (ToType->isReferenceType())
1669 return CheckReferenceInit(From, ToType);
1670
Douglas Gregor45920e82008-12-19 17:40:08 +00001671 if (!PerformImplicitConversion(From, ToType, Flavor))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001672 return false;
1673
1674 return Diag(From->getSourceRange().getBegin(),
1675 diag::err_typecheck_convert_incompatible)
1676 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001677}
1678
Douglas Gregor96176b32008-11-18 23:14:02 +00001679/// TryObjectArgumentInitialization - Try to initialize the object
1680/// parameter of the given member function (@c Method) from the
1681/// expression @p From.
1682ImplicitConversionSequence
1683Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1684 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1685 unsigned MethodQuals = Method->getTypeQualifiers();
1686 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1687
1688 // Set up the conversion sequence as a "bad" conversion, to allow us
1689 // to exit early.
1690 ImplicitConversionSequence ICS;
1691 ICS.Standard.setAsIdentityConversion();
1692 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1693
1694 // We need to have an object of class type.
1695 QualType FromType = From->getType();
1696 if (!FromType->isRecordType())
1697 return ICS;
1698
1699 // The implicit object parmeter is has the type "reference to cv X",
1700 // where X is the class of which the function is a member
1701 // (C++ [over.match.funcs]p4). However, when finding an implicit
1702 // conversion sequence for the argument, we are not allowed to
1703 // create temporaries or perform user-defined conversions
1704 // (C++ [over.match.funcs]p5). We perform a simplified version of
1705 // reference binding here, that allows class rvalues to bind to
1706 // non-constant references.
1707
1708 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1709 // with the implicit object parameter (C++ [over.match.funcs]p5).
1710 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1711 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1712 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1713 return ICS;
1714
1715 // Check that we have either the same type or a derived type. It
1716 // affects the conversion rank.
1717 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1718 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1719 ICS.Standard.Second = ICK_Identity;
1720 else if (IsDerivedFrom(FromType, ClassType))
1721 ICS.Standard.Second = ICK_Derived_To_Base;
1722 else
1723 return ICS;
1724
1725 // Success. Mark this as a reference binding.
1726 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1727 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1728 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1729 ICS.Standard.ReferenceBinding = true;
1730 ICS.Standard.DirectBinding = true;
1731 return ICS;
1732}
1733
1734/// PerformObjectArgumentInitialization - Perform initialization of
1735/// the implicit object parameter for the given Method with the given
1736/// expression.
1737bool
1738Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
1739 QualType ImplicitParamType
1740 = Method->getThisType(Context)->getAsPointerType()->getPointeeType();
1741 ImplicitConversionSequence ICS
1742 = TryObjectArgumentInitialization(From, Method);
1743 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
1744 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001745 diag::err_implicit_object_parameter_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00001746 << ImplicitParamType << From->getType() << From->getSourceRange();
Douglas Gregor96176b32008-11-18 23:14:02 +00001747
1748 if (ICS.Standard.Second == ICK_Derived_To_Base &&
1749 CheckDerivedToBaseConversion(From->getType(), ImplicitParamType,
1750 From->getSourceRange().getBegin(),
1751 From->getSourceRange()))
1752 return true;
1753
1754 ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true);
1755 return false;
1756}
1757
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001758/// TryContextuallyConvertToBool - Attempt to contextually convert the
1759/// expression From to bool (C++0x [conv]p3).
1760ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
1761 return TryImplicitConversion(From, Context.BoolTy, false, true);
1762}
1763
1764/// PerformContextuallyConvertToBool - Perform a contextual conversion
1765/// of the expression From to bool (C++0x [conv]p3).
1766bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
1767 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
1768 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
1769 return false;
1770
1771 return Diag(From->getSourceRange().getBegin(),
1772 diag::err_typecheck_bool_condition)
1773 << From->getType() << From->getSourceRange();
1774}
1775
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001776/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00001777/// candidate functions, using the given function call arguments. If
1778/// @p SuppressUserConversions, then don't allow user-defined
1779/// conversions via constructors or conversion operators.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001780void
1781Sema::AddOverloadCandidate(FunctionDecl *Function,
1782 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00001783 OverloadCandidateSet& CandidateSet,
1784 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001785{
1786 const FunctionTypeProto* Proto
1787 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType());
1788 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001789 assert(!isa<CXXConversionDecl>(Function) &&
1790 "Use AddConversionCandidate for conversion functions");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001791
Douglas Gregor88a35142008-12-22 05:46:06 +00001792 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
1793 // If we get here, it's because we're calling a member function
1794 // that is named without a member access expression (e.g.,
1795 // "this->f") that was either written explicitly or created
1796 // implicitly. This can happen with a qualified call to a member
1797 // function, e.g., X::f(). We use a NULL object as the implied
1798 // object argument (C++ [over.call.func]p3).
1799 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
1800 SuppressUserConversions);
1801 return;
1802 }
1803
1804
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001805 // Add this candidate
1806 CandidateSet.push_back(OverloadCandidate());
1807 OverloadCandidate& Candidate = CandidateSet.back();
1808 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00001809 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001810 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00001811 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001812
1813 unsigned NumArgsInProto = Proto->getNumArgs();
1814
1815 // (C++ 13.3.2p2): A candidate function having fewer than m
1816 // parameters is viable only if it has an ellipsis in its parameter
1817 // list (8.3.5).
1818 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1819 Candidate.Viable = false;
1820 return;
1821 }
1822
1823 // (C++ 13.3.2p2): A candidate function having more than m parameters
1824 // is viable only if the (m+1)st parameter has a default argument
1825 // (8.3.6). For the purposes of overload resolution, the
1826 // parameter list is truncated on the right, so that there are
1827 // exactly m parameters.
1828 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
1829 if (NumArgs < MinRequiredArgs) {
1830 // Not enough arguments.
1831 Candidate.Viable = false;
1832 return;
1833 }
1834
1835 // Determine the implicit conversion sequences for each of the
1836 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001837 Candidate.Conversions.resize(NumArgs);
1838 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1839 if (ArgIdx < NumArgsInProto) {
1840 // (C++ 13.3.2p3): for F to be a viable function, there shall
1841 // exist for each argument an implicit conversion sequence
1842 // (13.3.3.1) that converts that argument to the corresponding
1843 // parameter of F.
1844 QualType ParamType = Proto->getArgType(ArgIdx);
1845 Candidate.Conversions[ArgIdx]
Douglas Gregor225c41e2008-11-03 19:09:14 +00001846 = TryCopyInitialization(Args[ArgIdx], ParamType,
1847 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001848 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00001849 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001850 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001851 break;
1852 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001853 } else {
1854 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1855 // argument for which there is no corresponding parameter is
1856 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1857 Candidate.Conversions[ArgIdx].ConversionKind
1858 = ImplicitConversionSequence::EllipsisConversion;
1859 }
1860 }
1861}
1862
Douglas Gregor96176b32008-11-18 23:14:02 +00001863/// AddMethodCandidate - Adds the given C++ member function to the set
1864/// of candidate functions, using the given function call arguments
1865/// and the object argument (@c Object). For example, in a call
1866/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
1867/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
1868/// allow user-defined conversions via constructors or conversion
1869/// operators.
1870void
1871Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
1872 Expr **Args, unsigned NumArgs,
1873 OverloadCandidateSet& CandidateSet,
1874 bool SuppressUserConversions)
1875{
1876 const FunctionTypeProto* Proto
1877 = dyn_cast<FunctionTypeProto>(Method->getType()->getAsFunctionType());
1878 assert(Proto && "Methods without a prototype cannot be overloaded");
1879 assert(!isa<CXXConversionDecl>(Method) &&
1880 "Use AddConversionCandidate for conversion functions");
1881
1882 // Add this candidate
1883 CandidateSet.push_back(OverloadCandidate());
1884 OverloadCandidate& Candidate = CandidateSet.back();
1885 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001886 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00001887 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001888
1889 unsigned NumArgsInProto = Proto->getNumArgs();
1890
1891 // (C++ 13.3.2p2): A candidate function having fewer than m
1892 // parameters is viable only if it has an ellipsis in its parameter
1893 // list (8.3.5).
1894 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1895 Candidate.Viable = false;
1896 return;
1897 }
1898
1899 // (C++ 13.3.2p2): A candidate function having more than m parameters
1900 // is viable only if the (m+1)st parameter has a default argument
1901 // (8.3.6). For the purposes of overload resolution, the
1902 // parameter list is truncated on the right, so that there are
1903 // exactly m parameters.
1904 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
1905 if (NumArgs < MinRequiredArgs) {
1906 // Not enough arguments.
1907 Candidate.Viable = false;
1908 return;
1909 }
1910
1911 Candidate.Viable = true;
1912 Candidate.Conversions.resize(NumArgs + 1);
1913
Douglas Gregor88a35142008-12-22 05:46:06 +00001914 if (Method->isStatic() || !Object)
1915 // The implicit object argument is ignored.
1916 Candidate.IgnoreObjectArgument = true;
1917 else {
1918 // Determine the implicit conversion sequence for the object
1919 // parameter.
1920 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
1921 if (Candidate.Conversions[0].ConversionKind
1922 == ImplicitConversionSequence::BadConversion) {
1923 Candidate.Viable = false;
1924 return;
1925 }
Douglas Gregor96176b32008-11-18 23:14:02 +00001926 }
1927
1928 // Determine the implicit conversion sequences for each of the
1929 // arguments.
1930 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1931 if (ArgIdx < NumArgsInProto) {
1932 // (C++ 13.3.2p3): for F to be a viable function, there shall
1933 // exist for each argument an implicit conversion sequence
1934 // (13.3.3.1) that converts that argument to the corresponding
1935 // parameter of F.
1936 QualType ParamType = Proto->getArgType(ArgIdx);
1937 Candidate.Conversions[ArgIdx + 1]
1938 = TryCopyInitialization(Args[ArgIdx], ParamType,
1939 SuppressUserConversions);
1940 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
1941 == ImplicitConversionSequence::BadConversion) {
1942 Candidate.Viable = false;
1943 break;
1944 }
1945 } else {
1946 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1947 // argument for which there is no corresponding parameter is
1948 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1949 Candidate.Conversions[ArgIdx + 1].ConversionKind
1950 = ImplicitConversionSequence::EllipsisConversion;
1951 }
1952 }
1953}
1954
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001955/// AddConversionCandidate - Add a C++ conversion function as a
1956/// candidate in the candidate set (C++ [over.match.conv],
1957/// C++ [over.match.copy]). From is the expression we're converting from,
1958/// and ToType is the type that we're eventually trying to convert to
1959/// (which may or may not be the same type as the type that the
1960/// conversion function produces).
1961void
1962Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
1963 Expr *From, QualType ToType,
1964 OverloadCandidateSet& CandidateSet) {
1965 // Add this candidate
1966 CandidateSet.push_back(OverloadCandidate());
1967 OverloadCandidate& Candidate = CandidateSet.back();
1968 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001969 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00001970 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001971 Candidate.FinalConversion.setAsIdentityConversion();
1972 Candidate.FinalConversion.FromTypePtr
1973 = Conversion->getConversionType().getAsOpaquePtr();
1974 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
1975
Douglas Gregor96176b32008-11-18 23:14:02 +00001976 // Determine the implicit conversion sequence for the implicit
1977 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001978 Candidate.Viable = true;
1979 Candidate.Conversions.resize(1);
Douglas Gregor96176b32008-11-18 23:14:02 +00001980 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001981
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001982 if (Candidate.Conversions[0].ConversionKind
1983 == ImplicitConversionSequence::BadConversion) {
1984 Candidate.Viable = false;
1985 return;
1986 }
1987
1988 // To determine what the conversion from the result of calling the
1989 // conversion function to the type we're eventually trying to
1990 // convert to (ToType), we need to synthesize a call to the
1991 // conversion function and attempt copy initialization from it. This
1992 // makes sure that we get the right semantics with respect to
1993 // lvalues/rvalues and the type. Fortunately, we can allocate this
1994 // call on the stack and we don't need its arguments to be
1995 // well-formed.
1996 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
1997 SourceLocation());
1998 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001999 &ConversionRef, false);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002000 CallExpr Call(&ConversionFn, 0, 0,
2001 Conversion->getConversionType().getNonReferenceType(),
2002 SourceLocation());
2003 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2004 switch (ICS.ConversionKind) {
2005 case ImplicitConversionSequence::StandardConversion:
2006 Candidate.FinalConversion = ICS.Standard;
2007 break;
2008
2009 case ImplicitConversionSequence::BadConversion:
2010 Candidate.Viable = false;
2011 break;
2012
2013 default:
2014 assert(false &&
2015 "Can only end up with a standard conversion sequence or failure");
2016 }
2017}
2018
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002019/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2020/// converts the given @c Object to a function pointer via the
2021/// conversion function @c Conversion, and then attempts to call it
2022/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2023/// the type of function that we'll eventually be calling.
2024void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
2025 const FunctionTypeProto *Proto,
2026 Expr *Object, Expr **Args, unsigned NumArgs,
2027 OverloadCandidateSet& CandidateSet) {
2028 CandidateSet.push_back(OverloadCandidate());
2029 OverloadCandidate& Candidate = CandidateSet.back();
2030 Candidate.Function = 0;
2031 Candidate.Surrogate = Conversion;
2032 Candidate.Viable = true;
2033 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002034 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002035 Candidate.Conversions.resize(NumArgs + 1);
2036
2037 // Determine the implicit conversion sequence for the implicit
2038 // object parameter.
2039 ImplicitConversionSequence ObjectInit
2040 = TryObjectArgumentInitialization(Object, Conversion);
2041 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2042 Candidate.Viable = false;
2043 return;
2044 }
2045
2046 // The first conversion is actually a user-defined conversion whose
2047 // first conversion is ObjectInit's standard conversion (which is
2048 // effectively a reference binding). Record it as such.
2049 Candidate.Conversions[0].ConversionKind
2050 = ImplicitConversionSequence::UserDefinedConversion;
2051 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2052 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2053 Candidate.Conversions[0].UserDefined.After
2054 = Candidate.Conversions[0].UserDefined.Before;
2055 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2056
2057 // Find the
2058 unsigned NumArgsInProto = Proto->getNumArgs();
2059
2060 // (C++ 13.3.2p2): A candidate function having fewer than m
2061 // parameters is viable only if it has an ellipsis in its parameter
2062 // list (8.3.5).
2063 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2064 Candidate.Viable = false;
2065 return;
2066 }
2067
2068 // Function types don't have any default arguments, so just check if
2069 // we have enough arguments.
2070 if (NumArgs < NumArgsInProto) {
2071 // Not enough arguments.
2072 Candidate.Viable = false;
2073 return;
2074 }
2075
2076 // Determine the implicit conversion sequences for each of the
2077 // arguments.
2078 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2079 if (ArgIdx < NumArgsInProto) {
2080 // (C++ 13.3.2p3): for F to be a viable function, there shall
2081 // exist for each argument an implicit conversion sequence
2082 // (13.3.3.1) that converts that argument to the corresponding
2083 // parameter of F.
2084 QualType ParamType = Proto->getArgType(ArgIdx);
2085 Candidate.Conversions[ArgIdx + 1]
2086 = TryCopyInitialization(Args[ArgIdx], ParamType,
2087 /*SuppressUserConversions=*/false);
2088 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2089 == ImplicitConversionSequence::BadConversion) {
2090 Candidate.Viable = false;
2091 break;
2092 }
2093 } else {
2094 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2095 // argument for which there is no corresponding parameter is
2096 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2097 Candidate.Conversions[ArgIdx + 1].ConversionKind
2098 = ImplicitConversionSequence::EllipsisConversion;
2099 }
2100 }
2101}
2102
Douglas Gregor447b69e2008-11-19 03:25:36 +00002103/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2104/// an acceptable non-member overloaded operator for a call whose
2105/// arguments have types T1 (and, if non-empty, T2). This routine
2106/// implements the check in C++ [over.match.oper]p3b2 concerning
2107/// enumeration types.
2108static bool
2109IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2110 QualType T1, QualType T2,
2111 ASTContext &Context) {
2112 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2113 return true;
2114
2115 const FunctionTypeProto *Proto = Fn->getType()->getAsFunctionTypeProto();
2116 if (Proto->getNumArgs() < 1)
2117 return false;
2118
2119 if (T1->isEnumeralType()) {
2120 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
2121 if (Context.getCanonicalType(T1).getUnqualifiedType()
2122 == Context.getCanonicalType(ArgType).getUnqualifiedType())
2123 return true;
2124 }
2125
2126 if (Proto->getNumArgs() < 2)
2127 return false;
2128
2129 if (!T2.isNull() && T2->isEnumeralType()) {
2130 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
2131 if (Context.getCanonicalType(T2).getUnqualifiedType()
2132 == Context.getCanonicalType(ArgType).getUnqualifiedType())
2133 return true;
2134 }
2135
2136 return false;
2137}
2138
Douglas Gregor96176b32008-11-18 23:14:02 +00002139/// AddOperatorCandidates - Add the overloaded operator candidates for
2140/// the operator Op that was used in an operator expression such as "x
2141/// Op y". S is the scope in which the expression occurred (used for
2142/// name lookup of the operator), Args/NumArgs provides the operator
2143/// arguments, and CandidateSet will store the added overload
2144/// candidates. (C++ [over.match.oper]).
2145void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
2146 Expr **Args, unsigned NumArgs,
2147 OverloadCandidateSet& CandidateSet) {
2148 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2149
2150 // C++ [over.match.oper]p3:
2151 // For a unary operator @ with an operand of a type whose
2152 // cv-unqualified version is T1, and for a binary operator @ with
2153 // a left operand of a type whose cv-unqualified version is T1 and
2154 // a right operand of a type whose cv-unqualified version is T2,
2155 // three sets of candidate functions, designated member
2156 // candidates, non-member candidates and built-in candidates, are
2157 // constructed as follows:
2158 QualType T1 = Args[0]->getType();
2159 QualType T2;
2160 if (NumArgs > 1)
2161 T2 = Args[1]->getType();
2162
2163 // -- If T1 is a class type, the set of member candidates is the
2164 // result of the qualified lookup of T1::operator@
2165 // (13.3.1.1.1); otherwise, the set of member candidates is
2166 // empty.
2167 if (const RecordType *T1Rec = T1->getAsRecordType()) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002168 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00002169 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002170 Oper != OperEnd; ++Oper)
2171 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2172 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor96176b32008-11-18 23:14:02 +00002173 /*SuppressUserConversions=*/false);
Douglas Gregor96176b32008-11-18 23:14:02 +00002174 }
2175
2176 // -- The set of non-member candidates is the result of the
2177 // unqualified lookup of operator@ in the context of the
2178 // expression according to the usual rules for name lookup in
2179 // unqualified function calls (3.4.2) except that all member
2180 // functions are ignored. However, if no operand has a class
2181 // type, only those non-member functions in the lookup set
2182 // that have a first parameter of type T1 or “reference to
2183 // (possibly cv-qualified) T1”, when T1 is an enumeration
2184 // type, or (if there is a right operand) a second parameter
2185 // of type T2 or “reference to (possibly cv-qualified) T2”,
2186 // when T2 is an enumeration type, are candidate functions.
2187 {
Douglas Gregor6ed40e32008-12-23 21:05:05 +00002188 IdentifierResolver::iterator
2189 I = IdResolver.begin(OpName, CurContext, true/*LookInParentCtx*/),
2190 IEnd = IdResolver.end();
2191 for (; I != IEnd; ++I) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002192 // We don't need to check the identifier namespace, because
2193 // operator names can only be ordinary identifiers.
2194
2195 // Ignore member functions.
2196 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(*I)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002197 if (SD->getDeclContext()->isRecord())
Douglas Gregor96176b32008-11-18 23:14:02 +00002198 continue;
2199 }
2200
2201 // We found something with this name. We're done.
Douglas Gregor96176b32008-11-18 23:14:02 +00002202 break;
2203 }
2204
Douglas Gregor6ed40e32008-12-23 21:05:05 +00002205 if (I != IEnd && isa<ScopedDecl>(*I)) {
2206 ScopedDecl *FirstDecl = cast<ScopedDecl>(*I);
2207 for (; I != IEnd; ++I) {
2208 ScopedDecl *SD = cast<ScopedDecl>(*I);
2209 if (FirstDecl->getDeclContext() != SD->getDeclContext())
2210 break;
2211
2212 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I))
2213 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
2214 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2215 /*SuppressUserConversions=*/false);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002216 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002217 }
2218 }
2219
2220 // Add builtin overload candidates (C++ [over.built]).
Douglas Gregor74253732008-11-19 15:42:04 +00002221 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
Douglas Gregor96176b32008-11-18 23:14:02 +00002222}
2223
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002224/// AddBuiltinCandidate - Add a candidate for a built-in
2225/// operator. ResultTy and ParamTys are the result and parameter types
2226/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002227/// arguments being passed to the candidate. IsAssignmentOperator
2228/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002229/// operator. NumContextualBoolArguments is the number of arguments
2230/// (at the beginning of the argument list) that will be contextually
2231/// converted to bool.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002232void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2233 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002234 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002235 bool IsAssignmentOperator,
2236 unsigned NumContextualBoolArguments) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002237 // Add this candidate
2238 CandidateSet.push_back(OverloadCandidate());
2239 OverloadCandidate& Candidate = CandidateSet.back();
2240 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00002241 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002242 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002243 Candidate.BuiltinTypes.ResultTy = ResultTy;
2244 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2245 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2246
2247 // Determine the implicit conversion sequences for each of the
2248 // arguments.
2249 Candidate.Viable = true;
2250 Candidate.Conversions.resize(NumArgs);
2251 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002252 // C++ [over.match.oper]p4:
2253 // For the built-in assignment operators, conversions of the
2254 // left operand are restricted as follows:
2255 // -- no temporaries are introduced to hold the left operand, and
2256 // -- no user-defined conversions are applied to the left
2257 // operand to achieve a type match with the left-most
2258 // parameter of a built-in candidate.
2259 //
2260 // We block these conversions by turning off user-defined
2261 // conversions, since that is the only way that initialization of
2262 // a reference to a non-class type can occur from something that
2263 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002264 if (ArgIdx < NumContextualBoolArguments) {
2265 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2266 "Contextual conversion to bool requires bool type");
2267 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2268 } else {
2269 Candidate.Conversions[ArgIdx]
2270 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2271 ArgIdx == 0 && IsAssignmentOperator);
2272 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002273 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002274 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002275 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002276 break;
2277 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002278 }
2279}
2280
2281/// BuiltinCandidateTypeSet - A set of types that will be used for the
2282/// candidate operator functions for built-in operators (C++
2283/// [over.built]). The types are separated into pointer types and
2284/// enumeration types.
2285class BuiltinCandidateTypeSet {
2286 /// TypeSet - A set of types.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002287 typedef llvm::SmallPtrSet<void*, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002288
2289 /// PointerTypes - The set of pointer types that will be used in the
2290 /// built-in candidates.
2291 TypeSet PointerTypes;
2292
2293 /// EnumerationTypes - The set of enumeration types that will be
2294 /// used in the built-in candidates.
2295 TypeSet EnumerationTypes;
2296
2297 /// Context - The AST context in which we will build the type sets.
2298 ASTContext &Context;
2299
2300 bool AddWithMoreQualifiedTypeVariants(QualType Ty);
2301
2302public:
2303 /// iterator - Iterates through the types that are part of the set.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002304 class iterator {
2305 TypeSet::iterator Base;
2306
2307 public:
2308 typedef QualType value_type;
2309 typedef QualType reference;
2310 typedef QualType pointer;
2311 typedef std::ptrdiff_t difference_type;
2312 typedef std::input_iterator_tag iterator_category;
2313
2314 iterator(TypeSet::iterator B) : Base(B) { }
2315
2316 iterator& operator++() {
2317 ++Base;
2318 return *this;
2319 }
2320
2321 iterator operator++(int) {
2322 iterator tmp(*this);
2323 ++(*this);
2324 return tmp;
2325 }
2326
2327 reference operator*() const {
2328 return QualType::getFromOpaquePtr(*Base);
2329 }
2330
2331 pointer operator->() const {
2332 return **this;
2333 }
2334
2335 friend bool operator==(iterator LHS, iterator RHS) {
2336 return LHS.Base == RHS.Base;
2337 }
2338
2339 friend bool operator!=(iterator LHS, iterator RHS) {
2340 return LHS.Base != RHS.Base;
2341 }
2342 };
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002343
2344 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2345
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002346 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2347 bool AllowExplicitConversions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002348
2349 /// pointer_begin - First pointer type found;
2350 iterator pointer_begin() { return PointerTypes.begin(); }
2351
2352 /// pointer_end - Last pointer type found;
2353 iterator pointer_end() { return PointerTypes.end(); }
2354
2355 /// enumeration_begin - First enumeration type found;
2356 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2357
2358 /// enumeration_end - Last enumeration type found;
2359 iterator enumeration_end() { return EnumerationTypes.end(); }
2360};
2361
2362/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2363/// the set of pointer types along with any more-qualified variants of
2364/// that type. For example, if @p Ty is "int const *", this routine
2365/// will add "int const *", "int const volatile *", "int const
2366/// restrict *", and "int const volatile restrict *" to the set of
2367/// pointer types. Returns true if the add of @p Ty itself succeeded,
2368/// false otherwise.
2369bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) {
2370 // Insert this type.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002371 if (!PointerTypes.insert(Ty.getAsOpaquePtr()))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002372 return false;
2373
2374 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2375 QualType PointeeTy = PointerTy->getPointeeType();
2376 // FIXME: Optimize this so that we don't keep trying to add the same types.
2377
2378 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
2379 // with all pointer conversions that don't cast away constness?
2380 if (!PointeeTy.isConstQualified())
2381 AddWithMoreQualifiedTypeVariants
2382 (Context.getPointerType(PointeeTy.withConst()));
2383 if (!PointeeTy.isVolatileQualified())
2384 AddWithMoreQualifiedTypeVariants
2385 (Context.getPointerType(PointeeTy.withVolatile()));
2386 if (!PointeeTy.isRestrictQualified())
2387 AddWithMoreQualifiedTypeVariants
2388 (Context.getPointerType(PointeeTy.withRestrict()));
2389 }
2390
2391 return true;
2392}
2393
2394/// AddTypesConvertedFrom - Add each of the types to which the type @p
2395/// Ty can be implicit converted to the given set of @p Types. We're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002396/// primarily interested in pointer types and enumeration types.
2397/// AllowUserConversions is true if we should look at the conversion
2398/// functions of a class type, and AllowExplicitConversions if we
2399/// should also include the explicit conversion functions of a class
2400/// type.
2401void
2402BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2403 bool AllowUserConversions,
2404 bool AllowExplicitConversions) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002405 // Only deal with canonical types.
2406 Ty = Context.getCanonicalType(Ty);
2407
2408 // Look through reference types; they aren't part of the type of an
2409 // expression for the purposes of conversions.
2410 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2411 Ty = RefTy->getPointeeType();
2412
2413 // We don't care about qualifiers on the type.
2414 Ty = Ty.getUnqualifiedType();
2415
2416 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2417 QualType PointeeTy = PointerTy->getPointeeType();
2418
2419 // Insert our type, and its more-qualified variants, into the set
2420 // of types.
2421 if (!AddWithMoreQualifiedTypeVariants(Ty))
2422 return;
2423
2424 // Add 'cv void*' to our set of types.
2425 if (!Ty->isVoidType()) {
2426 QualType QualVoid
2427 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2428 AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2429 }
2430
2431 // If this is a pointer to a class type, add pointers to its bases
2432 // (with the same level of cv-qualification as the original
2433 // derived class, of course).
2434 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2435 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2436 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2437 Base != ClassDecl->bases_end(); ++Base) {
2438 QualType BaseTy = Context.getCanonicalType(Base->getType());
2439 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2440
2441 // Add the pointer type, recursively, so that we get all of
2442 // the indirect base classes, too.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002443 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002444 }
2445 }
2446 } else if (Ty->isEnumeralType()) {
Douglas Gregorbf3af052008-11-13 20:12:29 +00002447 EnumerationTypes.insert(Ty.getAsOpaquePtr());
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002448 } else if (AllowUserConversions) {
2449 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2450 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2451 // FIXME: Visit conversion functions in the base classes, too.
2452 OverloadedFunctionDecl *Conversions
2453 = ClassDecl->getConversionFunctions();
2454 for (OverloadedFunctionDecl::function_iterator Func
2455 = Conversions->function_begin();
2456 Func != Conversions->function_end(); ++Func) {
2457 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002458 if (AllowExplicitConversions || !Conv->isExplicit())
2459 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002460 }
2461 }
2462 }
2463}
2464
Douglas Gregor74253732008-11-19 15:42:04 +00002465/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2466/// operator overloads to the candidate set (C++ [over.built]), based
2467/// on the operator @p Op and the arguments given. For example, if the
2468/// operator is a binary '+', this routine might add "int
2469/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002470void
Douglas Gregor74253732008-11-19 15:42:04 +00002471Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2472 Expr **Args, unsigned NumArgs,
2473 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002474 // The set of "promoted arithmetic types", which are the arithmetic
2475 // types are that preserved by promotion (C++ [over.built]p2). Note
2476 // that the first few of these types are the promoted integral
2477 // types; these types need to be first.
2478 // FIXME: What about complex?
2479 const unsigned FirstIntegralType = 0;
2480 const unsigned LastIntegralType = 13;
2481 const unsigned FirstPromotedIntegralType = 7,
2482 LastPromotedIntegralType = 13;
2483 const unsigned FirstPromotedArithmeticType = 7,
2484 LastPromotedArithmeticType = 16;
2485 const unsigned NumArithmeticTypes = 16;
2486 QualType ArithmeticTypes[NumArithmeticTypes] = {
2487 Context.BoolTy, Context.CharTy, Context.WCharTy,
2488 Context.SignedCharTy, Context.ShortTy,
2489 Context.UnsignedCharTy, Context.UnsignedShortTy,
2490 Context.IntTy, Context.LongTy, Context.LongLongTy,
2491 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2492 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2493 };
2494
2495 // Find all of the types that the arguments can convert to, but only
2496 // if the operator we're looking at has built-in operator candidates
2497 // that make use of these types.
2498 BuiltinCandidateTypeSet CandidateTypes(Context);
2499 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2500 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00002501 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002502 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00002503 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
2504 (Op == OO_Star && NumArgs == 1)) {
2505 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002506 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2507 true,
2508 (Op == OO_Exclaim ||
2509 Op == OO_AmpAmp ||
2510 Op == OO_PipePipe));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002511 }
2512
2513 bool isComparison = false;
2514 switch (Op) {
2515 case OO_None:
2516 case NUM_OVERLOADED_OPERATORS:
2517 assert(false && "Expected an overloaded operator");
2518 break;
2519
Douglas Gregor74253732008-11-19 15:42:04 +00002520 case OO_Star: // '*' is either unary or binary
2521 if (NumArgs == 1)
2522 goto UnaryStar;
2523 else
2524 goto BinaryStar;
2525 break;
2526
2527 case OO_Plus: // '+' is either unary or binary
2528 if (NumArgs == 1)
2529 goto UnaryPlus;
2530 else
2531 goto BinaryPlus;
2532 break;
2533
2534 case OO_Minus: // '-' is either unary or binary
2535 if (NumArgs == 1)
2536 goto UnaryMinus;
2537 else
2538 goto BinaryMinus;
2539 break;
2540
2541 case OO_Amp: // '&' is either unary or binary
2542 if (NumArgs == 1)
2543 goto UnaryAmp;
2544 else
2545 goto BinaryAmp;
2546
2547 case OO_PlusPlus:
2548 case OO_MinusMinus:
2549 // C++ [over.built]p3:
2550 //
2551 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2552 // is either volatile or empty, there exist candidate operator
2553 // functions of the form
2554 //
2555 // VQ T& operator++(VQ T&);
2556 // T operator++(VQ T&, int);
2557 //
2558 // C++ [over.built]p4:
2559 //
2560 // For every pair (T, VQ), where T is an arithmetic type other
2561 // than bool, and VQ is either volatile or empty, there exist
2562 // candidate operator functions of the form
2563 //
2564 // VQ T& operator--(VQ T&);
2565 // T operator--(VQ T&, int);
2566 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2567 Arith < NumArithmeticTypes; ++Arith) {
2568 QualType ArithTy = ArithmeticTypes[Arith];
2569 QualType ParamTypes[2]
2570 = { Context.getReferenceType(ArithTy), Context.IntTy };
2571
2572 // Non-volatile version.
2573 if (NumArgs == 1)
2574 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2575 else
2576 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2577
2578 // Volatile version
2579 ParamTypes[0] = Context.getReferenceType(ArithTy.withVolatile());
2580 if (NumArgs == 1)
2581 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2582 else
2583 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2584 }
2585
2586 // C++ [over.built]p5:
2587 //
2588 // For every pair (T, VQ), where T is a cv-qualified or
2589 // cv-unqualified object type, and VQ is either volatile or
2590 // empty, there exist candidate operator functions of the form
2591 //
2592 // T*VQ& operator++(T*VQ&);
2593 // T*VQ& operator--(T*VQ&);
2594 // T* operator++(T*VQ&, int);
2595 // T* operator--(T*VQ&, int);
2596 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2597 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2598 // Skip pointer types that aren't pointers to object types.
Douglas Gregorcb7de522008-11-26 23:31:11 +00002599 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00002600 continue;
2601
2602 QualType ParamTypes[2] = {
2603 Context.getReferenceType(*Ptr), Context.IntTy
2604 };
2605
2606 // Without volatile
2607 if (NumArgs == 1)
2608 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2609 else
2610 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2611
2612 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2613 // With volatile
2614 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2615 if (NumArgs == 1)
2616 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2617 else
2618 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2619 }
2620 }
2621 break;
2622
2623 UnaryStar:
2624 // C++ [over.built]p6:
2625 // For every cv-qualified or cv-unqualified object type T, there
2626 // exist candidate operator functions of the form
2627 //
2628 // T& operator*(T*);
2629 //
2630 // C++ [over.built]p7:
2631 // For every function type T, there exist candidate operator
2632 // functions of the form
2633 // T& operator*(T*);
2634 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2635 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2636 QualType ParamTy = *Ptr;
2637 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
2638 AddBuiltinCandidate(Context.getReferenceType(PointeeTy),
2639 &ParamTy, Args, 1, CandidateSet);
2640 }
2641 break;
2642
2643 UnaryPlus:
2644 // C++ [over.built]p8:
2645 // For every type T, there exist candidate operator functions of
2646 // the form
2647 //
2648 // T* operator+(T*);
2649 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2650 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2651 QualType ParamTy = *Ptr;
2652 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2653 }
2654
2655 // Fall through
2656
2657 UnaryMinus:
2658 // C++ [over.built]p9:
2659 // For every promoted arithmetic type T, there exist candidate
2660 // operator functions of the form
2661 //
2662 // T operator+(T);
2663 // T operator-(T);
2664 for (unsigned Arith = FirstPromotedArithmeticType;
2665 Arith < LastPromotedArithmeticType; ++Arith) {
2666 QualType ArithTy = ArithmeticTypes[Arith];
2667 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2668 }
2669 break;
2670
2671 case OO_Tilde:
2672 // C++ [over.built]p10:
2673 // For every promoted integral type T, there exist candidate
2674 // operator functions of the form
2675 //
2676 // T operator~(T);
2677 for (unsigned Int = FirstPromotedIntegralType;
2678 Int < LastPromotedIntegralType; ++Int) {
2679 QualType IntTy = ArithmeticTypes[Int];
2680 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2681 }
2682 break;
2683
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002684 case OO_New:
2685 case OO_Delete:
2686 case OO_Array_New:
2687 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002688 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00002689 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002690 break;
2691
2692 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00002693 UnaryAmp:
2694 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002695 // C++ [over.match.oper]p3:
2696 // -- For the operator ',', the unary operator '&', or the
2697 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002698 break;
2699
2700 case OO_Less:
2701 case OO_Greater:
2702 case OO_LessEqual:
2703 case OO_GreaterEqual:
2704 case OO_EqualEqual:
2705 case OO_ExclaimEqual:
2706 // C++ [over.built]p15:
2707 //
2708 // For every pointer or enumeration type T, there exist
2709 // candidate operator functions of the form
2710 //
2711 // bool operator<(T, T);
2712 // bool operator>(T, T);
2713 // bool operator<=(T, T);
2714 // bool operator>=(T, T);
2715 // bool operator==(T, T);
2716 // bool operator!=(T, T);
2717 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2718 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2719 QualType ParamTypes[2] = { *Ptr, *Ptr };
2720 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2721 }
2722 for (BuiltinCandidateTypeSet::iterator Enum
2723 = CandidateTypes.enumeration_begin();
2724 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2725 QualType ParamTypes[2] = { *Enum, *Enum };
2726 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2727 }
2728
2729 // Fall through.
2730 isComparison = true;
2731
Douglas Gregor74253732008-11-19 15:42:04 +00002732 BinaryPlus:
2733 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002734 if (!isComparison) {
2735 // We didn't fall through, so we must have OO_Plus or OO_Minus.
2736
2737 // C++ [over.built]p13:
2738 //
2739 // For every cv-qualified or cv-unqualified object type T
2740 // there exist candidate operator functions of the form
2741 //
2742 // T* operator+(T*, ptrdiff_t);
2743 // T& operator[](T*, ptrdiff_t); [BELOW]
2744 // T* operator-(T*, ptrdiff_t);
2745 // T* operator+(ptrdiff_t, T*);
2746 // T& operator[](ptrdiff_t, T*); [BELOW]
2747 //
2748 // C++ [over.built]p14:
2749 //
2750 // For every T, where T is a pointer to object type, there
2751 // exist candidate operator functions of the form
2752 //
2753 // ptrdiff_t operator-(T, T);
2754 for (BuiltinCandidateTypeSet::iterator Ptr
2755 = CandidateTypes.pointer_begin();
2756 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2757 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2758
2759 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
2760 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2761
2762 if (Op == OO_Plus) {
2763 // T* operator+(ptrdiff_t, T*);
2764 ParamTypes[0] = ParamTypes[1];
2765 ParamTypes[1] = *Ptr;
2766 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2767 } else {
2768 // ptrdiff_t operator-(T, T);
2769 ParamTypes[1] = *Ptr;
2770 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
2771 Args, 2, CandidateSet);
2772 }
2773 }
2774 }
2775 // Fall through
2776
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002777 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00002778 BinaryStar:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002779 // C++ [over.built]p12:
2780 //
2781 // For every pair of promoted arithmetic types L and R, there
2782 // exist candidate operator functions of the form
2783 //
2784 // LR operator*(L, R);
2785 // LR operator/(L, R);
2786 // LR operator+(L, R);
2787 // LR operator-(L, R);
2788 // bool operator<(L, R);
2789 // bool operator>(L, R);
2790 // bool operator<=(L, R);
2791 // bool operator>=(L, R);
2792 // bool operator==(L, R);
2793 // bool operator!=(L, R);
2794 //
2795 // where LR is the result of the usual arithmetic conversions
2796 // between types L and R.
2797 for (unsigned Left = FirstPromotedArithmeticType;
2798 Left < LastPromotedArithmeticType; ++Left) {
2799 for (unsigned Right = FirstPromotedArithmeticType;
2800 Right < LastPromotedArithmeticType; ++Right) {
2801 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2802 QualType Result
2803 = isComparison? Context.BoolTy
2804 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2805 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2806 }
2807 }
2808 break;
2809
2810 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00002811 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002812 case OO_Caret:
2813 case OO_Pipe:
2814 case OO_LessLess:
2815 case OO_GreaterGreater:
2816 // C++ [over.built]p17:
2817 //
2818 // For every pair of promoted integral types L and R, there
2819 // exist candidate operator functions of the form
2820 //
2821 // LR operator%(L, R);
2822 // LR operator&(L, R);
2823 // LR operator^(L, R);
2824 // LR operator|(L, R);
2825 // L operator<<(L, R);
2826 // L operator>>(L, R);
2827 //
2828 // where LR is the result of the usual arithmetic conversions
2829 // between types L and R.
2830 for (unsigned Left = FirstPromotedIntegralType;
2831 Left < LastPromotedIntegralType; ++Left) {
2832 for (unsigned Right = FirstPromotedIntegralType;
2833 Right < LastPromotedIntegralType; ++Right) {
2834 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2835 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
2836 ? LandR[0]
2837 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2838 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2839 }
2840 }
2841 break;
2842
2843 case OO_Equal:
2844 // C++ [over.built]p20:
2845 //
2846 // For every pair (T, VQ), where T is an enumeration or
2847 // (FIXME:) pointer to member type and VQ is either volatile or
2848 // empty, there exist candidate operator functions of the form
2849 //
2850 // VQ T& operator=(VQ T&, T);
2851 for (BuiltinCandidateTypeSet::iterator Enum
2852 = CandidateTypes.enumeration_begin();
2853 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2854 QualType ParamTypes[2];
2855
2856 // T& operator=(T&, T)
2857 ParamTypes[0] = Context.getReferenceType(*Enum);
2858 ParamTypes[1] = *Enum;
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002859 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002860 /*IsAssignmentOperator=*/false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002861
Douglas Gregor74253732008-11-19 15:42:04 +00002862 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
2863 // volatile T& operator=(volatile T&, T)
2864 ParamTypes[0] = Context.getReferenceType((*Enum).withVolatile());
2865 ParamTypes[1] = *Enum;
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002866 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002867 /*IsAssignmentOperator=*/false);
Douglas Gregor74253732008-11-19 15:42:04 +00002868 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002869 }
2870 // Fall through.
2871
2872 case OO_PlusEqual:
2873 case OO_MinusEqual:
2874 // C++ [over.built]p19:
2875 //
2876 // For every pair (T, VQ), where T is any type and VQ is either
2877 // volatile or empty, there exist candidate operator functions
2878 // of the form
2879 //
2880 // T*VQ& operator=(T*VQ&, T*);
2881 //
2882 // C++ [over.built]p21:
2883 //
2884 // For every pair (T, VQ), where T is a cv-qualified or
2885 // cv-unqualified object type and VQ is either volatile or
2886 // empty, there exist candidate operator functions of the form
2887 //
2888 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
2889 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
2890 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2891 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2892 QualType ParamTypes[2];
2893 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
2894
2895 // non-volatile version
2896 ParamTypes[0] = Context.getReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002897 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2898 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002899
Douglas Gregor74253732008-11-19 15:42:04 +00002900 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2901 // volatile version
2902 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002903 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2904 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00002905 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002906 }
2907 // Fall through.
2908
2909 case OO_StarEqual:
2910 case OO_SlashEqual:
2911 // C++ [over.built]p18:
2912 //
2913 // For every triple (L, VQ, R), where L is an arithmetic type,
2914 // VQ is either volatile or empty, and R is a promoted
2915 // arithmetic type, there exist candidate operator functions of
2916 // the form
2917 //
2918 // VQ L& operator=(VQ L&, R);
2919 // VQ L& operator*=(VQ L&, R);
2920 // VQ L& operator/=(VQ L&, R);
2921 // VQ L& operator+=(VQ L&, R);
2922 // VQ L& operator-=(VQ L&, R);
2923 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
2924 for (unsigned Right = FirstPromotedArithmeticType;
2925 Right < LastPromotedArithmeticType; ++Right) {
2926 QualType ParamTypes[2];
2927 ParamTypes[1] = ArithmeticTypes[Right];
2928
2929 // Add this built-in operator as a candidate (VQ is empty).
2930 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002931 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2932 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002933
2934 // Add this built-in operator as a candidate (VQ is 'volatile').
2935 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
2936 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002937 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2938 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002939 }
2940 }
2941 break;
2942
2943 case OO_PercentEqual:
2944 case OO_LessLessEqual:
2945 case OO_GreaterGreaterEqual:
2946 case OO_AmpEqual:
2947 case OO_CaretEqual:
2948 case OO_PipeEqual:
2949 // C++ [over.built]p22:
2950 //
2951 // For every triple (L, VQ, R), where L is an integral type, VQ
2952 // is either volatile or empty, and R is a promoted integral
2953 // type, there exist candidate operator functions of the form
2954 //
2955 // VQ L& operator%=(VQ L&, R);
2956 // VQ L& operator<<=(VQ L&, R);
2957 // VQ L& operator>>=(VQ L&, R);
2958 // VQ L& operator&=(VQ L&, R);
2959 // VQ L& operator^=(VQ L&, R);
2960 // VQ L& operator|=(VQ L&, R);
2961 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
2962 for (unsigned Right = FirstPromotedIntegralType;
2963 Right < LastPromotedIntegralType; ++Right) {
2964 QualType ParamTypes[2];
2965 ParamTypes[1] = ArithmeticTypes[Right];
2966
2967 // Add this built-in operator as a candidate (VQ is empty).
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002968 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
2969 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2970
2971 // Add this built-in operator as a candidate (VQ is 'volatile').
2972 ParamTypes[0] = ArithmeticTypes[Left];
2973 ParamTypes[0].addVolatile();
2974 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
2975 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2976 }
2977 }
2978 break;
2979
Douglas Gregor74253732008-11-19 15:42:04 +00002980 case OO_Exclaim: {
2981 // C++ [over.operator]p23:
2982 //
2983 // There also exist candidate operator functions of the form
2984 //
2985 // bool operator!(bool);
2986 // bool operator&&(bool, bool); [BELOW]
2987 // bool operator||(bool, bool); [BELOW]
2988 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002989 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
2990 /*IsAssignmentOperator=*/false,
2991 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00002992 break;
2993 }
2994
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002995 case OO_AmpAmp:
2996 case OO_PipePipe: {
2997 // C++ [over.operator]p23:
2998 //
2999 // There also exist candidate operator functions of the form
3000 //
Douglas Gregor74253732008-11-19 15:42:04 +00003001 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003002 // bool operator&&(bool, bool);
3003 // bool operator||(bool, bool);
3004 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003005 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3006 /*IsAssignmentOperator=*/false,
3007 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003008 break;
3009 }
3010
3011 case OO_Subscript:
3012 // C++ [over.built]p13:
3013 //
3014 // For every cv-qualified or cv-unqualified object type T there
3015 // exist candidate operator functions of the form
3016 //
3017 // T* operator+(T*, ptrdiff_t); [ABOVE]
3018 // T& operator[](T*, ptrdiff_t);
3019 // T* operator-(T*, ptrdiff_t); [ABOVE]
3020 // T* operator+(ptrdiff_t, T*); [ABOVE]
3021 // T& operator[](ptrdiff_t, T*);
3022 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3023 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3024 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3025 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
3026 QualType ResultTy = Context.getReferenceType(PointeeType);
3027
3028 // T& operator[](T*, ptrdiff_t)
3029 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3030
3031 // T& operator[](ptrdiff_t, T*);
3032 ParamTypes[0] = ParamTypes[1];
3033 ParamTypes[1] = *Ptr;
3034 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3035 }
3036 break;
3037
3038 case OO_ArrowStar:
3039 // FIXME: No support for pointer-to-members yet.
3040 break;
3041 }
3042}
3043
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003044/// AddOverloadCandidates - Add all of the function overloads in Ovl
3045/// to the candidate set.
3046void
Douglas Gregor18fe5682008-11-03 20:45:27 +00003047Sema::AddOverloadCandidates(const OverloadedFunctionDecl *Ovl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003048 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00003049 OverloadCandidateSet& CandidateSet,
3050 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003051{
Douglas Gregor18fe5682008-11-03 20:45:27 +00003052 for (OverloadedFunctionDecl::function_const_iterator Func
3053 = Ovl->function_begin();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003054 Func != Ovl->function_end(); ++Func)
Douglas Gregor225c41e2008-11-03 19:09:14 +00003055 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet,
3056 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003057}
3058
3059/// isBetterOverloadCandidate - Determines whether the first overload
3060/// candidate is a better candidate than the second (C++ 13.3.3p1).
3061bool
3062Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3063 const OverloadCandidate& Cand2)
3064{
3065 // Define viable functions to be better candidates than non-viable
3066 // functions.
3067 if (!Cand2.Viable)
3068 return Cand1.Viable;
3069 else if (!Cand1.Viable)
3070 return false;
3071
Douglas Gregor88a35142008-12-22 05:46:06 +00003072 // C++ [over.match.best]p1:
3073 //
3074 // -- if F is a static member function, ICS1(F) is defined such
3075 // that ICS1(F) is neither better nor worse than ICS1(G) for
3076 // any function G, and, symmetrically, ICS1(G) is neither
3077 // better nor worse than ICS1(F).
3078 unsigned StartArg = 0;
3079 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3080 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003081
3082 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
3083 // function than another viable function F2 if for all arguments i,
3084 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
3085 // then...
3086 unsigned NumArgs = Cand1.Conversions.size();
3087 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3088 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003089 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003090 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3091 Cand2.Conversions[ArgIdx])) {
3092 case ImplicitConversionSequence::Better:
3093 // Cand1 has a better conversion sequence.
3094 HasBetterConversion = true;
3095 break;
3096
3097 case ImplicitConversionSequence::Worse:
3098 // Cand1 can't be better than Cand2.
3099 return false;
3100
3101 case ImplicitConversionSequence::Indistinguishable:
3102 // Do nothing.
3103 break;
3104 }
3105 }
3106
3107 if (HasBetterConversion)
3108 return true;
3109
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003110 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
3111 // implemented, but they require template support.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003112
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003113 // C++ [over.match.best]p1b4:
3114 //
3115 // -- the context is an initialization by user-defined conversion
3116 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3117 // from the return type of F1 to the destination type (i.e.,
3118 // the type of the entity being initialized) is a better
3119 // conversion sequence than the standard conversion sequence
3120 // from the return type of F2 to the destination type.
Douglas Gregor447b69e2008-11-19 03:25:36 +00003121 if (Cand1.Function && Cand2.Function &&
3122 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003123 isa<CXXConversionDecl>(Cand2.Function)) {
3124 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3125 Cand2.FinalConversion)) {
3126 case ImplicitConversionSequence::Better:
3127 // Cand1 has a better conversion sequence.
3128 return true;
3129
3130 case ImplicitConversionSequence::Worse:
3131 // Cand1 can't be better than Cand2.
3132 return false;
3133
3134 case ImplicitConversionSequence::Indistinguishable:
3135 // Do nothing
3136 break;
3137 }
3138 }
3139
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003140 return false;
3141}
3142
3143/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
3144/// within an overload candidate set. If overloading is successful,
3145/// the result will be OR_Success and Best will be set to point to the
3146/// best viable function within the candidate set. Otherwise, one of
3147/// several kinds of errors will be returned; see
3148/// Sema::OverloadingResult.
3149Sema::OverloadingResult
3150Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
3151 OverloadCandidateSet::iterator& Best)
3152{
3153 // Find the best viable function.
3154 Best = CandidateSet.end();
3155 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3156 Cand != CandidateSet.end(); ++Cand) {
3157 if (Cand->Viable) {
3158 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3159 Best = Cand;
3160 }
3161 }
3162
3163 // If we didn't find any viable functions, abort.
3164 if (Best == CandidateSet.end())
3165 return OR_No_Viable_Function;
3166
3167 // Make sure that this function is better than every other viable
3168 // function. If not, we have an ambiguity.
3169 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3170 Cand != CandidateSet.end(); ++Cand) {
3171 if (Cand->Viable &&
3172 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003173 !isBetterOverloadCandidate(*Best, *Cand)) {
3174 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003175 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003176 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003177 }
3178
3179 // Best is the best viable function.
3180 return OR_Success;
3181}
3182
3183/// PrintOverloadCandidates - When overload resolution fails, prints
3184/// diagnostic messages containing the candidates in the candidate
3185/// set. If OnlyViable is true, only viable candidates will be printed.
3186void
3187Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3188 bool OnlyViable)
3189{
3190 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3191 LastCand = CandidateSet.end();
3192 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003193 if (Cand->Viable || !OnlyViable) {
3194 if (Cand->Function) {
3195 // Normal function
3196 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003197 } else if (Cand->IsSurrogate) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003198 // Desugar the type of the surrogate down to a function type,
3199 // retaining as many typedefs as possible while still showing
3200 // the function type (and, therefore, its parameter types).
3201 QualType FnType = Cand->Surrogate->getConversionType();
3202 bool isReference = false;
3203 bool isPointer = false;
3204 if (const ReferenceType *FnTypeRef = FnType->getAsReferenceType()) {
3205 FnType = FnTypeRef->getPointeeType();
3206 isReference = true;
3207 }
3208 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
3209 FnType = FnTypePtr->getPointeeType();
3210 isPointer = true;
3211 }
3212 // Desugar down to a function type.
3213 FnType = QualType(FnType->getAsFunctionType(), 0);
3214 // Reconstruct the pointer/reference as appropriate.
3215 if (isPointer) FnType = Context.getPointerType(FnType);
3216 if (isReference) FnType = Context.getReferenceType(FnType);
3217
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003218 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003219 << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003220 } else {
3221 // FIXME: We need to get the identifier in here
3222 // FIXME: Do we want the error message to point at the
3223 // operator? (built-ins won't have a location)
3224 QualType FnType
3225 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3226 Cand->BuiltinTypes.ParamTypes,
3227 Cand->Conversions.size(),
3228 false, 0);
3229
Chris Lattnerd1625842008-11-24 06:25:27 +00003230 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003231 }
3232 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003233 }
3234}
3235
Douglas Gregor904eed32008-11-10 20:40:00 +00003236/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3237/// an overloaded function (C++ [over.over]), where @p From is an
3238/// expression with overloaded function type and @p ToType is the type
3239/// we're trying to resolve to. For example:
3240///
3241/// @code
3242/// int f(double);
3243/// int f(int);
3244///
3245/// int (*pfd)(double) = f; // selects f(double)
3246/// @endcode
3247///
3248/// This routine returns the resulting FunctionDecl if it could be
3249/// resolved, and NULL otherwise. When @p Complain is true, this
3250/// routine will emit diagnostics if there is an error.
3251FunctionDecl *
3252Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
3253 bool Complain) {
3254 QualType FunctionType = ToType;
3255 if (const PointerLikeType *ToTypePtr = ToType->getAsPointerLikeType())
3256 FunctionType = ToTypePtr->getPointeeType();
3257
3258 // We only look at pointers or references to functions.
3259 if (!FunctionType->isFunctionType())
3260 return 0;
3261
3262 // Find the actual overloaded function declaration.
3263 OverloadedFunctionDecl *Ovl = 0;
3264
3265 // C++ [over.over]p1:
3266 // [...] [Note: any redundant set of parentheses surrounding the
3267 // overloaded function name is ignored (5.1). ]
3268 Expr *OvlExpr = From->IgnoreParens();
3269
3270 // C++ [over.over]p1:
3271 // [...] The overloaded function name can be preceded by the &
3272 // operator.
3273 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3274 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3275 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3276 }
3277
3278 // Try to dig out the overloaded function.
3279 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
3280 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
3281
3282 // If there's no overloaded function declaration, we're done.
3283 if (!Ovl)
3284 return 0;
3285
3286 // Look through all of the overloaded functions, searching for one
3287 // whose type matches exactly.
3288 // FIXME: When templates or using declarations come along, we'll actually
3289 // have to deal with duplicates, partial ordering, etc. For now, we
3290 // can just do a simple search.
3291 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
3292 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
3293 Fun != Ovl->function_end(); ++Fun) {
3294 // C++ [over.over]p3:
3295 // Non-member functions and static member functions match
3296 // targets of type “pointer-to-function”or
3297 // “reference-to-function.”
3298 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun))
3299 if (!Method->isStatic())
3300 continue;
3301
3302 if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
3303 return *Fun;
3304 }
3305
3306 return 0;
3307}
3308
Douglas Gregorf6b89692008-11-26 05:54:23 +00003309/// ResolveOverloadedCallFn - Given the call expression that calls Fn
3310/// (which eventually refers to the set of overloaded functions in
3311/// Ovl) and the call arguments Args/NumArgs, attempt to resolve the
3312/// function call down to a specific function. If overload resolution
Douglas Gregor0a396682008-11-26 06:01:48 +00003313/// succeeds, returns the function declaration produced by overload
3314/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00003315/// arguments and Fn, and returns NULL.
Douglas Gregor0a396682008-11-26 06:01:48 +00003316FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, OverloadedFunctionDecl *Ovl,
3317 SourceLocation LParenLoc,
3318 Expr **Args, unsigned NumArgs,
3319 SourceLocation *CommaLocs,
3320 SourceLocation RParenLoc) {
Douglas Gregorf6b89692008-11-26 05:54:23 +00003321 OverloadCandidateSet CandidateSet;
3322 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet);
3323 OverloadCandidateSet::iterator Best;
3324 switch (BestViableFunction(CandidateSet, Best)) {
Douglas Gregor0a396682008-11-26 06:01:48 +00003325 case OR_Success:
3326 return Best->Function;
Douglas Gregorf6b89692008-11-26 05:54:23 +00003327
3328 case OR_No_Viable_Function:
3329 Diag(Fn->getSourceRange().getBegin(),
3330 diag::err_ovl_no_viable_function_in_call)
3331 << Ovl->getDeclName() << (unsigned)CandidateSet.size()
3332 << Fn->getSourceRange();
3333 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3334 break;
3335
3336 case OR_Ambiguous:
3337 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
3338 << Ovl->getDeclName() << Fn->getSourceRange();
3339 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3340 break;
3341 }
3342
3343 // Overload resolution failed. Destroy all of the subexpressions and
3344 // return NULL.
3345 Fn->Destroy(Context);
3346 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3347 Args[Arg]->Destroy(Context);
3348 return 0;
3349}
3350
Douglas Gregor88a35142008-12-22 05:46:06 +00003351/// BuildCallToMemberFunction - Build a call to a member
3352/// function. MemExpr is the expression that refers to the member
3353/// function (and includes the object parameter), Args/NumArgs are the
3354/// arguments to the function call (not including the object
3355/// parameter). The caller needs to validate that the member
3356/// expression refers to a member function or an overloaded member
3357/// function.
3358Sema::ExprResult
3359Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
3360 SourceLocation LParenLoc, Expr **Args,
3361 unsigned NumArgs, SourceLocation *CommaLocs,
3362 SourceLocation RParenLoc) {
3363 // Dig out the member expression. This holds both the object
3364 // argument and the member function we're referring to.
3365 MemberExpr *MemExpr = 0;
3366 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
3367 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
3368 else
3369 MemExpr = dyn_cast<MemberExpr>(MemExprE);
3370 assert(MemExpr && "Building member call without member expression");
3371
3372 // Extract the object argument.
3373 Expr *ObjectArg = MemExpr->getBase();
3374 if (MemExpr->isArrow())
3375 ObjectArg = new UnaryOperator(ObjectArg, UnaryOperator::Deref,
3376 ObjectArg->getType()->getAsPointerType()->getPointeeType(),
3377 SourceLocation());
3378 CXXMethodDecl *Method = 0;
3379 if (OverloadedFunctionDecl *Ovl
3380 = dyn_cast<OverloadedFunctionDecl>(MemExpr->getMemberDecl())) {
3381 // Add overload candidates
3382 OverloadCandidateSet CandidateSet;
3383 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3384 FuncEnd = Ovl->function_end();
3385 Func != FuncEnd; ++Func) {
3386 assert(isa<CXXMethodDecl>(*Func) && "Function is not a method");
3387 Method = cast<CXXMethodDecl>(*Func);
3388 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
3389 /*SuppressUserConversions=*/false);
3390 }
3391
3392 OverloadCandidateSet::iterator Best;
3393 switch (BestViableFunction(CandidateSet, Best)) {
3394 case OR_Success:
3395 Method = cast<CXXMethodDecl>(Best->Function);
3396 break;
3397
3398 case OR_No_Viable_Function:
3399 Diag(MemExpr->getSourceRange().getBegin(),
3400 diag::err_ovl_no_viable_member_function_in_call)
3401 << Ovl->getDeclName() << (unsigned)CandidateSet.size()
3402 << MemExprE->getSourceRange();
3403 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3404 // FIXME: Leaking incoming expressions!
3405 return true;
3406
3407 case OR_Ambiguous:
3408 Diag(MemExpr->getSourceRange().getBegin(),
3409 diag::err_ovl_ambiguous_member_call)
3410 << Ovl->getDeclName() << MemExprE->getSourceRange();
3411 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3412 // FIXME: Leaking incoming expressions!
3413 return true;
3414 }
3415
3416 FixOverloadedFunctionReference(MemExpr, Method);
3417 } else {
3418 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
3419 }
3420
3421 assert(Method && "Member call to something that isn't a method?");
3422 llvm::OwningPtr<CXXMemberCallExpr>
3423 TheCall(new CXXMemberCallExpr(MemExpr, Args, NumArgs,
3424 Method->getResultType().getNonReferenceType(),
3425 RParenLoc));
3426
3427 // Convert the object argument (for a non-static member function call).
3428 if (!Method->isStatic() &&
3429 PerformObjectArgumentInitialization(ObjectArg, Method))
3430 return true;
3431 MemExpr->setBase(ObjectArg);
3432
3433 // Convert the rest of the arguments
3434 const FunctionTypeProto *Proto = cast<FunctionTypeProto>(Method->getType());
3435 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
3436 RParenLoc))
3437 return true;
3438
3439 return CheckFunctionCall(Method, TheCall.take());
3440}
3441
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003442/// BuildCallToObjectOfClassType - Build a call to an object of class
3443/// type (C++ [over.call.object]), which can end up invoking an
3444/// overloaded function call operator (@c operator()) or performing a
3445/// user-defined conversion on the object argument.
Douglas Gregor88a35142008-12-22 05:46:06 +00003446Sema::ExprResult
Douglas Gregor5c37de72008-12-06 00:22:45 +00003447Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
3448 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003449 Expr **Args, unsigned NumArgs,
3450 SourceLocation *CommaLocs,
3451 SourceLocation RParenLoc) {
3452 assert(Object->getType()->isRecordType() && "Requires object type argument");
3453 const RecordType *Record = Object->getType()->getAsRecordType();
3454
3455 // C++ [over.call.object]p1:
3456 // If the primary-expression E in the function call syntax
3457 // evaluates to a class object of type “cv T”, then the set of
3458 // candidate functions includes at least the function call
3459 // operators of T. The function call operators of T are obtained by
3460 // ordinary lookup of the name operator() in the context of
3461 // (E).operator().
3462 OverloadCandidateSet CandidateSet;
Douglas Gregor44b43212008-12-11 16:49:14 +00003463 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003464 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00003465 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003466 Oper != OperEnd; ++Oper)
3467 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
3468 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003469
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003470 // C++ [over.call.object]p2:
3471 // In addition, for each conversion function declared in T of the
3472 // form
3473 //
3474 // operator conversion-type-id () cv-qualifier;
3475 //
3476 // where cv-qualifier is the same cv-qualification as, or a
3477 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00003478 // denotes the type "pointer to function of (P1,...,Pn) returning
3479 // R", or the type "reference to pointer to function of
3480 // (P1,...,Pn) returning R", or the type "reference to function
3481 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003482 // is also considered as a candidate function. Similarly,
3483 // surrogate call functions are added to the set of candidate
3484 // functions for each conversion function declared in an
3485 // accessible base class provided the function is not hidden
3486 // within T by another intervening declaration.
3487 //
3488 // FIXME: Look in base classes for more conversion operators!
3489 OverloadedFunctionDecl *Conversions
3490 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor621b3932008-11-21 02:54:28 +00003491 for (OverloadedFunctionDecl::function_iterator
3492 Func = Conversions->function_begin(),
3493 FuncEnd = Conversions->function_end();
3494 Func != FuncEnd; ++Func) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003495 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
3496
3497 // Strip the reference type (if any) and then the pointer type (if
3498 // any) to get down to what might be a function type.
3499 QualType ConvType = Conv->getConversionType().getNonReferenceType();
3500 if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
3501 ConvType = ConvPtrType->getPointeeType();
3502
3503 if (const FunctionTypeProto *Proto = ConvType->getAsFunctionTypeProto())
3504 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
3505 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003506
3507 // Perform overload resolution.
3508 OverloadCandidateSet::iterator Best;
3509 switch (BestViableFunction(CandidateSet, Best)) {
3510 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003511 // Overload resolution succeeded; we'll build the appropriate call
3512 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003513 break;
3514
3515 case OR_No_Viable_Function:
Sebastian Redle4c452c2008-11-22 13:44:36 +00003516 Diag(Object->getSourceRange().getBegin(),
3517 diag::err_ovl_no_viable_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00003518 << Object->getType() << (unsigned)CandidateSet.size()
Sebastian Redle4c452c2008-11-22 13:44:36 +00003519 << Object->getSourceRange();
3520 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003521 break;
3522
3523 case OR_Ambiguous:
3524 Diag(Object->getSourceRange().getBegin(),
3525 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00003526 << Object->getType() << Object->getSourceRange();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003527 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3528 break;
3529 }
3530
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003531 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003532 // We had an error; delete all of the subexpressions and return
3533 // the error.
3534 delete Object;
3535 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3536 delete Args[ArgIdx];
3537 return true;
3538 }
3539
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003540 if (Best->Function == 0) {
3541 // Since there is no function declaration, this is one of the
3542 // surrogate candidates. Dig out the conversion function.
3543 CXXConversionDecl *Conv
3544 = cast<CXXConversionDecl>(
3545 Best->Conversions[0].UserDefined.ConversionFunction);
3546
3547 // We selected one of the surrogate functions that converts the
3548 // object parameter to a function pointer. Perform the conversion
3549 // on the object argument, then let ActOnCallExpr finish the job.
3550 // FIXME: Represent the user-defined conversion in the AST!
3551 ImpCastExprToType(Object,
3552 Conv->getConversionType().getNonReferenceType(),
3553 Conv->getConversionType()->isReferenceType());
Douglas Gregor5c37de72008-12-06 00:22:45 +00003554 return ActOnCallExpr(S, (ExprTy*)Object, LParenLoc, (ExprTy**)Args, NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003555 CommaLocs, RParenLoc);
3556 }
3557
3558 // We found an overloaded operator(). Build a CXXOperatorCallExpr
3559 // that calls this method, using Object for the implicit object
3560 // parameter and passing along the remaining arguments.
3561 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003562 const FunctionTypeProto *Proto = Method->getType()->getAsFunctionTypeProto();
3563
3564 unsigned NumArgsInProto = Proto->getNumArgs();
3565 unsigned NumArgsToCheck = NumArgs;
3566
3567 // Build the full argument list for the method call (the
3568 // implicit object parameter is placed at the beginning of the
3569 // list).
3570 Expr **MethodArgs;
3571 if (NumArgs < NumArgsInProto) {
3572 NumArgsToCheck = NumArgsInProto;
3573 MethodArgs = new Expr*[NumArgsInProto + 1];
3574 } else {
3575 MethodArgs = new Expr*[NumArgs + 1];
3576 }
3577 MethodArgs[0] = Object;
3578 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3579 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
3580
3581 Expr *NewFn = new DeclRefExpr(Method, Method->getType(),
3582 SourceLocation());
3583 UsualUnaryConversions(NewFn);
3584
3585 // Once we've built TheCall, all of the expressions are properly
3586 // owned.
3587 QualType ResultTy = Method->getResultType().getNonReferenceType();
3588 llvm::OwningPtr<CXXOperatorCallExpr>
3589 TheCall(new CXXOperatorCallExpr(NewFn, MethodArgs, NumArgs + 1,
3590 ResultTy, RParenLoc));
3591 delete [] MethodArgs;
3592
Douglas Gregor518fda12009-01-13 05:10:00 +00003593 // We may have default arguments. If so, we need to allocate more
3594 // slots in the call for them.
3595 if (NumArgs < NumArgsInProto)
3596 TheCall->setNumArgs(NumArgsInProto + 1);
3597 else if (NumArgs > NumArgsInProto)
3598 NumArgsToCheck = NumArgsInProto;
3599
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003600 // Initialize the implicit object parameter.
Douglas Gregor518fda12009-01-13 05:10:00 +00003601 if (PerformObjectArgumentInitialization(Object, Method))
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003602 return true;
3603 TheCall->setArg(0, Object);
3604
3605 // Check the argument types.
3606 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003607 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00003608 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003609 Arg = Args[i];
Douglas Gregor518fda12009-01-13 05:10:00 +00003610
3611 // Pass the argument.
3612 QualType ProtoArgType = Proto->getArgType(i);
3613 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3614 return true;
3615 } else {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003616 Arg = new CXXDefaultArgExpr(Method->getParamDecl(i));
Douglas Gregor518fda12009-01-13 05:10:00 +00003617 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003618
3619 TheCall->setArg(i + 1, Arg);
3620 }
3621
3622 // If this is a variadic call, handle args passed through "...".
3623 if (Proto->isVariadic()) {
3624 // Promote the arguments (C99 6.5.2.2p7).
3625 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3626 Expr *Arg = Args[i];
Anders Carlsson906fed02009-01-13 05:48:52 +00003627
Anders Carlssondce5e2c2009-01-16 16:48:51 +00003628 DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003629 TheCall->setArg(i + 1, Arg);
3630 }
3631 }
3632
3633 return CheckFunctionCall(Method, TheCall.take());
3634}
3635
Douglas Gregor8ba10742008-11-20 16:27:02 +00003636/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
3637/// (if one exists), where @c Base is an expression of class type and
3638/// @c Member is the name of the member we're trying to find.
3639Action::ExprResult
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003640Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
Douglas Gregor8ba10742008-11-20 16:27:02 +00003641 SourceLocation MemberLoc,
3642 IdentifierInfo &Member) {
3643 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
3644
3645 // C++ [over.ref]p1:
3646 //
3647 // [...] An expression x->m is interpreted as (x.operator->())->m
3648 // for a class object x of type T if T::operator->() exists and if
3649 // the operator is selected as the best match function by the
3650 // overload resolution mechanism (13.3).
3651 // FIXME: look in base classes.
3652 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
3653 OverloadCandidateSet CandidateSet;
3654 const RecordType *BaseRecord = Base->getType()->getAsRecordType();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003655
3656 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00003657 for (llvm::tie(Oper, OperEnd) = BaseRecord->getDecl()->lookup(OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003658 Oper != OperEnd; ++Oper)
3659 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00003660 /*SuppressUserConversions=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003661
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003662 llvm::OwningPtr<Expr> BasePtr(Base);
3663
Douglas Gregor8ba10742008-11-20 16:27:02 +00003664 // Perform overload resolution.
3665 OverloadCandidateSet::iterator Best;
3666 switch (BestViableFunction(CandidateSet, Best)) {
3667 case OR_Success:
3668 // Overload resolution succeeded; we'll build the call below.
3669 break;
3670
3671 case OR_No_Viable_Function:
3672 if (CandidateSet.empty())
3673 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattnerd1625842008-11-24 06:25:27 +00003674 << BasePtr->getType() << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003675 else
3676 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Sebastian Redle4c452c2008-11-22 13:44:36 +00003677 << "operator->" << (unsigned)CandidateSet.size()
3678 << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003679 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003680 return true;
3681
3682 case OR_Ambiguous:
3683 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Chris Lattnerd1625842008-11-24 06:25:27 +00003684 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003685 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003686 return true;
3687 }
3688
3689 // Convert the object parameter.
3690 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003691 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregor8ba10742008-11-20 16:27:02 +00003692 return true;
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003693
3694 // No concerns about early exits now.
3695 BasePtr.take();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003696
3697 // Build the operator call.
3698 Expr *FnExpr = new DeclRefExpr(Method, Method->getType(), SourceLocation());
3699 UsualUnaryConversions(FnExpr);
3700 Base = new CXXOperatorCallExpr(FnExpr, &Base, 1,
3701 Method->getResultType().getNonReferenceType(),
3702 OpLoc);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003703 return ActOnMemberReferenceExpr(S, Base, OpLoc, tok::arrow, MemberLoc, Member);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003704}
3705
Douglas Gregor904eed32008-11-10 20:40:00 +00003706/// FixOverloadedFunctionReference - E is an expression that refers to
3707/// a C++ overloaded function (possibly with some parentheses and
3708/// perhaps a '&' around it). We have resolved the overloaded function
3709/// to the function declaration Fn, so patch up the expression E to
3710/// refer (possibly indirectly) to Fn.
3711void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
3712 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
3713 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
3714 E->setType(PE->getSubExpr()->getType());
3715 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
3716 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
3717 "Can only take the address of an overloaded function");
3718 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
3719 E->setType(Context.getPointerType(E->getType()));
3720 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
3721 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
3722 "Expected overloaded function");
3723 DR->setDecl(Fn);
3724 E->setType(Fn->getType());
Douglas Gregor88a35142008-12-22 05:46:06 +00003725 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
3726 MemExpr->setMemberDecl(Fn);
3727 E->setType(Fn->getType());
Douglas Gregor904eed32008-11-10 20:40:00 +00003728 } else {
3729 assert(false && "Invalid reference to overloaded function");
3730 }
3731}
3732
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003733} // end namespace clang