blob: def85ca9e95d5656daa1802eb85783ae0db843a9 [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 Gregor8e9bebd2008-10-21 16:13:35 +000023#include "llvm/Support/Compiler.h"
24#include <algorithm>
25
26namespace clang {
27
28/// GetConversionCategory - Retrieve the implicit conversion
29/// category corresponding to the given implicit conversion kind.
30ImplicitConversionCategory
31GetConversionCategory(ImplicitConversionKind Kind) {
32 static const ImplicitConversionCategory
33 Category[(int)ICK_Num_Conversion_Kinds] = {
34 ICC_Identity,
35 ICC_Lvalue_Transformation,
36 ICC_Lvalue_Transformation,
37 ICC_Lvalue_Transformation,
38 ICC_Qualification_Adjustment,
39 ICC_Promotion,
40 ICC_Promotion,
41 ICC_Conversion,
42 ICC_Conversion,
43 ICC_Conversion,
44 ICC_Conversion,
45 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000046 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000047 ICC_Conversion
48 };
49 return Category[(int)Kind];
50}
51
52/// GetConversionRank - Retrieve the implicit conversion rank
53/// corresponding to the given implicit conversion kind.
54ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
55 static const ImplicitConversionRank
56 Rank[(int)ICK_Num_Conversion_Kinds] = {
57 ICR_Exact_Match,
58 ICR_Exact_Match,
59 ICR_Exact_Match,
60 ICR_Exact_Match,
61 ICR_Exact_Match,
62 ICR_Promotion,
63 ICR_Promotion,
64 ICR_Conversion,
65 ICR_Conversion,
66 ICR_Conversion,
67 ICR_Conversion,
68 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000069 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000070 ICR_Conversion
71 };
72 return Rank[(int)Kind];
73}
74
75/// GetImplicitConversionName - Return the name of this kind of
76/// implicit conversion.
77const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
78 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
79 "No conversion",
80 "Lvalue-to-rvalue",
81 "Array-to-pointer",
82 "Function-to-pointer",
83 "Qualification",
84 "Integral promotion",
85 "Floating point promotion",
86 "Integral conversion",
87 "Floating conversion",
88 "Floating-integral conversion",
89 "Pointer conversion",
90 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +000091 "Boolean conversion",
92 "Derived-to-base conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000093 };
94 return Name[Kind];
95}
96
Douglas Gregor60d62c22008-10-31 16:23:19 +000097/// StandardConversionSequence - Set the standard conversion
98/// sequence to the identity conversion.
99void StandardConversionSequence::setAsIdentityConversion() {
100 First = ICK_Identity;
101 Second = ICK_Identity;
102 Third = ICK_Identity;
103 Deprecated = false;
104 ReferenceBinding = false;
105 DirectBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000106 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000107}
108
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000109/// getRank - Retrieve the rank of this standard conversion sequence
110/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
111/// implicit conversions.
112ImplicitConversionRank StandardConversionSequence::getRank() const {
113 ImplicitConversionRank Rank = ICR_Exact_Match;
114 if (GetConversionRank(First) > Rank)
115 Rank = GetConversionRank(First);
116 if (GetConversionRank(Second) > Rank)
117 Rank = GetConversionRank(Second);
118 if (GetConversionRank(Third) > Rank)
119 Rank = GetConversionRank(Third);
120 return Rank;
121}
122
123/// isPointerConversionToBool - Determines whether this conversion is
124/// a conversion of a pointer or pointer-to-member to bool. This is
125/// used as part of the ranking of standard conversion sequences
126/// (C++ 13.3.3.2p4).
127bool StandardConversionSequence::isPointerConversionToBool() const
128{
129 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
130 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
131
132 // Note that FromType has not necessarily been transformed by the
133 // array-to-pointer or function-to-pointer implicit conversions, so
134 // check for their presence as well as checking whether FromType is
135 // a pointer.
136 if (ToType->isBooleanType() &&
137 (FromType->isPointerType() ||
138 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
139 return true;
140
141 return false;
142}
143
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000144/// isPointerConversionToVoidPointer - Determines whether this
145/// conversion is a conversion of a pointer to a void pointer. This is
146/// used as part of the ranking of standard conversion sequences (C++
147/// 13.3.3.2p4).
148bool
149StandardConversionSequence::
150isPointerConversionToVoidPointer(ASTContext& Context) const
151{
152 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
153 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
154
155 // Note that FromType has not necessarily been transformed by the
156 // array-to-pointer implicit conversion, so check for its presence
157 // and redo the conversion to get a pointer.
158 if (First == ICK_Array_To_Pointer)
159 FromType = Context.getArrayDecayedType(FromType);
160
161 if (Second == ICK_Pointer_Conversion)
162 if (const PointerType* ToPtrType = ToType->getAsPointerType())
163 return ToPtrType->getPointeeType()->isVoidType();
164
165 return false;
166}
167
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000168/// DebugPrint - Print this standard conversion sequence to standard
169/// error. Useful for debugging overloading issues.
170void StandardConversionSequence::DebugPrint() const {
171 bool PrintedSomething = false;
172 if (First != ICK_Identity) {
173 fprintf(stderr, "%s", GetImplicitConversionName(First));
174 PrintedSomething = true;
175 }
176
177 if (Second != ICK_Identity) {
178 if (PrintedSomething) {
179 fprintf(stderr, " -> ");
180 }
181 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregor225c41e2008-11-03 19:09:14 +0000182
183 if (CopyConstructor) {
184 fprintf(stderr, " (by copy constructor)");
185 } else if (DirectBinding) {
186 fprintf(stderr, " (direct reference binding)");
187 } else if (ReferenceBinding) {
188 fprintf(stderr, " (reference binding)");
189 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000190 PrintedSomething = true;
191 }
192
193 if (Third != ICK_Identity) {
194 if (PrintedSomething) {
195 fprintf(stderr, " -> ");
196 }
197 fprintf(stderr, "%s", GetImplicitConversionName(Third));
198 PrintedSomething = true;
199 }
200
201 if (!PrintedSomething) {
202 fprintf(stderr, "No conversions required");
203 }
204}
205
206/// DebugPrint - Print this user-defined conversion sequence to standard
207/// error. Useful for debugging overloading issues.
208void UserDefinedConversionSequence::DebugPrint() const {
209 if (Before.First || Before.Second || Before.Third) {
210 Before.DebugPrint();
211 fprintf(stderr, " -> ");
212 }
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000213 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000214 if (After.First || After.Second || After.Third) {
215 fprintf(stderr, " -> ");
216 After.DebugPrint();
217 }
218}
219
220/// DebugPrint - Print this implicit conversion sequence to standard
221/// error. Useful for debugging overloading issues.
222void ImplicitConversionSequence::DebugPrint() const {
223 switch (ConversionKind) {
224 case StandardConversion:
225 fprintf(stderr, "Standard conversion: ");
226 Standard.DebugPrint();
227 break;
228 case UserDefinedConversion:
229 fprintf(stderr, "User-defined conversion: ");
230 UserDefined.DebugPrint();
231 break;
232 case EllipsisConversion:
233 fprintf(stderr, "Ellipsis conversion");
234 break;
235 case BadConversion:
236 fprintf(stderr, "Bad conversion");
237 break;
238 }
239
240 fprintf(stderr, "\n");
241}
242
243// IsOverload - Determine whether the given New declaration is an
244// overload of the Old declaration. This routine returns false if New
245// and Old cannot be overloaded, e.g., if they are functions with the
246// same signature (C++ 1.3.10) or if the Old declaration isn't a
247// function (or overload set). When it does return false and Old is an
248// OverloadedFunctionDecl, MatchedDecl will be set to point to the
249// FunctionDecl that New cannot be overloaded with.
250//
251// Example: Given the following input:
252//
253// void f(int, float); // #1
254// void f(int, int); // #2
255// int f(int, int); // #3
256//
257// When we process #1, there is no previous declaration of "f",
258// so IsOverload will not be used.
259//
260// When we process #2, Old is a FunctionDecl for #1. By comparing the
261// parameter types, we see that #1 and #2 are overloaded (since they
262// have different signatures), so this routine returns false;
263// MatchedDecl is unchanged.
264//
265// When we process #3, Old is an OverloadedFunctionDecl containing #1
266// and #2. We compare the signatures of #3 to #1 (they're overloaded,
267// so we do nothing) and then #3 to #2. Since the signatures of #3 and
268// #2 are identical (return types of functions are not part of the
269// signature), IsOverload returns false and MatchedDecl will be set to
270// point to the FunctionDecl for #2.
271bool
272Sema::IsOverload(FunctionDecl *New, Decl* OldD,
273 OverloadedFunctionDecl::function_iterator& MatchedDecl)
274{
275 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
276 // Is this new function an overload of every function in the
277 // overload set?
278 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
279 FuncEnd = Ovl->function_end();
280 for (; Func != FuncEnd; ++Func) {
281 if (!IsOverload(New, *Func, MatchedDecl)) {
282 MatchedDecl = Func;
283 return false;
284 }
285 }
286
287 // This function overloads every function in the overload set.
288 return true;
289 } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
290 // Is the function New an overload of the function Old?
291 QualType OldQType = Context.getCanonicalType(Old->getType());
292 QualType NewQType = Context.getCanonicalType(New->getType());
293
294 // Compare the signatures (C++ 1.3.10) of the two functions to
295 // determine whether they are overloads. If we find any mismatch
296 // in the signature, they are overloads.
297
298 // If either of these functions is a K&R-style function (no
299 // prototype), then we consider them to have matching signatures.
300 if (isa<FunctionTypeNoProto>(OldQType.getTypePtr()) ||
301 isa<FunctionTypeNoProto>(NewQType.getTypePtr()))
302 return false;
303
304 FunctionTypeProto* OldType = cast<FunctionTypeProto>(OldQType.getTypePtr());
305 FunctionTypeProto* NewType = cast<FunctionTypeProto>(NewQType.getTypePtr());
306
307 // The signature of a function includes the types of its
308 // parameters (C++ 1.3.10), which includes the presence or absence
309 // of the ellipsis; see C++ DR 357).
310 if (OldQType != NewQType &&
311 (OldType->getNumArgs() != NewType->getNumArgs() ||
312 OldType->isVariadic() != NewType->isVariadic() ||
313 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
314 NewType->arg_type_begin())))
315 return true;
316
317 // If the function is a class member, its signature includes the
318 // cv-qualifiers (if any) on the function itself.
319 //
320 // As part of this, also check whether one of the member functions
321 // is static, in which case they are not overloads (C++
322 // 13.1p2). While not part of the definition of the signature,
323 // this check is important to determine whether these functions
324 // can be overloaded.
325 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
326 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
327 if (OldMethod && NewMethod &&
328 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor1ca50c32008-11-21 15:36:28 +0000329 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000330 return true;
331
332 // The signatures match; this is not an overload.
333 return false;
334 } else {
335 // (C++ 13p1):
336 // Only function declarations can be overloaded; object and type
337 // declarations cannot be overloaded.
338 return false;
339 }
340}
341
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000342/// TryImplicitConversion - Attempt to perform an implicit conversion
343/// from the given expression (Expr) to the given type (ToType). This
344/// function returns an implicit conversion sequence that can be used
345/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000346///
347/// void f(float f);
348/// void g(int i) { f(i); }
349///
350/// this routine would produce an implicit conversion sequence to
351/// describe the initialization of f from i, which will be a standard
352/// conversion sequence containing an lvalue-to-rvalue conversion (C++
353/// 4.1) followed by a floating-integral conversion (C++ 4.9).
354//
355/// Note that this routine only determines how the conversion can be
356/// performed; it does not actually perform the conversion. As such,
357/// it will not produce any diagnostics if no conversion is available,
358/// but will instead return an implicit conversion sequence of kind
359/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000360///
361/// If @p SuppressUserConversions, then user-defined conversions are
362/// not permitted.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000363ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +0000364Sema::TryImplicitConversion(Expr* From, QualType ToType,
365 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000366{
367 ImplicitConversionSequence ICS;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000368 if (IsStandardConversion(From, ToType, ICS.Standard))
369 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000370 else if (!SuppressUserConversions &&
371 IsUserDefinedConversion(From, ToType, ICS.UserDefined)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000372 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000373 // C++ [over.ics.user]p4:
374 // A conversion of an expression of class type to the same class
375 // type is given Exact Match rank, and a conversion of an
376 // expression of class type to a base class of that type is
377 // given Conversion rank, in spite of the fact that a copy
378 // constructor (i.e., a user-defined conversion function) is
379 // called for those cases.
380 if (CXXConstructorDecl *Constructor
381 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
382 if (Constructor->isCopyConstructor(Context)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000383 // Turn this into a "standard" conversion sequence, so that it
384 // gets ranked with standard conversion sequences.
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000385 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
386 ICS.Standard.setAsIdentityConversion();
387 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
388 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000389 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000390 if (IsDerivedFrom(From->getType().getUnqualifiedType(),
391 ToType.getUnqualifiedType()))
392 ICS.Standard.Second = ICK_Derived_To_Base;
393 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000394 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000395 } else
Douglas Gregor60d62c22008-10-31 16:23:19 +0000396 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000397
398 return ICS;
399}
400
401/// IsStandardConversion - Determines whether there is a standard
402/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
403/// expression From to the type ToType. Standard conversion sequences
404/// only consider non-class types; for conversions that involve class
405/// types, use TryImplicitConversion. If a conversion exists, SCS will
406/// contain the standard conversion sequence required to perform this
407/// conversion and this routine will return true. Otherwise, this
408/// routine will return false and the value of SCS is unspecified.
409bool
410Sema::IsStandardConversion(Expr* From, QualType ToType,
411 StandardConversionSequence &SCS)
412{
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000413 QualType FromType = From->getType();
414
Douglas Gregor60d62c22008-10-31 16:23:19 +0000415 // There are no standard conversions for class types, so abort early.
416 if (FromType->isRecordType() || ToType->isRecordType())
417 return false;
418
419 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000420 SCS.setAsIdentityConversion();
Douglas Gregor60d62c22008-10-31 16:23:19 +0000421 SCS.Deprecated = false;
422 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000423 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000424
425 // The first conversion can be an lvalue-to-rvalue conversion,
426 // array-to-pointer conversion, or function-to-pointer conversion
427 // (C++ 4p1).
428
429 // Lvalue-to-rvalue conversion (C++ 4.1):
430 // An lvalue (3.10) of a non-function, non-array type T can be
431 // converted to an rvalue.
432 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
433 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000434 !FromType->isFunctionType() && !FromType->isArrayType() &&
435 !FromType->isOverloadType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000436 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000437
438 // If T is a non-class type, the type of the rvalue is the
439 // cv-unqualified version of T. Otherwise, the type of the rvalue
440 // is T (C++ 4.1p1).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000441 FromType = FromType.getUnqualifiedType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000442 }
443 // Array-to-pointer conversion (C++ 4.2)
444 else if (FromType->isArrayType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000445 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000446
447 // An lvalue or rvalue of type "array of N T" or "array of unknown
448 // bound of T" can be converted to an rvalue of type "pointer to
449 // T" (C++ 4.2p1).
450 FromType = Context.getArrayDecayedType(FromType);
451
452 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
453 // This conversion is deprecated. (C++ D.4).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000454 SCS.Deprecated = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000455
456 // For the purpose of ranking in overload resolution
457 // (13.3.3.1.1), this conversion is considered an
458 // array-to-pointer conversion followed by a qualification
459 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000460 SCS.Second = ICK_Identity;
461 SCS.Third = ICK_Qualification;
462 SCS.ToTypePtr = ToType.getAsOpaquePtr();
463 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000464 }
465 }
466 // Function-to-pointer conversion (C++ 4.3).
467 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000468 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000469
470 // An lvalue of function type T can be converted to an rvalue of
471 // type "pointer to T." The result is a pointer to the
472 // function. (C++ 4.3p1).
473 FromType = Context.getPointerType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000474 }
Douglas Gregor904eed32008-11-10 20:40:00 +0000475 // Address of overloaded function (C++ [over.over]).
476 else if (FunctionDecl *Fn
477 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
478 SCS.First = ICK_Function_To_Pointer;
479
480 // We were able to resolve the address of the overloaded function,
481 // so we can convert to the type of that function.
482 FromType = Fn->getType();
483 if (ToType->isReferenceType())
484 FromType = Context.getReferenceType(FromType);
485 else
486 FromType = Context.getPointerType(FromType);
487 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000488 // We don't require any conversions for the first step.
489 else {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000490 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000491 }
492
493 // The second conversion can be an integral promotion, floating
494 // point promotion, integral conversion, floating point conversion,
495 // floating-integral conversion, pointer conversion,
496 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
497 if (Context.getCanonicalType(FromType).getUnqualifiedType() ==
498 Context.getCanonicalType(ToType).getUnqualifiedType()) {
499 // The unqualified versions of the types are the same: there's no
500 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000501 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000502 }
503 // Integral promotion (C++ 4.5).
504 else if (IsIntegralPromotion(From, FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000505 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000506 FromType = ToType.getUnqualifiedType();
507 }
508 // Floating point promotion (C++ 4.6).
509 else if (IsFloatingPointPromotion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000510 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000511 FromType = ToType.getUnqualifiedType();
512 }
513 // Integral conversions (C++ 4.7).
Sebastian Redl07779722008-10-31 14:43:28 +0000514 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000515 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000516 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000517 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000518 FromType = ToType.getUnqualifiedType();
519 }
520 // Floating point conversions (C++ 4.8).
521 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000522 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000523 FromType = ToType.getUnqualifiedType();
524 }
525 // Floating-integral conversions (C++ 4.9).
Sebastian Redl07779722008-10-31 14:43:28 +0000526 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000527 else if ((FromType->isFloatingType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000528 ToType->isIntegralType() && !ToType->isBooleanType() &&
529 !ToType->isEnumeralType()) ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000530 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
531 ToType->isFloatingType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000532 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000533 FromType = ToType.getUnqualifiedType();
534 }
535 // Pointer conversions (C++ 4.10).
Sebastian Redl07779722008-10-31 14:43:28 +0000536 else if (IsPointerConversion(From, FromType, ToType, FromType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000537 SCS.Second = ICK_Pointer_Conversion;
Sebastian Redl07779722008-10-31 14:43:28 +0000538 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000539 // FIXME: Pointer to member conversions (4.11).
540 // Boolean conversions (C++ 4.12).
541 // FIXME: pointer-to-member type
542 else if (ToType->isBooleanType() &&
543 (FromType->isArithmeticType() ||
544 FromType->isEnumeralType() ||
545 FromType->isPointerType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000546 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000547 FromType = Context.BoolTy;
548 } else {
549 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000550 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000551 }
552
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000553 QualType CanonFrom;
554 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000555 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000556 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000557 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000558 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000559 CanonFrom = Context.getCanonicalType(FromType);
560 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000561 } else {
562 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000563 SCS.Third = ICK_Identity;
564
565 // C++ [over.best.ics]p6:
566 // [...] Any difference in top-level cv-qualification is
567 // subsumed by the initialization itself and does not constitute
568 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000569 CanonFrom = Context.getCanonicalType(FromType);
570 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000571 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000572 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
573 FromType = ToType;
574 CanonFrom = CanonTo;
575 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000576 }
577
578 // If we have not converted the argument type to the parameter type,
579 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000580 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000581 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000582
Douglas Gregor60d62c22008-10-31 16:23:19 +0000583 SCS.ToTypePtr = FromType.getAsOpaquePtr();
584 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000585}
586
587/// IsIntegralPromotion - Determines whether the conversion from the
588/// expression From (whose potentially-adjusted type is FromType) to
589/// ToType is an integral promotion (C++ 4.5). If so, returns true and
590/// sets PromotedType to the promoted type.
591bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
592{
593 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000594 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000595 if (!To) {
596 return false;
597 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000598
599 // An rvalue of type char, signed char, unsigned char, short int, or
600 // unsigned short int can be converted to an rvalue of type int if
601 // int can represent all the values of the source type; otherwise,
602 // the source rvalue can be converted to an rvalue of type unsigned
603 // int (C++ 4.5p1).
Sebastian Redl07779722008-10-31 14:43:28 +0000604 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000605 if (// We can promote any signed, promotable integer type to an int
606 (FromType->isSignedIntegerType() ||
607 // We can promote any unsigned integer type whose size is
608 // less than int to an int.
609 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000610 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000611 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000612 }
613
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000614 return To->getKind() == BuiltinType::UInt;
615 }
616
617 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
618 // can be converted to an rvalue of the first of the following types
619 // that can represent all the values of its underlying type: int,
620 // unsigned int, long, or unsigned long (C++ 4.5p2).
621 if ((FromType->isEnumeralType() || FromType->isWideCharType())
622 && ToType->isIntegerType()) {
623 // Determine whether the type we're converting from is signed or
624 // unsigned.
625 bool FromIsSigned;
626 uint64_t FromSize = Context.getTypeSize(FromType);
627 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
628 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
629 FromIsSigned = UnderlyingType->isSignedIntegerType();
630 } else {
631 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
632 FromIsSigned = true;
633 }
634
635 // The types we'll try to promote to, in the appropriate
636 // order. Try each of these types.
637 QualType PromoteTypes[4] = {
638 Context.IntTy, Context.UnsignedIntTy,
639 Context.LongTy, Context.UnsignedLongTy
640 };
Douglas Gregor447b69e2008-11-19 03:25:36 +0000641 for (int Idx = 0; Idx < 4; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000642 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
643 if (FromSize < ToSize ||
644 (FromSize == ToSize &&
645 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
646 // We found the type that we can promote to. If this is the
647 // type we wanted, we have a promotion. Otherwise, no
648 // promotion.
Sebastian Redl07779722008-10-31 14:43:28 +0000649 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000650 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
651 }
652 }
653 }
654
655 // An rvalue for an integral bit-field (9.6) can be converted to an
656 // rvalue of type int if int can represent all the values of the
657 // bit-field; otherwise, it can be converted to unsigned int if
658 // unsigned int can represent all the values of the bit-field. If
659 // the bit-field is larger yet, no integral promotion applies to
660 // it. If the bit-field has an enumerated type, it is treated as any
661 // other value of that type for promotion purposes (C++ 4.5p3).
662 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) {
663 using llvm::APSInt;
664 FieldDecl *MemberDecl = MemRef->getMemberDecl();
665 APSInt BitWidth;
666 if (MemberDecl->isBitField() &&
667 FromType->isIntegralType() && !FromType->isEnumeralType() &&
668 From->isIntegerConstantExpr(BitWidth, Context)) {
669 APSInt ToSize(Context.getTypeSize(ToType));
670
671 // Are we promoting to an int from a bitfield that fits in an int?
672 if (BitWidth < ToSize ||
Sebastian Redl07779722008-10-31 14:43:28 +0000673 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000674 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000675 }
676
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000677 // Are we promoting to an unsigned int from an unsigned bitfield
678 // that fits into an unsigned int?
Sebastian Redl07779722008-10-31 14:43:28 +0000679 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000680 return To->getKind() == BuiltinType::UInt;
Sebastian Redl07779722008-10-31 14:43:28 +0000681 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000682
683 return false;
684 }
685 }
686
687 // An rvalue of type bool can be converted to an rvalue of type int,
688 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000689 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000690 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000691 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000692
693 return false;
694}
695
696/// IsFloatingPointPromotion - Determines whether the conversion from
697/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
698/// returns true and sets PromotedType to the promoted type.
699bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
700{
701 /// An rvalue of type float can be converted to an rvalue of type
702 /// double. (C++ 4.6p1).
703 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
704 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType())
705 if (FromBuiltin->getKind() == BuiltinType::Float &&
706 ToBuiltin->getKind() == BuiltinType::Double)
707 return true;
708
709 return false;
710}
711
Douglas Gregorcb7de522008-11-26 23:31:11 +0000712/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
713/// the pointer type FromPtr to a pointer to type ToPointee, with the
714/// same type qualifiers as FromPtr has on its pointee type. ToType,
715/// if non-empty, will be a pointer to ToType that may or may not have
716/// the right set of qualifiers on its pointee.
717static QualType
718BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
719 QualType ToPointee, QualType ToType,
720 ASTContext &Context) {
721 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
722 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
723 unsigned Quals = CanonFromPointee.getCVRQualifiers();
724
725 // Exact qualifier match -> return the pointer type we're converting to.
726 if (CanonToPointee.getCVRQualifiers() == Quals) {
727 // ToType is exactly what we need. Return it.
728 if (ToType.getTypePtr())
729 return ToType;
730
731 // Build a pointer to ToPointee. It has the right qualifiers
732 // already.
733 return Context.getPointerType(ToPointee);
734 }
735
736 // Just build a canonical type that has the right qualifiers.
737 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
738}
739
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000740/// IsPointerConversion - Determines whether the conversion of the
741/// expression From, which has the (possibly adjusted) type FromType,
742/// can be converted to the type ToType via a pointer conversion (C++
743/// 4.10). If so, returns true and places the converted type (that
744/// might differ from ToType in its cv-qualifiers at some level) into
745/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000746///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000747/// This routine also supports conversions to and from block pointers
748/// and conversions with Objective-C's 'id', 'id<protocols...>', and
749/// pointers to interfaces. FIXME: Once we've determined the
750/// appropriate overloading rules for Objective-C, we may want to
751/// split the Objective-C checks into a different routine; however,
752/// GCC seems to consider all of these conversions to be pointer
753/// conversions, so for now they live here.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000754bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
755 QualType& ConvertedType)
756{
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000757 // Blocks: Block pointers can be converted to void*.
758 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
759 ToType->getAsPointerType()->getPointeeType()->isVoidType()) {
760 ConvertedType = ToType;
761 return true;
762 }
763 // Blocks: A null pointer constant can be converted to a block
764 // pointer type.
765 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
766 ConvertedType = ToType;
767 return true;
768 }
769
Douglas Gregor7ca09762008-11-27 01:19:21 +0000770 // Conversions with Objective-C's id<...>.
771 if ((FromType->isObjCQualifiedIdType() || ToType->isObjCQualifiedIdType()) &&
772 ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) {
773 ConvertedType = ToType;
774 return true;
775 }
776
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000777 const PointerType* ToTypePtr = ToType->getAsPointerType();
778 if (!ToTypePtr)
779 return false;
780
781 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
782 if (From->isNullPointerConstant(Context)) {
783 ConvertedType = ToType;
784 return true;
785 }
Sebastian Redl07779722008-10-31 14:43:28 +0000786
Douglas Gregorcb7de522008-11-26 23:31:11 +0000787 // Beyond this point, both types need to be pointers.
788 const PointerType *FromTypePtr = FromType->getAsPointerType();
789 if (!FromTypePtr)
790 return false;
791
792 QualType FromPointeeType = FromTypePtr->getPointeeType();
793 QualType ToPointeeType = ToTypePtr->getPointeeType();
794
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000795 // An rvalue of type "pointer to cv T," where T is an object type,
796 // can be converted to an rvalue of type "pointer to cv void" (C++
797 // 4.10p2).
Douglas Gregorcb7de522008-11-26 23:31:11 +0000798 if (FromPointeeType->isIncompleteOrObjectType() && ToPointeeType->isVoidType()) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000799 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
800 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000801 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000802 return true;
803 }
804
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000805 // C++ [conv.ptr]p3:
806 //
807 // An rvalue of type "pointer to cv D," where D is a class type,
808 // can be converted to an rvalue of type "pointer to cv B," where
809 // B is a base class (clause 10) of D. If B is an inaccessible
810 // (clause 11) or ambiguous (10.2) base class of D, a program that
811 // necessitates this conversion is ill-formed. The result of the
812 // conversion is a pointer to the base class sub-object of the
813 // derived class object. The null pointer value is converted to
814 // the null pointer value of the destination type.
815 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000816 // Note that we do not check for ambiguity or inaccessibility
817 // here. That is handled by CheckPointerConversion.
Douglas Gregorcb7de522008-11-26 23:31:11 +0000818 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
819 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000820 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
821 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000822 ToType, Context);
823 return true;
824 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000825
Douglas Gregorcb7de522008-11-26 23:31:11 +0000826 // Objective C++: We're able to convert from a pointer to an
827 // interface to a pointer to a different interface.
828 const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType();
829 const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType();
830 if (FromIface && ToIface &&
831 Context.canAssignObjCInterfaces(ToIface, FromIface)) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000832 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
833 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000834 ToType, Context);
835 return true;
836 }
837
838 // Objective C++: We're able to convert between "id" and a pointer
839 // to any interface (in both directions).
840 if ((FromIface && Context.isObjCIdType(ToPointeeType))
841 || (ToIface && Context.isObjCIdType(FromPointeeType))) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000842 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
843 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000844 ToType, Context);
845 return true;
846 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000847
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000848 return false;
849}
850
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000851/// CheckPointerConversion - Check the pointer conversion from the
852/// expression From to the type ToType. This routine checks for
853/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
854/// conversions for which IsPointerConversion has already returned
855/// true. It returns true and produces a diagnostic if there was an
856/// error, or returns false otherwise.
857bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
858 QualType FromType = From->getType();
859
860 if (const PointerType *FromPtrType = FromType->getAsPointerType())
861 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
Sebastian Redl07779722008-10-31 14:43:28 +0000862 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
863 /*DetectVirtual=*/false);
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000864 QualType FromPointeeType = FromPtrType->getPointeeType(),
865 ToPointeeType = ToPtrType->getPointeeType();
866 if (FromPointeeType->isRecordType() &&
867 ToPointeeType->isRecordType()) {
868 // We must have a derived-to-base conversion. Check an
869 // ambiguous or inaccessible conversion.
Douglas Gregor0575d4a2008-10-24 16:17:19 +0000870 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
871 From->getExprLoc(),
872 From->getSourceRange());
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000873 }
874 }
875
876 return false;
877}
878
Douglas Gregor98cd5992008-10-21 23:43:52 +0000879/// IsQualificationConversion - Determines whether the conversion from
880/// an rvalue of type FromType to ToType is a qualification conversion
881/// (C++ 4.4).
882bool
883Sema::IsQualificationConversion(QualType FromType, QualType ToType)
884{
885 FromType = Context.getCanonicalType(FromType);
886 ToType = Context.getCanonicalType(ToType);
887
888 // If FromType and ToType are the same type, this is not a
889 // qualification conversion.
890 if (FromType == ToType)
891 return false;
892
893 // (C++ 4.4p4):
894 // A conversion can add cv-qualifiers at levels other than the first
895 // in multi-level pointers, subject to the following rules: [...]
896 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +0000897 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +0000898 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +0000899 // Within each iteration of the loop, we check the qualifiers to
900 // determine if this still looks like a qualification
901 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000902 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +0000903 // until there are no more pointers or pointers-to-members left to
904 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +0000905 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +0000906
907 // -- for every j > 0, if const is in cv 1,j then const is in cv
908 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +0000909 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +0000910 return false;
Douglas Gregor57373262008-10-22 14:17:15 +0000911
Douglas Gregor98cd5992008-10-21 23:43:52 +0000912 // -- if the cv 1,j and cv 2,j are different, then const is in
913 // every cv for 0 < k < j.
914 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +0000915 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +0000916 return false;
Douglas Gregor57373262008-10-22 14:17:15 +0000917
Douglas Gregor98cd5992008-10-21 23:43:52 +0000918 // Keep track of whether all prior cv-qualifiers in the "to" type
919 // include const.
920 PreviousToQualsIncludeConst
921 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +0000922 }
Douglas Gregor98cd5992008-10-21 23:43:52 +0000923
924 // We are left with FromType and ToType being the pointee types
925 // after unwrapping the original FromType and ToType the same number
926 // of types. If we unwrapped any pointers, and if FromType and
927 // ToType have the same unqualified type (since we checked
928 // qualifiers above), then this is a qualification conversion.
929 return UnwrappedAnyPointer &&
930 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
931}
932
Douglas Gregor60d62c22008-10-31 16:23:19 +0000933/// IsUserDefinedConversion - Determines whether there is a
934/// user-defined conversion sequence (C++ [over.ics.user]) that
935/// converts expression From to the type ToType. If such a conversion
936/// exists, User will contain the user-defined conversion sequence
937/// that performs such a conversion and this routine will return
938/// true. Otherwise, this routine returns false and User is
939/// unspecified.
940bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
941 UserDefinedConversionSequence& User)
942{
943 OverloadCandidateSet CandidateSet;
944 if (const CXXRecordType *ToRecordType
945 = dyn_cast_or_null<CXXRecordType>(ToType->getAsRecordType())) {
946 // C++ [over.match.ctor]p1:
947 // When objects of class type are direct-initialized (8.5), or
948 // copy-initialized from an expression of the same or a
949 // derived class type (8.5), overload resolution selects the
950 // constructor. [...] For copy-initialization, the candidate
951 // functions are all the converting constructors (12.3.1) of
952 // that class. The argument list is the expression-list within
953 // the parentheses of the initializer.
954 CXXRecordDecl *ToRecordDecl = ToRecordType->getDecl();
955 const OverloadedFunctionDecl *Constructors = ToRecordDecl->getConstructors();
956 for (OverloadedFunctionDecl::function_const_iterator func
957 = Constructors->function_begin();
958 func != Constructors->function_end(); ++func) {
959 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*func);
960 if (Constructor->isConvertingConstructor())
Douglas Gregor225c41e2008-11-03 19:09:14 +0000961 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
962 /*SuppressUserConversions=*/true);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000963 }
964 }
965
Douglas Gregorf1991ea2008-11-07 22:36:19 +0000966 if (const CXXRecordType *FromRecordType
967 = dyn_cast_or_null<CXXRecordType>(From->getType()->getAsRecordType())) {
968 // Add all of the conversion functions as candidates.
969 // FIXME: Look for conversions in base classes!
970 CXXRecordDecl *FromRecordDecl = FromRecordType->getDecl();
971 OverloadedFunctionDecl *Conversions
972 = FromRecordDecl->getConversionFunctions();
973 for (OverloadedFunctionDecl::function_iterator Func
974 = Conversions->function_begin();
975 Func != Conversions->function_end(); ++Func) {
976 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
977 AddConversionCandidate(Conv, From, ToType, CandidateSet);
978 }
979 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000980
981 OverloadCandidateSet::iterator Best;
982 switch (BestViableFunction(CandidateSet, Best)) {
983 case OR_Success:
984 // Record the standard conversion we used and the conversion function.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000985 if (CXXConstructorDecl *Constructor
986 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
987 // C++ [over.ics.user]p1:
988 // If the user-defined conversion is specified by a
989 // constructor (12.3.1), the initial standard conversion
990 // sequence converts the source type to the type required by
991 // the argument of the constructor.
992 //
993 // FIXME: What about ellipsis conversions?
994 QualType ThisType = Constructor->getThisType(Context);
995 User.Before = Best->Conversions[0].Standard;
996 User.ConversionFunction = Constructor;
997 User.After.setAsIdentityConversion();
998 User.After.FromTypePtr
999 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
1000 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1001 return true;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001002 } else if (CXXConversionDecl *Conversion
1003 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1004 // C++ [over.ics.user]p1:
1005 //
1006 // [...] If the user-defined conversion is specified by a
1007 // conversion function (12.3.2), the initial standard
1008 // conversion sequence converts the source type to the
1009 // implicit object parameter of the conversion function.
1010 User.Before = Best->Conversions[0].Standard;
1011 User.ConversionFunction = Conversion;
1012
1013 // C++ [over.ics.user]p2:
1014 // The second standard conversion sequence converts the
1015 // result of the user-defined conversion to the target type
1016 // for the sequence. Since an implicit conversion sequence
1017 // is an initialization, the special rules for
1018 // initialization by user-defined conversion apply when
1019 // selecting the best user-defined conversion for a
1020 // user-defined conversion sequence (see 13.3.3 and
1021 // 13.3.3.1).
1022 User.After = Best->FinalConversion;
1023 return true;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001024 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001025 assert(false && "Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001026 return false;
1027 }
1028
1029 case OR_No_Viable_Function:
1030 // No conversion here! We're done.
1031 return false;
1032
1033 case OR_Ambiguous:
1034 // FIXME: See C++ [over.best.ics]p10 for the handling of
1035 // ambiguous conversion sequences.
1036 return false;
1037 }
1038
1039 return false;
1040}
1041
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001042/// CompareImplicitConversionSequences - Compare two implicit
1043/// conversion sequences to determine whether one is better than the
1044/// other or if they are indistinguishable (C++ 13.3.3.2).
1045ImplicitConversionSequence::CompareKind
1046Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1047 const ImplicitConversionSequence& ICS2)
1048{
1049 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1050 // conversion sequences (as defined in 13.3.3.1)
1051 // -- a standard conversion sequence (13.3.3.1.1) is a better
1052 // conversion sequence than a user-defined conversion sequence or
1053 // an ellipsis conversion sequence, and
1054 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1055 // conversion sequence than an ellipsis conversion sequence
1056 // (13.3.3.1.3).
1057 //
1058 if (ICS1.ConversionKind < ICS2.ConversionKind)
1059 return ImplicitConversionSequence::Better;
1060 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1061 return ImplicitConversionSequence::Worse;
1062
1063 // Two implicit conversion sequences of the same form are
1064 // indistinguishable conversion sequences unless one of the
1065 // following rules apply: (C++ 13.3.3.2p3):
1066 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1067 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1068 else if (ICS1.ConversionKind ==
1069 ImplicitConversionSequence::UserDefinedConversion) {
1070 // User-defined conversion sequence U1 is a better conversion
1071 // sequence than another user-defined conversion sequence U2 if
1072 // they contain the same user-defined conversion function or
1073 // constructor and if the second standard conversion sequence of
1074 // U1 is better than the second standard conversion sequence of
1075 // U2 (C++ 13.3.3.2p3).
1076 if (ICS1.UserDefined.ConversionFunction ==
1077 ICS2.UserDefined.ConversionFunction)
1078 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1079 ICS2.UserDefined.After);
1080 }
1081
1082 return ImplicitConversionSequence::Indistinguishable;
1083}
1084
1085/// CompareStandardConversionSequences - Compare two standard
1086/// conversion sequences to determine whether one is better than the
1087/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1088ImplicitConversionSequence::CompareKind
1089Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1090 const StandardConversionSequence& SCS2)
1091{
1092 // Standard conversion sequence S1 is a better conversion sequence
1093 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1094
1095 // -- S1 is a proper subsequence of S2 (comparing the conversion
1096 // sequences in the canonical form defined by 13.3.3.1.1,
1097 // excluding any Lvalue Transformation; the identity conversion
1098 // sequence is considered to be a subsequence of any
1099 // non-identity conversion sequence) or, if not that,
1100 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1101 // Neither is a proper subsequence of the other. Do nothing.
1102 ;
1103 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1104 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1105 (SCS1.Second == ICK_Identity &&
1106 SCS1.Third == ICK_Identity))
1107 // SCS1 is a proper subsequence of SCS2.
1108 return ImplicitConversionSequence::Better;
1109 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1110 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1111 (SCS2.Second == ICK_Identity &&
1112 SCS2.Third == ICK_Identity))
1113 // SCS2 is a proper subsequence of SCS1.
1114 return ImplicitConversionSequence::Worse;
1115
1116 // -- the rank of S1 is better than the rank of S2 (by the rules
1117 // defined below), or, if not that,
1118 ImplicitConversionRank Rank1 = SCS1.getRank();
1119 ImplicitConversionRank Rank2 = SCS2.getRank();
1120 if (Rank1 < Rank2)
1121 return ImplicitConversionSequence::Better;
1122 else if (Rank2 < Rank1)
1123 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001124
Douglas Gregor57373262008-10-22 14:17:15 +00001125 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1126 // are indistinguishable unless one of the following rules
1127 // applies:
1128
1129 // A conversion that is not a conversion of a pointer, or
1130 // pointer to member, to bool is better than another conversion
1131 // that is such a conversion.
1132 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1133 return SCS2.isPointerConversionToBool()
1134 ? ImplicitConversionSequence::Better
1135 : ImplicitConversionSequence::Worse;
1136
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001137 // C++ [over.ics.rank]p4b2:
1138 //
1139 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001140 // conversion of B* to A* is better than conversion of B* to
1141 // void*, and conversion of A* to void* is better than conversion
1142 // of B* to void*.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001143 bool SCS1ConvertsToVoid
1144 = SCS1.isPointerConversionToVoidPointer(Context);
1145 bool SCS2ConvertsToVoid
1146 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001147 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1148 // Exactly one of the conversion sequences is a conversion to
1149 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001150 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1151 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001152 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1153 // Neither conversion sequence converts to a void pointer; compare
1154 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001155 if (ImplicitConversionSequence::CompareKind DerivedCK
1156 = CompareDerivedToBaseConversions(SCS1, SCS2))
1157 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001158 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1159 // Both conversion sequences are conversions to void
1160 // pointers. Compare the source types to determine if there's an
1161 // inheritance relationship in their sources.
1162 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1163 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1164
1165 // Adjust the types we're converting from via the array-to-pointer
1166 // conversion, if we need to.
1167 if (SCS1.First == ICK_Array_To_Pointer)
1168 FromType1 = Context.getArrayDecayedType(FromType1);
1169 if (SCS2.First == ICK_Array_To_Pointer)
1170 FromType2 = Context.getArrayDecayedType(FromType2);
1171
1172 QualType FromPointee1
1173 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1174 QualType FromPointee2
1175 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1176
1177 if (IsDerivedFrom(FromPointee2, FromPointee1))
1178 return ImplicitConversionSequence::Better;
1179 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1180 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001181
1182 // Objective-C++: If one interface is more specific than the
1183 // other, it is the better one.
1184 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1185 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1186 if (FromIface1 && FromIface1) {
1187 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1188 return ImplicitConversionSequence::Better;
1189 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1190 return ImplicitConversionSequence::Worse;
1191 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001192 }
Douglas Gregor57373262008-10-22 14:17:15 +00001193
1194 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1195 // bullet 3).
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001196 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001197 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001198 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001199
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001200 // C++ [over.ics.rank]p3b4:
1201 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1202 // which the references refer are the same type except for
1203 // top-level cv-qualifiers, and the type to which the reference
1204 // initialized by S2 refers is more cv-qualified than the type
1205 // to which the reference initialized by S1 refers.
1206 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1207 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1208 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1209 T1 = Context.getCanonicalType(T1);
1210 T2 = Context.getCanonicalType(T2);
1211 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1212 if (T2.isMoreQualifiedThan(T1))
1213 return ImplicitConversionSequence::Better;
1214 else if (T1.isMoreQualifiedThan(T2))
1215 return ImplicitConversionSequence::Worse;
1216 }
1217 }
Douglas Gregor57373262008-10-22 14:17:15 +00001218
1219 return ImplicitConversionSequence::Indistinguishable;
1220}
1221
1222/// CompareQualificationConversions - Compares two standard conversion
1223/// sequences to determine whether they can be ranked based on their
1224/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1225ImplicitConversionSequence::CompareKind
1226Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1227 const StandardConversionSequence& SCS2)
1228{
Douglas Gregorba7e2102008-10-22 15:04:37 +00001229 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001230 // -- S1 and S2 differ only in their qualification conversion and
1231 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1232 // cv-qualification signature of type T1 is a proper subset of
1233 // the cv-qualification signature of type T2, and S1 is not the
1234 // deprecated string literal array-to-pointer conversion (4.2).
1235 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1236 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1237 return ImplicitConversionSequence::Indistinguishable;
1238
1239 // FIXME: the example in the standard doesn't use a qualification
1240 // conversion (!)
1241 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1242 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1243 T1 = Context.getCanonicalType(T1);
1244 T2 = Context.getCanonicalType(T2);
1245
1246 // If the types are the same, we won't learn anything by unwrapped
1247 // them.
1248 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1249 return ImplicitConversionSequence::Indistinguishable;
1250
1251 ImplicitConversionSequence::CompareKind Result
1252 = ImplicitConversionSequence::Indistinguishable;
1253 while (UnwrapSimilarPointerTypes(T1, T2)) {
1254 // Within each iteration of the loop, we check the qualifiers to
1255 // determine if this still looks like a qualification
1256 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001257 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001258 // until there are no more pointers or pointers-to-members left
1259 // to unwrap. This essentially mimics what
1260 // IsQualificationConversion does, but here we're checking for a
1261 // strict subset of qualifiers.
1262 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1263 // The qualifiers are the same, so this doesn't tell us anything
1264 // about how the sequences rank.
1265 ;
1266 else if (T2.isMoreQualifiedThan(T1)) {
1267 // T1 has fewer qualifiers, so it could be the better sequence.
1268 if (Result == ImplicitConversionSequence::Worse)
1269 // Neither has qualifiers that are a subset of the other's
1270 // qualifiers.
1271 return ImplicitConversionSequence::Indistinguishable;
1272
1273 Result = ImplicitConversionSequence::Better;
1274 } else if (T1.isMoreQualifiedThan(T2)) {
1275 // T2 has fewer qualifiers, so it could be the better sequence.
1276 if (Result == ImplicitConversionSequence::Better)
1277 // Neither has qualifiers that are a subset of the other's
1278 // qualifiers.
1279 return ImplicitConversionSequence::Indistinguishable;
1280
1281 Result = ImplicitConversionSequence::Worse;
1282 } else {
1283 // Qualifiers are disjoint.
1284 return ImplicitConversionSequence::Indistinguishable;
1285 }
1286
1287 // If the types after this point are equivalent, we're done.
1288 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1289 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001290 }
1291
Douglas Gregor57373262008-10-22 14:17:15 +00001292 // Check that the winning standard conversion sequence isn't using
1293 // the deprecated string literal array to pointer conversion.
1294 switch (Result) {
1295 case ImplicitConversionSequence::Better:
1296 if (SCS1.Deprecated)
1297 Result = ImplicitConversionSequence::Indistinguishable;
1298 break;
1299
1300 case ImplicitConversionSequence::Indistinguishable:
1301 break;
1302
1303 case ImplicitConversionSequence::Worse:
1304 if (SCS2.Deprecated)
1305 Result = ImplicitConversionSequence::Indistinguishable;
1306 break;
1307 }
1308
1309 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001310}
1311
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001312/// CompareDerivedToBaseConversions - Compares two standard conversion
1313/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00001314/// various kinds of derived-to-base conversions (C++
1315/// [over.ics.rank]p4b3). As part of these checks, we also look at
1316/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001317ImplicitConversionSequence::CompareKind
1318Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1319 const StandardConversionSequence& SCS2) {
1320 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1321 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1322 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1323 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1324
1325 // Adjust the types we're converting from via the array-to-pointer
1326 // conversion, if we need to.
1327 if (SCS1.First == ICK_Array_To_Pointer)
1328 FromType1 = Context.getArrayDecayedType(FromType1);
1329 if (SCS2.First == ICK_Array_To_Pointer)
1330 FromType2 = Context.getArrayDecayedType(FromType2);
1331
1332 // Canonicalize all of the types.
1333 FromType1 = Context.getCanonicalType(FromType1);
1334 ToType1 = Context.getCanonicalType(ToType1);
1335 FromType2 = Context.getCanonicalType(FromType2);
1336 ToType2 = Context.getCanonicalType(ToType2);
1337
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001338 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001339 //
1340 // If class B is derived directly or indirectly from class A and
1341 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001342 //
1343 // For Objective-C, we let A, B, and C also be Objective-C
1344 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001345
1346 // Compare based on pointer conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001347 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00001348 SCS2.Second == ICK_Pointer_Conversion &&
1349 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1350 FromType1->isPointerType() && FromType2->isPointerType() &&
1351 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001352 QualType FromPointee1
1353 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1354 QualType ToPointee1
1355 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1356 QualType FromPointee2
1357 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1358 QualType ToPointee2
1359 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001360
1361 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1362 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1363 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1364 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1365
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001366 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001367 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1368 if (IsDerivedFrom(ToPointee1, ToPointee2))
1369 return ImplicitConversionSequence::Better;
1370 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1371 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001372
1373 if (ToIface1 && ToIface2) {
1374 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1375 return ImplicitConversionSequence::Better;
1376 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1377 return ImplicitConversionSequence::Worse;
1378 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001379 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001380
1381 // -- conversion of B* to A* is better than conversion of C* to A*,
1382 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1383 if (IsDerivedFrom(FromPointee2, FromPointee1))
1384 return ImplicitConversionSequence::Better;
1385 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1386 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001387
1388 if (FromIface1 && FromIface2) {
1389 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1390 return ImplicitConversionSequence::Better;
1391 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1392 return ImplicitConversionSequence::Worse;
1393 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001394 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001395 }
1396
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001397 // Compare based on reference bindings.
1398 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1399 SCS1.Second == ICK_Derived_To_Base) {
1400 // -- binding of an expression of type C to a reference of type
1401 // B& is better than binding an expression of type C to a
1402 // reference of type A&,
1403 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1404 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1405 if (IsDerivedFrom(ToType1, ToType2))
1406 return ImplicitConversionSequence::Better;
1407 else if (IsDerivedFrom(ToType2, ToType1))
1408 return ImplicitConversionSequence::Worse;
1409 }
1410
Douglas Gregor225c41e2008-11-03 19:09:14 +00001411 // -- binding of an expression of type B to a reference of type
1412 // A& is better than binding an expression of type C to a
1413 // reference of type A&,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001414 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1415 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1416 if (IsDerivedFrom(FromType2, FromType1))
1417 return ImplicitConversionSequence::Better;
1418 else if (IsDerivedFrom(FromType1, FromType2))
1419 return ImplicitConversionSequence::Worse;
1420 }
1421 }
1422
1423
1424 // FIXME: conversion of A::* to B::* is better than conversion of
1425 // A::* to C::*,
1426
1427 // FIXME: conversion of B::* to C::* is better than conversion of
1428 // A::* to C::*, and
1429
Douglas Gregor225c41e2008-11-03 19:09:14 +00001430 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1431 SCS1.Second == ICK_Derived_To_Base) {
1432 // -- conversion of C to B is better than conversion of C to A,
1433 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1434 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1435 if (IsDerivedFrom(ToType1, ToType2))
1436 return ImplicitConversionSequence::Better;
1437 else if (IsDerivedFrom(ToType2, ToType1))
1438 return ImplicitConversionSequence::Worse;
1439 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001440
Douglas Gregor225c41e2008-11-03 19:09:14 +00001441 // -- conversion of B to A is better than conversion of C to A.
1442 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1443 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1444 if (IsDerivedFrom(FromType2, FromType1))
1445 return ImplicitConversionSequence::Better;
1446 else if (IsDerivedFrom(FromType1, FromType2))
1447 return ImplicitConversionSequence::Worse;
1448 }
1449 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001450
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001451 return ImplicitConversionSequence::Indistinguishable;
1452}
1453
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001454/// TryCopyInitialization - Try to copy-initialize a value of type
1455/// ToType from the expression From. Return the implicit conversion
1456/// sequence required to pass this argument, which may be a bad
1457/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00001458/// a parameter of this type). If @p SuppressUserConversions, then we
1459/// do not permit any user-defined conversion sequences.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001460ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +00001461Sema::TryCopyInitialization(Expr *From, QualType ToType,
1462 bool SuppressUserConversions) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001463 if (!getLangOptions().CPlusPlus) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001464 // In C, copy initialization is the same as performing an assignment.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001465 AssignConvertType ConvTy =
1466 CheckSingleAssignmentConstraints(ToType, From);
1467 ImplicitConversionSequence ICS;
1468 if (getLangOptions().NoExtensions? ConvTy != Compatible
1469 : ConvTy == Incompatible)
1470 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1471 else
1472 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1473 return ICS;
1474 } else if (ToType->isReferenceType()) {
1475 ImplicitConversionSequence ICS;
Douglas Gregor225c41e2008-11-03 19:09:14 +00001476 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001477 return ICS;
1478 } else {
Douglas Gregor225c41e2008-11-03 19:09:14 +00001479 return TryImplicitConversion(From, ToType, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001480 }
1481}
1482
1483/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1484/// type ToType. Returns true (and emits a diagnostic) if there was
1485/// an error, returns false if the initialization succeeded.
1486bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1487 const char* Flavor) {
1488 if (!getLangOptions().CPlusPlus) {
1489 // In C, argument passing is the same as performing an assignment.
1490 QualType FromType = From->getType();
1491 AssignConvertType ConvTy =
1492 CheckSingleAssignmentConstraints(ToType, From);
1493
1494 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1495 FromType, From, Flavor);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001496 }
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001497
1498 if (ToType->isReferenceType())
1499 return CheckReferenceInit(From, ToType);
1500
1501 if (!PerformImplicitConversion(From, ToType))
1502 return false;
1503
1504 return Diag(From->getSourceRange().getBegin(),
1505 diag::err_typecheck_convert_incompatible)
1506 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001507}
1508
Douglas Gregor96176b32008-11-18 23:14:02 +00001509/// TryObjectArgumentInitialization - Try to initialize the object
1510/// parameter of the given member function (@c Method) from the
1511/// expression @p From.
1512ImplicitConversionSequence
1513Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1514 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1515 unsigned MethodQuals = Method->getTypeQualifiers();
1516 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1517
1518 // Set up the conversion sequence as a "bad" conversion, to allow us
1519 // to exit early.
1520 ImplicitConversionSequence ICS;
1521 ICS.Standard.setAsIdentityConversion();
1522 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1523
1524 // We need to have an object of class type.
1525 QualType FromType = From->getType();
1526 if (!FromType->isRecordType())
1527 return ICS;
1528
1529 // The implicit object parmeter is has the type "reference to cv X",
1530 // where X is the class of which the function is a member
1531 // (C++ [over.match.funcs]p4). However, when finding an implicit
1532 // conversion sequence for the argument, we are not allowed to
1533 // create temporaries or perform user-defined conversions
1534 // (C++ [over.match.funcs]p5). We perform a simplified version of
1535 // reference binding here, that allows class rvalues to bind to
1536 // non-constant references.
1537
1538 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1539 // with the implicit object parameter (C++ [over.match.funcs]p5).
1540 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1541 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1542 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1543 return ICS;
1544
1545 // Check that we have either the same type or a derived type. It
1546 // affects the conversion rank.
1547 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1548 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1549 ICS.Standard.Second = ICK_Identity;
1550 else if (IsDerivedFrom(FromType, ClassType))
1551 ICS.Standard.Second = ICK_Derived_To_Base;
1552 else
1553 return ICS;
1554
1555 // Success. Mark this as a reference binding.
1556 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1557 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1558 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1559 ICS.Standard.ReferenceBinding = true;
1560 ICS.Standard.DirectBinding = true;
1561 return ICS;
1562}
1563
1564/// PerformObjectArgumentInitialization - Perform initialization of
1565/// the implicit object parameter for the given Method with the given
1566/// expression.
1567bool
1568Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
1569 QualType ImplicitParamType
1570 = Method->getThisType(Context)->getAsPointerType()->getPointeeType();
1571 ImplicitConversionSequence ICS
1572 = TryObjectArgumentInitialization(From, Method);
1573 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
1574 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001575 diag::err_implicit_object_parameter_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00001576 << ImplicitParamType << From->getType() << From->getSourceRange();
Douglas Gregor96176b32008-11-18 23:14:02 +00001577
1578 if (ICS.Standard.Second == ICK_Derived_To_Base &&
1579 CheckDerivedToBaseConversion(From->getType(), ImplicitParamType,
1580 From->getSourceRange().getBegin(),
1581 From->getSourceRange()))
1582 return true;
1583
1584 ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true);
1585 return false;
1586}
1587
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001588/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00001589/// candidate functions, using the given function call arguments. If
1590/// @p SuppressUserConversions, then don't allow user-defined
1591/// conversions via constructors or conversion operators.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001592void
1593Sema::AddOverloadCandidate(FunctionDecl *Function,
1594 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00001595 OverloadCandidateSet& CandidateSet,
1596 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001597{
1598 const FunctionTypeProto* Proto
1599 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType());
1600 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001601 assert(!isa<CXXConversionDecl>(Function) &&
1602 "Use AddConversionCandidate for conversion functions");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001603
1604 // Add this candidate
1605 CandidateSet.push_back(OverloadCandidate());
1606 OverloadCandidate& Candidate = CandidateSet.back();
1607 Candidate.Function = Function;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001608 Candidate.IsSurrogate = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001609
1610 unsigned NumArgsInProto = Proto->getNumArgs();
1611
1612 // (C++ 13.3.2p2): A candidate function having fewer than m
1613 // parameters is viable only if it has an ellipsis in its parameter
1614 // list (8.3.5).
1615 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1616 Candidate.Viable = false;
1617 return;
1618 }
1619
1620 // (C++ 13.3.2p2): A candidate function having more than m parameters
1621 // is viable only if the (m+1)st parameter has a default argument
1622 // (8.3.6). For the purposes of overload resolution, the
1623 // parameter list is truncated on the right, so that there are
1624 // exactly m parameters.
1625 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
1626 if (NumArgs < MinRequiredArgs) {
1627 // Not enough arguments.
1628 Candidate.Viable = false;
1629 return;
1630 }
1631
1632 // Determine the implicit conversion sequences for each of the
1633 // arguments.
1634 Candidate.Viable = true;
1635 Candidate.Conversions.resize(NumArgs);
1636 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1637 if (ArgIdx < NumArgsInProto) {
1638 // (C++ 13.3.2p3): for F to be a viable function, there shall
1639 // exist for each argument an implicit conversion sequence
1640 // (13.3.3.1) that converts that argument to the corresponding
1641 // parameter of F.
1642 QualType ParamType = Proto->getArgType(ArgIdx);
1643 Candidate.Conversions[ArgIdx]
Douglas Gregor225c41e2008-11-03 19:09:14 +00001644 = TryCopyInitialization(Args[ArgIdx], ParamType,
1645 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001646 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00001647 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001648 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001649 break;
1650 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001651 } else {
1652 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1653 // argument for which there is no corresponding parameter is
1654 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1655 Candidate.Conversions[ArgIdx].ConversionKind
1656 = ImplicitConversionSequence::EllipsisConversion;
1657 }
1658 }
1659}
1660
Douglas Gregor96176b32008-11-18 23:14:02 +00001661/// AddMethodCandidate - Adds the given C++ member function to the set
1662/// of candidate functions, using the given function call arguments
1663/// and the object argument (@c Object). For example, in a call
1664/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
1665/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
1666/// allow user-defined conversions via constructors or conversion
1667/// operators.
1668void
1669Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
1670 Expr **Args, unsigned NumArgs,
1671 OverloadCandidateSet& CandidateSet,
1672 bool SuppressUserConversions)
1673{
1674 const FunctionTypeProto* Proto
1675 = dyn_cast<FunctionTypeProto>(Method->getType()->getAsFunctionType());
1676 assert(Proto && "Methods without a prototype cannot be overloaded");
1677 assert(!isa<CXXConversionDecl>(Method) &&
1678 "Use AddConversionCandidate for conversion functions");
1679
1680 // Add this candidate
1681 CandidateSet.push_back(OverloadCandidate());
1682 OverloadCandidate& Candidate = CandidateSet.back();
1683 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001684 Candidate.IsSurrogate = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001685
1686 unsigned NumArgsInProto = Proto->getNumArgs();
1687
1688 // (C++ 13.3.2p2): A candidate function having fewer than m
1689 // parameters is viable only if it has an ellipsis in its parameter
1690 // list (8.3.5).
1691 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1692 Candidate.Viable = false;
1693 return;
1694 }
1695
1696 // (C++ 13.3.2p2): A candidate function having more than m parameters
1697 // is viable only if the (m+1)st parameter has a default argument
1698 // (8.3.6). For the purposes of overload resolution, the
1699 // parameter list is truncated on the right, so that there are
1700 // exactly m parameters.
1701 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
1702 if (NumArgs < MinRequiredArgs) {
1703 // Not enough arguments.
1704 Candidate.Viable = false;
1705 return;
1706 }
1707
1708 Candidate.Viable = true;
1709 Candidate.Conversions.resize(NumArgs + 1);
1710
1711 // Determine the implicit conversion sequence for the object
1712 // parameter.
1713 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
1714 if (Candidate.Conversions[0].ConversionKind
1715 == ImplicitConversionSequence::BadConversion) {
1716 Candidate.Viable = false;
1717 return;
1718 }
1719
1720 // Determine the implicit conversion sequences for each of the
1721 // arguments.
1722 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1723 if (ArgIdx < NumArgsInProto) {
1724 // (C++ 13.3.2p3): for F to be a viable function, there shall
1725 // exist for each argument an implicit conversion sequence
1726 // (13.3.3.1) that converts that argument to the corresponding
1727 // parameter of F.
1728 QualType ParamType = Proto->getArgType(ArgIdx);
1729 Candidate.Conversions[ArgIdx + 1]
1730 = TryCopyInitialization(Args[ArgIdx], ParamType,
1731 SuppressUserConversions);
1732 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
1733 == ImplicitConversionSequence::BadConversion) {
1734 Candidate.Viable = false;
1735 break;
1736 }
1737 } else {
1738 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1739 // argument for which there is no corresponding parameter is
1740 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1741 Candidate.Conversions[ArgIdx + 1].ConversionKind
1742 = ImplicitConversionSequence::EllipsisConversion;
1743 }
1744 }
1745}
1746
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001747/// AddConversionCandidate - Add a C++ conversion function as a
1748/// candidate in the candidate set (C++ [over.match.conv],
1749/// C++ [over.match.copy]). From is the expression we're converting from,
1750/// and ToType is the type that we're eventually trying to convert to
1751/// (which may or may not be the same type as the type that the
1752/// conversion function produces).
1753void
1754Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
1755 Expr *From, QualType ToType,
1756 OverloadCandidateSet& CandidateSet) {
1757 // Add this candidate
1758 CandidateSet.push_back(OverloadCandidate());
1759 OverloadCandidate& Candidate = CandidateSet.back();
1760 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001761 Candidate.IsSurrogate = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001762 Candidate.FinalConversion.setAsIdentityConversion();
1763 Candidate.FinalConversion.FromTypePtr
1764 = Conversion->getConversionType().getAsOpaquePtr();
1765 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
1766
Douglas Gregor96176b32008-11-18 23:14:02 +00001767 // Determine the implicit conversion sequence for the implicit
1768 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001769 Candidate.Viable = true;
1770 Candidate.Conversions.resize(1);
Douglas Gregor96176b32008-11-18 23:14:02 +00001771 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001772
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001773 if (Candidate.Conversions[0].ConversionKind
1774 == ImplicitConversionSequence::BadConversion) {
1775 Candidate.Viable = false;
1776 return;
1777 }
1778
1779 // To determine what the conversion from the result of calling the
1780 // conversion function to the type we're eventually trying to
1781 // convert to (ToType), we need to synthesize a call to the
1782 // conversion function and attempt copy initialization from it. This
1783 // makes sure that we get the right semantics with respect to
1784 // lvalues/rvalues and the type. Fortunately, we can allocate this
1785 // call on the stack and we don't need its arguments to be
1786 // well-formed.
1787 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
1788 SourceLocation());
1789 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001790 &ConversionRef, false);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001791 CallExpr Call(&ConversionFn, 0, 0,
1792 Conversion->getConversionType().getNonReferenceType(),
1793 SourceLocation());
1794 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
1795 switch (ICS.ConversionKind) {
1796 case ImplicitConversionSequence::StandardConversion:
1797 Candidate.FinalConversion = ICS.Standard;
1798 break;
1799
1800 case ImplicitConversionSequence::BadConversion:
1801 Candidate.Viable = false;
1802 break;
1803
1804 default:
1805 assert(false &&
1806 "Can only end up with a standard conversion sequence or failure");
1807 }
1808}
1809
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001810/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
1811/// converts the given @c Object to a function pointer via the
1812/// conversion function @c Conversion, and then attempts to call it
1813/// with the given arguments (C++ [over.call.object]p2-4). Proto is
1814/// the type of function that we'll eventually be calling.
1815void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
1816 const FunctionTypeProto *Proto,
1817 Expr *Object, Expr **Args, unsigned NumArgs,
1818 OverloadCandidateSet& CandidateSet) {
1819 CandidateSet.push_back(OverloadCandidate());
1820 OverloadCandidate& Candidate = CandidateSet.back();
1821 Candidate.Function = 0;
1822 Candidate.Surrogate = Conversion;
1823 Candidate.Viable = true;
1824 Candidate.IsSurrogate = true;
1825 Candidate.Conversions.resize(NumArgs + 1);
1826
1827 // Determine the implicit conversion sequence for the implicit
1828 // object parameter.
1829 ImplicitConversionSequence ObjectInit
1830 = TryObjectArgumentInitialization(Object, Conversion);
1831 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
1832 Candidate.Viable = false;
1833 return;
1834 }
1835
1836 // The first conversion is actually a user-defined conversion whose
1837 // first conversion is ObjectInit's standard conversion (which is
1838 // effectively a reference binding). Record it as such.
1839 Candidate.Conversions[0].ConversionKind
1840 = ImplicitConversionSequence::UserDefinedConversion;
1841 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
1842 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
1843 Candidate.Conversions[0].UserDefined.After
1844 = Candidate.Conversions[0].UserDefined.Before;
1845 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
1846
1847 // Find the
1848 unsigned NumArgsInProto = Proto->getNumArgs();
1849
1850 // (C++ 13.3.2p2): A candidate function having fewer than m
1851 // parameters is viable only if it has an ellipsis in its parameter
1852 // list (8.3.5).
1853 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1854 Candidate.Viable = false;
1855 return;
1856 }
1857
1858 // Function types don't have any default arguments, so just check if
1859 // we have enough arguments.
1860 if (NumArgs < NumArgsInProto) {
1861 // Not enough arguments.
1862 Candidate.Viable = false;
1863 return;
1864 }
1865
1866 // Determine the implicit conversion sequences for each of the
1867 // arguments.
1868 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1869 if (ArgIdx < NumArgsInProto) {
1870 // (C++ 13.3.2p3): for F to be a viable function, there shall
1871 // exist for each argument an implicit conversion sequence
1872 // (13.3.3.1) that converts that argument to the corresponding
1873 // parameter of F.
1874 QualType ParamType = Proto->getArgType(ArgIdx);
1875 Candidate.Conversions[ArgIdx + 1]
1876 = TryCopyInitialization(Args[ArgIdx], ParamType,
1877 /*SuppressUserConversions=*/false);
1878 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
1879 == ImplicitConversionSequence::BadConversion) {
1880 Candidate.Viable = false;
1881 break;
1882 }
1883 } else {
1884 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1885 // argument for which there is no corresponding parameter is
1886 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1887 Candidate.Conversions[ArgIdx + 1].ConversionKind
1888 = ImplicitConversionSequence::EllipsisConversion;
1889 }
1890 }
1891}
1892
Douglas Gregor447b69e2008-11-19 03:25:36 +00001893/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1894/// an acceptable non-member overloaded operator for a call whose
1895/// arguments have types T1 (and, if non-empty, T2). This routine
1896/// implements the check in C++ [over.match.oper]p3b2 concerning
1897/// enumeration types.
1898static bool
1899IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1900 QualType T1, QualType T2,
1901 ASTContext &Context) {
1902 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1903 return true;
1904
1905 const FunctionTypeProto *Proto = Fn->getType()->getAsFunctionTypeProto();
1906 if (Proto->getNumArgs() < 1)
1907 return false;
1908
1909 if (T1->isEnumeralType()) {
1910 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
1911 if (Context.getCanonicalType(T1).getUnqualifiedType()
1912 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1913 return true;
1914 }
1915
1916 if (Proto->getNumArgs() < 2)
1917 return false;
1918
1919 if (!T2.isNull() && T2->isEnumeralType()) {
1920 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
1921 if (Context.getCanonicalType(T2).getUnqualifiedType()
1922 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1923 return true;
1924 }
1925
1926 return false;
1927}
1928
Douglas Gregor96176b32008-11-18 23:14:02 +00001929/// AddOperatorCandidates - Add the overloaded operator candidates for
1930/// the operator Op that was used in an operator expression such as "x
1931/// Op y". S is the scope in which the expression occurred (used for
1932/// name lookup of the operator), Args/NumArgs provides the operator
1933/// arguments, and CandidateSet will store the added overload
1934/// candidates. (C++ [over.match.oper]).
1935void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
1936 Expr **Args, unsigned NumArgs,
1937 OverloadCandidateSet& CandidateSet) {
1938 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
1939
1940 // C++ [over.match.oper]p3:
1941 // For a unary operator @ with an operand of a type whose
1942 // cv-unqualified version is T1, and for a binary operator @ with
1943 // a left operand of a type whose cv-unqualified version is T1 and
1944 // a right operand of a type whose cv-unqualified version is T2,
1945 // three sets of candidate functions, designated member
1946 // candidates, non-member candidates and built-in candidates, are
1947 // constructed as follows:
1948 QualType T1 = Args[0]->getType();
1949 QualType T2;
1950 if (NumArgs > 1)
1951 T2 = Args[1]->getType();
1952
1953 // -- If T1 is a class type, the set of member candidates is the
1954 // result of the qualified lookup of T1::operator@
1955 // (13.3.1.1.1); otherwise, the set of member candidates is
1956 // empty.
1957 if (const RecordType *T1Rec = T1->getAsRecordType()) {
Douglas Gregor44b43212008-12-11 16:49:14 +00001958 DeclContext::lookup_const_result Lookup
Douglas Gregore267ff32008-12-11 20:41:00 +00001959 = T1Rec->getDecl()->lookup(Context, OpName);
Douglas Gregor44b43212008-12-11 16:49:14 +00001960 NamedDecl *MemberOps = (Lookup.first == Lookup.second)? 0 : *Lookup.first;
Douglas Gregor96176b32008-11-18 23:14:02 +00001961 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps))
1962 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet,
1963 /*SuppressUserConversions=*/false);
1964 else if (OverloadedFunctionDecl *Ovl
1965 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) {
1966 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
1967 FEnd = Ovl->function_end();
1968 F != FEnd; ++F) {
1969 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F))
1970 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet,
1971 /*SuppressUserConversions=*/false);
1972 }
1973 }
1974 }
1975
1976 // -- The set of non-member candidates is the result of the
1977 // unqualified lookup of operator@ in the context of the
1978 // expression according to the usual rules for name lookup in
1979 // unqualified function calls (3.4.2) except that all member
1980 // functions are ignored. However, if no operand has a class
1981 // type, only those non-member functions in the lookup set
1982 // that have a first parameter of type T1 or “reference to
1983 // (possibly cv-qualified) T1”, when T1 is an enumeration
1984 // type, or (if there is a right operand) a second parameter
1985 // of type T2 or “reference to (possibly cv-qualified) T2”,
1986 // when T2 is an enumeration type, are candidate functions.
1987 {
1988 NamedDecl *NonMemberOps = 0;
1989 for (IdentifierResolver::iterator I
1990 = IdResolver.begin(OpName, CurContext, true/*LookInParentCtx*/);
1991 I != IdResolver.end(); ++I) {
1992 // We don't need to check the identifier namespace, because
1993 // operator names can only be ordinary identifiers.
1994
1995 // Ignore member functions.
1996 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(*I)) {
1997 if (SD->getDeclContext()->isCXXRecord())
1998 continue;
1999 }
2000
2001 // We found something with this name. We're done.
2002 NonMemberOps = *I;
2003 break;
2004 }
2005
Douglas Gregor447b69e2008-11-19 03:25:36 +00002006 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NonMemberOps)) {
2007 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
2008 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2009 /*SuppressUserConversions=*/false);
2010 } else if (OverloadedFunctionDecl *Ovl
2011 = dyn_cast_or_null<OverloadedFunctionDecl>(NonMemberOps)) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002012 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
2013 FEnd = Ovl->function_end();
Douglas Gregor447b69e2008-11-19 03:25:36 +00002014 F != FEnd; ++F) {
2015 if (IsAcceptableNonMemberOperatorCandidate(*F, T1, T2, Context))
2016 AddOverloadCandidate(*F, Args, NumArgs, CandidateSet,
2017 /*SuppressUserConversions=*/false);
2018 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002019 }
2020 }
2021
2022 // Add builtin overload candidates (C++ [over.built]).
Douglas Gregor74253732008-11-19 15:42:04 +00002023 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
Douglas Gregor96176b32008-11-18 23:14:02 +00002024}
2025
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002026/// AddBuiltinCandidate - Add a candidate for a built-in
2027/// operator. ResultTy and ParamTys are the result and parameter types
2028/// of the built-in candidate, respectively. Args and NumArgs are the
2029/// arguments being passed to the candidate.
2030void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2031 Expr **Args, unsigned NumArgs,
2032 OverloadCandidateSet& CandidateSet) {
2033 // Add this candidate
2034 CandidateSet.push_back(OverloadCandidate());
2035 OverloadCandidate& Candidate = CandidateSet.back();
2036 Candidate.Function = 0;
2037 Candidate.BuiltinTypes.ResultTy = ResultTy;
2038 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2039 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2040
2041 // Determine the implicit conversion sequences for each of the
2042 // arguments.
2043 Candidate.Viable = true;
2044 Candidate.Conversions.resize(NumArgs);
2045 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2046 Candidate.Conversions[ArgIdx]
2047 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx], false);
2048 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002049 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002050 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002051 break;
2052 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002053 }
2054}
2055
2056/// BuiltinCandidateTypeSet - A set of types that will be used for the
2057/// candidate operator functions for built-in operators (C++
2058/// [over.built]). The types are separated into pointer types and
2059/// enumeration types.
2060class BuiltinCandidateTypeSet {
2061 /// TypeSet - A set of types.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002062 typedef llvm::SmallPtrSet<void*, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002063
2064 /// PointerTypes - The set of pointer types that will be used in the
2065 /// built-in candidates.
2066 TypeSet PointerTypes;
2067
2068 /// EnumerationTypes - The set of enumeration types that will be
2069 /// used in the built-in candidates.
2070 TypeSet EnumerationTypes;
2071
2072 /// Context - The AST context in which we will build the type sets.
2073 ASTContext &Context;
2074
2075 bool AddWithMoreQualifiedTypeVariants(QualType Ty);
2076
2077public:
2078 /// iterator - Iterates through the types that are part of the set.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002079 class iterator {
2080 TypeSet::iterator Base;
2081
2082 public:
2083 typedef QualType value_type;
2084 typedef QualType reference;
2085 typedef QualType pointer;
2086 typedef std::ptrdiff_t difference_type;
2087 typedef std::input_iterator_tag iterator_category;
2088
2089 iterator(TypeSet::iterator B) : Base(B) { }
2090
2091 iterator& operator++() {
2092 ++Base;
2093 return *this;
2094 }
2095
2096 iterator operator++(int) {
2097 iterator tmp(*this);
2098 ++(*this);
2099 return tmp;
2100 }
2101
2102 reference operator*() const {
2103 return QualType::getFromOpaquePtr(*Base);
2104 }
2105
2106 pointer operator->() const {
2107 return **this;
2108 }
2109
2110 friend bool operator==(iterator LHS, iterator RHS) {
2111 return LHS.Base == RHS.Base;
2112 }
2113
2114 friend bool operator!=(iterator LHS, iterator RHS) {
2115 return LHS.Base != RHS.Base;
2116 }
2117 };
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002118
2119 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2120
2121 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions = true);
2122
2123 /// pointer_begin - First pointer type found;
2124 iterator pointer_begin() { return PointerTypes.begin(); }
2125
2126 /// pointer_end - Last pointer type found;
2127 iterator pointer_end() { return PointerTypes.end(); }
2128
2129 /// enumeration_begin - First enumeration type found;
2130 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2131
2132 /// enumeration_end - Last enumeration type found;
2133 iterator enumeration_end() { return EnumerationTypes.end(); }
2134};
2135
2136/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2137/// the set of pointer types along with any more-qualified variants of
2138/// that type. For example, if @p Ty is "int const *", this routine
2139/// will add "int const *", "int const volatile *", "int const
2140/// restrict *", and "int const volatile restrict *" to the set of
2141/// pointer types. Returns true if the add of @p Ty itself succeeded,
2142/// false otherwise.
2143bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) {
2144 // Insert this type.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002145 if (!PointerTypes.insert(Ty.getAsOpaquePtr()))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002146 return false;
2147
2148 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2149 QualType PointeeTy = PointerTy->getPointeeType();
2150 // FIXME: Optimize this so that we don't keep trying to add the same types.
2151
2152 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
2153 // with all pointer conversions that don't cast away constness?
2154 if (!PointeeTy.isConstQualified())
2155 AddWithMoreQualifiedTypeVariants
2156 (Context.getPointerType(PointeeTy.withConst()));
2157 if (!PointeeTy.isVolatileQualified())
2158 AddWithMoreQualifiedTypeVariants
2159 (Context.getPointerType(PointeeTy.withVolatile()));
2160 if (!PointeeTy.isRestrictQualified())
2161 AddWithMoreQualifiedTypeVariants
2162 (Context.getPointerType(PointeeTy.withRestrict()));
2163 }
2164
2165 return true;
2166}
2167
2168/// AddTypesConvertedFrom - Add each of the types to which the type @p
2169/// Ty can be implicit converted to the given set of @p Types. We're
2170/// primarily interested in pointer types, enumeration types,
2171void BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2172 bool AllowUserConversions) {
2173 // Only deal with canonical types.
2174 Ty = Context.getCanonicalType(Ty);
2175
2176 // Look through reference types; they aren't part of the type of an
2177 // expression for the purposes of conversions.
2178 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2179 Ty = RefTy->getPointeeType();
2180
2181 // We don't care about qualifiers on the type.
2182 Ty = Ty.getUnqualifiedType();
2183
2184 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2185 QualType PointeeTy = PointerTy->getPointeeType();
2186
2187 // Insert our type, and its more-qualified variants, into the set
2188 // of types.
2189 if (!AddWithMoreQualifiedTypeVariants(Ty))
2190 return;
2191
2192 // Add 'cv void*' to our set of types.
2193 if (!Ty->isVoidType()) {
2194 QualType QualVoid
2195 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2196 AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2197 }
2198
2199 // If this is a pointer to a class type, add pointers to its bases
2200 // (with the same level of cv-qualification as the original
2201 // derived class, of course).
2202 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2203 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2204 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2205 Base != ClassDecl->bases_end(); ++Base) {
2206 QualType BaseTy = Context.getCanonicalType(Base->getType());
2207 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2208
2209 // Add the pointer type, recursively, so that we get all of
2210 // the indirect base classes, too.
2211 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false);
2212 }
2213 }
2214 } else if (Ty->isEnumeralType()) {
Douglas Gregorbf3af052008-11-13 20:12:29 +00002215 EnumerationTypes.insert(Ty.getAsOpaquePtr());
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002216 } else if (AllowUserConversions) {
2217 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2218 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2219 // FIXME: Visit conversion functions in the base classes, too.
2220 OverloadedFunctionDecl *Conversions
2221 = ClassDecl->getConversionFunctions();
2222 for (OverloadedFunctionDecl::function_iterator Func
2223 = Conversions->function_begin();
2224 Func != Conversions->function_end(); ++Func) {
2225 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
2226 AddTypesConvertedFrom(Conv->getConversionType(), false);
2227 }
2228 }
2229 }
2230}
2231
Douglas Gregor74253732008-11-19 15:42:04 +00002232/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2233/// operator overloads to the candidate set (C++ [over.built]), based
2234/// on the operator @p Op and the arguments given. For example, if the
2235/// operator is a binary '+', this routine might add "int
2236/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002237void
Douglas Gregor74253732008-11-19 15:42:04 +00002238Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2239 Expr **Args, unsigned NumArgs,
2240 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002241 // The set of "promoted arithmetic types", which are the arithmetic
2242 // types are that preserved by promotion (C++ [over.built]p2). Note
2243 // that the first few of these types are the promoted integral
2244 // types; these types need to be first.
2245 // FIXME: What about complex?
2246 const unsigned FirstIntegralType = 0;
2247 const unsigned LastIntegralType = 13;
2248 const unsigned FirstPromotedIntegralType = 7,
2249 LastPromotedIntegralType = 13;
2250 const unsigned FirstPromotedArithmeticType = 7,
2251 LastPromotedArithmeticType = 16;
2252 const unsigned NumArithmeticTypes = 16;
2253 QualType ArithmeticTypes[NumArithmeticTypes] = {
2254 Context.BoolTy, Context.CharTy, Context.WCharTy,
2255 Context.SignedCharTy, Context.ShortTy,
2256 Context.UnsignedCharTy, Context.UnsignedShortTy,
2257 Context.IntTy, Context.LongTy, Context.LongLongTy,
2258 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2259 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2260 };
2261
2262 // Find all of the types that the arguments can convert to, but only
2263 // if the operator we're looking at has built-in operator candidates
2264 // that make use of these types.
2265 BuiltinCandidateTypeSet CandidateTypes(Context);
2266 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2267 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00002268 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002269 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00002270 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
2271 (Op == OO_Star && NumArgs == 1)) {
2272 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002273 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType());
2274 }
2275
2276 bool isComparison = false;
2277 switch (Op) {
2278 case OO_None:
2279 case NUM_OVERLOADED_OPERATORS:
2280 assert(false && "Expected an overloaded operator");
2281 break;
2282
Douglas Gregor74253732008-11-19 15:42:04 +00002283 case OO_Star: // '*' is either unary or binary
2284 if (NumArgs == 1)
2285 goto UnaryStar;
2286 else
2287 goto BinaryStar;
2288 break;
2289
2290 case OO_Plus: // '+' is either unary or binary
2291 if (NumArgs == 1)
2292 goto UnaryPlus;
2293 else
2294 goto BinaryPlus;
2295 break;
2296
2297 case OO_Minus: // '-' is either unary or binary
2298 if (NumArgs == 1)
2299 goto UnaryMinus;
2300 else
2301 goto BinaryMinus;
2302 break;
2303
2304 case OO_Amp: // '&' is either unary or binary
2305 if (NumArgs == 1)
2306 goto UnaryAmp;
2307 else
2308 goto BinaryAmp;
2309
2310 case OO_PlusPlus:
2311 case OO_MinusMinus:
2312 // C++ [over.built]p3:
2313 //
2314 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2315 // is either volatile or empty, there exist candidate operator
2316 // functions of the form
2317 //
2318 // VQ T& operator++(VQ T&);
2319 // T operator++(VQ T&, int);
2320 //
2321 // C++ [over.built]p4:
2322 //
2323 // For every pair (T, VQ), where T is an arithmetic type other
2324 // than bool, and VQ is either volatile or empty, there exist
2325 // candidate operator functions of the form
2326 //
2327 // VQ T& operator--(VQ T&);
2328 // T operator--(VQ T&, int);
2329 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2330 Arith < NumArithmeticTypes; ++Arith) {
2331 QualType ArithTy = ArithmeticTypes[Arith];
2332 QualType ParamTypes[2]
2333 = { Context.getReferenceType(ArithTy), Context.IntTy };
2334
2335 // Non-volatile version.
2336 if (NumArgs == 1)
2337 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2338 else
2339 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2340
2341 // Volatile version
2342 ParamTypes[0] = Context.getReferenceType(ArithTy.withVolatile());
2343 if (NumArgs == 1)
2344 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2345 else
2346 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2347 }
2348
2349 // C++ [over.built]p5:
2350 //
2351 // For every pair (T, VQ), where T is a cv-qualified or
2352 // cv-unqualified object type, and VQ is either volatile or
2353 // empty, there exist candidate operator functions of the form
2354 //
2355 // T*VQ& operator++(T*VQ&);
2356 // T*VQ& operator--(T*VQ&);
2357 // T* operator++(T*VQ&, int);
2358 // T* operator--(T*VQ&, int);
2359 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2360 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2361 // Skip pointer types that aren't pointers to object types.
Douglas Gregorcb7de522008-11-26 23:31:11 +00002362 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00002363 continue;
2364
2365 QualType ParamTypes[2] = {
2366 Context.getReferenceType(*Ptr), Context.IntTy
2367 };
2368
2369 // Without volatile
2370 if (NumArgs == 1)
2371 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2372 else
2373 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2374
2375 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2376 // With volatile
2377 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2378 if (NumArgs == 1)
2379 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2380 else
2381 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2382 }
2383 }
2384 break;
2385
2386 UnaryStar:
2387 // C++ [over.built]p6:
2388 // For every cv-qualified or cv-unqualified object type T, there
2389 // exist candidate operator functions of the form
2390 //
2391 // T& operator*(T*);
2392 //
2393 // C++ [over.built]p7:
2394 // For every function type T, there exist candidate operator
2395 // functions of the form
2396 // T& operator*(T*);
2397 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2398 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2399 QualType ParamTy = *Ptr;
2400 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
2401 AddBuiltinCandidate(Context.getReferenceType(PointeeTy),
2402 &ParamTy, Args, 1, CandidateSet);
2403 }
2404 break;
2405
2406 UnaryPlus:
2407 // C++ [over.built]p8:
2408 // For every type T, there exist candidate operator functions of
2409 // the form
2410 //
2411 // T* operator+(T*);
2412 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2413 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2414 QualType ParamTy = *Ptr;
2415 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2416 }
2417
2418 // Fall through
2419
2420 UnaryMinus:
2421 // C++ [over.built]p9:
2422 // For every promoted arithmetic type T, there exist candidate
2423 // operator functions of the form
2424 //
2425 // T operator+(T);
2426 // T operator-(T);
2427 for (unsigned Arith = FirstPromotedArithmeticType;
2428 Arith < LastPromotedArithmeticType; ++Arith) {
2429 QualType ArithTy = ArithmeticTypes[Arith];
2430 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2431 }
2432 break;
2433
2434 case OO_Tilde:
2435 // C++ [over.built]p10:
2436 // For every promoted integral type T, there exist candidate
2437 // operator functions of the form
2438 //
2439 // T operator~(T);
2440 for (unsigned Int = FirstPromotedIntegralType;
2441 Int < LastPromotedIntegralType; ++Int) {
2442 QualType IntTy = ArithmeticTypes[Int];
2443 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2444 }
2445 break;
2446
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002447 case OO_New:
2448 case OO_Delete:
2449 case OO_Array_New:
2450 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002451 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00002452 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002453 break;
2454
2455 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00002456 UnaryAmp:
2457 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002458 // C++ [over.match.oper]p3:
2459 // -- For the operator ',', the unary operator '&', or the
2460 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002461 break;
2462
2463 case OO_Less:
2464 case OO_Greater:
2465 case OO_LessEqual:
2466 case OO_GreaterEqual:
2467 case OO_EqualEqual:
2468 case OO_ExclaimEqual:
2469 // C++ [over.built]p15:
2470 //
2471 // For every pointer or enumeration type T, there exist
2472 // candidate operator functions of the form
2473 //
2474 // bool operator<(T, T);
2475 // bool operator>(T, T);
2476 // bool operator<=(T, T);
2477 // bool operator>=(T, T);
2478 // bool operator==(T, T);
2479 // bool operator!=(T, T);
2480 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2481 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2482 QualType ParamTypes[2] = { *Ptr, *Ptr };
2483 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2484 }
2485 for (BuiltinCandidateTypeSet::iterator Enum
2486 = CandidateTypes.enumeration_begin();
2487 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2488 QualType ParamTypes[2] = { *Enum, *Enum };
2489 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2490 }
2491
2492 // Fall through.
2493 isComparison = true;
2494
Douglas Gregor74253732008-11-19 15:42:04 +00002495 BinaryPlus:
2496 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002497 if (!isComparison) {
2498 // We didn't fall through, so we must have OO_Plus or OO_Minus.
2499
2500 // C++ [over.built]p13:
2501 //
2502 // For every cv-qualified or cv-unqualified object type T
2503 // there exist candidate operator functions of the form
2504 //
2505 // T* operator+(T*, ptrdiff_t);
2506 // T& operator[](T*, ptrdiff_t); [BELOW]
2507 // T* operator-(T*, ptrdiff_t);
2508 // T* operator+(ptrdiff_t, T*);
2509 // T& operator[](ptrdiff_t, T*); [BELOW]
2510 //
2511 // C++ [over.built]p14:
2512 //
2513 // For every T, where T is a pointer to object type, there
2514 // exist candidate operator functions of the form
2515 //
2516 // ptrdiff_t operator-(T, T);
2517 for (BuiltinCandidateTypeSet::iterator Ptr
2518 = CandidateTypes.pointer_begin();
2519 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2520 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2521
2522 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
2523 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2524
2525 if (Op == OO_Plus) {
2526 // T* operator+(ptrdiff_t, T*);
2527 ParamTypes[0] = ParamTypes[1];
2528 ParamTypes[1] = *Ptr;
2529 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2530 } else {
2531 // ptrdiff_t operator-(T, T);
2532 ParamTypes[1] = *Ptr;
2533 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
2534 Args, 2, CandidateSet);
2535 }
2536 }
2537 }
2538 // Fall through
2539
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002540 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00002541 BinaryStar:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002542 // C++ [over.built]p12:
2543 //
2544 // For every pair of promoted arithmetic types L and R, there
2545 // exist candidate operator functions of the form
2546 //
2547 // LR operator*(L, R);
2548 // LR operator/(L, R);
2549 // LR operator+(L, R);
2550 // LR operator-(L, R);
2551 // bool operator<(L, R);
2552 // bool operator>(L, R);
2553 // bool operator<=(L, R);
2554 // bool operator>=(L, R);
2555 // bool operator==(L, R);
2556 // bool operator!=(L, R);
2557 //
2558 // where LR is the result of the usual arithmetic conversions
2559 // between types L and R.
2560 for (unsigned Left = FirstPromotedArithmeticType;
2561 Left < LastPromotedArithmeticType; ++Left) {
2562 for (unsigned Right = FirstPromotedArithmeticType;
2563 Right < LastPromotedArithmeticType; ++Right) {
2564 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2565 QualType Result
2566 = isComparison? Context.BoolTy
2567 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2568 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2569 }
2570 }
2571 break;
2572
2573 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00002574 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002575 case OO_Caret:
2576 case OO_Pipe:
2577 case OO_LessLess:
2578 case OO_GreaterGreater:
2579 // C++ [over.built]p17:
2580 //
2581 // For every pair of promoted integral types L and R, there
2582 // exist candidate operator functions of the form
2583 //
2584 // LR operator%(L, R);
2585 // LR operator&(L, R);
2586 // LR operator^(L, R);
2587 // LR operator|(L, R);
2588 // L operator<<(L, R);
2589 // L operator>>(L, R);
2590 //
2591 // where LR is the result of the usual arithmetic conversions
2592 // between types L and R.
2593 for (unsigned Left = FirstPromotedIntegralType;
2594 Left < LastPromotedIntegralType; ++Left) {
2595 for (unsigned Right = FirstPromotedIntegralType;
2596 Right < LastPromotedIntegralType; ++Right) {
2597 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2598 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
2599 ? LandR[0]
2600 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2601 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2602 }
2603 }
2604 break;
2605
2606 case OO_Equal:
2607 // C++ [over.built]p20:
2608 //
2609 // For every pair (T, VQ), where T is an enumeration or
2610 // (FIXME:) pointer to member type and VQ is either volatile or
2611 // empty, there exist candidate operator functions of the form
2612 //
2613 // VQ T& operator=(VQ T&, T);
2614 for (BuiltinCandidateTypeSet::iterator Enum
2615 = CandidateTypes.enumeration_begin();
2616 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2617 QualType ParamTypes[2];
2618
2619 // T& operator=(T&, T)
2620 ParamTypes[0] = Context.getReferenceType(*Enum);
2621 ParamTypes[1] = *Enum;
2622 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2623
Douglas Gregor74253732008-11-19 15:42:04 +00002624 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
2625 // volatile T& operator=(volatile T&, T)
2626 ParamTypes[0] = Context.getReferenceType((*Enum).withVolatile());
2627 ParamTypes[1] = *Enum;
2628 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2629 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002630 }
2631 // Fall through.
2632
2633 case OO_PlusEqual:
2634 case OO_MinusEqual:
2635 // C++ [over.built]p19:
2636 //
2637 // For every pair (T, VQ), where T is any type and VQ is either
2638 // volatile or empty, there exist candidate operator functions
2639 // of the form
2640 //
2641 // T*VQ& operator=(T*VQ&, T*);
2642 //
2643 // C++ [over.built]p21:
2644 //
2645 // For every pair (T, VQ), where T is a cv-qualified or
2646 // cv-unqualified object type and VQ is either volatile or
2647 // empty, there exist candidate operator functions of the form
2648 //
2649 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
2650 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
2651 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2652 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2653 QualType ParamTypes[2];
2654 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
2655
2656 // non-volatile version
2657 ParamTypes[0] = Context.getReferenceType(*Ptr);
2658 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2659
Douglas Gregor74253732008-11-19 15:42:04 +00002660 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2661 // volatile version
2662 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2663 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2664 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002665 }
2666 // Fall through.
2667
2668 case OO_StarEqual:
2669 case OO_SlashEqual:
2670 // C++ [over.built]p18:
2671 //
2672 // For every triple (L, VQ, R), where L is an arithmetic type,
2673 // VQ is either volatile or empty, and R is a promoted
2674 // arithmetic type, there exist candidate operator functions of
2675 // the form
2676 //
2677 // VQ L& operator=(VQ L&, R);
2678 // VQ L& operator*=(VQ L&, R);
2679 // VQ L& operator/=(VQ L&, R);
2680 // VQ L& operator+=(VQ L&, R);
2681 // VQ L& operator-=(VQ L&, R);
2682 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
2683 for (unsigned Right = FirstPromotedArithmeticType;
2684 Right < LastPromotedArithmeticType; ++Right) {
2685 QualType ParamTypes[2];
2686 ParamTypes[1] = ArithmeticTypes[Right];
2687
2688 // Add this built-in operator as a candidate (VQ is empty).
2689 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
2690 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2691
2692 // Add this built-in operator as a candidate (VQ is 'volatile').
2693 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
2694 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
2695 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2696 }
2697 }
2698 break;
2699
2700 case OO_PercentEqual:
2701 case OO_LessLessEqual:
2702 case OO_GreaterGreaterEqual:
2703 case OO_AmpEqual:
2704 case OO_CaretEqual:
2705 case OO_PipeEqual:
2706 // C++ [over.built]p22:
2707 //
2708 // For every triple (L, VQ, R), where L is an integral type, VQ
2709 // is either volatile or empty, and R is a promoted integral
2710 // type, there exist candidate operator functions of the form
2711 //
2712 // VQ L& operator%=(VQ L&, R);
2713 // VQ L& operator<<=(VQ L&, R);
2714 // VQ L& operator>>=(VQ L&, R);
2715 // VQ L& operator&=(VQ L&, R);
2716 // VQ L& operator^=(VQ L&, R);
2717 // VQ L& operator|=(VQ L&, R);
2718 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
2719 for (unsigned Right = FirstPromotedIntegralType;
2720 Right < LastPromotedIntegralType; ++Right) {
2721 QualType ParamTypes[2];
2722 ParamTypes[1] = ArithmeticTypes[Right];
2723
2724 // Add this built-in operator as a candidate (VQ is empty).
2725 // FIXME: We should be caching these declarations somewhere,
2726 // rather than re-building them every time.
2727 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
2728 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2729
2730 // Add this built-in operator as a candidate (VQ is 'volatile').
2731 ParamTypes[0] = ArithmeticTypes[Left];
2732 ParamTypes[0].addVolatile();
2733 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
2734 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2735 }
2736 }
2737 break;
2738
Douglas Gregor74253732008-11-19 15:42:04 +00002739 case OO_Exclaim: {
2740 // C++ [over.operator]p23:
2741 //
2742 // There also exist candidate operator functions of the form
2743 //
2744 // bool operator!(bool);
2745 // bool operator&&(bool, bool); [BELOW]
2746 // bool operator||(bool, bool); [BELOW]
2747 QualType ParamTy = Context.BoolTy;
2748 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2749 break;
2750 }
2751
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002752 case OO_AmpAmp:
2753 case OO_PipePipe: {
2754 // C++ [over.operator]p23:
2755 //
2756 // There also exist candidate operator functions of the form
2757 //
Douglas Gregor74253732008-11-19 15:42:04 +00002758 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002759 // bool operator&&(bool, bool);
2760 // bool operator||(bool, bool);
2761 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
2762 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2763 break;
2764 }
2765
2766 case OO_Subscript:
2767 // C++ [over.built]p13:
2768 //
2769 // For every cv-qualified or cv-unqualified object type T there
2770 // exist candidate operator functions of the form
2771 //
2772 // T* operator+(T*, ptrdiff_t); [ABOVE]
2773 // T& operator[](T*, ptrdiff_t);
2774 // T* operator-(T*, ptrdiff_t); [ABOVE]
2775 // T* operator+(ptrdiff_t, T*); [ABOVE]
2776 // T& operator[](ptrdiff_t, T*);
2777 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2778 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2779 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2780 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
2781 QualType ResultTy = Context.getReferenceType(PointeeType);
2782
2783 // T& operator[](T*, ptrdiff_t)
2784 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
2785
2786 // T& operator[](ptrdiff_t, T*);
2787 ParamTypes[0] = ParamTypes[1];
2788 ParamTypes[1] = *Ptr;
2789 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
2790 }
2791 break;
2792
2793 case OO_ArrowStar:
2794 // FIXME: No support for pointer-to-members yet.
2795 break;
2796 }
2797}
2798
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002799/// AddOverloadCandidates - Add all of the function overloads in Ovl
2800/// to the candidate set.
2801void
Douglas Gregor18fe5682008-11-03 20:45:27 +00002802Sema::AddOverloadCandidates(const OverloadedFunctionDecl *Ovl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002803 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002804 OverloadCandidateSet& CandidateSet,
2805 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002806{
Douglas Gregor18fe5682008-11-03 20:45:27 +00002807 for (OverloadedFunctionDecl::function_const_iterator Func
2808 = Ovl->function_begin();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002809 Func != Ovl->function_end(); ++Func)
Douglas Gregor225c41e2008-11-03 19:09:14 +00002810 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet,
2811 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002812}
2813
2814/// isBetterOverloadCandidate - Determines whether the first overload
2815/// candidate is a better candidate than the second (C++ 13.3.3p1).
2816bool
2817Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
2818 const OverloadCandidate& Cand2)
2819{
2820 // Define viable functions to be better candidates than non-viable
2821 // functions.
2822 if (!Cand2.Viable)
2823 return Cand1.Viable;
2824 else if (!Cand1.Viable)
2825 return false;
2826
2827 // FIXME: Deal with the implicit object parameter for static member
2828 // functions. (C++ 13.3.3p1).
2829
2830 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
2831 // function than another viable function F2 if for all arguments i,
2832 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
2833 // then...
2834 unsigned NumArgs = Cand1.Conversions.size();
2835 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
2836 bool HasBetterConversion = false;
2837 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2838 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
2839 Cand2.Conversions[ArgIdx])) {
2840 case ImplicitConversionSequence::Better:
2841 // Cand1 has a better conversion sequence.
2842 HasBetterConversion = true;
2843 break;
2844
2845 case ImplicitConversionSequence::Worse:
2846 // Cand1 can't be better than Cand2.
2847 return false;
2848
2849 case ImplicitConversionSequence::Indistinguishable:
2850 // Do nothing.
2851 break;
2852 }
2853 }
2854
2855 if (HasBetterConversion)
2856 return true;
2857
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002858 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
2859 // implemented, but they require template support.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002860
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002861 // C++ [over.match.best]p1b4:
2862 //
2863 // -- the context is an initialization by user-defined conversion
2864 // (see 8.5, 13.3.1.5) and the standard conversion sequence
2865 // from the return type of F1 to the destination type (i.e.,
2866 // the type of the entity being initialized) is a better
2867 // conversion sequence than the standard conversion sequence
2868 // from the return type of F2 to the destination type.
Douglas Gregor447b69e2008-11-19 03:25:36 +00002869 if (Cand1.Function && Cand2.Function &&
2870 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002871 isa<CXXConversionDecl>(Cand2.Function)) {
2872 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
2873 Cand2.FinalConversion)) {
2874 case ImplicitConversionSequence::Better:
2875 // Cand1 has a better conversion sequence.
2876 return true;
2877
2878 case ImplicitConversionSequence::Worse:
2879 // Cand1 can't be better than Cand2.
2880 return false;
2881
2882 case ImplicitConversionSequence::Indistinguishable:
2883 // Do nothing
2884 break;
2885 }
2886 }
2887
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002888 return false;
2889}
2890
2891/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
2892/// within an overload candidate set. If overloading is successful,
2893/// the result will be OR_Success and Best will be set to point to the
2894/// best viable function within the candidate set. Otherwise, one of
2895/// several kinds of errors will be returned; see
2896/// Sema::OverloadingResult.
2897Sema::OverloadingResult
2898Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
2899 OverloadCandidateSet::iterator& Best)
2900{
2901 // Find the best viable function.
2902 Best = CandidateSet.end();
2903 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2904 Cand != CandidateSet.end(); ++Cand) {
2905 if (Cand->Viable) {
2906 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
2907 Best = Cand;
2908 }
2909 }
2910
2911 // If we didn't find any viable functions, abort.
2912 if (Best == CandidateSet.end())
2913 return OR_No_Viable_Function;
2914
2915 // Make sure that this function is better than every other viable
2916 // function. If not, we have an ambiguity.
2917 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2918 Cand != CandidateSet.end(); ++Cand) {
2919 if (Cand->Viable &&
2920 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002921 !isBetterOverloadCandidate(*Best, *Cand)) {
2922 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002923 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002924 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002925 }
2926
2927 // Best is the best viable function.
2928 return OR_Success;
2929}
2930
2931/// PrintOverloadCandidates - When overload resolution fails, prints
2932/// diagnostic messages containing the candidates in the candidate
2933/// set. If OnlyViable is true, only viable candidates will be printed.
2934void
2935Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
2936 bool OnlyViable)
2937{
2938 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
2939 LastCand = CandidateSet.end();
2940 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002941 if (Cand->Viable || !OnlyViable) {
2942 if (Cand->Function) {
2943 // Normal function
2944 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002945 } else if (Cand->IsSurrogate) {
Douglas Gregor621b3932008-11-21 02:54:28 +00002946 // Desugar the type of the surrogate down to a function type,
2947 // retaining as many typedefs as possible while still showing
2948 // the function type (and, therefore, its parameter types).
2949 QualType FnType = Cand->Surrogate->getConversionType();
2950 bool isReference = false;
2951 bool isPointer = false;
2952 if (const ReferenceType *FnTypeRef = FnType->getAsReferenceType()) {
2953 FnType = FnTypeRef->getPointeeType();
2954 isReference = true;
2955 }
2956 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
2957 FnType = FnTypePtr->getPointeeType();
2958 isPointer = true;
2959 }
2960 // Desugar down to a function type.
2961 FnType = QualType(FnType->getAsFunctionType(), 0);
2962 // Reconstruct the pointer/reference as appropriate.
2963 if (isPointer) FnType = Context.getPointerType(FnType);
2964 if (isReference) FnType = Context.getReferenceType(FnType);
2965
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002966 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattnerd1625842008-11-24 06:25:27 +00002967 << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002968 } else {
2969 // FIXME: We need to get the identifier in here
2970 // FIXME: Do we want the error message to point at the
2971 // operator? (built-ins won't have a location)
2972 QualType FnType
2973 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
2974 Cand->BuiltinTypes.ParamTypes,
2975 Cand->Conversions.size(),
2976 false, 0);
2977
Chris Lattnerd1625842008-11-24 06:25:27 +00002978 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002979 }
2980 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002981 }
2982}
2983
Douglas Gregor904eed32008-11-10 20:40:00 +00002984/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
2985/// an overloaded function (C++ [over.over]), where @p From is an
2986/// expression with overloaded function type and @p ToType is the type
2987/// we're trying to resolve to. For example:
2988///
2989/// @code
2990/// int f(double);
2991/// int f(int);
2992///
2993/// int (*pfd)(double) = f; // selects f(double)
2994/// @endcode
2995///
2996/// This routine returns the resulting FunctionDecl if it could be
2997/// resolved, and NULL otherwise. When @p Complain is true, this
2998/// routine will emit diagnostics if there is an error.
2999FunctionDecl *
3000Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
3001 bool Complain) {
3002 QualType FunctionType = ToType;
3003 if (const PointerLikeType *ToTypePtr = ToType->getAsPointerLikeType())
3004 FunctionType = ToTypePtr->getPointeeType();
3005
3006 // We only look at pointers or references to functions.
3007 if (!FunctionType->isFunctionType())
3008 return 0;
3009
3010 // Find the actual overloaded function declaration.
3011 OverloadedFunctionDecl *Ovl = 0;
3012
3013 // C++ [over.over]p1:
3014 // [...] [Note: any redundant set of parentheses surrounding the
3015 // overloaded function name is ignored (5.1). ]
3016 Expr *OvlExpr = From->IgnoreParens();
3017
3018 // C++ [over.over]p1:
3019 // [...] The overloaded function name can be preceded by the &
3020 // operator.
3021 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3022 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3023 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3024 }
3025
3026 // Try to dig out the overloaded function.
3027 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
3028 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
3029
3030 // If there's no overloaded function declaration, we're done.
3031 if (!Ovl)
3032 return 0;
3033
3034 // Look through all of the overloaded functions, searching for one
3035 // whose type matches exactly.
3036 // FIXME: When templates or using declarations come along, we'll actually
3037 // have to deal with duplicates, partial ordering, etc. For now, we
3038 // can just do a simple search.
3039 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
3040 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
3041 Fun != Ovl->function_end(); ++Fun) {
3042 // C++ [over.over]p3:
3043 // Non-member functions and static member functions match
3044 // targets of type “pointer-to-function”or
3045 // “reference-to-function.”
3046 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun))
3047 if (!Method->isStatic())
3048 continue;
3049
3050 if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
3051 return *Fun;
3052 }
3053
3054 return 0;
3055}
3056
Douglas Gregorf6b89692008-11-26 05:54:23 +00003057/// ResolveOverloadedCallFn - Given the call expression that calls Fn
3058/// (which eventually refers to the set of overloaded functions in
3059/// Ovl) and the call arguments Args/NumArgs, attempt to resolve the
3060/// function call down to a specific function. If overload resolution
Douglas Gregor0a396682008-11-26 06:01:48 +00003061/// succeeds, returns the function declaration produced by overload
3062/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00003063/// arguments and Fn, and returns NULL.
Douglas Gregor0a396682008-11-26 06:01:48 +00003064FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, OverloadedFunctionDecl *Ovl,
3065 SourceLocation LParenLoc,
3066 Expr **Args, unsigned NumArgs,
3067 SourceLocation *CommaLocs,
3068 SourceLocation RParenLoc) {
Douglas Gregorf6b89692008-11-26 05:54:23 +00003069 OverloadCandidateSet CandidateSet;
3070 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet);
3071 OverloadCandidateSet::iterator Best;
3072 switch (BestViableFunction(CandidateSet, Best)) {
Douglas Gregor0a396682008-11-26 06:01:48 +00003073 case OR_Success:
3074 return Best->Function;
Douglas Gregorf6b89692008-11-26 05:54:23 +00003075
3076 case OR_No_Viable_Function:
3077 Diag(Fn->getSourceRange().getBegin(),
3078 diag::err_ovl_no_viable_function_in_call)
3079 << Ovl->getDeclName() << (unsigned)CandidateSet.size()
3080 << Fn->getSourceRange();
3081 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3082 break;
3083
3084 case OR_Ambiguous:
3085 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
3086 << Ovl->getDeclName() << Fn->getSourceRange();
3087 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3088 break;
3089 }
3090
3091 // Overload resolution failed. Destroy all of the subexpressions and
3092 // return NULL.
3093 Fn->Destroy(Context);
3094 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3095 Args[Arg]->Destroy(Context);
3096 return 0;
3097}
3098
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003099/// BuildCallToObjectOfClassType - Build a call to an object of class
3100/// type (C++ [over.call.object]), which can end up invoking an
3101/// overloaded function call operator (@c operator()) or performing a
3102/// user-defined conversion on the object argument.
3103Action::ExprResult
Douglas Gregor5c37de72008-12-06 00:22:45 +00003104Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
3105 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003106 Expr **Args, unsigned NumArgs,
3107 SourceLocation *CommaLocs,
3108 SourceLocation RParenLoc) {
3109 assert(Object->getType()->isRecordType() && "Requires object type argument");
3110 const RecordType *Record = Object->getType()->getAsRecordType();
3111
3112 // C++ [over.call.object]p1:
3113 // If the primary-expression E in the function call syntax
3114 // evaluates to a class object of type “cv T”, then the set of
3115 // candidate functions includes at least the function call
3116 // operators of T. The function call operators of T are obtained by
3117 // ordinary lookup of the name operator() in the context of
3118 // (E).operator().
3119 OverloadCandidateSet CandidateSet;
Douglas Gregor44b43212008-12-11 16:49:14 +00003120 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
3121 DeclContext::lookup_const_result Lookup
Douglas Gregore267ff32008-12-11 20:41:00 +00003122 = Record->getDecl()->lookup(Context, OpName);
Douglas Gregor44b43212008-12-11 16:49:14 +00003123 NamedDecl *MemberOps = (Lookup.first == Lookup.second)? 0 : *Lookup.first;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003124 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps))
3125 AddMethodCandidate(Method, Object, Args, NumArgs, CandidateSet,
3126 /*SuppressUserConversions=*/false);
3127 else if (OverloadedFunctionDecl *Ovl
3128 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) {
3129 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
3130 FEnd = Ovl->function_end();
3131 F != FEnd; ++F) {
3132 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F))
3133 AddMethodCandidate(Method, Object, Args, NumArgs, CandidateSet,
3134 /*SuppressUserConversions=*/false);
3135 }
3136 }
3137
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003138 // C++ [over.call.object]p2:
3139 // In addition, for each conversion function declared in T of the
3140 // form
3141 //
3142 // operator conversion-type-id () cv-qualifier;
3143 //
3144 // where cv-qualifier is the same cv-qualification as, or a
3145 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00003146 // denotes the type "pointer to function of (P1,...,Pn) returning
3147 // R", or the type "reference to pointer to function of
3148 // (P1,...,Pn) returning R", or the type "reference to function
3149 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003150 // is also considered as a candidate function. Similarly,
3151 // surrogate call functions are added to the set of candidate
3152 // functions for each conversion function declared in an
3153 // accessible base class provided the function is not hidden
3154 // within T by another intervening declaration.
3155 //
3156 // FIXME: Look in base classes for more conversion operators!
3157 OverloadedFunctionDecl *Conversions
3158 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor621b3932008-11-21 02:54:28 +00003159 for (OverloadedFunctionDecl::function_iterator
3160 Func = Conversions->function_begin(),
3161 FuncEnd = Conversions->function_end();
3162 Func != FuncEnd; ++Func) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003163 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
3164
3165 // Strip the reference type (if any) and then the pointer type (if
3166 // any) to get down to what might be a function type.
3167 QualType ConvType = Conv->getConversionType().getNonReferenceType();
3168 if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
3169 ConvType = ConvPtrType->getPointeeType();
3170
3171 if (const FunctionTypeProto *Proto = ConvType->getAsFunctionTypeProto())
3172 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
3173 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003174
3175 // Perform overload resolution.
3176 OverloadCandidateSet::iterator Best;
3177 switch (BestViableFunction(CandidateSet, Best)) {
3178 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003179 // Overload resolution succeeded; we'll build the appropriate call
3180 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003181 break;
3182
3183 case OR_No_Viable_Function:
Sebastian Redle4c452c2008-11-22 13:44:36 +00003184 Diag(Object->getSourceRange().getBegin(),
3185 diag::err_ovl_no_viable_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00003186 << Object->getType() << (unsigned)CandidateSet.size()
Sebastian Redle4c452c2008-11-22 13:44:36 +00003187 << Object->getSourceRange();
3188 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003189 break;
3190
3191 case OR_Ambiguous:
3192 Diag(Object->getSourceRange().getBegin(),
3193 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00003194 << Object->getType() << Object->getSourceRange();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003195 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3196 break;
3197 }
3198
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003199 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003200 // We had an error; delete all of the subexpressions and return
3201 // the error.
3202 delete Object;
3203 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3204 delete Args[ArgIdx];
3205 return true;
3206 }
3207
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003208 if (Best->Function == 0) {
3209 // Since there is no function declaration, this is one of the
3210 // surrogate candidates. Dig out the conversion function.
3211 CXXConversionDecl *Conv
3212 = cast<CXXConversionDecl>(
3213 Best->Conversions[0].UserDefined.ConversionFunction);
3214
3215 // We selected one of the surrogate functions that converts the
3216 // object parameter to a function pointer. Perform the conversion
3217 // on the object argument, then let ActOnCallExpr finish the job.
3218 // FIXME: Represent the user-defined conversion in the AST!
3219 ImpCastExprToType(Object,
3220 Conv->getConversionType().getNonReferenceType(),
3221 Conv->getConversionType()->isReferenceType());
Douglas Gregor5c37de72008-12-06 00:22:45 +00003222 return ActOnCallExpr(S, (ExprTy*)Object, LParenLoc, (ExprTy**)Args, NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003223 CommaLocs, RParenLoc);
3224 }
3225
3226 // We found an overloaded operator(). Build a CXXOperatorCallExpr
3227 // that calls this method, using Object for the implicit object
3228 // parameter and passing along the remaining arguments.
3229 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003230 const FunctionTypeProto *Proto = Method->getType()->getAsFunctionTypeProto();
3231
3232 unsigned NumArgsInProto = Proto->getNumArgs();
3233 unsigned NumArgsToCheck = NumArgs;
3234
3235 // Build the full argument list for the method call (the
3236 // implicit object parameter is placed at the beginning of the
3237 // list).
3238 Expr **MethodArgs;
3239 if (NumArgs < NumArgsInProto) {
3240 NumArgsToCheck = NumArgsInProto;
3241 MethodArgs = new Expr*[NumArgsInProto + 1];
3242 } else {
3243 MethodArgs = new Expr*[NumArgs + 1];
3244 }
3245 MethodArgs[0] = Object;
3246 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3247 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
3248
3249 Expr *NewFn = new DeclRefExpr(Method, Method->getType(),
3250 SourceLocation());
3251 UsualUnaryConversions(NewFn);
3252
3253 // Once we've built TheCall, all of the expressions are properly
3254 // owned.
3255 QualType ResultTy = Method->getResultType().getNonReferenceType();
3256 llvm::OwningPtr<CXXOperatorCallExpr>
3257 TheCall(new CXXOperatorCallExpr(NewFn, MethodArgs, NumArgs + 1,
3258 ResultTy, RParenLoc));
3259 delete [] MethodArgs;
3260
3261 // Initialize the implicit object parameter.
3262 if (!PerformObjectArgumentInitialization(Object, Method))
3263 return true;
3264 TheCall->setArg(0, Object);
3265
3266 // Check the argument types.
3267 for (unsigned i = 0; i != NumArgsToCheck; i++) {
3268 QualType ProtoArgType = Proto->getArgType(i);
3269
3270 Expr *Arg;
3271 if (i < NumArgs)
3272 Arg = Args[i];
3273 else
3274 Arg = new CXXDefaultArgExpr(Method->getParamDecl(i));
3275 QualType ArgType = Arg->getType();
3276
3277 // Pass the argument.
3278 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3279 return true;
3280
3281 TheCall->setArg(i + 1, Arg);
3282 }
3283
3284 // If this is a variadic call, handle args passed through "...".
3285 if (Proto->isVariadic()) {
3286 // Promote the arguments (C99 6.5.2.2p7).
3287 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3288 Expr *Arg = Args[i];
3289 DefaultArgumentPromotion(Arg);
3290 TheCall->setArg(i + 1, Arg);
3291 }
3292 }
3293
3294 return CheckFunctionCall(Method, TheCall.take());
3295}
3296
Douglas Gregor8ba10742008-11-20 16:27:02 +00003297/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
3298/// (if one exists), where @c Base is an expression of class type and
3299/// @c Member is the name of the member we're trying to find.
3300Action::ExprResult
3301Sema::BuildOverloadedArrowExpr(Expr *Base, SourceLocation OpLoc,
3302 SourceLocation MemberLoc,
3303 IdentifierInfo &Member) {
3304 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
3305
3306 // C++ [over.ref]p1:
3307 //
3308 // [...] An expression x->m is interpreted as (x.operator->())->m
3309 // for a class object x of type T if T::operator->() exists and if
3310 // the operator is selected as the best match function by the
3311 // overload resolution mechanism (13.3).
3312 // FIXME: look in base classes.
3313 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
3314 OverloadCandidateSet CandidateSet;
3315 const RecordType *BaseRecord = Base->getType()->getAsRecordType();
Douglas Gregor44b43212008-12-11 16:49:14 +00003316 DeclContext::lookup_const_result Lookup
Douglas Gregore267ff32008-12-11 20:41:00 +00003317 = BaseRecord->getDecl()->lookup(Context, OpName);
Douglas Gregor44b43212008-12-11 16:49:14 +00003318 NamedDecl *MemberOps = (Lookup.first == Lookup.second)? 0 : *Lookup.first;
Douglas Gregor8ba10742008-11-20 16:27:02 +00003319 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps))
3320 AddMethodCandidate(Method, Base, 0, 0, CandidateSet,
3321 /*SuppressUserConversions=*/false);
3322 else if (OverloadedFunctionDecl *Ovl
3323 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) {
3324 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
3325 FEnd = Ovl->function_end();
3326 F != FEnd; ++F) {
3327 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F))
3328 AddMethodCandidate(Method, Base, 0, 0, CandidateSet,
3329 /*SuppressUserConversions=*/false);
3330 }
3331 }
3332
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003333 llvm::OwningPtr<Expr> BasePtr(Base);
3334
Douglas Gregor8ba10742008-11-20 16:27:02 +00003335 // Perform overload resolution.
3336 OverloadCandidateSet::iterator Best;
3337 switch (BestViableFunction(CandidateSet, Best)) {
3338 case OR_Success:
3339 // Overload resolution succeeded; we'll build the call below.
3340 break;
3341
3342 case OR_No_Viable_Function:
3343 if (CandidateSet.empty())
3344 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattnerd1625842008-11-24 06:25:27 +00003345 << BasePtr->getType() << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003346 else
3347 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Sebastian Redle4c452c2008-11-22 13:44:36 +00003348 << "operator->" << (unsigned)CandidateSet.size()
3349 << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003350 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003351 return true;
3352
3353 case OR_Ambiguous:
3354 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Chris Lattnerd1625842008-11-24 06:25:27 +00003355 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003356 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003357 return true;
3358 }
3359
3360 // Convert the object parameter.
3361 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003362 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregor8ba10742008-11-20 16:27:02 +00003363 return true;
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003364
3365 // No concerns about early exits now.
3366 BasePtr.take();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003367
3368 // Build the operator call.
3369 Expr *FnExpr = new DeclRefExpr(Method, Method->getType(), SourceLocation());
3370 UsualUnaryConversions(FnExpr);
3371 Base = new CXXOperatorCallExpr(FnExpr, &Base, 1,
3372 Method->getResultType().getNonReferenceType(),
3373 OpLoc);
3374 return ActOnMemberReferenceExpr(Base, OpLoc, tok::arrow, MemberLoc, Member);
3375}
3376
Douglas Gregor904eed32008-11-10 20:40:00 +00003377/// FixOverloadedFunctionReference - E is an expression that refers to
3378/// a C++ overloaded function (possibly with some parentheses and
3379/// perhaps a '&' around it). We have resolved the overloaded function
3380/// to the function declaration Fn, so patch up the expression E to
3381/// refer (possibly indirectly) to Fn.
3382void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
3383 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
3384 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
3385 E->setType(PE->getSubExpr()->getType());
3386 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
3387 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
3388 "Can only take the address of an overloaded function");
3389 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
3390 E->setType(Context.getPointerType(E->getType()));
3391 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
3392 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
3393 "Expected overloaded function");
3394 DR->setDecl(Fn);
3395 E->setType(Fn->getType());
3396 } else {
3397 assert(false && "Invalid reference to overloaded function");
3398 }
3399}
3400
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003401} // end namespace clang