blob: 4bfe0c4dab22d3ab50bb7a720d36ba08e77add74 [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.
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000637 QualType PromoteTypes[6] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000638 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000639 Context.LongTy, Context.UnsignedLongTy ,
640 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000641 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000642 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000643 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
644 if (FromSize < ToSize ||
645 (FromSize == ToSize &&
646 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
647 // We found the type that we can promote to. If this is the
648 // type we wanted, we have a promotion. Otherwise, no
649 // promotion.
Sebastian Redl07779722008-10-31 14:43:28 +0000650 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000651 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
652 }
653 }
654 }
655
656 // An rvalue for an integral bit-field (9.6) can be converted to an
657 // rvalue of type int if int can represent all the values of the
658 // bit-field; otherwise, it can be converted to unsigned int if
659 // unsigned int can represent all the values of the bit-field. If
660 // the bit-field is larger yet, no integral promotion applies to
661 // it. If the bit-field has an enumerated type, it is treated as any
662 // other value of that type for promotion purposes (C++ 4.5p3).
663 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) {
664 using llvm::APSInt;
665 FieldDecl *MemberDecl = MemRef->getMemberDecl();
666 APSInt BitWidth;
667 if (MemberDecl->isBitField() &&
668 FromType->isIntegralType() && !FromType->isEnumeralType() &&
669 From->isIntegerConstantExpr(BitWidth, Context)) {
670 APSInt ToSize(Context.getTypeSize(ToType));
671
672 // Are we promoting to an int from a bitfield that fits in an int?
673 if (BitWidth < ToSize ||
Sebastian Redl07779722008-10-31 14:43:28 +0000674 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000675 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000676 }
677
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000678 // Are we promoting to an unsigned int from an unsigned bitfield
679 // that fits into an unsigned int?
Sebastian Redl07779722008-10-31 14:43:28 +0000680 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000681 return To->getKind() == BuiltinType::UInt;
Sebastian Redl07779722008-10-31 14:43:28 +0000682 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000683
684 return false;
685 }
686 }
687
688 // An rvalue of type bool can be converted to an rvalue of type int,
689 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000690 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000691 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000692 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000693
694 return false;
695}
696
697/// IsFloatingPointPromotion - Determines whether the conversion from
698/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
699/// returns true and sets PromotedType to the promoted type.
700bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
701{
702 /// An rvalue of type float can be converted to an rvalue of type
703 /// double. (C++ 4.6p1).
704 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
705 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType())
706 if (FromBuiltin->getKind() == BuiltinType::Float &&
707 ToBuiltin->getKind() == BuiltinType::Double)
708 return true;
709
710 return false;
711}
712
Douglas Gregorcb7de522008-11-26 23:31:11 +0000713/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
714/// the pointer type FromPtr to a pointer to type ToPointee, with the
715/// same type qualifiers as FromPtr has on its pointee type. ToType,
716/// if non-empty, will be a pointer to ToType that may or may not have
717/// the right set of qualifiers on its pointee.
718static QualType
719BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
720 QualType ToPointee, QualType ToType,
721 ASTContext &Context) {
722 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
723 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
724 unsigned Quals = CanonFromPointee.getCVRQualifiers();
725
726 // Exact qualifier match -> return the pointer type we're converting to.
727 if (CanonToPointee.getCVRQualifiers() == Quals) {
728 // ToType is exactly what we need. Return it.
729 if (ToType.getTypePtr())
730 return ToType;
731
732 // Build a pointer to ToPointee. It has the right qualifiers
733 // already.
734 return Context.getPointerType(ToPointee);
735 }
736
737 // Just build a canonical type that has the right qualifiers.
738 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
739}
740
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000741/// IsPointerConversion - Determines whether the conversion of the
742/// expression From, which has the (possibly adjusted) type FromType,
743/// can be converted to the type ToType via a pointer conversion (C++
744/// 4.10). If so, returns true and places the converted type (that
745/// might differ from ToType in its cv-qualifiers at some level) into
746/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000747///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000748/// This routine also supports conversions to and from block pointers
749/// and conversions with Objective-C's 'id', 'id<protocols...>', and
750/// pointers to interfaces. FIXME: Once we've determined the
751/// appropriate overloading rules for Objective-C, we may want to
752/// split the Objective-C checks into a different routine; however,
753/// GCC seems to consider all of these conversions to be pointer
754/// conversions, so for now they live here.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000755bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
756 QualType& ConvertedType)
757{
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000758 // Blocks: Block pointers can be converted to void*.
759 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
760 ToType->getAsPointerType()->getPointeeType()->isVoidType()) {
761 ConvertedType = ToType;
762 return true;
763 }
764 // Blocks: A null pointer constant can be converted to a block
765 // pointer type.
766 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
767 ConvertedType = ToType;
768 return true;
769 }
770
Douglas Gregor7ca09762008-11-27 01:19:21 +0000771 // Conversions with Objective-C's id<...>.
772 if ((FromType->isObjCQualifiedIdType() || ToType->isObjCQualifiedIdType()) &&
773 ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) {
774 ConvertedType = ToType;
775 return true;
776 }
777
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000778 const PointerType* ToTypePtr = ToType->getAsPointerType();
779 if (!ToTypePtr)
780 return false;
781
782 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
783 if (From->isNullPointerConstant(Context)) {
784 ConvertedType = ToType;
785 return true;
786 }
Sebastian Redl07779722008-10-31 14:43:28 +0000787
Douglas Gregorcb7de522008-11-26 23:31:11 +0000788 // Beyond this point, both types need to be pointers.
789 const PointerType *FromTypePtr = FromType->getAsPointerType();
790 if (!FromTypePtr)
791 return false;
792
793 QualType FromPointeeType = FromTypePtr->getPointeeType();
794 QualType ToPointeeType = ToTypePtr->getPointeeType();
795
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000796 // An rvalue of type "pointer to cv T," where T is an object type,
797 // can be converted to an rvalue of type "pointer to cv void" (C++
798 // 4.10p2).
Douglas Gregorcb7de522008-11-26 23:31:11 +0000799 if (FromPointeeType->isIncompleteOrObjectType() && ToPointeeType->isVoidType()) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000800 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
801 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000802 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000803 return true;
804 }
805
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000806 // C++ [conv.ptr]p3:
807 //
808 // An rvalue of type "pointer to cv D," where D is a class type,
809 // can be converted to an rvalue of type "pointer to cv B," where
810 // B is a base class (clause 10) of D. If B is an inaccessible
811 // (clause 11) or ambiguous (10.2) base class of D, a program that
812 // necessitates this conversion is ill-formed. The result of the
813 // conversion is a pointer to the base class sub-object of the
814 // derived class object. The null pointer value is converted to
815 // the null pointer value of the destination type.
816 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000817 // Note that we do not check for ambiguity or inaccessibility
818 // here. That is handled by CheckPointerConversion.
Douglas Gregorcb7de522008-11-26 23:31:11 +0000819 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
820 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000821 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
822 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000823 ToType, Context);
824 return true;
825 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000826
Douglas Gregorcb7de522008-11-26 23:31:11 +0000827 // Objective C++: We're able to convert from a pointer to an
828 // interface to a pointer to a different interface.
829 const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType();
830 const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType();
831 if (FromIface && ToIface &&
832 Context.canAssignObjCInterfaces(ToIface, FromIface)) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000833 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
834 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000835 ToType, Context);
836 return true;
837 }
838
839 // Objective C++: We're able to convert between "id" and a pointer
840 // to any interface (in both directions).
841 if ((FromIface && Context.isObjCIdType(ToPointeeType))
842 || (ToIface && Context.isObjCIdType(FromPointeeType))) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000843 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
844 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000845 ToType, Context);
846 return true;
847 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000848
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000849 return false;
850}
851
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000852/// CheckPointerConversion - Check the pointer conversion from the
853/// expression From to the type ToType. This routine checks for
854/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
855/// conversions for which IsPointerConversion has already returned
856/// true. It returns true and produces a diagnostic if there was an
857/// error, or returns false otherwise.
858bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
859 QualType FromType = From->getType();
860
861 if (const PointerType *FromPtrType = FromType->getAsPointerType())
862 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
Sebastian Redl07779722008-10-31 14:43:28 +0000863 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
864 /*DetectVirtual=*/false);
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000865 QualType FromPointeeType = FromPtrType->getPointeeType(),
866 ToPointeeType = ToPtrType->getPointeeType();
867 if (FromPointeeType->isRecordType() &&
868 ToPointeeType->isRecordType()) {
869 // We must have a derived-to-base conversion. Check an
870 // ambiguous or inaccessible conversion.
Douglas Gregor0575d4a2008-10-24 16:17:19 +0000871 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
872 From->getExprLoc(),
873 From->getSourceRange());
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000874 }
875 }
876
877 return false;
878}
879
Douglas Gregor98cd5992008-10-21 23:43:52 +0000880/// IsQualificationConversion - Determines whether the conversion from
881/// an rvalue of type FromType to ToType is a qualification conversion
882/// (C++ 4.4).
883bool
884Sema::IsQualificationConversion(QualType FromType, QualType ToType)
885{
886 FromType = Context.getCanonicalType(FromType);
887 ToType = Context.getCanonicalType(ToType);
888
889 // If FromType and ToType are the same type, this is not a
890 // qualification conversion.
891 if (FromType == ToType)
892 return false;
893
894 // (C++ 4.4p4):
895 // A conversion can add cv-qualifiers at levels other than the first
896 // in multi-level pointers, subject to the following rules: [...]
897 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +0000898 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +0000899 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +0000900 // Within each iteration of the loop, we check the qualifiers to
901 // determine if this still looks like a qualification
902 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000903 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +0000904 // until there are no more pointers or pointers-to-members left to
905 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +0000906 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +0000907
908 // -- for every j > 0, if const is in cv 1,j then const is in cv
909 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +0000910 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +0000911 return false;
Douglas Gregor57373262008-10-22 14:17:15 +0000912
Douglas Gregor98cd5992008-10-21 23:43:52 +0000913 // -- if the cv 1,j and cv 2,j are different, then const is in
914 // every cv for 0 < k < j.
915 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +0000916 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +0000917 return false;
Douglas Gregor57373262008-10-22 14:17:15 +0000918
Douglas Gregor98cd5992008-10-21 23:43:52 +0000919 // Keep track of whether all prior cv-qualifiers in the "to" type
920 // include const.
921 PreviousToQualsIncludeConst
922 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +0000923 }
Douglas Gregor98cd5992008-10-21 23:43:52 +0000924
925 // We are left with FromType and ToType being the pointee types
926 // after unwrapping the original FromType and ToType the same number
927 // of types. If we unwrapped any pointers, and if FromType and
928 // ToType have the same unqualified type (since we checked
929 // qualifiers above), then this is a qualification conversion.
930 return UnwrappedAnyPointer &&
931 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
932}
933
Douglas Gregor60d62c22008-10-31 16:23:19 +0000934/// IsUserDefinedConversion - Determines whether there is a
935/// user-defined conversion sequence (C++ [over.ics.user]) that
936/// converts expression From to the type ToType. If such a conversion
937/// exists, User will contain the user-defined conversion sequence
938/// that performs such a conversion and this routine will return
939/// true. Otherwise, this routine returns false and User is
940/// unspecified.
941bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
942 UserDefinedConversionSequence& User)
943{
944 OverloadCandidateSet CandidateSet;
945 if (const CXXRecordType *ToRecordType
946 = dyn_cast_or_null<CXXRecordType>(ToType->getAsRecordType())) {
947 // C++ [over.match.ctor]p1:
948 // When objects of class type are direct-initialized (8.5), or
949 // copy-initialized from an expression of the same or a
950 // derived class type (8.5), overload resolution selects the
951 // constructor. [...] For copy-initialization, the candidate
952 // functions are all the converting constructors (12.3.1) of
953 // that class. The argument list is the expression-list within
954 // the parentheses of the initializer.
955 CXXRecordDecl *ToRecordDecl = ToRecordType->getDecl();
956 const OverloadedFunctionDecl *Constructors = ToRecordDecl->getConstructors();
957 for (OverloadedFunctionDecl::function_const_iterator func
958 = Constructors->function_begin();
959 func != Constructors->function_end(); ++func) {
960 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*func);
961 if (Constructor->isConvertingConstructor())
Douglas Gregor225c41e2008-11-03 19:09:14 +0000962 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
963 /*SuppressUserConversions=*/true);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000964 }
965 }
966
Douglas Gregorf1991ea2008-11-07 22:36:19 +0000967 if (const CXXRecordType *FromRecordType
968 = dyn_cast_or_null<CXXRecordType>(From->getType()->getAsRecordType())) {
969 // Add all of the conversion functions as candidates.
970 // FIXME: Look for conversions in base classes!
971 CXXRecordDecl *FromRecordDecl = FromRecordType->getDecl();
972 OverloadedFunctionDecl *Conversions
973 = FromRecordDecl->getConversionFunctions();
974 for (OverloadedFunctionDecl::function_iterator Func
975 = Conversions->function_begin();
976 Func != Conversions->function_end(); ++Func) {
977 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
978 AddConversionCandidate(Conv, From, ToType, CandidateSet);
979 }
980 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000981
982 OverloadCandidateSet::iterator Best;
983 switch (BestViableFunction(CandidateSet, Best)) {
984 case OR_Success:
985 // Record the standard conversion we used and the conversion function.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000986 if (CXXConstructorDecl *Constructor
987 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
988 // C++ [over.ics.user]p1:
989 // If the user-defined conversion is specified by a
990 // constructor (12.3.1), the initial standard conversion
991 // sequence converts the source type to the type required by
992 // the argument of the constructor.
993 //
994 // FIXME: What about ellipsis conversions?
995 QualType ThisType = Constructor->getThisType(Context);
996 User.Before = Best->Conversions[0].Standard;
997 User.ConversionFunction = Constructor;
998 User.After.setAsIdentityConversion();
999 User.After.FromTypePtr
1000 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
1001 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1002 return true;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001003 } else if (CXXConversionDecl *Conversion
1004 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1005 // C++ [over.ics.user]p1:
1006 //
1007 // [...] If the user-defined conversion is specified by a
1008 // conversion function (12.3.2), the initial standard
1009 // conversion sequence converts the source type to the
1010 // implicit object parameter of the conversion function.
1011 User.Before = Best->Conversions[0].Standard;
1012 User.ConversionFunction = Conversion;
1013
1014 // C++ [over.ics.user]p2:
1015 // The second standard conversion sequence converts the
1016 // result of the user-defined conversion to the target type
1017 // for the sequence. Since an implicit conversion sequence
1018 // is an initialization, the special rules for
1019 // initialization by user-defined conversion apply when
1020 // selecting the best user-defined conversion for a
1021 // user-defined conversion sequence (see 13.3.3 and
1022 // 13.3.3.1).
1023 User.After = Best->FinalConversion;
1024 return true;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001025 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001026 assert(false && "Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001027 return false;
1028 }
1029
1030 case OR_No_Viable_Function:
1031 // No conversion here! We're done.
1032 return false;
1033
1034 case OR_Ambiguous:
1035 // FIXME: See C++ [over.best.ics]p10 for the handling of
1036 // ambiguous conversion sequences.
1037 return false;
1038 }
1039
1040 return false;
1041}
1042
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001043/// CompareImplicitConversionSequences - Compare two implicit
1044/// conversion sequences to determine whether one is better than the
1045/// other or if they are indistinguishable (C++ 13.3.3.2).
1046ImplicitConversionSequence::CompareKind
1047Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1048 const ImplicitConversionSequence& ICS2)
1049{
1050 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1051 // conversion sequences (as defined in 13.3.3.1)
1052 // -- a standard conversion sequence (13.3.3.1.1) is a better
1053 // conversion sequence than a user-defined conversion sequence or
1054 // an ellipsis conversion sequence, and
1055 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1056 // conversion sequence than an ellipsis conversion sequence
1057 // (13.3.3.1.3).
1058 //
1059 if (ICS1.ConversionKind < ICS2.ConversionKind)
1060 return ImplicitConversionSequence::Better;
1061 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1062 return ImplicitConversionSequence::Worse;
1063
1064 // Two implicit conversion sequences of the same form are
1065 // indistinguishable conversion sequences unless one of the
1066 // following rules apply: (C++ 13.3.3.2p3):
1067 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1068 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1069 else if (ICS1.ConversionKind ==
1070 ImplicitConversionSequence::UserDefinedConversion) {
1071 // User-defined conversion sequence U1 is a better conversion
1072 // sequence than another user-defined conversion sequence U2 if
1073 // they contain the same user-defined conversion function or
1074 // constructor and if the second standard conversion sequence of
1075 // U1 is better than the second standard conversion sequence of
1076 // U2 (C++ 13.3.3.2p3).
1077 if (ICS1.UserDefined.ConversionFunction ==
1078 ICS2.UserDefined.ConversionFunction)
1079 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1080 ICS2.UserDefined.After);
1081 }
1082
1083 return ImplicitConversionSequence::Indistinguishable;
1084}
1085
1086/// CompareStandardConversionSequences - Compare two standard
1087/// conversion sequences to determine whether one is better than the
1088/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1089ImplicitConversionSequence::CompareKind
1090Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1091 const StandardConversionSequence& SCS2)
1092{
1093 // Standard conversion sequence S1 is a better conversion sequence
1094 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1095
1096 // -- S1 is a proper subsequence of S2 (comparing the conversion
1097 // sequences in the canonical form defined by 13.3.3.1.1,
1098 // excluding any Lvalue Transformation; the identity conversion
1099 // sequence is considered to be a subsequence of any
1100 // non-identity conversion sequence) or, if not that,
1101 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1102 // Neither is a proper subsequence of the other. Do nothing.
1103 ;
1104 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1105 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1106 (SCS1.Second == ICK_Identity &&
1107 SCS1.Third == ICK_Identity))
1108 // SCS1 is a proper subsequence of SCS2.
1109 return ImplicitConversionSequence::Better;
1110 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1111 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1112 (SCS2.Second == ICK_Identity &&
1113 SCS2.Third == ICK_Identity))
1114 // SCS2 is a proper subsequence of SCS1.
1115 return ImplicitConversionSequence::Worse;
1116
1117 // -- the rank of S1 is better than the rank of S2 (by the rules
1118 // defined below), or, if not that,
1119 ImplicitConversionRank Rank1 = SCS1.getRank();
1120 ImplicitConversionRank Rank2 = SCS2.getRank();
1121 if (Rank1 < Rank2)
1122 return ImplicitConversionSequence::Better;
1123 else if (Rank2 < Rank1)
1124 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001125
Douglas Gregor57373262008-10-22 14:17:15 +00001126 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1127 // are indistinguishable unless one of the following rules
1128 // applies:
1129
1130 // A conversion that is not a conversion of a pointer, or
1131 // pointer to member, to bool is better than another conversion
1132 // that is such a conversion.
1133 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1134 return SCS2.isPointerConversionToBool()
1135 ? ImplicitConversionSequence::Better
1136 : ImplicitConversionSequence::Worse;
1137
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001138 // C++ [over.ics.rank]p4b2:
1139 //
1140 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001141 // conversion of B* to A* is better than conversion of B* to
1142 // void*, and conversion of A* to void* is better than conversion
1143 // of B* to void*.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001144 bool SCS1ConvertsToVoid
1145 = SCS1.isPointerConversionToVoidPointer(Context);
1146 bool SCS2ConvertsToVoid
1147 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001148 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1149 // Exactly one of the conversion sequences is a conversion to
1150 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001151 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1152 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001153 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1154 // Neither conversion sequence converts to a void pointer; compare
1155 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001156 if (ImplicitConversionSequence::CompareKind DerivedCK
1157 = CompareDerivedToBaseConversions(SCS1, SCS2))
1158 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001159 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1160 // Both conversion sequences are conversions to void
1161 // pointers. Compare the source types to determine if there's an
1162 // inheritance relationship in their sources.
1163 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1164 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1165
1166 // Adjust the types we're converting from via the array-to-pointer
1167 // conversion, if we need to.
1168 if (SCS1.First == ICK_Array_To_Pointer)
1169 FromType1 = Context.getArrayDecayedType(FromType1);
1170 if (SCS2.First == ICK_Array_To_Pointer)
1171 FromType2 = Context.getArrayDecayedType(FromType2);
1172
1173 QualType FromPointee1
1174 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1175 QualType FromPointee2
1176 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1177
1178 if (IsDerivedFrom(FromPointee2, FromPointee1))
1179 return ImplicitConversionSequence::Better;
1180 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1181 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001182
1183 // Objective-C++: If one interface is more specific than the
1184 // other, it is the better one.
1185 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1186 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1187 if (FromIface1 && FromIface1) {
1188 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1189 return ImplicitConversionSequence::Better;
1190 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1191 return ImplicitConversionSequence::Worse;
1192 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001193 }
Douglas Gregor57373262008-10-22 14:17:15 +00001194
1195 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1196 // bullet 3).
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001197 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001198 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001199 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001200
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001201 // C++ [over.ics.rank]p3b4:
1202 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1203 // which the references refer are the same type except for
1204 // top-level cv-qualifiers, and the type to which the reference
1205 // initialized by S2 refers is more cv-qualified than the type
1206 // to which the reference initialized by S1 refers.
1207 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1208 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1209 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1210 T1 = Context.getCanonicalType(T1);
1211 T2 = Context.getCanonicalType(T2);
1212 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1213 if (T2.isMoreQualifiedThan(T1))
1214 return ImplicitConversionSequence::Better;
1215 else if (T1.isMoreQualifiedThan(T2))
1216 return ImplicitConversionSequence::Worse;
1217 }
1218 }
Douglas Gregor57373262008-10-22 14:17:15 +00001219
1220 return ImplicitConversionSequence::Indistinguishable;
1221}
1222
1223/// CompareQualificationConversions - Compares two standard conversion
1224/// sequences to determine whether they can be ranked based on their
1225/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1226ImplicitConversionSequence::CompareKind
1227Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1228 const StandardConversionSequence& SCS2)
1229{
Douglas Gregorba7e2102008-10-22 15:04:37 +00001230 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001231 // -- S1 and S2 differ only in their qualification conversion and
1232 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1233 // cv-qualification signature of type T1 is a proper subset of
1234 // the cv-qualification signature of type T2, and S1 is not the
1235 // deprecated string literal array-to-pointer conversion (4.2).
1236 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1237 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1238 return ImplicitConversionSequence::Indistinguishable;
1239
1240 // FIXME: the example in the standard doesn't use a qualification
1241 // conversion (!)
1242 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1243 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1244 T1 = Context.getCanonicalType(T1);
1245 T2 = Context.getCanonicalType(T2);
1246
1247 // If the types are the same, we won't learn anything by unwrapped
1248 // them.
1249 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1250 return ImplicitConversionSequence::Indistinguishable;
1251
1252 ImplicitConversionSequence::CompareKind Result
1253 = ImplicitConversionSequence::Indistinguishable;
1254 while (UnwrapSimilarPointerTypes(T1, T2)) {
1255 // Within each iteration of the loop, we check the qualifiers to
1256 // determine if this still looks like a qualification
1257 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001258 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001259 // until there are no more pointers or pointers-to-members left
1260 // to unwrap. This essentially mimics what
1261 // IsQualificationConversion does, but here we're checking for a
1262 // strict subset of qualifiers.
1263 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1264 // The qualifiers are the same, so this doesn't tell us anything
1265 // about how the sequences rank.
1266 ;
1267 else if (T2.isMoreQualifiedThan(T1)) {
1268 // T1 has fewer qualifiers, so it could be the better sequence.
1269 if (Result == ImplicitConversionSequence::Worse)
1270 // Neither has qualifiers that are a subset of the other's
1271 // qualifiers.
1272 return ImplicitConversionSequence::Indistinguishable;
1273
1274 Result = ImplicitConversionSequence::Better;
1275 } else if (T1.isMoreQualifiedThan(T2)) {
1276 // T2 has fewer qualifiers, so it could be the better sequence.
1277 if (Result == ImplicitConversionSequence::Better)
1278 // Neither has qualifiers that are a subset of the other's
1279 // qualifiers.
1280 return ImplicitConversionSequence::Indistinguishable;
1281
1282 Result = ImplicitConversionSequence::Worse;
1283 } else {
1284 // Qualifiers are disjoint.
1285 return ImplicitConversionSequence::Indistinguishable;
1286 }
1287
1288 // If the types after this point are equivalent, we're done.
1289 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1290 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001291 }
1292
Douglas Gregor57373262008-10-22 14:17:15 +00001293 // Check that the winning standard conversion sequence isn't using
1294 // the deprecated string literal array to pointer conversion.
1295 switch (Result) {
1296 case ImplicitConversionSequence::Better:
1297 if (SCS1.Deprecated)
1298 Result = ImplicitConversionSequence::Indistinguishable;
1299 break;
1300
1301 case ImplicitConversionSequence::Indistinguishable:
1302 break;
1303
1304 case ImplicitConversionSequence::Worse:
1305 if (SCS2.Deprecated)
1306 Result = ImplicitConversionSequence::Indistinguishable;
1307 break;
1308 }
1309
1310 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001311}
1312
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001313/// CompareDerivedToBaseConversions - Compares two standard conversion
1314/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00001315/// various kinds of derived-to-base conversions (C++
1316/// [over.ics.rank]p4b3). As part of these checks, we also look at
1317/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001318ImplicitConversionSequence::CompareKind
1319Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1320 const StandardConversionSequence& SCS2) {
1321 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1322 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1323 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1324 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1325
1326 // Adjust the types we're converting from via the array-to-pointer
1327 // conversion, if we need to.
1328 if (SCS1.First == ICK_Array_To_Pointer)
1329 FromType1 = Context.getArrayDecayedType(FromType1);
1330 if (SCS2.First == ICK_Array_To_Pointer)
1331 FromType2 = Context.getArrayDecayedType(FromType2);
1332
1333 // Canonicalize all of the types.
1334 FromType1 = Context.getCanonicalType(FromType1);
1335 ToType1 = Context.getCanonicalType(ToType1);
1336 FromType2 = Context.getCanonicalType(FromType2);
1337 ToType2 = Context.getCanonicalType(ToType2);
1338
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001339 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001340 //
1341 // If class B is derived directly or indirectly from class A and
1342 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001343 //
1344 // For Objective-C, we let A, B, and C also be Objective-C
1345 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001346
1347 // Compare based on pointer conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001348 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00001349 SCS2.Second == ICK_Pointer_Conversion &&
1350 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1351 FromType1->isPointerType() && FromType2->isPointerType() &&
1352 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001353 QualType FromPointee1
1354 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1355 QualType ToPointee1
1356 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1357 QualType FromPointee2
1358 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1359 QualType ToPointee2
1360 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001361
1362 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1363 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1364 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1365 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1366
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001367 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001368 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1369 if (IsDerivedFrom(ToPointee1, ToPointee2))
1370 return ImplicitConversionSequence::Better;
1371 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1372 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001373
1374 if (ToIface1 && ToIface2) {
1375 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1376 return ImplicitConversionSequence::Better;
1377 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1378 return ImplicitConversionSequence::Worse;
1379 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001380 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001381
1382 // -- conversion of B* to A* is better than conversion of C* to A*,
1383 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1384 if (IsDerivedFrom(FromPointee2, FromPointee1))
1385 return ImplicitConversionSequence::Better;
1386 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1387 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001388
1389 if (FromIface1 && FromIface2) {
1390 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1391 return ImplicitConversionSequence::Better;
1392 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1393 return ImplicitConversionSequence::Worse;
1394 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001395 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001396 }
1397
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001398 // Compare based on reference bindings.
1399 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1400 SCS1.Second == ICK_Derived_To_Base) {
1401 // -- binding of an expression of type C to a reference of type
1402 // B& is better than binding an expression of type C to a
1403 // reference of type A&,
1404 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1405 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1406 if (IsDerivedFrom(ToType1, ToType2))
1407 return ImplicitConversionSequence::Better;
1408 else if (IsDerivedFrom(ToType2, ToType1))
1409 return ImplicitConversionSequence::Worse;
1410 }
1411
Douglas Gregor225c41e2008-11-03 19:09:14 +00001412 // -- binding of an expression of type B to a reference of type
1413 // A& is better than binding an expression of type C to a
1414 // reference of type A&,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001415 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1416 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1417 if (IsDerivedFrom(FromType2, FromType1))
1418 return ImplicitConversionSequence::Better;
1419 else if (IsDerivedFrom(FromType1, FromType2))
1420 return ImplicitConversionSequence::Worse;
1421 }
1422 }
1423
1424
1425 // FIXME: conversion of A::* to B::* is better than conversion of
1426 // A::* to C::*,
1427
1428 // FIXME: conversion of B::* to C::* is better than conversion of
1429 // A::* to C::*, and
1430
Douglas Gregor225c41e2008-11-03 19:09:14 +00001431 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1432 SCS1.Second == ICK_Derived_To_Base) {
1433 // -- conversion of C to B is better than conversion of C to A,
1434 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1435 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1436 if (IsDerivedFrom(ToType1, ToType2))
1437 return ImplicitConversionSequence::Better;
1438 else if (IsDerivedFrom(ToType2, ToType1))
1439 return ImplicitConversionSequence::Worse;
1440 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001441
Douglas Gregor225c41e2008-11-03 19:09:14 +00001442 // -- conversion of B to A is better than conversion of C to A.
1443 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1444 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1445 if (IsDerivedFrom(FromType2, FromType1))
1446 return ImplicitConversionSequence::Better;
1447 else if (IsDerivedFrom(FromType1, FromType2))
1448 return ImplicitConversionSequence::Worse;
1449 }
1450 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001451
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001452 return ImplicitConversionSequence::Indistinguishable;
1453}
1454
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001455/// TryCopyInitialization - Try to copy-initialize a value of type
1456/// ToType from the expression From. Return the implicit conversion
1457/// sequence required to pass this argument, which may be a bad
1458/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00001459/// a parameter of this type). If @p SuppressUserConversions, then we
1460/// do not permit any user-defined conversion sequences.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001461ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +00001462Sema::TryCopyInitialization(Expr *From, QualType ToType,
1463 bool SuppressUserConversions) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001464 if (!getLangOptions().CPlusPlus) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001465 // In C, copy initialization is the same as performing an assignment.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001466 AssignConvertType ConvTy =
1467 CheckSingleAssignmentConstraints(ToType, From);
1468 ImplicitConversionSequence ICS;
1469 if (getLangOptions().NoExtensions? ConvTy != Compatible
1470 : ConvTy == Incompatible)
1471 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1472 else
1473 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1474 return ICS;
1475 } else if (ToType->isReferenceType()) {
1476 ImplicitConversionSequence ICS;
Douglas Gregor225c41e2008-11-03 19:09:14 +00001477 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001478 return ICS;
1479 } else {
Douglas Gregor225c41e2008-11-03 19:09:14 +00001480 return TryImplicitConversion(From, ToType, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001481 }
1482}
1483
1484/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1485/// type ToType. Returns true (and emits a diagnostic) if there was
1486/// an error, returns false if the initialization succeeded.
1487bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1488 const char* Flavor) {
1489 if (!getLangOptions().CPlusPlus) {
1490 // In C, argument passing is the same as performing an assignment.
1491 QualType FromType = From->getType();
1492 AssignConvertType ConvTy =
1493 CheckSingleAssignmentConstraints(ToType, From);
1494
1495 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1496 FromType, From, Flavor);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001497 }
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001498
1499 if (ToType->isReferenceType())
1500 return CheckReferenceInit(From, ToType);
1501
1502 if (!PerformImplicitConversion(From, ToType))
1503 return false;
1504
1505 return Diag(From->getSourceRange().getBegin(),
1506 diag::err_typecheck_convert_incompatible)
1507 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001508}
1509
Douglas Gregor96176b32008-11-18 23:14:02 +00001510/// TryObjectArgumentInitialization - Try to initialize the object
1511/// parameter of the given member function (@c Method) from the
1512/// expression @p From.
1513ImplicitConversionSequence
1514Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1515 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1516 unsigned MethodQuals = Method->getTypeQualifiers();
1517 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1518
1519 // Set up the conversion sequence as a "bad" conversion, to allow us
1520 // to exit early.
1521 ImplicitConversionSequence ICS;
1522 ICS.Standard.setAsIdentityConversion();
1523 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1524
1525 // We need to have an object of class type.
1526 QualType FromType = From->getType();
1527 if (!FromType->isRecordType())
1528 return ICS;
1529
1530 // The implicit object parmeter is has the type "reference to cv X",
1531 // where X is the class of which the function is a member
1532 // (C++ [over.match.funcs]p4). However, when finding an implicit
1533 // conversion sequence for the argument, we are not allowed to
1534 // create temporaries or perform user-defined conversions
1535 // (C++ [over.match.funcs]p5). We perform a simplified version of
1536 // reference binding here, that allows class rvalues to bind to
1537 // non-constant references.
1538
1539 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1540 // with the implicit object parameter (C++ [over.match.funcs]p5).
1541 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1542 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1543 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1544 return ICS;
1545
1546 // Check that we have either the same type or a derived type. It
1547 // affects the conversion rank.
1548 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1549 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1550 ICS.Standard.Second = ICK_Identity;
1551 else if (IsDerivedFrom(FromType, ClassType))
1552 ICS.Standard.Second = ICK_Derived_To_Base;
1553 else
1554 return ICS;
1555
1556 // Success. Mark this as a reference binding.
1557 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1558 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1559 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1560 ICS.Standard.ReferenceBinding = true;
1561 ICS.Standard.DirectBinding = true;
1562 return ICS;
1563}
1564
1565/// PerformObjectArgumentInitialization - Perform initialization of
1566/// the implicit object parameter for the given Method with the given
1567/// expression.
1568bool
1569Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
1570 QualType ImplicitParamType
1571 = Method->getThisType(Context)->getAsPointerType()->getPointeeType();
1572 ImplicitConversionSequence ICS
1573 = TryObjectArgumentInitialization(From, Method);
1574 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
1575 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001576 diag::err_implicit_object_parameter_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00001577 << ImplicitParamType << From->getType() << From->getSourceRange();
Douglas Gregor96176b32008-11-18 23:14:02 +00001578
1579 if (ICS.Standard.Second == ICK_Derived_To_Base &&
1580 CheckDerivedToBaseConversion(From->getType(), ImplicitParamType,
1581 From->getSourceRange().getBegin(),
1582 From->getSourceRange()))
1583 return true;
1584
1585 ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true);
1586 return false;
1587}
1588
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001589/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00001590/// candidate functions, using the given function call arguments. If
1591/// @p SuppressUserConversions, then don't allow user-defined
1592/// conversions via constructors or conversion operators.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001593void
1594Sema::AddOverloadCandidate(FunctionDecl *Function,
1595 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00001596 OverloadCandidateSet& CandidateSet,
1597 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001598{
1599 const FunctionTypeProto* Proto
1600 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType());
1601 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001602 assert(!isa<CXXConversionDecl>(Function) &&
1603 "Use AddConversionCandidate for conversion functions");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001604
1605 // Add this candidate
1606 CandidateSet.push_back(OverloadCandidate());
1607 OverloadCandidate& Candidate = CandidateSet.back();
1608 Candidate.Function = Function;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001609 Candidate.IsSurrogate = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001610
1611 unsigned NumArgsInProto = Proto->getNumArgs();
1612
1613 // (C++ 13.3.2p2): A candidate function having fewer than m
1614 // parameters is viable only if it has an ellipsis in its parameter
1615 // list (8.3.5).
1616 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1617 Candidate.Viable = false;
1618 return;
1619 }
1620
1621 // (C++ 13.3.2p2): A candidate function having more than m parameters
1622 // is viable only if the (m+1)st parameter has a default argument
1623 // (8.3.6). For the purposes of overload resolution, the
1624 // parameter list is truncated on the right, so that there are
1625 // exactly m parameters.
1626 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
1627 if (NumArgs < MinRequiredArgs) {
1628 // Not enough arguments.
1629 Candidate.Viable = false;
1630 return;
1631 }
1632
1633 // Determine the implicit conversion sequences for each of the
1634 // arguments.
1635 Candidate.Viable = true;
1636 Candidate.Conversions.resize(NumArgs);
1637 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1638 if (ArgIdx < NumArgsInProto) {
1639 // (C++ 13.3.2p3): for F to be a viable function, there shall
1640 // exist for each argument an implicit conversion sequence
1641 // (13.3.3.1) that converts that argument to the corresponding
1642 // parameter of F.
1643 QualType ParamType = Proto->getArgType(ArgIdx);
1644 Candidate.Conversions[ArgIdx]
Douglas Gregor225c41e2008-11-03 19:09:14 +00001645 = TryCopyInitialization(Args[ArgIdx], ParamType,
1646 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001647 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00001648 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001649 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001650 break;
1651 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001652 } else {
1653 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1654 // argument for which there is no corresponding parameter is
1655 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1656 Candidate.Conversions[ArgIdx].ConversionKind
1657 = ImplicitConversionSequence::EllipsisConversion;
1658 }
1659 }
1660}
1661
Douglas Gregor96176b32008-11-18 23:14:02 +00001662/// AddMethodCandidate - Adds the given C++ member function to the set
1663/// of candidate functions, using the given function call arguments
1664/// and the object argument (@c Object). For example, in a call
1665/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
1666/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
1667/// allow user-defined conversions via constructors or conversion
1668/// operators.
1669void
1670Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
1671 Expr **Args, unsigned NumArgs,
1672 OverloadCandidateSet& CandidateSet,
1673 bool SuppressUserConversions)
1674{
1675 const FunctionTypeProto* Proto
1676 = dyn_cast<FunctionTypeProto>(Method->getType()->getAsFunctionType());
1677 assert(Proto && "Methods without a prototype cannot be overloaded");
1678 assert(!isa<CXXConversionDecl>(Method) &&
1679 "Use AddConversionCandidate for conversion functions");
1680
1681 // Add this candidate
1682 CandidateSet.push_back(OverloadCandidate());
1683 OverloadCandidate& Candidate = CandidateSet.back();
1684 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001685 Candidate.IsSurrogate = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001686
1687 unsigned NumArgsInProto = Proto->getNumArgs();
1688
1689 // (C++ 13.3.2p2): A candidate function having fewer than m
1690 // parameters is viable only if it has an ellipsis in its parameter
1691 // list (8.3.5).
1692 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1693 Candidate.Viable = false;
1694 return;
1695 }
1696
1697 // (C++ 13.3.2p2): A candidate function having more than m parameters
1698 // is viable only if the (m+1)st parameter has a default argument
1699 // (8.3.6). For the purposes of overload resolution, the
1700 // parameter list is truncated on the right, so that there are
1701 // exactly m parameters.
1702 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
1703 if (NumArgs < MinRequiredArgs) {
1704 // Not enough arguments.
1705 Candidate.Viable = false;
1706 return;
1707 }
1708
1709 Candidate.Viable = true;
1710 Candidate.Conversions.resize(NumArgs + 1);
1711
1712 // Determine the implicit conversion sequence for the object
1713 // parameter.
1714 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
1715 if (Candidate.Conversions[0].ConversionKind
1716 == ImplicitConversionSequence::BadConversion) {
1717 Candidate.Viable = false;
1718 return;
1719 }
1720
1721 // Determine the implicit conversion sequences for each of the
1722 // arguments.
1723 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1724 if (ArgIdx < NumArgsInProto) {
1725 // (C++ 13.3.2p3): for F to be a viable function, there shall
1726 // exist for each argument an implicit conversion sequence
1727 // (13.3.3.1) that converts that argument to the corresponding
1728 // parameter of F.
1729 QualType ParamType = Proto->getArgType(ArgIdx);
1730 Candidate.Conversions[ArgIdx + 1]
1731 = TryCopyInitialization(Args[ArgIdx], ParamType,
1732 SuppressUserConversions);
1733 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
1734 == ImplicitConversionSequence::BadConversion) {
1735 Candidate.Viable = false;
1736 break;
1737 }
1738 } else {
1739 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1740 // argument for which there is no corresponding parameter is
1741 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1742 Candidate.Conversions[ArgIdx + 1].ConversionKind
1743 = ImplicitConversionSequence::EllipsisConversion;
1744 }
1745 }
1746}
1747
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001748/// AddConversionCandidate - Add a C++ conversion function as a
1749/// candidate in the candidate set (C++ [over.match.conv],
1750/// C++ [over.match.copy]). From is the expression we're converting from,
1751/// and ToType is the type that we're eventually trying to convert to
1752/// (which may or may not be the same type as the type that the
1753/// conversion function produces).
1754void
1755Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
1756 Expr *From, QualType ToType,
1757 OverloadCandidateSet& CandidateSet) {
1758 // Add this candidate
1759 CandidateSet.push_back(OverloadCandidate());
1760 OverloadCandidate& Candidate = CandidateSet.back();
1761 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001762 Candidate.IsSurrogate = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001763 Candidate.FinalConversion.setAsIdentityConversion();
1764 Candidate.FinalConversion.FromTypePtr
1765 = Conversion->getConversionType().getAsOpaquePtr();
1766 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
1767
Douglas Gregor96176b32008-11-18 23:14:02 +00001768 // Determine the implicit conversion sequence for the implicit
1769 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001770 Candidate.Viable = true;
1771 Candidate.Conversions.resize(1);
Douglas Gregor96176b32008-11-18 23:14:02 +00001772 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001773
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001774 if (Candidate.Conversions[0].ConversionKind
1775 == ImplicitConversionSequence::BadConversion) {
1776 Candidate.Viable = false;
1777 return;
1778 }
1779
1780 // To determine what the conversion from the result of calling the
1781 // conversion function to the type we're eventually trying to
1782 // convert to (ToType), we need to synthesize a call to the
1783 // conversion function and attempt copy initialization from it. This
1784 // makes sure that we get the right semantics with respect to
1785 // lvalues/rvalues and the type. Fortunately, we can allocate this
1786 // call on the stack and we don't need its arguments to be
1787 // well-formed.
1788 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
1789 SourceLocation());
1790 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001791 &ConversionRef, false);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001792 CallExpr Call(&ConversionFn, 0, 0,
1793 Conversion->getConversionType().getNonReferenceType(),
1794 SourceLocation());
1795 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
1796 switch (ICS.ConversionKind) {
1797 case ImplicitConversionSequence::StandardConversion:
1798 Candidate.FinalConversion = ICS.Standard;
1799 break;
1800
1801 case ImplicitConversionSequence::BadConversion:
1802 Candidate.Viable = false;
1803 break;
1804
1805 default:
1806 assert(false &&
1807 "Can only end up with a standard conversion sequence or failure");
1808 }
1809}
1810
Douglas Gregor106c6eb2008-11-19 22:57:39 +00001811/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
1812/// converts the given @c Object to a function pointer via the
1813/// conversion function @c Conversion, and then attempts to call it
1814/// with the given arguments (C++ [over.call.object]p2-4). Proto is
1815/// the type of function that we'll eventually be calling.
1816void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
1817 const FunctionTypeProto *Proto,
1818 Expr *Object, Expr **Args, unsigned NumArgs,
1819 OverloadCandidateSet& CandidateSet) {
1820 CandidateSet.push_back(OverloadCandidate());
1821 OverloadCandidate& Candidate = CandidateSet.back();
1822 Candidate.Function = 0;
1823 Candidate.Surrogate = Conversion;
1824 Candidate.Viable = true;
1825 Candidate.IsSurrogate = true;
1826 Candidate.Conversions.resize(NumArgs + 1);
1827
1828 // Determine the implicit conversion sequence for the implicit
1829 // object parameter.
1830 ImplicitConversionSequence ObjectInit
1831 = TryObjectArgumentInitialization(Object, Conversion);
1832 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
1833 Candidate.Viable = false;
1834 return;
1835 }
1836
1837 // The first conversion is actually a user-defined conversion whose
1838 // first conversion is ObjectInit's standard conversion (which is
1839 // effectively a reference binding). Record it as such.
1840 Candidate.Conversions[0].ConversionKind
1841 = ImplicitConversionSequence::UserDefinedConversion;
1842 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
1843 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
1844 Candidate.Conversions[0].UserDefined.After
1845 = Candidate.Conversions[0].UserDefined.Before;
1846 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
1847
1848 // Find the
1849 unsigned NumArgsInProto = Proto->getNumArgs();
1850
1851 // (C++ 13.3.2p2): A candidate function having fewer than m
1852 // parameters is viable only if it has an ellipsis in its parameter
1853 // list (8.3.5).
1854 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1855 Candidate.Viable = false;
1856 return;
1857 }
1858
1859 // Function types don't have any default arguments, so just check if
1860 // we have enough arguments.
1861 if (NumArgs < NumArgsInProto) {
1862 // Not enough arguments.
1863 Candidate.Viable = false;
1864 return;
1865 }
1866
1867 // Determine the implicit conversion sequences for each of the
1868 // arguments.
1869 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1870 if (ArgIdx < NumArgsInProto) {
1871 // (C++ 13.3.2p3): for F to be a viable function, there shall
1872 // exist for each argument an implicit conversion sequence
1873 // (13.3.3.1) that converts that argument to the corresponding
1874 // parameter of F.
1875 QualType ParamType = Proto->getArgType(ArgIdx);
1876 Candidate.Conversions[ArgIdx + 1]
1877 = TryCopyInitialization(Args[ArgIdx], ParamType,
1878 /*SuppressUserConversions=*/false);
1879 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
1880 == ImplicitConversionSequence::BadConversion) {
1881 Candidate.Viable = false;
1882 break;
1883 }
1884 } else {
1885 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1886 // argument for which there is no corresponding parameter is
1887 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1888 Candidate.Conversions[ArgIdx + 1].ConversionKind
1889 = ImplicitConversionSequence::EllipsisConversion;
1890 }
1891 }
1892}
1893
Douglas Gregor447b69e2008-11-19 03:25:36 +00001894/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1895/// an acceptable non-member overloaded operator for a call whose
1896/// arguments have types T1 (and, if non-empty, T2). This routine
1897/// implements the check in C++ [over.match.oper]p3b2 concerning
1898/// enumeration types.
1899static bool
1900IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1901 QualType T1, QualType T2,
1902 ASTContext &Context) {
1903 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1904 return true;
1905
1906 const FunctionTypeProto *Proto = Fn->getType()->getAsFunctionTypeProto();
1907 if (Proto->getNumArgs() < 1)
1908 return false;
1909
1910 if (T1->isEnumeralType()) {
1911 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
1912 if (Context.getCanonicalType(T1).getUnqualifiedType()
1913 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1914 return true;
1915 }
1916
1917 if (Proto->getNumArgs() < 2)
1918 return false;
1919
1920 if (!T2.isNull() && T2->isEnumeralType()) {
1921 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
1922 if (Context.getCanonicalType(T2).getUnqualifiedType()
1923 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1924 return true;
1925 }
1926
1927 return false;
1928}
1929
Douglas Gregor96176b32008-11-18 23:14:02 +00001930/// AddOperatorCandidates - Add the overloaded operator candidates for
1931/// the operator Op that was used in an operator expression such as "x
1932/// Op y". S is the scope in which the expression occurred (used for
1933/// name lookup of the operator), Args/NumArgs provides the operator
1934/// arguments, and CandidateSet will store the added overload
1935/// candidates. (C++ [over.match.oper]).
1936void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
1937 Expr **Args, unsigned NumArgs,
1938 OverloadCandidateSet& CandidateSet) {
1939 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
1940
1941 // C++ [over.match.oper]p3:
1942 // For a unary operator @ with an operand of a type whose
1943 // cv-unqualified version is T1, and for a binary operator @ with
1944 // a left operand of a type whose cv-unqualified version is T1 and
1945 // a right operand of a type whose cv-unqualified version is T2,
1946 // three sets of candidate functions, designated member
1947 // candidates, non-member candidates and built-in candidates, are
1948 // constructed as follows:
1949 QualType T1 = Args[0]->getType();
1950 QualType T2;
1951 if (NumArgs > 1)
1952 T2 = Args[1]->getType();
1953
1954 // -- If T1 is a class type, the set of member candidates is the
1955 // result of the qualified lookup of T1::operator@
1956 // (13.3.1.1.1); otherwise, the set of member candidates is
1957 // empty.
1958 if (const RecordType *T1Rec = T1->getAsRecordType()) {
Douglas Gregor44b43212008-12-11 16:49:14 +00001959 DeclContext::lookup_const_result Lookup
Douglas Gregore267ff32008-12-11 20:41:00 +00001960 = T1Rec->getDecl()->lookup(Context, OpName);
Douglas Gregor44b43212008-12-11 16:49:14 +00001961 NamedDecl *MemberOps = (Lookup.first == Lookup.second)? 0 : *Lookup.first;
Douglas Gregor96176b32008-11-18 23:14:02 +00001962 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps))
1963 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet,
1964 /*SuppressUserConversions=*/false);
1965 else if (OverloadedFunctionDecl *Ovl
1966 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) {
1967 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
1968 FEnd = Ovl->function_end();
1969 F != FEnd; ++F) {
1970 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F))
1971 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet,
1972 /*SuppressUserConversions=*/false);
1973 }
1974 }
1975 }
1976
1977 // -- The set of non-member candidates is the result of the
1978 // unqualified lookup of operator@ in the context of the
1979 // expression according to the usual rules for name lookup in
1980 // unqualified function calls (3.4.2) except that all member
1981 // functions are ignored. However, if no operand has a class
1982 // type, only those non-member functions in the lookup set
1983 // that have a first parameter of type T1 or “reference to
1984 // (possibly cv-qualified) T1”, when T1 is an enumeration
1985 // type, or (if there is a right operand) a second parameter
1986 // of type T2 or “reference to (possibly cv-qualified) T2”,
1987 // when T2 is an enumeration type, are candidate functions.
1988 {
1989 NamedDecl *NonMemberOps = 0;
1990 for (IdentifierResolver::iterator I
1991 = IdResolver.begin(OpName, CurContext, true/*LookInParentCtx*/);
1992 I != IdResolver.end(); ++I) {
1993 // We don't need to check the identifier namespace, because
1994 // operator names can only be ordinary identifiers.
1995
1996 // Ignore member functions.
1997 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(*I)) {
1998 if (SD->getDeclContext()->isCXXRecord())
1999 continue;
2000 }
2001
2002 // We found something with this name. We're done.
2003 NonMemberOps = *I;
2004 break;
2005 }
2006
Douglas Gregor447b69e2008-11-19 03:25:36 +00002007 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NonMemberOps)) {
2008 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
2009 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2010 /*SuppressUserConversions=*/false);
2011 } else if (OverloadedFunctionDecl *Ovl
2012 = dyn_cast_or_null<OverloadedFunctionDecl>(NonMemberOps)) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002013 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
2014 FEnd = Ovl->function_end();
Douglas Gregor447b69e2008-11-19 03:25:36 +00002015 F != FEnd; ++F) {
2016 if (IsAcceptableNonMemberOperatorCandidate(*F, T1, T2, Context))
2017 AddOverloadCandidate(*F, Args, NumArgs, CandidateSet,
2018 /*SuppressUserConversions=*/false);
2019 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002020 }
2021 }
2022
2023 // Add builtin overload candidates (C++ [over.built]).
Douglas Gregor74253732008-11-19 15:42:04 +00002024 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
Douglas Gregor96176b32008-11-18 23:14:02 +00002025}
2026
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002027/// AddBuiltinCandidate - Add a candidate for a built-in
2028/// operator. ResultTy and ParamTys are the result and parameter types
2029/// of the built-in candidate, respectively. Args and NumArgs are the
2030/// arguments being passed to the candidate.
2031void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2032 Expr **Args, unsigned NumArgs,
2033 OverloadCandidateSet& CandidateSet) {
2034 // Add this candidate
2035 CandidateSet.push_back(OverloadCandidate());
2036 OverloadCandidate& Candidate = CandidateSet.back();
2037 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00002038 Candidate.IsSurrogate = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002039 Candidate.BuiltinTypes.ResultTy = ResultTy;
2040 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2041 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2042
2043 // Determine the implicit conversion sequences for each of the
2044 // arguments.
2045 Candidate.Viable = true;
2046 Candidate.Conversions.resize(NumArgs);
2047 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2048 Candidate.Conversions[ArgIdx]
2049 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx], false);
2050 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002051 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002052 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002053 break;
2054 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002055 }
2056}
2057
2058/// BuiltinCandidateTypeSet - A set of types that will be used for the
2059/// candidate operator functions for built-in operators (C++
2060/// [over.built]). The types are separated into pointer types and
2061/// enumeration types.
2062class BuiltinCandidateTypeSet {
2063 /// TypeSet - A set of types.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002064 typedef llvm::SmallPtrSet<void*, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002065
2066 /// PointerTypes - The set of pointer types that will be used in the
2067 /// built-in candidates.
2068 TypeSet PointerTypes;
2069
2070 /// EnumerationTypes - The set of enumeration types that will be
2071 /// used in the built-in candidates.
2072 TypeSet EnumerationTypes;
2073
2074 /// Context - The AST context in which we will build the type sets.
2075 ASTContext &Context;
2076
2077 bool AddWithMoreQualifiedTypeVariants(QualType Ty);
2078
2079public:
2080 /// iterator - Iterates through the types that are part of the set.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002081 class iterator {
2082 TypeSet::iterator Base;
2083
2084 public:
2085 typedef QualType value_type;
2086 typedef QualType reference;
2087 typedef QualType pointer;
2088 typedef std::ptrdiff_t difference_type;
2089 typedef std::input_iterator_tag iterator_category;
2090
2091 iterator(TypeSet::iterator B) : Base(B) { }
2092
2093 iterator& operator++() {
2094 ++Base;
2095 return *this;
2096 }
2097
2098 iterator operator++(int) {
2099 iterator tmp(*this);
2100 ++(*this);
2101 return tmp;
2102 }
2103
2104 reference operator*() const {
2105 return QualType::getFromOpaquePtr(*Base);
2106 }
2107
2108 pointer operator->() const {
2109 return **this;
2110 }
2111
2112 friend bool operator==(iterator LHS, iterator RHS) {
2113 return LHS.Base == RHS.Base;
2114 }
2115
2116 friend bool operator!=(iterator LHS, iterator RHS) {
2117 return LHS.Base != RHS.Base;
2118 }
2119 };
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002120
2121 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2122
2123 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions = true);
2124
2125 /// pointer_begin - First pointer type found;
2126 iterator pointer_begin() { return PointerTypes.begin(); }
2127
2128 /// pointer_end - Last pointer type found;
2129 iterator pointer_end() { return PointerTypes.end(); }
2130
2131 /// enumeration_begin - First enumeration type found;
2132 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2133
2134 /// enumeration_end - Last enumeration type found;
2135 iterator enumeration_end() { return EnumerationTypes.end(); }
2136};
2137
2138/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2139/// the set of pointer types along with any more-qualified variants of
2140/// that type. For example, if @p Ty is "int const *", this routine
2141/// will add "int const *", "int const volatile *", "int const
2142/// restrict *", and "int const volatile restrict *" to the set of
2143/// pointer types. Returns true if the add of @p Ty itself succeeded,
2144/// false otherwise.
2145bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) {
2146 // Insert this type.
Douglas Gregorbf3af052008-11-13 20:12:29 +00002147 if (!PointerTypes.insert(Ty.getAsOpaquePtr()))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002148 return false;
2149
2150 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2151 QualType PointeeTy = PointerTy->getPointeeType();
2152 // FIXME: Optimize this so that we don't keep trying to add the same types.
2153
2154 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
2155 // with all pointer conversions that don't cast away constness?
2156 if (!PointeeTy.isConstQualified())
2157 AddWithMoreQualifiedTypeVariants
2158 (Context.getPointerType(PointeeTy.withConst()));
2159 if (!PointeeTy.isVolatileQualified())
2160 AddWithMoreQualifiedTypeVariants
2161 (Context.getPointerType(PointeeTy.withVolatile()));
2162 if (!PointeeTy.isRestrictQualified())
2163 AddWithMoreQualifiedTypeVariants
2164 (Context.getPointerType(PointeeTy.withRestrict()));
2165 }
2166
2167 return true;
2168}
2169
2170/// AddTypesConvertedFrom - Add each of the types to which the type @p
2171/// Ty can be implicit converted to the given set of @p Types. We're
2172/// primarily interested in pointer types, enumeration types,
2173void BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2174 bool AllowUserConversions) {
2175 // Only deal with canonical types.
2176 Ty = Context.getCanonicalType(Ty);
2177
2178 // Look through reference types; they aren't part of the type of an
2179 // expression for the purposes of conversions.
2180 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2181 Ty = RefTy->getPointeeType();
2182
2183 // We don't care about qualifiers on the type.
2184 Ty = Ty.getUnqualifiedType();
2185
2186 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2187 QualType PointeeTy = PointerTy->getPointeeType();
2188
2189 // Insert our type, and its more-qualified variants, into the set
2190 // of types.
2191 if (!AddWithMoreQualifiedTypeVariants(Ty))
2192 return;
2193
2194 // Add 'cv void*' to our set of types.
2195 if (!Ty->isVoidType()) {
2196 QualType QualVoid
2197 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2198 AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2199 }
2200
2201 // If this is a pointer to a class type, add pointers to its bases
2202 // (with the same level of cv-qualification as the original
2203 // derived class, of course).
2204 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2205 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2206 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2207 Base != ClassDecl->bases_end(); ++Base) {
2208 QualType BaseTy = Context.getCanonicalType(Base->getType());
2209 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2210
2211 // Add the pointer type, recursively, so that we get all of
2212 // the indirect base classes, too.
2213 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false);
2214 }
2215 }
2216 } else if (Ty->isEnumeralType()) {
Douglas Gregorbf3af052008-11-13 20:12:29 +00002217 EnumerationTypes.insert(Ty.getAsOpaquePtr());
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002218 } else if (AllowUserConversions) {
2219 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2220 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2221 // FIXME: Visit conversion functions in the base classes, too.
2222 OverloadedFunctionDecl *Conversions
2223 = ClassDecl->getConversionFunctions();
2224 for (OverloadedFunctionDecl::function_iterator Func
2225 = Conversions->function_begin();
2226 Func != Conversions->function_end(); ++Func) {
2227 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
2228 AddTypesConvertedFrom(Conv->getConversionType(), false);
2229 }
2230 }
2231 }
2232}
2233
Douglas Gregor74253732008-11-19 15:42:04 +00002234/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2235/// operator overloads to the candidate set (C++ [over.built]), based
2236/// on the operator @p Op and the arguments given. For example, if the
2237/// operator is a binary '+', this routine might add "int
2238/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002239void
Douglas Gregor74253732008-11-19 15:42:04 +00002240Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2241 Expr **Args, unsigned NumArgs,
2242 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002243 // The set of "promoted arithmetic types", which are the arithmetic
2244 // types are that preserved by promotion (C++ [over.built]p2). Note
2245 // that the first few of these types are the promoted integral
2246 // types; these types need to be first.
2247 // FIXME: What about complex?
2248 const unsigned FirstIntegralType = 0;
2249 const unsigned LastIntegralType = 13;
2250 const unsigned FirstPromotedIntegralType = 7,
2251 LastPromotedIntegralType = 13;
2252 const unsigned FirstPromotedArithmeticType = 7,
2253 LastPromotedArithmeticType = 16;
2254 const unsigned NumArithmeticTypes = 16;
2255 QualType ArithmeticTypes[NumArithmeticTypes] = {
2256 Context.BoolTy, Context.CharTy, Context.WCharTy,
2257 Context.SignedCharTy, Context.ShortTy,
2258 Context.UnsignedCharTy, Context.UnsignedShortTy,
2259 Context.IntTy, Context.LongTy, Context.LongLongTy,
2260 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2261 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2262 };
2263
2264 // Find all of the types that the arguments can convert to, but only
2265 // if the operator we're looking at has built-in operator candidates
2266 // that make use of these types.
2267 BuiltinCandidateTypeSet CandidateTypes(Context);
2268 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2269 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00002270 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002271 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00002272 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
2273 (Op == OO_Star && NumArgs == 1)) {
2274 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002275 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType());
2276 }
2277
2278 bool isComparison = false;
2279 switch (Op) {
2280 case OO_None:
2281 case NUM_OVERLOADED_OPERATORS:
2282 assert(false && "Expected an overloaded operator");
2283 break;
2284
Douglas Gregor74253732008-11-19 15:42:04 +00002285 case OO_Star: // '*' is either unary or binary
2286 if (NumArgs == 1)
2287 goto UnaryStar;
2288 else
2289 goto BinaryStar;
2290 break;
2291
2292 case OO_Plus: // '+' is either unary or binary
2293 if (NumArgs == 1)
2294 goto UnaryPlus;
2295 else
2296 goto BinaryPlus;
2297 break;
2298
2299 case OO_Minus: // '-' is either unary or binary
2300 if (NumArgs == 1)
2301 goto UnaryMinus;
2302 else
2303 goto BinaryMinus;
2304 break;
2305
2306 case OO_Amp: // '&' is either unary or binary
2307 if (NumArgs == 1)
2308 goto UnaryAmp;
2309 else
2310 goto BinaryAmp;
2311
2312 case OO_PlusPlus:
2313 case OO_MinusMinus:
2314 // C++ [over.built]p3:
2315 //
2316 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2317 // is either volatile or empty, there exist candidate operator
2318 // functions of the form
2319 //
2320 // VQ T& operator++(VQ T&);
2321 // T operator++(VQ T&, int);
2322 //
2323 // C++ [over.built]p4:
2324 //
2325 // For every pair (T, VQ), where T is an arithmetic type other
2326 // than bool, and VQ is either volatile or empty, there exist
2327 // candidate operator functions of the form
2328 //
2329 // VQ T& operator--(VQ T&);
2330 // T operator--(VQ T&, int);
2331 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2332 Arith < NumArithmeticTypes; ++Arith) {
2333 QualType ArithTy = ArithmeticTypes[Arith];
2334 QualType ParamTypes[2]
2335 = { Context.getReferenceType(ArithTy), Context.IntTy };
2336
2337 // Non-volatile version.
2338 if (NumArgs == 1)
2339 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2340 else
2341 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2342
2343 // Volatile version
2344 ParamTypes[0] = Context.getReferenceType(ArithTy.withVolatile());
2345 if (NumArgs == 1)
2346 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2347 else
2348 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2349 }
2350
2351 // C++ [over.built]p5:
2352 //
2353 // For every pair (T, VQ), where T is a cv-qualified or
2354 // cv-unqualified object type, and VQ is either volatile or
2355 // empty, there exist candidate operator functions of the form
2356 //
2357 // T*VQ& operator++(T*VQ&);
2358 // T*VQ& operator--(T*VQ&);
2359 // T* operator++(T*VQ&, int);
2360 // T* operator--(T*VQ&, int);
2361 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2362 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2363 // Skip pointer types that aren't pointers to object types.
Douglas Gregorcb7de522008-11-26 23:31:11 +00002364 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00002365 continue;
2366
2367 QualType ParamTypes[2] = {
2368 Context.getReferenceType(*Ptr), Context.IntTy
2369 };
2370
2371 // Without volatile
2372 if (NumArgs == 1)
2373 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2374 else
2375 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2376
2377 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2378 // With volatile
2379 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2380 if (NumArgs == 1)
2381 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2382 else
2383 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2384 }
2385 }
2386 break;
2387
2388 UnaryStar:
2389 // C++ [over.built]p6:
2390 // For every cv-qualified or cv-unqualified object type T, there
2391 // exist candidate operator functions of the form
2392 //
2393 // T& operator*(T*);
2394 //
2395 // C++ [over.built]p7:
2396 // For every function type T, there exist candidate operator
2397 // functions of the form
2398 // T& operator*(T*);
2399 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2400 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2401 QualType ParamTy = *Ptr;
2402 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
2403 AddBuiltinCandidate(Context.getReferenceType(PointeeTy),
2404 &ParamTy, Args, 1, CandidateSet);
2405 }
2406 break;
2407
2408 UnaryPlus:
2409 // C++ [over.built]p8:
2410 // For every type T, there exist candidate operator functions of
2411 // the form
2412 //
2413 // T* operator+(T*);
2414 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2415 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2416 QualType ParamTy = *Ptr;
2417 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2418 }
2419
2420 // Fall through
2421
2422 UnaryMinus:
2423 // C++ [over.built]p9:
2424 // For every promoted arithmetic type T, there exist candidate
2425 // operator functions of the form
2426 //
2427 // T operator+(T);
2428 // T operator-(T);
2429 for (unsigned Arith = FirstPromotedArithmeticType;
2430 Arith < LastPromotedArithmeticType; ++Arith) {
2431 QualType ArithTy = ArithmeticTypes[Arith];
2432 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2433 }
2434 break;
2435
2436 case OO_Tilde:
2437 // C++ [over.built]p10:
2438 // For every promoted integral type T, there exist candidate
2439 // operator functions of the form
2440 //
2441 // T operator~(T);
2442 for (unsigned Int = FirstPromotedIntegralType;
2443 Int < LastPromotedIntegralType; ++Int) {
2444 QualType IntTy = ArithmeticTypes[Int];
2445 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2446 }
2447 break;
2448
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002449 case OO_New:
2450 case OO_Delete:
2451 case OO_Array_New:
2452 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002453 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00002454 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002455 break;
2456
2457 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00002458 UnaryAmp:
2459 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002460 // C++ [over.match.oper]p3:
2461 // -- For the operator ',', the unary operator '&', or the
2462 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002463 break;
2464
2465 case OO_Less:
2466 case OO_Greater:
2467 case OO_LessEqual:
2468 case OO_GreaterEqual:
2469 case OO_EqualEqual:
2470 case OO_ExclaimEqual:
2471 // C++ [over.built]p15:
2472 //
2473 // For every pointer or enumeration type T, there exist
2474 // candidate operator functions of the form
2475 //
2476 // bool operator<(T, T);
2477 // bool operator>(T, T);
2478 // bool operator<=(T, T);
2479 // bool operator>=(T, T);
2480 // bool operator==(T, T);
2481 // bool operator!=(T, T);
2482 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2483 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2484 QualType ParamTypes[2] = { *Ptr, *Ptr };
2485 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2486 }
2487 for (BuiltinCandidateTypeSet::iterator Enum
2488 = CandidateTypes.enumeration_begin();
2489 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2490 QualType ParamTypes[2] = { *Enum, *Enum };
2491 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2492 }
2493
2494 // Fall through.
2495 isComparison = true;
2496
Douglas Gregor74253732008-11-19 15:42:04 +00002497 BinaryPlus:
2498 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002499 if (!isComparison) {
2500 // We didn't fall through, so we must have OO_Plus or OO_Minus.
2501
2502 // C++ [over.built]p13:
2503 //
2504 // For every cv-qualified or cv-unqualified object type T
2505 // there exist candidate operator functions of the form
2506 //
2507 // T* operator+(T*, ptrdiff_t);
2508 // T& operator[](T*, ptrdiff_t); [BELOW]
2509 // T* operator-(T*, ptrdiff_t);
2510 // T* operator+(ptrdiff_t, T*);
2511 // T& operator[](ptrdiff_t, T*); [BELOW]
2512 //
2513 // C++ [over.built]p14:
2514 //
2515 // For every T, where T is a pointer to object type, there
2516 // exist candidate operator functions of the form
2517 //
2518 // ptrdiff_t operator-(T, T);
2519 for (BuiltinCandidateTypeSet::iterator Ptr
2520 = CandidateTypes.pointer_begin();
2521 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2522 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2523
2524 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
2525 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2526
2527 if (Op == OO_Plus) {
2528 // T* operator+(ptrdiff_t, T*);
2529 ParamTypes[0] = ParamTypes[1];
2530 ParamTypes[1] = *Ptr;
2531 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2532 } else {
2533 // ptrdiff_t operator-(T, T);
2534 ParamTypes[1] = *Ptr;
2535 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
2536 Args, 2, CandidateSet);
2537 }
2538 }
2539 }
2540 // Fall through
2541
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002542 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00002543 BinaryStar:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002544 // C++ [over.built]p12:
2545 //
2546 // For every pair of promoted arithmetic types L and R, there
2547 // exist candidate operator functions of the form
2548 //
2549 // LR operator*(L, R);
2550 // LR operator/(L, R);
2551 // LR operator+(L, R);
2552 // LR operator-(L, R);
2553 // bool operator<(L, R);
2554 // bool operator>(L, R);
2555 // bool operator<=(L, R);
2556 // bool operator>=(L, R);
2557 // bool operator==(L, R);
2558 // bool operator!=(L, R);
2559 //
2560 // where LR is the result of the usual arithmetic conversions
2561 // between types L and R.
2562 for (unsigned Left = FirstPromotedArithmeticType;
2563 Left < LastPromotedArithmeticType; ++Left) {
2564 for (unsigned Right = FirstPromotedArithmeticType;
2565 Right < LastPromotedArithmeticType; ++Right) {
2566 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2567 QualType Result
2568 = isComparison? Context.BoolTy
2569 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2570 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2571 }
2572 }
2573 break;
2574
2575 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00002576 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002577 case OO_Caret:
2578 case OO_Pipe:
2579 case OO_LessLess:
2580 case OO_GreaterGreater:
2581 // C++ [over.built]p17:
2582 //
2583 // For every pair of promoted integral types L and R, there
2584 // exist candidate operator functions of the form
2585 //
2586 // LR operator%(L, R);
2587 // LR operator&(L, R);
2588 // LR operator^(L, R);
2589 // LR operator|(L, R);
2590 // L operator<<(L, R);
2591 // L operator>>(L, R);
2592 //
2593 // where LR is the result of the usual arithmetic conversions
2594 // between types L and R.
2595 for (unsigned Left = FirstPromotedIntegralType;
2596 Left < LastPromotedIntegralType; ++Left) {
2597 for (unsigned Right = FirstPromotedIntegralType;
2598 Right < LastPromotedIntegralType; ++Right) {
2599 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2600 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
2601 ? LandR[0]
2602 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2603 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2604 }
2605 }
2606 break;
2607
2608 case OO_Equal:
2609 // C++ [over.built]p20:
2610 //
2611 // For every pair (T, VQ), where T is an enumeration or
2612 // (FIXME:) pointer to member type and VQ is either volatile or
2613 // empty, there exist candidate operator functions of the form
2614 //
2615 // VQ T& operator=(VQ T&, T);
2616 for (BuiltinCandidateTypeSet::iterator Enum
2617 = CandidateTypes.enumeration_begin();
2618 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2619 QualType ParamTypes[2];
2620
2621 // T& operator=(T&, T)
2622 ParamTypes[0] = Context.getReferenceType(*Enum);
2623 ParamTypes[1] = *Enum;
2624 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2625
Douglas Gregor74253732008-11-19 15:42:04 +00002626 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
2627 // volatile T& operator=(volatile T&, T)
2628 ParamTypes[0] = Context.getReferenceType((*Enum).withVolatile());
2629 ParamTypes[1] = *Enum;
2630 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2631 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002632 }
2633 // Fall through.
2634
2635 case OO_PlusEqual:
2636 case OO_MinusEqual:
2637 // C++ [over.built]p19:
2638 //
2639 // For every pair (T, VQ), where T is any type and VQ is either
2640 // volatile or empty, there exist candidate operator functions
2641 // of the form
2642 //
2643 // T*VQ& operator=(T*VQ&, T*);
2644 //
2645 // C++ [over.built]p21:
2646 //
2647 // For every pair (T, VQ), where T is a cv-qualified or
2648 // cv-unqualified object type and VQ is either volatile or
2649 // empty, there exist candidate operator functions of the form
2650 //
2651 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
2652 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
2653 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2654 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2655 QualType ParamTypes[2];
2656 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
2657
2658 // non-volatile version
2659 ParamTypes[0] = Context.getReferenceType(*Ptr);
2660 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2661
Douglas Gregor74253732008-11-19 15:42:04 +00002662 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2663 // volatile version
2664 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2665 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2666 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002667 }
2668 // Fall through.
2669
2670 case OO_StarEqual:
2671 case OO_SlashEqual:
2672 // C++ [over.built]p18:
2673 //
2674 // For every triple (L, VQ, R), where L is an arithmetic type,
2675 // VQ is either volatile or empty, and R is a promoted
2676 // arithmetic type, there exist candidate operator functions of
2677 // the form
2678 //
2679 // VQ L& operator=(VQ L&, R);
2680 // VQ L& operator*=(VQ L&, R);
2681 // VQ L& operator/=(VQ L&, R);
2682 // VQ L& operator+=(VQ L&, R);
2683 // VQ L& operator-=(VQ L&, R);
2684 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
2685 for (unsigned Right = FirstPromotedArithmeticType;
2686 Right < LastPromotedArithmeticType; ++Right) {
2687 QualType ParamTypes[2];
2688 ParamTypes[1] = ArithmeticTypes[Right];
2689
2690 // Add this built-in operator as a candidate (VQ is empty).
2691 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
2692 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2693
2694 // Add this built-in operator as a candidate (VQ is 'volatile').
2695 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
2696 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
2697 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2698 }
2699 }
2700 break;
2701
2702 case OO_PercentEqual:
2703 case OO_LessLessEqual:
2704 case OO_GreaterGreaterEqual:
2705 case OO_AmpEqual:
2706 case OO_CaretEqual:
2707 case OO_PipeEqual:
2708 // C++ [over.built]p22:
2709 //
2710 // For every triple (L, VQ, R), where L is an integral type, VQ
2711 // is either volatile or empty, and R is a promoted integral
2712 // type, there exist candidate operator functions of the form
2713 //
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 // VQ L& operator^=(VQ L&, R);
2719 // VQ L& operator|=(VQ L&, R);
2720 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
2721 for (unsigned Right = FirstPromotedIntegralType;
2722 Right < LastPromotedIntegralType; ++Right) {
2723 QualType ParamTypes[2];
2724 ParamTypes[1] = ArithmeticTypes[Right];
2725
2726 // Add this built-in operator as a candidate (VQ is empty).
2727 // FIXME: We should be caching these declarations somewhere,
2728 // rather than re-building them every time.
2729 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
2730 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2731
2732 // Add this built-in operator as a candidate (VQ is 'volatile').
2733 ParamTypes[0] = ArithmeticTypes[Left];
2734 ParamTypes[0].addVolatile();
2735 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
2736 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2737 }
2738 }
2739 break;
2740
Douglas Gregor74253732008-11-19 15:42:04 +00002741 case OO_Exclaim: {
2742 // C++ [over.operator]p23:
2743 //
2744 // There also exist candidate operator functions of the form
2745 //
2746 // bool operator!(bool);
2747 // bool operator&&(bool, bool); [BELOW]
2748 // bool operator||(bool, bool); [BELOW]
2749 QualType ParamTy = Context.BoolTy;
2750 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2751 break;
2752 }
2753
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002754 case OO_AmpAmp:
2755 case OO_PipePipe: {
2756 // C++ [over.operator]p23:
2757 //
2758 // There also exist candidate operator functions of the form
2759 //
Douglas Gregor74253732008-11-19 15:42:04 +00002760 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002761 // bool operator&&(bool, bool);
2762 // bool operator||(bool, bool);
2763 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
2764 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2765 break;
2766 }
2767
2768 case OO_Subscript:
2769 // C++ [over.built]p13:
2770 //
2771 // For every cv-qualified or cv-unqualified object type T there
2772 // exist candidate operator functions of the form
2773 //
2774 // T* operator+(T*, ptrdiff_t); [ABOVE]
2775 // T& operator[](T*, ptrdiff_t);
2776 // T* operator-(T*, ptrdiff_t); [ABOVE]
2777 // T* operator+(ptrdiff_t, T*); [ABOVE]
2778 // T& operator[](ptrdiff_t, T*);
2779 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2780 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2781 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2782 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
2783 QualType ResultTy = Context.getReferenceType(PointeeType);
2784
2785 // T& operator[](T*, ptrdiff_t)
2786 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
2787
2788 // T& operator[](ptrdiff_t, T*);
2789 ParamTypes[0] = ParamTypes[1];
2790 ParamTypes[1] = *Ptr;
2791 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
2792 }
2793 break;
2794
2795 case OO_ArrowStar:
2796 // FIXME: No support for pointer-to-members yet.
2797 break;
2798 }
2799}
2800
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002801/// AddOverloadCandidates - Add all of the function overloads in Ovl
2802/// to the candidate set.
2803void
Douglas Gregor18fe5682008-11-03 20:45:27 +00002804Sema::AddOverloadCandidates(const OverloadedFunctionDecl *Ovl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002805 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002806 OverloadCandidateSet& CandidateSet,
2807 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002808{
Douglas Gregor18fe5682008-11-03 20:45:27 +00002809 for (OverloadedFunctionDecl::function_const_iterator Func
2810 = Ovl->function_begin();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002811 Func != Ovl->function_end(); ++Func)
Douglas Gregor225c41e2008-11-03 19:09:14 +00002812 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet,
2813 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002814}
2815
2816/// isBetterOverloadCandidate - Determines whether the first overload
2817/// candidate is a better candidate than the second (C++ 13.3.3p1).
2818bool
2819Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
2820 const OverloadCandidate& Cand2)
2821{
2822 // Define viable functions to be better candidates than non-viable
2823 // functions.
2824 if (!Cand2.Viable)
2825 return Cand1.Viable;
2826 else if (!Cand1.Viable)
2827 return false;
2828
2829 // FIXME: Deal with the implicit object parameter for static member
2830 // functions. (C++ 13.3.3p1).
2831
2832 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
2833 // function than another viable function F2 if for all arguments i,
2834 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
2835 // then...
2836 unsigned NumArgs = Cand1.Conversions.size();
2837 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
2838 bool HasBetterConversion = false;
2839 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2840 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
2841 Cand2.Conversions[ArgIdx])) {
2842 case ImplicitConversionSequence::Better:
2843 // Cand1 has a better conversion sequence.
2844 HasBetterConversion = true;
2845 break;
2846
2847 case ImplicitConversionSequence::Worse:
2848 // Cand1 can't be better than Cand2.
2849 return false;
2850
2851 case ImplicitConversionSequence::Indistinguishable:
2852 // Do nothing.
2853 break;
2854 }
2855 }
2856
2857 if (HasBetterConversion)
2858 return true;
2859
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002860 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
2861 // implemented, but they require template support.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002862
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002863 // C++ [over.match.best]p1b4:
2864 //
2865 // -- the context is an initialization by user-defined conversion
2866 // (see 8.5, 13.3.1.5) and the standard conversion sequence
2867 // from the return type of F1 to the destination type (i.e.,
2868 // the type of the entity being initialized) is a better
2869 // conversion sequence than the standard conversion sequence
2870 // from the return type of F2 to the destination type.
Douglas Gregor447b69e2008-11-19 03:25:36 +00002871 if (Cand1.Function && Cand2.Function &&
2872 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002873 isa<CXXConversionDecl>(Cand2.Function)) {
2874 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
2875 Cand2.FinalConversion)) {
2876 case ImplicitConversionSequence::Better:
2877 // Cand1 has a better conversion sequence.
2878 return true;
2879
2880 case ImplicitConversionSequence::Worse:
2881 // Cand1 can't be better than Cand2.
2882 return false;
2883
2884 case ImplicitConversionSequence::Indistinguishable:
2885 // Do nothing
2886 break;
2887 }
2888 }
2889
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002890 return false;
2891}
2892
2893/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
2894/// within an overload candidate set. If overloading is successful,
2895/// the result will be OR_Success and Best will be set to point to the
2896/// best viable function within the candidate set. Otherwise, one of
2897/// several kinds of errors will be returned; see
2898/// Sema::OverloadingResult.
2899Sema::OverloadingResult
2900Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
2901 OverloadCandidateSet::iterator& Best)
2902{
2903 // Find the best viable function.
2904 Best = CandidateSet.end();
2905 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2906 Cand != CandidateSet.end(); ++Cand) {
2907 if (Cand->Viable) {
2908 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
2909 Best = Cand;
2910 }
2911 }
2912
2913 // If we didn't find any viable functions, abort.
2914 if (Best == CandidateSet.end())
2915 return OR_No_Viable_Function;
2916
2917 // Make sure that this function is better than every other viable
2918 // function. If not, we have an ambiguity.
2919 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2920 Cand != CandidateSet.end(); ++Cand) {
2921 if (Cand->Viable &&
2922 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002923 !isBetterOverloadCandidate(*Best, *Cand)) {
2924 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002925 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002926 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002927 }
2928
2929 // Best is the best viable function.
2930 return OR_Success;
2931}
2932
2933/// PrintOverloadCandidates - When overload resolution fails, prints
2934/// diagnostic messages containing the candidates in the candidate
2935/// set. If OnlyViable is true, only viable candidates will be printed.
2936void
2937Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
2938 bool OnlyViable)
2939{
2940 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
2941 LastCand = CandidateSet.end();
2942 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002943 if (Cand->Viable || !OnlyViable) {
2944 if (Cand->Function) {
2945 // Normal function
2946 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002947 } else if (Cand->IsSurrogate) {
Douglas Gregor621b3932008-11-21 02:54:28 +00002948 // Desugar the type of the surrogate down to a function type,
2949 // retaining as many typedefs as possible while still showing
2950 // the function type (and, therefore, its parameter types).
2951 QualType FnType = Cand->Surrogate->getConversionType();
2952 bool isReference = false;
2953 bool isPointer = false;
2954 if (const ReferenceType *FnTypeRef = FnType->getAsReferenceType()) {
2955 FnType = FnTypeRef->getPointeeType();
2956 isReference = true;
2957 }
2958 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
2959 FnType = FnTypePtr->getPointeeType();
2960 isPointer = true;
2961 }
2962 // Desugar down to a function type.
2963 FnType = QualType(FnType->getAsFunctionType(), 0);
2964 // Reconstruct the pointer/reference as appropriate.
2965 if (isPointer) FnType = Context.getPointerType(FnType);
2966 if (isReference) FnType = Context.getReferenceType(FnType);
2967
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002968 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattnerd1625842008-11-24 06:25:27 +00002969 << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002970 } else {
2971 // FIXME: We need to get the identifier in here
2972 // FIXME: Do we want the error message to point at the
2973 // operator? (built-ins won't have a location)
2974 QualType FnType
2975 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
2976 Cand->BuiltinTypes.ParamTypes,
2977 Cand->Conversions.size(),
2978 false, 0);
2979
Chris Lattnerd1625842008-11-24 06:25:27 +00002980 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002981 }
2982 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002983 }
2984}
2985
Douglas Gregor904eed32008-11-10 20:40:00 +00002986/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
2987/// an overloaded function (C++ [over.over]), where @p From is an
2988/// expression with overloaded function type and @p ToType is the type
2989/// we're trying to resolve to. For example:
2990///
2991/// @code
2992/// int f(double);
2993/// int f(int);
2994///
2995/// int (*pfd)(double) = f; // selects f(double)
2996/// @endcode
2997///
2998/// This routine returns the resulting FunctionDecl if it could be
2999/// resolved, and NULL otherwise. When @p Complain is true, this
3000/// routine will emit diagnostics if there is an error.
3001FunctionDecl *
3002Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
3003 bool Complain) {
3004 QualType FunctionType = ToType;
3005 if (const PointerLikeType *ToTypePtr = ToType->getAsPointerLikeType())
3006 FunctionType = ToTypePtr->getPointeeType();
3007
3008 // We only look at pointers or references to functions.
3009 if (!FunctionType->isFunctionType())
3010 return 0;
3011
3012 // Find the actual overloaded function declaration.
3013 OverloadedFunctionDecl *Ovl = 0;
3014
3015 // C++ [over.over]p1:
3016 // [...] [Note: any redundant set of parentheses surrounding the
3017 // overloaded function name is ignored (5.1). ]
3018 Expr *OvlExpr = From->IgnoreParens();
3019
3020 // C++ [over.over]p1:
3021 // [...] The overloaded function name can be preceded by the &
3022 // operator.
3023 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3024 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3025 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3026 }
3027
3028 // Try to dig out the overloaded function.
3029 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
3030 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
3031
3032 // If there's no overloaded function declaration, we're done.
3033 if (!Ovl)
3034 return 0;
3035
3036 // Look through all of the overloaded functions, searching for one
3037 // whose type matches exactly.
3038 // FIXME: When templates or using declarations come along, we'll actually
3039 // have to deal with duplicates, partial ordering, etc. For now, we
3040 // can just do a simple search.
3041 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
3042 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
3043 Fun != Ovl->function_end(); ++Fun) {
3044 // C++ [over.over]p3:
3045 // Non-member functions and static member functions match
3046 // targets of type “pointer-to-function”or
3047 // “reference-to-function.”
3048 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun))
3049 if (!Method->isStatic())
3050 continue;
3051
3052 if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
3053 return *Fun;
3054 }
3055
3056 return 0;
3057}
3058
Douglas Gregorf6b89692008-11-26 05:54:23 +00003059/// ResolveOverloadedCallFn - Given the call expression that calls Fn
3060/// (which eventually refers to the set of overloaded functions in
3061/// Ovl) and the call arguments Args/NumArgs, attempt to resolve the
3062/// function call down to a specific function. If overload resolution
Douglas Gregor0a396682008-11-26 06:01:48 +00003063/// succeeds, returns the function declaration produced by overload
3064/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00003065/// arguments and Fn, and returns NULL.
Douglas Gregor0a396682008-11-26 06:01:48 +00003066FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, OverloadedFunctionDecl *Ovl,
3067 SourceLocation LParenLoc,
3068 Expr **Args, unsigned NumArgs,
3069 SourceLocation *CommaLocs,
3070 SourceLocation RParenLoc) {
Douglas Gregorf6b89692008-11-26 05:54:23 +00003071 OverloadCandidateSet CandidateSet;
3072 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet);
3073 OverloadCandidateSet::iterator Best;
3074 switch (BestViableFunction(CandidateSet, Best)) {
Douglas Gregor0a396682008-11-26 06:01:48 +00003075 case OR_Success:
3076 return Best->Function;
Douglas Gregorf6b89692008-11-26 05:54:23 +00003077
3078 case OR_No_Viable_Function:
3079 Diag(Fn->getSourceRange().getBegin(),
3080 diag::err_ovl_no_viable_function_in_call)
3081 << Ovl->getDeclName() << (unsigned)CandidateSet.size()
3082 << Fn->getSourceRange();
3083 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3084 break;
3085
3086 case OR_Ambiguous:
3087 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
3088 << Ovl->getDeclName() << Fn->getSourceRange();
3089 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3090 break;
3091 }
3092
3093 // Overload resolution failed. Destroy all of the subexpressions and
3094 // return NULL.
3095 Fn->Destroy(Context);
3096 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3097 Args[Arg]->Destroy(Context);
3098 return 0;
3099}
3100
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003101/// BuildCallToObjectOfClassType - Build a call to an object of class
3102/// type (C++ [over.call.object]), which can end up invoking an
3103/// overloaded function call operator (@c operator()) or performing a
3104/// user-defined conversion on the object argument.
3105Action::ExprResult
Douglas Gregor5c37de72008-12-06 00:22:45 +00003106Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
3107 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003108 Expr **Args, unsigned NumArgs,
3109 SourceLocation *CommaLocs,
3110 SourceLocation RParenLoc) {
3111 assert(Object->getType()->isRecordType() && "Requires object type argument");
3112 const RecordType *Record = Object->getType()->getAsRecordType();
3113
3114 // C++ [over.call.object]p1:
3115 // If the primary-expression E in the function call syntax
3116 // evaluates to a class object of type “cv T”, then the set of
3117 // candidate functions includes at least the function call
3118 // operators of T. The function call operators of T are obtained by
3119 // ordinary lookup of the name operator() in the context of
3120 // (E).operator().
3121 OverloadCandidateSet CandidateSet;
Douglas Gregor44b43212008-12-11 16:49:14 +00003122 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
3123 DeclContext::lookup_const_result Lookup
Douglas Gregore267ff32008-12-11 20:41:00 +00003124 = Record->getDecl()->lookup(Context, OpName);
Douglas Gregor44b43212008-12-11 16:49:14 +00003125 NamedDecl *MemberOps = (Lookup.first == Lookup.second)? 0 : *Lookup.first;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003126 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps))
3127 AddMethodCandidate(Method, Object, Args, NumArgs, CandidateSet,
3128 /*SuppressUserConversions=*/false);
3129 else if (OverloadedFunctionDecl *Ovl
3130 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) {
3131 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
3132 FEnd = Ovl->function_end();
3133 F != FEnd; ++F) {
3134 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F))
3135 AddMethodCandidate(Method, Object, Args, NumArgs, CandidateSet,
3136 /*SuppressUserConversions=*/false);
3137 }
3138 }
3139
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003140 // C++ [over.call.object]p2:
3141 // In addition, for each conversion function declared in T of the
3142 // form
3143 //
3144 // operator conversion-type-id () cv-qualifier;
3145 //
3146 // where cv-qualifier is the same cv-qualification as, or a
3147 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00003148 // denotes the type "pointer to function of (P1,...,Pn) returning
3149 // R", or the type "reference to pointer to function of
3150 // (P1,...,Pn) returning R", or the type "reference to function
3151 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003152 // is also considered as a candidate function. Similarly,
3153 // surrogate call functions are added to the set of candidate
3154 // functions for each conversion function declared in an
3155 // accessible base class provided the function is not hidden
3156 // within T by another intervening declaration.
3157 //
3158 // FIXME: Look in base classes for more conversion operators!
3159 OverloadedFunctionDecl *Conversions
3160 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor621b3932008-11-21 02:54:28 +00003161 for (OverloadedFunctionDecl::function_iterator
3162 Func = Conversions->function_begin(),
3163 FuncEnd = Conversions->function_end();
3164 Func != FuncEnd; ++Func) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003165 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
3166
3167 // Strip the reference type (if any) and then the pointer type (if
3168 // any) to get down to what might be a function type.
3169 QualType ConvType = Conv->getConversionType().getNonReferenceType();
3170 if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
3171 ConvType = ConvPtrType->getPointeeType();
3172
3173 if (const FunctionTypeProto *Proto = ConvType->getAsFunctionTypeProto())
3174 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
3175 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003176
3177 // Perform overload resolution.
3178 OverloadCandidateSet::iterator Best;
3179 switch (BestViableFunction(CandidateSet, Best)) {
3180 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003181 // Overload resolution succeeded; we'll build the appropriate call
3182 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003183 break;
3184
3185 case OR_No_Viable_Function:
Sebastian Redle4c452c2008-11-22 13:44:36 +00003186 Diag(Object->getSourceRange().getBegin(),
3187 diag::err_ovl_no_viable_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00003188 << Object->getType() << (unsigned)CandidateSet.size()
Sebastian Redle4c452c2008-11-22 13:44:36 +00003189 << Object->getSourceRange();
3190 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003191 break;
3192
3193 case OR_Ambiguous:
3194 Diag(Object->getSourceRange().getBegin(),
3195 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00003196 << Object->getType() << Object->getSourceRange();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003197 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3198 break;
3199 }
3200
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003201 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003202 // We had an error; delete all of the subexpressions and return
3203 // the error.
3204 delete Object;
3205 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3206 delete Args[ArgIdx];
3207 return true;
3208 }
3209
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003210 if (Best->Function == 0) {
3211 // Since there is no function declaration, this is one of the
3212 // surrogate candidates. Dig out the conversion function.
3213 CXXConversionDecl *Conv
3214 = cast<CXXConversionDecl>(
3215 Best->Conversions[0].UserDefined.ConversionFunction);
3216
3217 // We selected one of the surrogate functions that converts the
3218 // object parameter to a function pointer. Perform the conversion
3219 // on the object argument, then let ActOnCallExpr finish the job.
3220 // FIXME: Represent the user-defined conversion in the AST!
3221 ImpCastExprToType(Object,
3222 Conv->getConversionType().getNonReferenceType(),
3223 Conv->getConversionType()->isReferenceType());
Douglas Gregor5c37de72008-12-06 00:22:45 +00003224 return ActOnCallExpr(S, (ExprTy*)Object, LParenLoc, (ExprTy**)Args, NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003225 CommaLocs, RParenLoc);
3226 }
3227
3228 // We found an overloaded operator(). Build a CXXOperatorCallExpr
3229 // that calls this method, using Object for the implicit object
3230 // parameter and passing along the remaining arguments.
3231 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00003232 const FunctionTypeProto *Proto = Method->getType()->getAsFunctionTypeProto();
3233
3234 unsigned NumArgsInProto = Proto->getNumArgs();
3235 unsigned NumArgsToCheck = NumArgs;
3236
3237 // Build the full argument list for the method call (the
3238 // implicit object parameter is placed at the beginning of the
3239 // list).
3240 Expr **MethodArgs;
3241 if (NumArgs < NumArgsInProto) {
3242 NumArgsToCheck = NumArgsInProto;
3243 MethodArgs = new Expr*[NumArgsInProto + 1];
3244 } else {
3245 MethodArgs = new Expr*[NumArgs + 1];
3246 }
3247 MethodArgs[0] = Object;
3248 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3249 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
3250
3251 Expr *NewFn = new DeclRefExpr(Method, Method->getType(),
3252 SourceLocation());
3253 UsualUnaryConversions(NewFn);
3254
3255 // Once we've built TheCall, all of the expressions are properly
3256 // owned.
3257 QualType ResultTy = Method->getResultType().getNonReferenceType();
3258 llvm::OwningPtr<CXXOperatorCallExpr>
3259 TheCall(new CXXOperatorCallExpr(NewFn, MethodArgs, NumArgs + 1,
3260 ResultTy, RParenLoc));
3261 delete [] MethodArgs;
3262
3263 // Initialize the implicit object parameter.
3264 if (!PerformObjectArgumentInitialization(Object, Method))
3265 return true;
3266 TheCall->setArg(0, Object);
3267
3268 // Check the argument types.
3269 for (unsigned i = 0; i != NumArgsToCheck; i++) {
3270 QualType ProtoArgType = Proto->getArgType(i);
3271
3272 Expr *Arg;
3273 if (i < NumArgs)
3274 Arg = Args[i];
3275 else
3276 Arg = new CXXDefaultArgExpr(Method->getParamDecl(i));
3277 QualType ArgType = Arg->getType();
3278
3279 // Pass the argument.
3280 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3281 return true;
3282
3283 TheCall->setArg(i + 1, Arg);
3284 }
3285
3286 // If this is a variadic call, handle args passed through "...".
3287 if (Proto->isVariadic()) {
3288 // Promote the arguments (C99 6.5.2.2p7).
3289 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3290 Expr *Arg = Args[i];
3291 DefaultArgumentPromotion(Arg);
3292 TheCall->setArg(i + 1, Arg);
3293 }
3294 }
3295
3296 return CheckFunctionCall(Method, TheCall.take());
3297}
3298
Douglas Gregor8ba10742008-11-20 16:27:02 +00003299/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
3300/// (if one exists), where @c Base is an expression of class type and
3301/// @c Member is the name of the member we're trying to find.
3302Action::ExprResult
3303Sema::BuildOverloadedArrowExpr(Expr *Base, SourceLocation OpLoc,
3304 SourceLocation MemberLoc,
3305 IdentifierInfo &Member) {
3306 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
3307
3308 // C++ [over.ref]p1:
3309 //
3310 // [...] An expression x->m is interpreted as (x.operator->())->m
3311 // for a class object x of type T if T::operator->() exists and if
3312 // the operator is selected as the best match function by the
3313 // overload resolution mechanism (13.3).
3314 // FIXME: look in base classes.
3315 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
3316 OverloadCandidateSet CandidateSet;
3317 const RecordType *BaseRecord = Base->getType()->getAsRecordType();
Douglas Gregor44b43212008-12-11 16:49:14 +00003318 DeclContext::lookup_const_result Lookup
Douglas Gregore267ff32008-12-11 20:41:00 +00003319 = BaseRecord->getDecl()->lookup(Context, OpName);
Douglas Gregor44b43212008-12-11 16:49:14 +00003320 NamedDecl *MemberOps = (Lookup.first == Lookup.second)? 0 : *Lookup.first;
Douglas Gregor8ba10742008-11-20 16:27:02 +00003321 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps))
3322 AddMethodCandidate(Method, Base, 0, 0, CandidateSet,
3323 /*SuppressUserConversions=*/false);
3324 else if (OverloadedFunctionDecl *Ovl
3325 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) {
3326 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
3327 FEnd = Ovl->function_end();
3328 F != FEnd; ++F) {
3329 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F))
3330 AddMethodCandidate(Method, Base, 0, 0, CandidateSet,
3331 /*SuppressUserConversions=*/false);
3332 }
3333 }
3334
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003335 llvm::OwningPtr<Expr> BasePtr(Base);
3336
Douglas Gregor8ba10742008-11-20 16:27:02 +00003337 // Perform overload resolution.
3338 OverloadCandidateSet::iterator Best;
3339 switch (BestViableFunction(CandidateSet, Best)) {
3340 case OR_Success:
3341 // Overload resolution succeeded; we'll build the call below.
3342 break;
3343
3344 case OR_No_Viable_Function:
3345 if (CandidateSet.empty())
3346 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattnerd1625842008-11-24 06:25:27 +00003347 << BasePtr->getType() << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003348 else
3349 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Sebastian Redle4c452c2008-11-22 13:44:36 +00003350 << "operator->" << (unsigned)CandidateSet.size()
3351 << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003352 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003353 return true;
3354
3355 case OR_Ambiguous:
3356 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Chris Lattnerd1625842008-11-24 06:25:27 +00003357 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003358 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregor8ba10742008-11-20 16:27:02 +00003359 return true;
3360 }
3361
3362 // Convert the object parameter.
3363 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003364 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregor8ba10742008-11-20 16:27:02 +00003365 return true;
Douglas Gregorfc195ef2008-11-21 03:04:22 +00003366
3367 // No concerns about early exits now.
3368 BasePtr.take();
Douglas Gregor8ba10742008-11-20 16:27:02 +00003369
3370 // Build the operator call.
3371 Expr *FnExpr = new DeclRefExpr(Method, Method->getType(), SourceLocation());
3372 UsualUnaryConversions(FnExpr);
3373 Base = new CXXOperatorCallExpr(FnExpr, &Base, 1,
3374 Method->getResultType().getNonReferenceType(),
3375 OpLoc);
3376 return ActOnMemberReferenceExpr(Base, OpLoc, tok::arrow, MemberLoc, Member);
3377}
3378
Douglas Gregor904eed32008-11-10 20:40:00 +00003379/// FixOverloadedFunctionReference - E is an expression that refers to
3380/// a C++ overloaded function (possibly with some parentheses and
3381/// perhaps a '&' around it). We have resolved the overloaded function
3382/// to the function declaration Fn, so patch up the expression E to
3383/// refer (possibly indirectly) to Fn.
3384void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
3385 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
3386 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
3387 E->setType(PE->getSubExpr()->getType());
3388 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
3389 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
3390 "Can only take the address of an overloaded function");
3391 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
3392 E->setType(Context.getPointerType(E->getType()));
3393 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
3394 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
3395 "Expected overloaded function");
3396 DR->setDecl(Fn);
3397 E->setType(Fn->getType());
3398 } else {
3399 assert(false && "Invalid reference to overloaded function");
3400 }
3401}
3402
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003403} // end namespace clang