blob: 875a38253dabf1deac0bda10380da579219af2f6 [file] [log] [blame]
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor94b1dd22008-10-24 04:54:22 +000015#include "SemaInherit.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000020#include "clang/AST/ExprCXX.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000022#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000023#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000024#include "llvm/Support/Compiler.h"
25#include <algorithm>
26
27namespace clang {
28
29/// GetConversionCategory - Retrieve the implicit conversion
30/// category corresponding to the given implicit conversion kind.
31ImplicitConversionCategory
32GetConversionCategory(ImplicitConversionKind Kind) {
33 static const ImplicitConversionCategory
34 Category[(int)ICK_Num_Conversion_Kinds] = {
35 ICC_Identity,
36 ICC_Lvalue_Transformation,
37 ICC_Lvalue_Transformation,
38 ICC_Lvalue_Transformation,
39 ICC_Qualification_Adjustment,
40 ICC_Promotion,
41 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000042 ICC_Promotion,
43 ICC_Conversion,
44 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000045 ICC_Conversion,
46 ICC_Conversion,
47 ICC_Conversion,
48 ICC_Conversion,
49 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000050 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000051 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000052 ICC_Conversion
53 };
54 return Category[(int)Kind];
55}
56
57/// GetConversionRank - Retrieve the implicit conversion rank
58/// corresponding to the given implicit conversion kind.
59ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
60 static const ImplicitConversionRank
61 Rank[(int)ICK_Num_Conversion_Kinds] = {
62 ICR_Exact_Match,
63 ICR_Exact_Match,
64 ICR_Exact_Match,
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Promotion,
68 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000069 ICR_Promotion,
70 ICR_Conversion,
71 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000072 ICR_Conversion,
73 ICR_Conversion,
74 ICR_Conversion,
75 ICR_Conversion,
76 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000077 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000078 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000079 ICR_Conversion
80 };
81 return Rank[(int)Kind];
82}
83
84/// GetImplicitConversionName - Return the name of this kind of
85/// implicit conversion.
86const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
87 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
88 "No conversion",
89 "Lvalue-to-rvalue",
90 "Array-to-pointer",
91 "Function-to-pointer",
92 "Qualification",
93 "Integral promotion",
94 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +000095 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000096 "Integral conversion",
97 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +000098 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000099 "Floating-integral conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000100 "Complex-real conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000101 "Pointer conversion",
102 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000103 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000104 "Compatible-types conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000105 "Derived-to-base conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000106 };
107 return Name[Kind];
108}
109
Douglas Gregor60d62c22008-10-31 16:23:19 +0000110/// StandardConversionSequence - Set the standard conversion
111/// sequence to the identity conversion.
112void StandardConversionSequence::setAsIdentityConversion() {
113 First = ICK_Identity;
114 Second = ICK_Identity;
115 Third = ICK_Identity;
116 Deprecated = false;
117 ReferenceBinding = false;
118 DirectBinding = false;
Sebastian Redl85002392009-03-29 22:46:24 +0000119 RRefBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000120 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000121}
122
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000123/// getRank - Retrieve the rank of this standard conversion sequence
124/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
125/// implicit conversions.
126ImplicitConversionRank StandardConversionSequence::getRank() const {
127 ImplicitConversionRank Rank = ICR_Exact_Match;
128 if (GetConversionRank(First) > Rank)
129 Rank = GetConversionRank(First);
130 if (GetConversionRank(Second) > Rank)
131 Rank = GetConversionRank(Second);
132 if (GetConversionRank(Third) > Rank)
133 Rank = GetConversionRank(Third);
134 return Rank;
135}
136
137/// isPointerConversionToBool - Determines whether this conversion is
138/// a conversion of a pointer or pointer-to-member to bool. This is
139/// used as part of the ranking of standard conversion sequences
140/// (C++ 13.3.3.2p4).
141bool StandardConversionSequence::isPointerConversionToBool() const
142{
143 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
144 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
145
146 // Note that FromType has not necessarily been transformed by the
147 // array-to-pointer or function-to-pointer implicit conversions, so
148 // check for their presence as well as checking whether FromType is
149 // a pointer.
150 if (ToType->isBooleanType() &&
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000151 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000152 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
153 return true;
154
155 return false;
156}
157
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000158/// isPointerConversionToVoidPointer - Determines whether this
159/// conversion is a conversion of a pointer to a void pointer. This is
160/// used as part of the ranking of standard conversion sequences (C++
161/// 13.3.3.2p4).
162bool
163StandardConversionSequence::
164isPointerConversionToVoidPointer(ASTContext& Context) const
165{
166 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
167 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
168
169 // Note that FromType has not necessarily been transformed by the
170 // array-to-pointer implicit conversion, so check for its presence
171 // and redo the conversion to get a pointer.
172 if (First == ICK_Array_To_Pointer)
173 FromType = Context.getArrayDecayedType(FromType);
174
175 if (Second == ICK_Pointer_Conversion)
176 if (const PointerType* ToPtrType = ToType->getAsPointerType())
177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
185 bool PrintedSomething = false;
186 if (First != ICK_Identity) {
187 fprintf(stderr, "%s", GetImplicitConversionName(First));
188 PrintedSomething = true;
189 }
190
191 if (Second != ICK_Identity) {
192 if (PrintedSomething) {
193 fprintf(stderr, " -> ");
194 }
195 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregor225c41e2008-11-03 19:09:14 +0000196
197 if (CopyConstructor) {
198 fprintf(stderr, " (by copy constructor)");
199 } else if (DirectBinding) {
200 fprintf(stderr, " (direct reference binding)");
201 } else if (ReferenceBinding) {
202 fprintf(stderr, " (reference binding)");
203 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000204 PrintedSomething = true;
205 }
206
207 if (Third != ICK_Identity) {
208 if (PrintedSomething) {
209 fprintf(stderr, " -> ");
210 }
211 fprintf(stderr, "%s", GetImplicitConversionName(Third));
212 PrintedSomething = true;
213 }
214
215 if (!PrintedSomething) {
216 fprintf(stderr, "No conversions required");
217 }
218}
219
220/// DebugPrint - Print this user-defined conversion sequence to standard
221/// error. Useful for debugging overloading issues.
222void UserDefinedConversionSequence::DebugPrint() const {
223 if (Before.First || Before.Second || Before.Third) {
224 Before.DebugPrint();
225 fprintf(stderr, " -> ");
226 }
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000227 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000228 if (After.First || After.Second || After.Third) {
229 fprintf(stderr, " -> ");
230 After.DebugPrint();
231 }
232}
233
234/// DebugPrint - Print this implicit conversion sequence to standard
235/// error. Useful for debugging overloading issues.
236void ImplicitConversionSequence::DebugPrint() const {
237 switch (ConversionKind) {
238 case StandardConversion:
239 fprintf(stderr, "Standard conversion: ");
240 Standard.DebugPrint();
241 break;
242 case UserDefinedConversion:
243 fprintf(stderr, "User-defined conversion: ");
244 UserDefined.DebugPrint();
245 break;
246 case EllipsisConversion:
247 fprintf(stderr, "Ellipsis conversion");
248 break;
249 case BadConversion:
250 fprintf(stderr, "Bad conversion");
251 break;
252 }
253
254 fprintf(stderr, "\n");
255}
256
257// IsOverload - Determine whether the given New declaration is an
258// overload of the Old declaration. This routine returns false if New
259// and Old cannot be overloaded, e.g., if they are functions with the
260// same signature (C++ 1.3.10) or if the Old declaration isn't a
261// function (or overload set). When it does return false and Old is an
262// OverloadedFunctionDecl, MatchedDecl will be set to point to the
263// FunctionDecl that New cannot be overloaded with.
264//
265// Example: Given the following input:
266//
267// void f(int, float); // #1
268// void f(int, int); // #2
269// int f(int, int); // #3
270//
271// When we process #1, there is no previous declaration of "f",
272// so IsOverload will not be used.
273//
274// When we process #2, Old is a FunctionDecl for #1. By comparing the
275// parameter types, we see that #1 and #2 are overloaded (since they
276// have different signatures), so this routine returns false;
277// MatchedDecl is unchanged.
278//
279// When we process #3, Old is an OverloadedFunctionDecl containing #1
280// and #2. We compare the signatures of #3 to #1 (they're overloaded,
281// so we do nothing) and then #3 to #2. Since the signatures of #3 and
282// #2 are identical (return types of functions are not part of the
283// signature), IsOverload returns false and MatchedDecl will be set to
284// point to the FunctionDecl for #2.
285bool
286Sema::IsOverload(FunctionDecl *New, Decl* OldD,
287 OverloadedFunctionDecl::function_iterator& MatchedDecl)
288{
289 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
290 // Is this new function an overload of every function in the
291 // overload set?
292 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
293 FuncEnd = Ovl->function_end();
294 for (; Func != FuncEnd; ++Func) {
295 if (!IsOverload(New, *Func, MatchedDecl)) {
296 MatchedDecl = Func;
297 return false;
298 }
299 }
300
301 // This function overloads every function in the overload set.
302 return true;
303 } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
304 // Is the function New an overload of the function Old?
305 QualType OldQType = Context.getCanonicalType(Old->getType());
306 QualType NewQType = Context.getCanonicalType(New->getType());
307
308 // Compare the signatures (C++ 1.3.10) of the two functions to
309 // determine whether they are overloads. If we find any mismatch
310 // in the signature, they are overloads.
311
312 // If either of these functions is a K&R-style function (no
313 // prototype), then we consider them to have matching signatures.
Douglas Gregor72564e72009-02-26 23:50:07 +0000314 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
315 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000316 return false;
317
Douglas Gregor72564e72009-02-26 23:50:07 +0000318 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType.getTypePtr());
319 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType.getTypePtr());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000320
321 // The signature of a function includes the types of its
322 // parameters (C++ 1.3.10), which includes the presence or absence
323 // of the ellipsis; see C++ DR 357).
324 if (OldQType != NewQType &&
325 (OldType->getNumArgs() != NewType->getNumArgs() ||
326 OldType->isVariadic() != NewType->isVariadic() ||
327 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
328 NewType->arg_type_begin())))
329 return true;
330
331 // If the function is a class member, its signature includes the
332 // cv-qualifiers (if any) on the function itself.
333 //
334 // As part of this, also check whether one of the member functions
335 // is static, in which case they are not overloads (C++
336 // 13.1p2). While not part of the definition of the signature,
337 // this check is important to determine whether these functions
338 // can be overloaded.
339 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
340 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
341 if (OldMethod && NewMethod &&
342 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor1ca50c32008-11-21 15:36:28 +0000343 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000344 return true;
345
346 // The signatures match; this is not an overload.
347 return false;
348 } else {
349 // (C++ 13p1):
350 // Only function declarations can be overloaded; object and type
351 // declarations cannot be overloaded.
352 return false;
353 }
354}
355
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000356/// TryImplicitConversion - Attempt to perform an implicit conversion
357/// from the given expression (Expr) to the given type (ToType). This
358/// function returns an implicit conversion sequence that can be used
359/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000360///
361/// void f(float f);
362/// void g(int i) { f(i); }
363///
364/// this routine would produce an implicit conversion sequence to
365/// describe the initialization of f from i, which will be a standard
366/// conversion sequence containing an lvalue-to-rvalue conversion (C++
367/// 4.1) followed by a floating-integral conversion (C++ 4.9).
368//
369/// Note that this routine only determines how the conversion can be
370/// performed; it does not actually perform the conversion. As such,
371/// it will not produce any diagnostics if no conversion is available,
372/// but will instead return an implicit conversion sequence of kind
373/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000374///
375/// If @p SuppressUserConversions, then user-defined conversions are
376/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000377/// If @p AllowExplicit, then explicit user-defined conversions are
378/// permitted.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000379ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +0000380Sema::TryImplicitConversion(Expr* From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000381 bool SuppressUserConversions,
Douglas Gregor734d9862009-01-30 23:27:23 +0000382 bool AllowExplicit)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000383{
384 ImplicitConversionSequence ICS;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000385 if (IsStandardConversion(From, ToType, ICS.Standard))
386 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000387 else if (getLangOptions().CPlusPlus &&
388 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor734d9862009-01-30 23:27:23 +0000389 !SuppressUserConversions, AllowExplicit)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000390 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000391 // C++ [over.ics.user]p4:
392 // A conversion of an expression of class type to the same class
393 // type is given Exact Match rank, and a conversion of an
394 // expression of class type to a base class of that type is
395 // given Conversion rank, in spite of the fact that a copy
396 // constructor (i.e., a user-defined conversion function) is
397 // called for those cases.
398 if (CXXConstructorDecl *Constructor
399 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000400 QualType FromCanon
401 = Context.getCanonicalType(From->getType().getUnqualifiedType());
402 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
403 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000404 // Turn this into a "standard" conversion sequence, so that it
405 // gets ranked with standard conversion sequences.
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000406 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
407 ICS.Standard.setAsIdentityConversion();
408 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
409 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000410 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000411 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000412 ICS.Standard.Second = ICK_Derived_To_Base;
413 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000414 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000415
416 // C++ [over.best.ics]p4:
417 // However, when considering the argument of a user-defined
418 // conversion function that is a candidate by 13.3.1.3 when
419 // invoked for the copying of the temporary in the second step
420 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
421 // 13.3.1.6 in all cases, only standard conversion sequences and
422 // ellipsis conversion sequences are allowed.
423 if (SuppressUserConversions &&
424 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
425 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000426 } else
Douglas Gregor60d62c22008-10-31 16:23:19 +0000427 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000428
429 return ICS;
430}
431
432/// IsStandardConversion - Determines whether there is a standard
433/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
434/// expression From to the type ToType. Standard conversion sequences
435/// only consider non-class types; for conversions that involve class
436/// types, use TryImplicitConversion. If a conversion exists, SCS will
437/// contain the standard conversion sequence required to perform this
438/// conversion and this routine will return true. Otherwise, this
439/// routine will return false and the value of SCS is unspecified.
440bool
441Sema::IsStandardConversion(Expr* From, QualType ToType,
442 StandardConversionSequence &SCS)
443{
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000444 QualType FromType = From->getType();
445
Douglas Gregor60d62c22008-10-31 16:23:19 +0000446 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000447 SCS.setAsIdentityConversion();
Douglas Gregor60d62c22008-10-31 16:23:19 +0000448 SCS.Deprecated = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000449 SCS.IncompatibleObjC = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000450 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000451 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000452
Douglas Gregorf9201e02009-02-11 23:02:49 +0000453 // There are no standard conversions for class types in C++, so
454 // abort early. When overloading in C, however, we do permit
455 if (FromType->isRecordType() || ToType->isRecordType()) {
456 if (getLangOptions().CPlusPlus)
457 return false;
458
459 // When we're overloading in C, we allow, as standard conversions,
460 }
461
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000462 // The first conversion can be an lvalue-to-rvalue conversion,
463 // array-to-pointer conversion, or function-to-pointer conversion
464 // (C++ 4p1).
465
466 // Lvalue-to-rvalue conversion (C++ 4.1):
467 // An lvalue (3.10) of a non-function, non-array type T can be
468 // converted to an rvalue.
469 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
470 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000471 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor063daf62009-03-13 18:40:31 +0000472 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000473 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000474
475 // If T is a non-class type, the type of the rvalue is the
476 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +0000477 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
478 // just strip the qualifiers because they don't matter.
479
480 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregor60d62c22008-10-31 16:23:19 +0000481 FromType = FromType.getUnqualifiedType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000482 }
483 // Array-to-pointer conversion (C++ 4.2)
484 else if (FromType->isArrayType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000485 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000486
487 // An lvalue or rvalue of type "array of N T" or "array of unknown
488 // bound of T" can be converted to an rvalue of type "pointer to
489 // T" (C++ 4.2p1).
490 FromType = Context.getArrayDecayedType(FromType);
491
492 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
493 // This conversion is deprecated. (C++ D.4).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000494 SCS.Deprecated = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000495
496 // For the purpose of ranking in overload resolution
497 // (13.3.3.1.1), this conversion is considered an
498 // array-to-pointer conversion followed by a qualification
499 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000500 SCS.Second = ICK_Identity;
501 SCS.Third = ICK_Qualification;
502 SCS.ToTypePtr = ToType.getAsOpaquePtr();
503 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000504 }
505 }
506 // Function-to-pointer conversion (C++ 4.3).
507 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000508 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000509
510 // An lvalue of function type T can be converted to an rvalue of
511 // type "pointer to T." The result is a pointer to the
512 // function. (C++ 4.3p1).
513 FromType = Context.getPointerType(FromType);
Sebastian Redl33b399a2009-02-04 21:23:32 +0000514 }
Douglas Gregor904eed32008-11-10 20:40:00 +0000515 // Address of overloaded function (C++ [over.over]).
516 else if (FunctionDecl *Fn
517 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
518 SCS.First = ICK_Function_To_Pointer;
519
520 // We were able to resolve the address of the overloaded function,
521 // so we can convert to the type of that function.
522 FromType = Fn->getType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000523 if (ToType->isLValueReferenceType())
524 FromType = Context.getLValueReferenceType(FromType);
525 else if (ToType->isRValueReferenceType())
526 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl33b399a2009-02-04 21:23:32 +0000527 else if (ToType->isMemberPointerType()) {
528 // Resolve address only succeeds if both sides are member pointers,
529 // but it doesn't have to be the same class. See DR 247.
530 // Note that this means that the type of &Derived::fn can be
531 // Ret (Base::*)(Args) if the fn overload actually found is from the
532 // base class, even if it was brought into the derived class via a
533 // using declaration. The standard isn't clear on this issue at all.
534 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
535 FromType = Context.getMemberPointerType(FromType,
536 Context.getTypeDeclType(M->getParent()).getTypePtr());
537 } else
Douglas Gregor904eed32008-11-10 20:40:00 +0000538 FromType = Context.getPointerType(FromType);
539 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000540 // We don't require any conversions for the first step.
541 else {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000542 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000543 }
544
545 // The second conversion can be an integral promotion, floating
546 // point promotion, integral conversion, floating point conversion,
547 // floating-integral conversion, pointer conversion,
548 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +0000549 // For overloading in C, this can also be a "compatible-type"
550 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +0000551 bool IncompatibleObjC = false;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000552 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000553 // The unqualified versions of the types are the same: there's no
554 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000555 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000556 }
557 // Integral promotion (C++ 4.5).
558 else if (IsIntegralPromotion(From, FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000559 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000560 FromType = ToType.getUnqualifiedType();
561 }
562 // Floating point promotion (C++ 4.6).
563 else if (IsFloatingPointPromotion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000564 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000565 FromType = ToType.getUnqualifiedType();
566 }
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000567 // Complex promotion (Clang extension)
568 else if (IsComplexPromotion(FromType, ToType)) {
569 SCS.Second = ICK_Complex_Promotion;
570 FromType = ToType.getUnqualifiedType();
571 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000572 // Integral conversions (C++ 4.7).
Sebastian Redl07779722008-10-31 14:43:28 +0000573 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000574 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000575 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000576 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000577 FromType = ToType.getUnqualifiedType();
578 }
579 // Floating point conversions (C++ 4.8).
580 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000581 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000582 FromType = ToType.getUnqualifiedType();
583 }
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000584 // Complex conversions (C99 6.3.1.6)
585 else if (FromType->isComplexType() && ToType->isComplexType()) {
586 SCS.Second = ICK_Complex_Conversion;
587 FromType = ToType.getUnqualifiedType();
588 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000589 // Floating-integral conversions (C++ 4.9).
Sebastian Redl07779722008-10-31 14:43:28 +0000590 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000591 else if ((FromType->isFloatingType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000592 ToType->isIntegralType() && !ToType->isBooleanType() &&
593 !ToType->isEnumeralType()) ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000594 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
595 ToType->isFloatingType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000596 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000597 FromType = ToType.getUnqualifiedType();
598 }
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000599 // Complex-real conversions (C99 6.3.1.7)
600 else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
601 (ToType->isComplexType() && FromType->isArithmeticType())) {
602 SCS.Second = ICK_Complex_Real;
603 FromType = ToType.getUnqualifiedType();
604 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000605 // Pointer conversions (C++ 4.10).
Douglas Gregor45920e82008-12-19 17:40:08 +0000606 else if (IsPointerConversion(From, FromType, ToType, FromType,
607 IncompatibleObjC)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000608 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000609 SCS.IncompatibleObjC = IncompatibleObjC;
Sebastian Redl07779722008-10-31 14:43:28 +0000610 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000611 // Pointer to member conversions (4.11).
612 else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
613 SCS.Second = ICK_Pointer_Member;
614 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000615 // Boolean conversions (C++ 4.12).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000616 else if (ToType->isBooleanType() &&
617 (FromType->isArithmeticType() ||
618 FromType->isEnumeralType() ||
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000619 FromType->isPointerType() ||
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000620 FromType->isBlockPointerType() ||
621 FromType->isMemberPointerType())) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000622 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000623 FromType = Context.BoolTy;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000624 }
625 // Compatible conversions (Clang extension for C function overloading)
626 else if (!getLangOptions().CPlusPlus &&
627 Context.typesAreCompatible(ToType, FromType)) {
628 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000629 } else {
630 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000631 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000632 }
633
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000634 QualType CanonFrom;
635 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000636 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000637 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000638 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000639 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000640 CanonFrom = Context.getCanonicalType(FromType);
641 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000642 } else {
643 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000644 SCS.Third = ICK_Identity;
645
646 // C++ [over.best.ics]p6:
647 // [...] Any difference in top-level cv-qualification is
648 // subsumed by the initialization itself and does not constitute
649 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000650 CanonFrom = Context.getCanonicalType(FromType);
651 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000652 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000653 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
654 FromType = ToType;
655 CanonFrom = CanonTo;
656 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000657 }
658
659 // If we have not converted the argument type to the parameter type,
660 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000661 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000662 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000663
Douglas Gregor60d62c22008-10-31 16:23:19 +0000664 SCS.ToTypePtr = FromType.getAsOpaquePtr();
665 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000666}
667
668/// IsIntegralPromotion - Determines whether the conversion from the
669/// expression From (whose potentially-adjusted type is FromType) to
670/// ToType is an integral promotion (C++ 4.5). If so, returns true and
671/// sets PromotedType to the promoted type.
672bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
673{
674 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000675 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000676 if (!To) {
677 return false;
678 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000679
680 // An rvalue of type char, signed char, unsigned char, short int, or
681 // unsigned short int can be converted to an rvalue of type int if
682 // int can represent all the values of the source type; otherwise,
683 // the source rvalue can be converted to an rvalue of type unsigned
684 // int (C++ 4.5p1).
Sebastian Redl07779722008-10-31 14:43:28 +0000685 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000686 if (// We can promote any signed, promotable integer type to an int
687 (FromType->isSignedIntegerType() ||
688 // We can promote any unsigned integer type whose size is
689 // less than int to an int.
690 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000691 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000692 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000693 }
694
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000695 return To->getKind() == BuiltinType::UInt;
696 }
697
698 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
699 // can be converted to an rvalue of the first of the following types
700 // that can represent all the values of its underlying type: int,
701 // unsigned int, long, or unsigned long (C++ 4.5p2).
702 if ((FromType->isEnumeralType() || FromType->isWideCharType())
703 && ToType->isIntegerType()) {
704 // Determine whether the type we're converting from is signed or
705 // unsigned.
706 bool FromIsSigned;
707 uint64_t FromSize = Context.getTypeSize(FromType);
708 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
709 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
710 FromIsSigned = UnderlyingType->isSignedIntegerType();
711 } else {
712 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
713 FromIsSigned = true;
714 }
715
716 // The types we'll try to promote to, in the appropriate
717 // order. Try each of these types.
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000718 QualType PromoteTypes[6] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000719 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000720 Context.LongTy, Context.UnsignedLongTy ,
721 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000722 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000723 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000724 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
725 if (FromSize < ToSize ||
726 (FromSize == ToSize &&
727 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
728 // We found the type that we can promote to. If this is the
729 // type we wanted, we have a promotion. Otherwise, no
730 // promotion.
Sebastian Redl07779722008-10-31 14:43:28 +0000731 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000732 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
733 }
734 }
735 }
736
737 // An rvalue for an integral bit-field (9.6) can be converted to an
738 // rvalue of type int if int can represent all the values of the
739 // bit-field; otherwise, it can be converted to unsigned int if
740 // unsigned int can represent all the values of the bit-field. If
741 // the bit-field is larger yet, no integral promotion applies to
742 // it. If the bit-field has an enumerated type, it is treated as any
743 // other value of that type for promotion purposes (C++ 4.5p3).
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000744 // FIXME: We should delay checking of bit-fields until we actually
745 // perform the conversion.
746 if (MemberExpr *MemRef = dyn_cast_or_null<MemberExpr>(From)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000747 using llvm::APSInt;
Douglas Gregor86f19402008-12-20 23:49:58 +0000748 if (FieldDecl *MemberDecl = dyn_cast<FieldDecl>(MemRef->getMemberDecl())) {
749 APSInt BitWidth;
750 if (MemberDecl->isBitField() &&
751 FromType->isIntegralType() && !FromType->isEnumeralType() &&
752 From->isIntegerConstantExpr(BitWidth, Context)) {
753 APSInt ToSize(Context.getTypeSize(ToType));
754
755 // Are we promoting to an int from a bitfield that fits in an int?
756 if (BitWidth < ToSize ||
757 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
758 return To->getKind() == BuiltinType::Int;
759 }
760
761 // Are we promoting to an unsigned int from an unsigned bitfield
762 // that fits into an unsigned int?
763 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
764 return To->getKind() == BuiltinType::UInt;
765 }
766
767 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000768 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000769 }
770 }
771
772 // An rvalue of type bool can be converted to an rvalue of type int,
773 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000774 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000775 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000776 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000777
778 return false;
779}
780
781/// IsFloatingPointPromotion - Determines whether the conversion from
782/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
783/// returns true and sets PromotedType to the promoted type.
784bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
785{
786 /// An rvalue of type float can be converted to an rvalue of type
787 /// double. (C++ 4.6p1).
788 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000789 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000790 if (FromBuiltin->getKind() == BuiltinType::Float &&
791 ToBuiltin->getKind() == BuiltinType::Double)
792 return true;
793
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000794 // C99 6.3.1.5p1:
795 // When a float is promoted to double or long double, or a
796 // double is promoted to long double [...].
797 if (!getLangOptions().CPlusPlus &&
798 (FromBuiltin->getKind() == BuiltinType::Float ||
799 FromBuiltin->getKind() == BuiltinType::Double) &&
800 (ToBuiltin->getKind() == BuiltinType::LongDouble))
801 return true;
802 }
803
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000804 return false;
805}
806
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000807/// \brief Determine if a conversion is a complex promotion.
808///
809/// A complex promotion is defined as a complex -> complex conversion
810/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000811/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000812bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
813 const ComplexType *FromComplex = FromType->getAsComplexType();
814 if (!FromComplex)
815 return false;
816
817 const ComplexType *ToComplex = ToType->getAsComplexType();
818 if (!ToComplex)
819 return false;
820
821 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000822 ToComplex->getElementType()) ||
823 IsIntegralPromotion(0, FromComplex->getElementType(),
824 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000825}
826
Douglas Gregorcb7de522008-11-26 23:31:11 +0000827/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
828/// the pointer type FromPtr to a pointer to type ToPointee, with the
829/// same type qualifiers as FromPtr has on its pointee type. ToType,
830/// if non-empty, will be a pointer to ToType that may or may not have
831/// the right set of qualifiers on its pointee.
832static QualType
833BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
834 QualType ToPointee, QualType ToType,
835 ASTContext &Context) {
836 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
837 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
838 unsigned Quals = CanonFromPointee.getCVRQualifiers();
839
840 // Exact qualifier match -> return the pointer type we're converting to.
841 if (CanonToPointee.getCVRQualifiers() == Quals) {
842 // ToType is exactly what we need. Return it.
843 if (ToType.getTypePtr())
844 return ToType;
845
846 // Build a pointer to ToPointee. It has the right qualifiers
847 // already.
848 return Context.getPointerType(ToPointee);
849 }
850
851 // Just build a canonical type that has the right qualifiers.
852 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
853}
854
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000855/// IsPointerConversion - Determines whether the conversion of the
856/// expression From, which has the (possibly adjusted) type FromType,
857/// can be converted to the type ToType via a pointer conversion (C++
858/// 4.10). If so, returns true and places the converted type (that
859/// might differ from ToType in its cv-qualifiers at some level) into
860/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000861///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000862/// This routine also supports conversions to and from block pointers
863/// and conversions with Objective-C's 'id', 'id<protocols...>', and
864/// pointers to interfaces. FIXME: Once we've determined the
865/// appropriate overloading rules for Objective-C, we may want to
866/// split the Objective-C checks into a different routine; however,
867/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000868/// conversions, so for now they live here. IncompatibleObjC will be
869/// set if the conversion is an allowed Objective-C conversion that
870/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000871bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +0000872 QualType& ConvertedType,
873 bool &IncompatibleObjC)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000874{
Douglas Gregor45920e82008-12-19 17:40:08 +0000875 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +0000876 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
877 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +0000878
Douglas Gregor27b09ac2008-12-22 20:51:52 +0000879 // Conversion from a null pointer constant to any Objective-C pointer type.
880 if (Context.isObjCObjectPointerType(ToType) &&
881 From->isNullPointerConstant(Context)) {
882 ConvertedType = ToType;
883 return true;
884 }
885
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000886 // Blocks: Block pointers can be converted to void*.
887 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
888 ToType->getAsPointerType()->getPointeeType()->isVoidType()) {
889 ConvertedType = ToType;
890 return true;
891 }
892 // Blocks: A null pointer constant can be converted to a block
893 // pointer type.
894 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
895 ConvertedType = ToType;
896 return true;
897 }
898
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000899 const PointerType* ToTypePtr = ToType->getAsPointerType();
900 if (!ToTypePtr)
901 return false;
902
903 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
904 if (From->isNullPointerConstant(Context)) {
905 ConvertedType = ToType;
906 return true;
907 }
Sebastian Redl07779722008-10-31 14:43:28 +0000908
Douglas Gregorcb7de522008-11-26 23:31:11 +0000909 // Beyond this point, both types need to be pointers.
910 const PointerType *FromTypePtr = FromType->getAsPointerType();
911 if (!FromTypePtr)
912 return false;
913
914 QualType FromPointeeType = FromTypePtr->getPointeeType();
915 QualType ToPointeeType = ToTypePtr->getPointeeType();
916
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000917 // An rvalue of type "pointer to cv T," where T is an object type,
918 // can be converted to an rvalue of type "pointer to cv void" (C++
919 // 4.10p2).
Douglas Gregorbad0e652009-03-24 20:32:41 +0000920 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000921 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
922 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000923 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000924 return true;
925 }
926
Douglas Gregorf9201e02009-02-11 23:02:49 +0000927 // When we're overloading in C, we allow a special kind of pointer
928 // conversion for compatible-but-not-identical pointee types.
929 if (!getLangOptions().CPlusPlus &&
930 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
931 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
932 ToPointeeType,
933 ToType, Context);
934 return true;
935 }
936
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000937 // C++ [conv.ptr]p3:
938 //
939 // An rvalue of type "pointer to cv D," where D is a class type,
940 // can be converted to an rvalue of type "pointer to cv B," where
941 // B is a base class (clause 10) of D. If B is an inaccessible
942 // (clause 11) or ambiguous (10.2) base class of D, a program that
943 // necessitates this conversion is ill-formed. The result of the
944 // conversion is a pointer to the base class sub-object of the
945 // derived class object. The null pointer value is converted to
946 // the null pointer value of the destination type.
947 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000948 // Note that we do not check for ambiguity or inaccessibility
949 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +0000950 if (getLangOptions().CPlusPlus &&
951 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorcb7de522008-11-26 23:31:11 +0000952 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregorbf408182008-11-27 00:52:49 +0000953 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
954 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000955 ToType, Context);
956 return true;
957 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000958
Douglas Gregorc7887512008-12-19 19:13:09 +0000959 return false;
960}
961
962/// isObjCPointerConversion - Determines whether this is an
963/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
964/// with the same arguments and return values.
965bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
966 QualType& ConvertedType,
967 bool &IncompatibleObjC) {
968 if (!getLangOptions().ObjC1)
969 return false;
970
971 // Conversions with Objective-C's id<...>.
972 if ((FromType->isObjCQualifiedIdType() || ToType->isObjCQualifiedIdType()) &&
973 ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) {
974 ConvertedType = ToType;
975 return true;
976 }
977
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000978 // Beyond this point, both types need to be pointers or block pointers.
979 QualType ToPointeeType;
Douglas Gregorc7887512008-12-19 19:13:09 +0000980 const PointerType* ToTypePtr = ToType->getAsPointerType();
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000981 if (ToTypePtr)
982 ToPointeeType = ToTypePtr->getPointeeType();
983 else if (const BlockPointerType *ToBlockPtr = ToType->getAsBlockPointerType())
984 ToPointeeType = ToBlockPtr->getPointeeType();
985 else
Douglas Gregorc7887512008-12-19 19:13:09 +0000986 return false;
987
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000988 QualType FromPointeeType;
Douglas Gregorc7887512008-12-19 19:13:09 +0000989 const PointerType *FromTypePtr = FromType->getAsPointerType();
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000990 if (FromTypePtr)
991 FromPointeeType = FromTypePtr->getPointeeType();
992 else if (const BlockPointerType *FromBlockPtr
993 = FromType->getAsBlockPointerType())
994 FromPointeeType = FromBlockPtr->getPointeeType();
995 else
Douglas Gregorc7887512008-12-19 19:13:09 +0000996 return false;
997
Douglas Gregorcb7de522008-11-26 23:31:11 +0000998 // Objective C++: We're able to convert from a pointer to an
999 // interface to a pointer to a different interface.
1000 const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType();
1001 const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType();
1002 if (FromIface && ToIface &&
1003 Context.canAssignObjCInterfaces(ToIface, FromIface)) {
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001004 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001005 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001006 ToType, Context);
1007 return true;
1008 }
1009
Douglas Gregor45920e82008-12-19 17:40:08 +00001010 if (FromIface && ToIface &&
1011 Context.canAssignObjCInterfaces(FromIface, ToIface)) {
1012 // Okay: this is some kind of implicit downcast of Objective-C
1013 // interfaces, which is permitted. However, we're going to
1014 // complain about it.
1015 IncompatibleObjC = true;
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001016 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor45920e82008-12-19 17:40:08 +00001017 ToPointeeType,
1018 ToType, Context);
1019 return true;
1020 }
1021
Douglas Gregorcb7de522008-11-26 23:31:11 +00001022 // Objective C++: We're able to convert between "id" and a pointer
1023 // to any interface (in both directions).
Steve Naroff389bf462009-02-12 17:52:19 +00001024 if ((FromIface && Context.isObjCIdStructType(ToPointeeType))
1025 || (ToIface && Context.isObjCIdStructType(FromPointeeType))) {
Douglas Gregorbf408182008-11-27 00:52:49 +00001026 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1027 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001028 ToType, Context);
1029 return true;
1030 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001031
Douglas Gregordda78892008-12-18 23:43:31 +00001032 // Objective C++: Allow conversions between the Objective-C "id" and
1033 // "Class", in either direction.
Steve Naroff389bf462009-02-12 17:52:19 +00001034 if ((Context.isObjCIdStructType(FromPointeeType) &&
1035 Context.isObjCClassStructType(ToPointeeType)) ||
1036 (Context.isObjCClassStructType(FromPointeeType) &&
1037 Context.isObjCIdStructType(ToPointeeType))) {
Douglas Gregordda78892008-12-18 23:43:31 +00001038 ConvertedType = ToType;
1039 return true;
1040 }
1041
Douglas Gregorc7887512008-12-19 19:13:09 +00001042 // If we have pointers to pointers, recursively check whether this
1043 // is an Objective-C conversion.
1044 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1045 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1046 IncompatibleObjC)) {
1047 // We always complain about this conversion.
1048 IncompatibleObjC = true;
1049 ConvertedType = ToType;
1050 return true;
1051 }
1052
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001053 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001054 // differences in the argument and result types are in Objective-C
1055 // pointer conversions. If so, we permit the conversion (but
1056 // complain about it).
Douglas Gregor72564e72009-02-26 23:50:07 +00001057 const FunctionProtoType *FromFunctionType
1058 = FromPointeeType->getAsFunctionProtoType();
1059 const FunctionProtoType *ToFunctionType
1060 = ToPointeeType->getAsFunctionProtoType();
Douglas Gregorc7887512008-12-19 19:13:09 +00001061 if (FromFunctionType && ToFunctionType) {
1062 // If the function types are exactly the same, this isn't an
1063 // Objective-C pointer conversion.
1064 if (Context.getCanonicalType(FromPointeeType)
1065 == Context.getCanonicalType(ToPointeeType))
1066 return false;
1067
1068 // Perform the quick checks that will tell us whether these
1069 // function types are obviously different.
1070 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1071 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1072 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1073 return false;
1074
1075 bool HasObjCConversion = false;
1076 if (Context.getCanonicalType(FromFunctionType->getResultType())
1077 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1078 // Okay, the types match exactly. Nothing to do.
1079 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1080 ToFunctionType->getResultType(),
1081 ConvertedType, IncompatibleObjC)) {
1082 // Okay, we have an Objective-C pointer conversion.
1083 HasObjCConversion = true;
1084 } else {
1085 // Function types are too different. Abort.
1086 return false;
1087 }
1088
1089 // Check argument types.
1090 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1091 ArgIdx != NumArgs; ++ArgIdx) {
1092 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1093 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1094 if (Context.getCanonicalType(FromArgType)
1095 == Context.getCanonicalType(ToArgType)) {
1096 // Okay, the types match exactly. Nothing to do.
1097 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1098 ConvertedType, IncompatibleObjC)) {
1099 // Okay, we have an Objective-C pointer conversion.
1100 HasObjCConversion = true;
1101 } else {
1102 // Argument types are too different. Abort.
1103 return false;
1104 }
1105 }
1106
1107 if (HasObjCConversion) {
1108 // We had an Objective-C conversion. Allow this pointer
1109 // conversion, but complain about it.
1110 ConvertedType = ToType;
1111 IncompatibleObjC = true;
1112 return true;
1113 }
1114 }
1115
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001116 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001117}
1118
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001119/// CheckPointerConversion - Check the pointer conversion from the
1120/// expression From to the type ToType. This routine checks for
1121/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
1122/// conversions for which IsPointerConversion has already returned
1123/// true. It returns true and produces a diagnostic if there was an
1124/// error, or returns false otherwise.
1125bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1126 QualType FromType = From->getType();
1127
1128 if (const PointerType *FromPtrType = FromType->getAsPointerType())
1129 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001130 QualType FromPointeeType = FromPtrType->getPointeeType(),
1131 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001132
1133 // Objective-C++ conversions are always okay.
1134 // FIXME: We should have a different class of conversions for
1135 // the Objective-C++ implicit conversions.
Steve Naroff389bf462009-02-12 17:52:19 +00001136 if (Context.isObjCIdStructType(FromPointeeType) ||
1137 Context.isObjCIdStructType(ToPointeeType) ||
1138 Context.isObjCClassStructType(FromPointeeType) ||
1139 Context.isObjCClassStructType(ToPointeeType))
Douglas Gregordda78892008-12-18 23:43:31 +00001140 return false;
1141
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001142 if (FromPointeeType->isRecordType() &&
1143 ToPointeeType->isRecordType()) {
1144 // We must have a derived-to-base conversion. Check an
1145 // ambiguous or inaccessible conversion.
Douglas Gregor0575d4a2008-10-24 16:17:19 +00001146 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1147 From->getExprLoc(),
1148 From->getSourceRange());
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001149 }
1150 }
1151
1152 return false;
1153}
1154
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001155/// IsMemberPointerConversion - Determines whether the conversion of the
1156/// expression From, which has the (possibly adjusted) type FromType, can be
1157/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1158/// If so, returns true and places the converted type (that might differ from
1159/// ToType in its cv-qualifiers at some level) into ConvertedType.
1160bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1161 QualType ToType, QualType &ConvertedType)
1162{
1163 const MemberPointerType *ToTypePtr = ToType->getAsMemberPointerType();
1164 if (!ToTypePtr)
1165 return false;
1166
1167 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1168 if (From->isNullPointerConstant(Context)) {
1169 ConvertedType = ToType;
1170 return true;
1171 }
1172
1173 // Otherwise, both types have to be member pointers.
1174 const MemberPointerType *FromTypePtr = FromType->getAsMemberPointerType();
1175 if (!FromTypePtr)
1176 return false;
1177
1178 // A pointer to member of B can be converted to a pointer to member of D,
1179 // where D is derived from B (C++ 4.11p2).
1180 QualType FromClass(FromTypePtr->getClass(), 0);
1181 QualType ToClass(ToTypePtr->getClass(), 0);
1182 // FIXME: What happens when these are dependent? Is this function even called?
1183
1184 if (IsDerivedFrom(ToClass, FromClass)) {
1185 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1186 ToClass.getTypePtr());
1187 return true;
1188 }
1189
1190 return false;
1191}
1192
1193/// CheckMemberPointerConversion - Check the member pointer conversion from the
1194/// expression From to the type ToType. This routine checks for ambiguous or
1195/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1196/// for which IsMemberPointerConversion has already returned true. It returns
1197/// true and produces a diagnostic if there was an error, or returns false
1198/// otherwise.
1199bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType) {
1200 QualType FromType = From->getType();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001201 const MemberPointerType *FromPtrType = FromType->getAsMemberPointerType();
1202 if (!FromPtrType)
1203 return false;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001204
Sebastian Redl21593ac2009-01-28 18:33:18 +00001205 const MemberPointerType *ToPtrType = ToType->getAsMemberPointerType();
1206 assert(ToPtrType && "No member pointer cast has a target type "
1207 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001208
Sebastian Redl21593ac2009-01-28 18:33:18 +00001209 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1210 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001211
Sebastian Redl21593ac2009-01-28 18:33:18 +00001212 // FIXME: What about dependent types?
1213 assert(FromClass->isRecordType() && "Pointer into non-class.");
1214 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001215
Sebastian Redl21593ac2009-01-28 18:33:18 +00001216 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1217 /*DetectVirtual=*/true);
1218 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1219 assert(DerivationOkay &&
1220 "Should not have been called if derivation isn't OK.");
1221 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001222
Sebastian Redl21593ac2009-01-28 18:33:18 +00001223 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1224 getUnqualifiedType())) {
1225 // Derivation is ambiguous. Redo the check to find the exact paths.
1226 Paths.clear();
1227 Paths.setRecordingPaths(true);
1228 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1229 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1230 (void)StillOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001231
Sebastian Redl21593ac2009-01-28 18:33:18 +00001232 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1233 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1234 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1235 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001236 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001237
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001238 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001239 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1240 << FromClass << ToClass << QualType(VBase, 0)
1241 << From->getSourceRange();
1242 return true;
1243 }
1244
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001245 return false;
1246}
1247
Douglas Gregor98cd5992008-10-21 23:43:52 +00001248/// IsQualificationConversion - Determines whether the conversion from
1249/// an rvalue of type FromType to ToType is a qualification conversion
1250/// (C++ 4.4).
1251bool
1252Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1253{
1254 FromType = Context.getCanonicalType(FromType);
1255 ToType = Context.getCanonicalType(ToType);
1256
1257 // If FromType and ToType are the same type, this is not a
1258 // qualification conversion.
1259 if (FromType == ToType)
1260 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001261
Douglas Gregor98cd5992008-10-21 23:43:52 +00001262 // (C++ 4.4p4):
1263 // A conversion can add cv-qualifiers at levels other than the first
1264 // in multi-level pointers, subject to the following rules: [...]
1265 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001266 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001267 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001268 // Within each iteration of the loop, we check the qualifiers to
1269 // determine if this still looks like a qualification
1270 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001271 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001272 // until there are no more pointers or pointers-to-members left to
1273 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001274 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001275
1276 // -- for every j > 0, if const is in cv 1,j then const is in cv
1277 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001278 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001279 return false;
Douglas Gregor57373262008-10-22 14:17:15 +00001280
Douglas Gregor98cd5992008-10-21 23:43:52 +00001281 // -- if the cv 1,j and cv 2,j are different, then const is in
1282 // every cv for 0 < k < j.
1283 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001284 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001285 return false;
Douglas Gregor57373262008-10-22 14:17:15 +00001286
Douglas Gregor98cd5992008-10-21 23:43:52 +00001287 // Keep track of whether all prior cv-qualifiers in the "to" type
1288 // include const.
1289 PreviousToQualsIncludeConst
1290 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001291 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001292
1293 // We are left with FromType and ToType being the pointee types
1294 // after unwrapping the original FromType and ToType the same number
1295 // of types. If we unwrapped any pointers, and if FromType and
1296 // ToType have the same unqualified type (since we checked
1297 // qualifiers above), then this is a qualification conversion.
1298 return UnwrappedAnyPointer &&
1299 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1300}
1301
Douglas Gregor734d9862009-01-30 23:27:23 +00001302/// Determines whether there is a user-defined conversion sequence
1303/// (C++ [over.ics.user]) that converts expression From to the type
1304/// ToType. If such a conversion exists, User will contain the
1305/// user-defined conversion sequence that performs such a conversion
1306/// and this routine will return true. Otherwise, this routine returns
1307/// false and User is unspecified.
1308///
1309/// \param AllowConversionFunctions true if the conversion should
1310/// consider conversion functions at all. If false, only constructors
1311/// will be considered.
1312///
1313/// \param AllowExplicit true if the conversion should consider C++0x
1314/// "explicit" conversion functions as well as non-explicit conversion
1315/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001316bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001317 UserDefinedConversionSequence& User,
Douglas Gregor734d9862009-01-30 23:27:23 +00001318 bool AllowConversionFunctions,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001319 bool AllowExplicit)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001320{
1321 OverloadCandidateSet CandidateSet;
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001322 if (const RecordType *ToRecordType = ToType->getAsRecordType()) {
1323 if (CXXRecordDecl *ToRecordDecl
1324 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1325 // C++ [over.match.ctor]p1:
1326 // When objects of class type are direct-initialized (8.5), or
1327 // copy-initialized from an expression of the same or a
1328 // derived class type (8.5), overload resolution selects the
1329 // constructor. [...] For copy-initialization, the candidate
1330 // functions are all the converting constructors (12.3.1) of
1331 // that class. The argument list is the expression-list within
1332 // the parentheses of the initializer.
1333 DeclarationName ConstructorName
1334 = Context.DeclarationNames.getCXXConstructorName(
1335 Context.getCanonicalType(ToType).getUnqualifiedType());
1336 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001337 for (llvm::tie(Con, ConEnd)
1338 = ToRecordDecl->lookup(Context, ConstructorName);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001339 Con != ConEnd; ++Con) {
1340 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1341 if (Constructor->isConvertingConstructor())
1342 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1343 /*SuppressUserConversions=*/true);
1344 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001345 }
1346 }
1347
Douglas Gregor734d9862009-01-30 23:27:23 +00001348 if (!AllowConversionFunctions) {
1349 // Don't allow any conversion functions to enter the overload set.
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001350 } else if (const RecordType *FromRecordType
1351 = From->getType()->getAsRecordType()) {
1352 if (CXXRecordDecl *FromRecordDecl
1353 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1354 // Add all of the conversion functions as candidates.
1355 // FIXME: Look for conversions in base classes!
1356 OverloadedFunctionDecl *Conversions
1357 = FromRecordDecl->getConversionFunctions();
1358 for (OverloadedFunctionDecl::function_iterator Func
1359 = Conversions->function_begin();
1360 Func != Conversions->function_end(); ++Func) {
1361 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1362 if (AllowExplicit || !Conv->isExplicit())
1363 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1364 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001365 }
1366 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001367
1368 OverloadCandidateSet::iterator Best;
1369 switch (BestViableFunction(CandidateSet, Best)) {
1370 case OR_Success:
1371 // Record the standard conversion we used and the conversion function.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001372 if (CXXConstructorDecl *Constructor
1373 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1374 // C++ [over.ics.user]p1:
1375 // If the user-defined conversion is specified by a
1376 // constructor (12.3.1), the initial standard conversion
1377 // sequence converts the source type to the type required by
1378 // the argument of the constructor.
1379 //
1380 // FIXME: What about ellipsis conversions?
1381 QualType ThisType = Constructor->getThisType(Context);
1382 User.Before = Best->Conversions[0].Standard;
1383 User.ConversionFunction = Constructor;
1384 User.After.setAsIdentityConversion();
1385 User.After.FromTypePtr
1386 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
1387 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1388 return true;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001389 } else if (CXXConversionDecl *Conversion
1390 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1391 // C++ [over.ics.user]p1:
1392 //
1393 // [...] If the user-defined conversion is specified by a
1394 // conversion function (12.3.2), the initial standard
1395 // conversion sequence converts the source type to the
1396 // implicit object parameter of the conversion function.
1397 User.Before = Best->Conversions[0].Standard;
1398 User.ConversionFunction = Conversion;
1399
1400 // C++ [over.ics.user]p2:
1401 // The second standard conversion sequence converts the
1402 // result of the user-defined conversion to the target type
1403 // for the sequence. Since an implicit conversion sequence
1404 // is an initialization, the special rules for
1405 // initialization by user-defined conversion apply when
1406 // selecting the best user-defined conversion for a
1407 // user-defined conversion sequence (see 13.3.3 and
1408 // 13.3.3.1).
1409 User.After = Best->FinalConversion;
1410 return true;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001411 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001412 assert(false && "Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001413 return false;
1414 }
1415
1416 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001417 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001418 // No conversion here! We're done.
1419 return false;
1420
1421 case OR_Ambiguous:
1422 // FIXME: See C++ [over.best.ics]p10 for the handling of
1423 // ambiguous conversion sequences.
1424 return false;
1425 }
1426
1427 return false;
1428}
1429
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001430/// CompareImplicitConversionSequences - Compare two implicit
1431/// conversion sequences to determine whether one is better than the
1432/// other or if they are indistinguishable (C++ 13.3.3.2).
1433ImplicitConversionSequence::CompareKind
1434Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1435 const ImplicitConversionSequence& ICS2)
1436{
1437 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1438 // conversion sequences (as defined in 13.3.3.1)
1439 // -- a standard conversion sequence (13.3.3.1.1) is a better
1440 // conversion sequence than a user-defined conversion sequence or
1441 // an ellipsis conversion sequence, and
1442 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1443 // conversion sequence than an ellipsis conversion sequence
1444 // (13.3.3.1.3).
1445 //
1446 if (ICS1.ConversionKind < ICS2.ConversionKind)
1447 return ImplicitConversionSequence::Better;
1448 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1449 return ImplicitConversionSequence::Worse;
1450
1451 // Two implicit conversion sequences of the same form are
1452 // indistinguishable conversion sequences unless one of the
1453 // following rules apply: (C++ 13.3.3.2p3):
1454 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1455 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1456 else if (ICS1.ConversionKind ==
1457 ImplicitConversionSequence::UserDefinedConversion) {
1458 // User-defined conversion sequence U1 is a better conversion
1459 // sequence than another user-defined conversion sequence U2 if
1460 // they contain the same user-defined conversion function or
1461 // constructor and if the second standard conversion sequence of
1462 // U1 is better than the second standard conversion sequence of
1463 // U2 (C++ 13.3.3.2p3).
1464 if (ICS1.UserDefined.ConversionFunction ==
1465 ICS2.UserDefined.ConversionFunction)
1466 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1467 ICS2.UserDefined.After);
1468 }
1469
1470 return ImplicitConversionSequence::Indistinguishable;
1471}
1472
1473/// CompareStandardConversionSequences - Compare two standard
1474/// conversion sequences to determine whether one is better than the
1475/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1476ImplicitConversionSequence::CompareKind
1477Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1478 const StandardConversionSequence& SCS2)
1479{
1480 // Standard conversion sequence S1 is a better conversion sequence
1481 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1482
1483 // -- S1 is a proper subsequence of S2 (comparing the conversion
1484 // sequences in the canonical form defined by 13.3.3.1.1,
1485 // excluding any Lvalue Transformation; the identity conversion
1486 // sequence is considered to be a subsequence of any
1487 // non-identity conversion sequence) or, if not that,
1488 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1489 // Neither is a proper subsequence of the other. Do nothing.
1490 ;
1491 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1492 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1493 (SCS1.Second == ICK_Identity &&
1494 SCS1.Third == ICK_Identity))
1495 // SCS1 is a proper subsequence of SCS2.
1496 return ImplicitConversionSequence::Better;
1497 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1498 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1499 (SCS2.Second == ICK_Identity &&
1500 SCS2.Third == ICK_Identity))
1501 // SCS2 is a proper subsequence of SCS1.
1502 return ImplicitConversionSequence::Worse;
1503
1504 // -- the rank of S1 is better than the rank of S2 (by the rules
1505 // defined below), or, if not that,
1506 ImplicitConversionRank Rank1 = SCS1.getRank();
1507 ImplicitConversionRank Rank2 = SCS2.getRank();
1508 if (Rank1 < Rank2)
1509 return ImplicitConversionSequence::Better;
1510 else if (Rank2 < Rank1)
1511 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001512
Douglas Gregor57373262008-10-22 14:17:15 +00001513 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1514 // are indistinguishable unless one of the following rules
1515 // applies:
1516
1517 // A conversion that is not a conversion of a pointer, or
1518 // pointer to member, to bool is better than another conversion
1519 // that is such a conversion.
1520 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1521 return SCS2.isPointerConversionToBool()
1522 ? ImplicitConversionSequence::Better
1523 : ImplicitConversionSequence::Worse;
1524
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001525 // C++ [over.ics.rank]p4b2:
1526 //
1527 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001528 // conversion of B* to A* is better than conversion of B* to
1529 // void*, and conversion of A* to void* is better than conversion
1530 // of B* to void*.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001531 bool SCS1ConvertsToVoid
1532 = SCS1.isPointerConversionToVoidPointer(Context);
1533 bool SCS2ConvertsToVoid
1534 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001535 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1536 // Exactly one of the conversion sequences is a conversion to
1537 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001538 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1539 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001540 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1541 // Neither conversion sequence converts to a void pointer; compare
1542 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001543 if (ImplicitConversionSequence::CompareKind DerivedCK
1544 = CompareDerivedToBaseConversions(SCS1, SCS2))
1545 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001546 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1547 // Both conversion sequences are conversions to void
1548 // pointers. Compare the source types to determine if there's an
1549 // inheritance relationship in their sources.
1550 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1551 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1552
1553 // Adjust the types we're converting from via the array-to-pointer
1554 // conversion, if we need to.
1555 if (SCS1.First == ICK_Array_To_Pointer)
1556 FromType1 = Context.getArrayDecayedType(FromType1);
1557 if (SCS2.First == ICK_Array_To_Pointer)
1558 FromType2 = Context.getArrayDecayedType(FromType2);
1559
1560 QualType FromPointee1
1561 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1562 QualType FromPointee2
1563 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1564
1565 if (IsDerivedFrom(FromPointee2, FromPointee1))
1566 return ImplicitConversionSequence::Better;
1567 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1568 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001569
1570 // Objective-C++: If one interface is more specific than the
1571 // other, it is the better one.
1572 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1573 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1574 if (FromIface1 && FromIface1) {
1575 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1576 return ImplicitConversionSequence::Better;
1577 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1578 return ImplicitConversionSequence::Worse;
1579 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001580 }
Douglas Gregor57373262008-10-22 14:17:15 +00001581
1582 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1583 // bullet 3).
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001584 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001585 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001586 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001587
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001588 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001589 // C++0x [over.ics.rank]p3b4:
1590 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1591 // implicit object parameter of a non-static member function declared
1592 // without a ref-qualifier, and S1 binds an rvalue reference to an
1593 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00001594 // FIXME: We don't know if we're dealing with the implicit object parameter,
1595 // or if the member function in this case has a ref qualifier.
1596 // (Of course, we don't have ref qualifiers yet.)
1597 if (SCS1.RRefBinding != SCS2.RRefBinding)
1598 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1599 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001600
1601 // C++ [over.ics.rank]p3b4:
1602 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1603 // which the references refer are the same type except for
1604 // top-level cv-qualifiers, and the type to which the reference
1605 // initialized by S2 refers is more cv-qualified than the type
1606 // to which the reference initialized by S1 refers.
Sebastian Redla9845802009-03-29 15:27:50 +00001607 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1608 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001609 T1 = Context.getCanonicalType(T1);
1610 T2 = Context.getCanonicalType(T2);
1611 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1612 if (T2.isMoreQualifiedThan(T1))
1613 return ImplicitConversionSequence::Better;
1614 else if (T1.isMoreQualifiedThan(T2))
1615 return ImplicitConversionSequence::Worse;
1616 }
1617 }
Douglas Gregor57373262008-10-22 14:17:15 +00001618
1619 return ImplicitConversionSequence::Indistinguishable;
1620}
1621
1622/// CompareQualificationConversions - Compares two standard conversion
1623/// sequences to determine whether they can be ranked based on their
1624/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1625ImplicitConversionSequence::CompareKind
1626Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1627 const StandardConversionSequence& SCS2)
1628{
Douglas Gregorba7e2102008-10-22 15:04:37 +00001629 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001630 // -- S1 and S2 differ only in their qualification conversion and
1631 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1632 // cv-qualification signature of type T1 is a proper subset of
1633 // the cv-qualification signature of type T2, and S1 is not the
1634 // deprecated string literal array-to-pointer conversion (4.2).
1635 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1636 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1637 return ImplicitConversionSequence::Indistinguishable;
1638
1639 // FIXME: the example in the standard doesn't use a qualification
1640 // conversion (!)
1641 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1642 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1643 T1 = Context.getCanonicalType(T1);
1644 T2 = Context.getCanonicalType(T2);
1645
1646 // If the types are the same, we won't learn anything by unwrapped
1647 // them.
1648 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1649 return ImplicitConversionSequence::Indistinguishable;
1650
1651 ImplicitConversionSequence::CompareKind Result
1652 = ImplicitConversionSequence::Indistinguishable;
1653 while (UnwrapSimilarPointerTypes(T1, T2)) {
1654 // Within each iteration of the loop, we check the qualifiers to
1655 // determine if this still looks like a qualification
1656 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001657 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001658 // until there are no more pointers or pointers-to-members left
1659 // to unwrap. This essentially mimics what
1660 // IsQualificationConversion does, but here we're checking for a
1661 // strict subset of qualifiers.
1662 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1663 // The qualifiers are the same, so this doesn't tell us anything
1664 // about how the sequences rank.
1665 ;
1666 else if (T2.isMoreQualifiedThan(T1)) {
1667 // T1 has fewer qualifiers, so it could be the better sequence.
1668 if (Result == ImplicitConversionSequence::Worse)
1669 // Neither has qualifiers that are a subset of the other's
1670 // qualifiers.
1671 return ImplicitConversionSequence::Indistinguishable;
1672
1673 Result = ImplicitConversionSequence::Better;
1674 } else if (T1.isMoreQualifiedThan(T2)) {
1675 // T2 has fewer qualifiers, so it could be the better sequence.
1676 if (Result == ImplicitConversionSequence::Better)
1677 // Neither has qualifiers that are a subset of the other's
1678 // qualifiers.
1679 return ImplicitConversionSequence::Indistinguishable;
1680
1681 Result = ImplicitConversionSequence::Worse;
1682 } else {
1683 // Qualifiers are disjoint.
1684 return ImplicitConversionSequence::Indistinguishable;
1685 }
1686
1687 // If the types after this point are equivalent, we're done.
1688 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1689 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001690 }
1691
Douglas Gregor57373262008-10-22 14:17:15 +00001692 // Check that the winning standard conversion sequence isn't using
1693 // the deprecated string literal array to pointer conversion.
1694 switch (Result) {
1695 case ImplicitConversionSequence::Better:
1696 if (SCS1.Deprecated)
1697 Result = ImplicitConversionSequence::Indistinguishable;
1698 break;
1699
1700 case ImplicitConversionSequence::Indistinguishable:
1701 break;
1702
1703 case ImplicitConversionSequence::Worse:
1704 if (SCS2.Deprecated)
1705 Result = ImplicitConversionSequence::Indistinguishable;
1706 break;
1707 }
1708
1709 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001710}
1711
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001712/// CompareDerivedToBaseConversions - Compares two standard conversion
1713/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00001714/// various kinds of derived-to-base conversions (C++
1715/// [over.ics.rank]p4b3). As part of these checks, we also look at
1716/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001717ImplicitConversionSequence::CompareKind
1718Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1719 const StandardConversionSequence& SCS2) {
1720 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1721 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1722 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1723 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1724
1725 // Adjust the types we're converting from via the array-to-pointer
1726 // conversion, if we need to.
1727 if (SCS1.First == ICK_Array_To_Pointer)
1728 FromType1 = Context.getArrayDecayedType(FromType1);
1729 if (SCS2.First == ICK_Array_To_Pointer)
1730 FromType2 = Context.getArrayDecayedType(FromType2);
1731
1732 // Canonicalize all of the types.
1733 FromType1 = Context.getCanonicalType(FromType1);
1734 ToType1 = Context.getCanonicalType(ToType1);
1735 FromType2 = Context.getCanonicalType(FromType2);
1736 ToType2 = Context.getCanonicalType(ToType2);
1737
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001738 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001739 //
1740 // If class B is derived directly or indirectly from class A and
1741 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001742 //
1743 // For Objective-C, we let A, B, and C also be Objective-C
1744 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001745
1746 // Compare based on pointer conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001747 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00001748 SCS2.Second == ICK_Pointer_Conversion &&
1749 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1750 FromType1->isPointerType() && FromType2->isPointerType() &&
1751 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001752 QualType FromPointee1
1753 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1754 QualType ToPointee1
1755 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1756 QualType FromPointee2
1757 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1758 QualType ToPointee2
1759 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001760
1761 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1762 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1763 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1764 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1765
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001766 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001767 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1768 if (IsDerivedFrom(ToPointee1, ToPointee2))
1769 return ImplicitConversionSequence::Better;
1770 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1771 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001772
1773 if (ToIface1 && ToIface2) {
1774 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1775 return ImplicitConversionSequence::Better;
1776 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1777 return ImplicitConversionSequence::Worse;
1778 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001779 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001780
1781 // -- conversion of B* to A* is better than conversion of C* to A*,
1782 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1783 if (IsDerivedFrom(FromPointee2, FromPointee1))
1784 return ImplicitConversionSequence::Better;
1785 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1786 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001787
1788 if (FromIface1 && FromIface2) {
1789 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1790 return ImplicitConversionSequence::Better;
1791 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1792 return ImplicitConversionSequence::Worse;
1793 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001794 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001795 }
1796
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001797 // Compare based on reference bindings.
1798 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1799 SCS1.Second == ICK_Derived_To_Base) {
1800 // -- binding of an expression of type C to a reference of type
1801 // B& is better than binding an expression of type C to a
1802 // reference of type A&,
1803 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1804 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1805 if (IsDerivedFrom(ToType1, ToType2))
1806 return ImplicitConversionSequence::Better;
1807 else if (IsDerivedFrom(ToType2, ToType1))
1808 return ImplicitConversionSequence::Worse;
1809 }
1810
Douglas Gregor225c41e2008-11-03 19:09:14 +00001811 // -- binding of an expression of type B to a reference of type
1812 // A& is better than binding an expression of type C to a
1813 // reference of type A&,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001814 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1815 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1816 if (IsDerivedFrom(FromType2, FromType1))
1817 return ImplicitConversionSequence::Better;
1818 else if (IsDerivedFrom(FromType1, FromType2))
1819 return ImplicitConversionSequence::Worse;
1820 }
1821 }
1822
1823
1824 // FIXME: conversion of A::* to B::* is better than conversion of
1825 // A::* to C::*,
1826
1827 // FIXME: conversion of B::* to C::* is better than conversion of
1828 // A::* to C::*, and
1829
Douglas Gregor225c41e2008-11-03 19:09:14 +00001830 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1831 SCS1.Second == ICK_Derived_To_Base) {
1832 // -- conversion of C to B is better than conversion of C to A,
1833 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1834 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1835 if (IsDerivedFrom(ToType1, ToType2))
1836 return ImplicitConversionSequence::Better;
1837 else if (IsDerivedFrom(ToType2, ToType1))
1838 return ImplicitConversionSequence::Worse;
1839 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001840
Douglas Gregor225c41e2008-11-03 19:09:14 +00001841 // -- conversion of B to A is better than conversion of C to A.
1842 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1843 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1844 if (IsDerivedFrom(FromType2, FromType1))
1845 return ImplicitConversionSequence::Better;
1846 else if (IsDerivedFrom(FromType1, FromType2))
1847 return ImplicitConversionSequence::Worse;
1848 }
1849 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001850
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001851 return ImplicitConversionSequence::Indistinguishable;
1852}
1853
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001854/// TryCopyInitialization - Try to copy-initialize a value of type
1855/// ToType from the expression From. Return the implicit conversion
1856/// sequence required to pass this argument, which may be a bad
1857/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00001858/// a parameter of this type). If @p SuppressUserConversions, then we
1859/// do not permit any user-defined conversion sequences.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001860ImplicitConversionSequence
Douglas Gregor225c41e2008-11-03 19:09:14 +00001861Sema::TryCopyInitialization(Expr *From, QualType ToType,
1862 bool SuppressUserConversions) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00001863 if (ToType->isReferenceType()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001864 ImplicitConversionSequence ICS;
Douglas Gregor225c41e2008-11-03 19:09:14 +00001865 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001866 return ICS;
1867 } else {
Douglas Gregor225c41e2008-11-03 19:09:14 +00001868 return TryImplicitConversion(From, ToType, SuppressUserConversions);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001869 }
1870}
1871
1872/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1873/// type ToType. Returns true (and emits a diagnostic) if there was
1874/// an error, returns false if the initialization succeeded.
1875bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1876 const char* Flavor) {
1877 if (!getLangOptions().CPlusPlus) {
1878 // In C, argument passing is the same as performing an assignment.
1879 QualType FromType = From->getType();
1880 AssignConvertType ConvTy =
1881 CheckSingleAssignmentConstraints(ToType, From);
1882
1883 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1884 FromType, From, Flavor);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001885 }
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001886
1887 if (ToType->isReferenceType())
1888 return CheckReferenceInit(From, ToType);
1889
Douglas Gregor45920e82008-12-19 17:40:08 +00001890 if (!PerformImplicitConversion(From, ToType, Flavor))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001891 return false;
1892
1893 return Diag(From->getSourceRange().getBegin(),
1894 diag::err_typecheck_convert_incompatible)
1895 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001896}
1897
Douglas Gregor96176b32008-11-18 23:14:02 +00001898/// TryObjectArgumentInitialization - Try to initialize the object
1899/// parameter of the given member function (@c Method) from the
1900/// expression @p From.
1901ImplicitConversionSequence
1902Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1903 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1904 unsigned MethodQuals = Method->getTypeQualifiers();
1905 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1906
1907 // Set up the conversion sequence as a "bad" conversion, to allow us
1908 // to exit early.
1909 ImplicitConversionSequence ICS;
1910 ICS.Standard.setAsIdentityConversion();
1911 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1912
1913 // We need to have an object of class type.
1914 QualType FromType = From->getType();
1915 if (!FromType->isRecordType())
1916 return ICS;
1917
1918 // The implicit object parmeter is has the type "reference to cv X",
1919 // where X is the class of which the function is a member
1920 // (C++ [over.match.funcs]p4). However, when finding an implicit
1921 // conversion sequence for the argument, we are not allowed to
1922 // create temporaries or perform user-defined conversions
1923 // (C++ [over.match.funcs]p5). We perform a simplified version of
1924 // reference binding here, that allows class rvalues to bind to
1925 // non-constant references.
1926
1927 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1928 // with the implicit object parameter (C++ [over.match.funcs]p5).
1929 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1930 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1931 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1932 return ICS;
1933
1934 // Check that we have either the same type or a derived type. It
1935 // affects the conversion rank.
1936 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1937 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1938 ICS.Standard.Second = ICK_Identity;
1939 else if (IsDerivedFrom(FromType, ClassType))
1940 ICS.Standard.Second = ICK_Derived_To_Base;
1941 else
1942 return ICS;
1943
1944 // Success. Mark this as a reference binding.
1945 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1946 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1947 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1948 ICS.Standard.ReferenceBinding = true;
1949 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00001950 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00001951 return ICS;
1952}
1953
1954/// PerformObjectArgumentInitialization - Perform initialization of
1955/// the implicit object parameter for the given Method with the given
1956/// expression.
1957bool
1958Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
1959 QualType ImplicitParamType
1960 = Method->getThisType(Context)->getAsPointerType()->getPointeeType();
1961 ImplicitConversionSequence ICS
1962 = TryObjectArgumentInitialization(From, Method);
1963 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
1964 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001965 diag::err_implicit_object_parameter_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00001966 << ImplicitParamType << From->getType() << From->getSourceRange();
Douglas Gregor96176b32008-11-18 23:14:02 +00001967
1968 if (ICS.Standard.Second == ICK_Derived_To_Base &&
1969 CheckDerivedToBaseConversion(From->getType(), ImplicitParamType,
1970 From->getSourceRange().getBegin(),
1971 From->getSourceRange()))
1972 return true;
1973
1974 ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true);
1975 return false;
1976}
1977
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001978/// TryContextuallyConvertToBool - Attempt to contextually convert the
1979/// expression From to bool (C++0x [conv]p3).
1980ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
1981 return TryImplicitConversion(From, Context.BoolTy, false, true);
1982}
1983
1984/// PerformContextuallyConvertToBool - Perform a contextual conversion
1985/// of the expression From to bool (C++0x [conv]p3).
1986bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
1987 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
1988 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
1989 return false;
1990
1991 return Diag(From->getSourceRange().getBegin(),
1992 diag::err_typecheck_bool_condition)
1993 << From->getType() << From->getSourceRange();
1994}
1995
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001996/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00001997/// candidate functions, using the given function call arguments. If
1998/// @p SuppressUserConversions, then don't allow user-defined
1999/// conversions via constructors or conversion operators.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002000void
2001Sema::AddOverloadCandidate(FunctionDecl *Function,
2002 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002003 OverloadCandidateSet& CandidateSet,
2004 bool SuppressUserConversions)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002005{
Douglas Gregor72564e72009-02-26 23:50:07 +00002006 const FunctionProtoType* Proto
2007 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002008 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002009 assert(!isa<CXXConversionDecl>(Function) &&
2010 "Use AddConversionCandidate for conversion functions");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002011
Douglas Gregor88a35142008-12-22 05:46:06 +00002012 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2013 // If we get here, it's because we're calling a member function
2014 // that is named without a member access expression (e.g.,
2015 // "this->f") that was either written explicitly or created
2016 // implicitly. This can happen with a qualified call to a member
2017 // function, e.g., X::f(). We use a NULL object as the implied
2018 // object argument (C++ [over.call.func]p3).
2019 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2020 SuppressUserConversions);
2021 return;
2022 }
2023
2024
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002025 // Add this candidate
2026 CandidateSet.push_back(OverloadCandidate());
2027 OverloadCandidate& Candidate = CandidateSet.back();
2028 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00002029 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002030 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002031 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002032
2033 unsigned NumArgsInProto = Proto->getNumArgs();
2034
2035 // (C++ 13.3.2p2): A candidate function having fewer than m
2036 // parameters is viable only if it has an ellipsis in its parameter
2037 // list (8.3.5).
2038 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2039 Candidate.Viable = false;
2040 return;
2041 }
2042
2043 // (C++ 13.3.2p2): A candidate function having more than m parameters
2044 // is viable only if the (m+1)st parameter has a default argument
2045 // (8.3.6). For the purposes of overload resolution, the
2046 // parameter list is truncated on the right, so that there are
2047 // exactly m parameters.
2048 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2049 if (NumArgs < MinRequiredArgs) {
2050 // Not enough arguments.
2051 Candidate.Viable = false;
2052 return;
2053 }
2054
2055 // Determine the implicit conversion sequences for each of the
2056 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002057 Candidate.Conversions.resize(NumArgs);
2058 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2059 if (ArgIdx < NumArgsInProto) {
2060 // (C++ 13.3.2p3): for F to be a viable function, there shall
2061 // exist for each argument an implicit conversion sequence
2062 // (13.3.3.1) that converts that argument to the corresponding
2063 // parameter of F.
2064 QualType ParamType = Proto->getArgType(ArgIdx);
2065 Candidate.Conversions[ArgIdx]
Douglas Gregor225c41e2008-11-03 19:09:14 +00002066 = TryCopyInitialization(Args[ArgIdx], ParamType,
2067 SuppressUserConversions);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002068 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002069 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002070 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002071 break;
2072 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002073 } else {
2074 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2075 // argument for which there is no corresponding parameter is
2076 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2077 Candidate.Conversions[ArgIdx].ConversionKind
2078 = ImplicitConversionSequence::EllipsisConversion;
2079 }
2080 }
2081}
2082
Douglas Gregor063daf62009-03-13 18:40:31 +00002083/// \brief Add all of the function declarations in the given function set to
2084/// the overload canddiate set.
2085void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2086 Expr **Args, unsigned NumArgs,
2087 OverloadCandidateSet& CandidateSet,
2088 bool SuppressUserConversions) {
2089 for (FunctionSet::const_iterator F = Functions.begin(),
2090 FEnd = Functions.end();
2091 F != FEnd; ++F)
2092 AddOverloadCandidate(*F, Args, NumArgs, CandidateSet,
2093 SuppressUserConversions);
2094}
2095
Douglas Gregor96176b32008-11-18 23:14:02 +00002096/// AddMethodCandidate - Adds the given C++ member function to the set
2097/// of candidate functions, using the given function call arguments
2098/// and the object argument (@c Object). For example, in a call
2099/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2100/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2101/// allow user-defined conversions via constructors or conversion
2102/// operators.
2103void
2104Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2105 Expr **Args, unsigned NumArgs,
2106 OverloadCandidateSet& CandidateSet,
2107 bool SuppressUserConversions)
2108{
Douglas Gregor72564e72009-02-26 23:50:07 +00002109 const FunctionProtoType* Proto
2110 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002111 assert(Proto && "Methods without a prototype cannot be overloaded");
2112 assert(!isa<CXXConversionDecl>(Method) &&
2113 "Use AddConversionCandidate for conversion functions");
2114
2115 // Add this candidate
2116 CandidateSet.push_back(OverloadCandidate());
2117 OverloadCandidate& Candidate = CandidateSet.back();
2118 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002119 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002120 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002121
2122 unsigned NumArgsInProto = Proto->getNumArgs();
2123
2124 // (C++ 13.3.2p2): A candidate function having fewer than m
2125 // parameters is viable only if it has an ellipsis in its parameter
2126 // list (8.3.5).
2127 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2128 Candidate.Viable = false;
2129 return;
2130 }
2131
2132 // (C++ 13.3.2p2): A candidate function having more than m parameters
2133 // is viable only if the (m+1)st parameter has a default argument
2134 // (8.3.6). For the purposes of overload resolution, the
2135 // parameter list is truncated on the right, so that there are
2136 // exactly m parameters.
2137 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2138 if (NumArgs < MinRequiredArgs) {
2139 // Not enough arguments.
2140 Candidate.Viable = false;
2141 return;
2142 }
2143
2144 Candidate.Viable = true;
2145 Candidate.Conversions.resize(NumArgs + 1);
2146
Douglas Gregor88a35142008-12-22 05:46:06 +00002147 if (Method->isStatic() || !Object)
2148 // The implicit object argument is ignored.
2149 Candidate.IgnoreObjectArgument = true;
2150 else {
2151 // Determine the implicit conversion sequence for the object
2152 // parameter.
2153 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2154 if (Candidate.Conversions[0].ConversionKind
2155 == ImplicitConversionSequence::BadConversion) {
2156 Candidate.Viable = false;
2157 return;
2158 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002159 }
2160
2161 // Determine the implicit conversion sequences for each of the
2162 // arguments.
2163 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2164 if (ArgIdx < NumArgsInProto) {
2165 // (C++ 13.3.2p3): for F to be a viable function, there shall
2166 // exist for each argument an implicit conversion sequence
2167 // (13.3.3.1) that converts that argument to the corresponding
2168 // parameter of F.
2169 QualType ParamType = Proto->getArgType(ArgIdx);
2170 Candidate.Conversions[ArgIdx + 1]
2171 = TryCopyInitialization(Args[ArgIdx], ParamType,
2172 SuppressUserConversions);
2173 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2174 == ImplicitConversionSequence::BadConversion) {
2175 Candidate.Viable = false;
2176 break;
2177 }
2178 } else {
2179 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2180 // argument for which there is no corresponding parameter is
2181 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2182 Candidate.Conversions[ArgIdx + 1].ConversionKind
2183 = ImplicitConversionSequence::EllipsisConversion;
2184 }
2185 }
2186}
2187
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002188/// AddConversionCandidate - Add a C++ conversion function as a
2189/// candidate in the candidate set (C++ [over.match.conv],
2190/// C++ [over.match.copy]). From is the expression we're converting from,
2191/// and ToType is the type that we're eventually trying to convert to
2192/// (which may or may not be the same type as the type that the
2193/// conversion function produces).
2194void
2195Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2196 Expr *From, QualType ToType,
2197 OverloadCandidateSet& CandidateSet) {
2198 // Add this candidate
2199 CandidateSet.push_back(OverloadCandidate());
2200 OverloadCandidate& Candidate = CandidateSet.back();
2201 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002202 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002203 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002204 Candidate.FinalConversion.setAsIdentityConversion();
2205 Candidate.FinalConversion.FromTypePtr
2206 = Conversion->getConversionType().getAsOpaquePtr();
2207 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2208
Douglas Gregor96176b32008-11-18 23:14:02 +00002209 // Determine the implicit conversion sequence for the implicit
2210 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002211 Candidate.Viable = true;
2212 Candidate.Conversions.resize(1);
Douglas Gregor96176b32008-11-18 23:14:02 +00002213 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002214
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002215 if (Candidate.Conversions[0].ConversionKind
2216 == ImplicitConversionSequence::BadConversion) {
2217 Candidate.Viable = false;
2218 return;
2219 }
2220
2221 // To determine what the conversion from the result of calling the
2222 // conversion function to the type we're eventually trying to
2223 // convert to (ToType), we need to synthesize a call to the
2224 // conversion function and attempt copy initialization from it. This
2225 // makes sure that we get the right semantics with respect to
2226 // lvalues/rvalues and the type. Fortunately, we can allocate this
2227 // call on the stack and we don't need its arguments to be
2228 // well-formed.
2229 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2230 SourceLocation());
2231 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002232 &ConversionRef, false);
Ted Kremenek668bf912009-02-09 20:51:47 +00002233
2234 // Note that it is safe to allocate CallExpr on the stack here because
2235 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2236 // allocator).
2237 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002238 Conversion->getConversionType().getNonReferenceType(),
2239 SourceLocation());
2240 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2241 switch (ICS.ConversionKind) {
2242 case ImplicitConversionSequence::StandardConversion:
2243 Candidate.FinalConversion = ICS.Standard;
2244 break;
2245
2246 case ImplicitConversionSequence::BadConversion:
2247 Candidate.Viable = false;
2248 break;
2249
2250 default:
2251 assert(false &&
2252 "Can only end up with a standard conversion sequence or failure");
2253 }
2254}
2255
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002256/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2257/// converts the given @c Object to a function pointer via the
2258/// conversion function @c Conversion, and then attempts to call it
2259/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2260/// the type of function that we'll eventually be calling.
2261void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregor72564e72009-02-26 23:50:07 +00002262 const FunctionProtoType *Proto,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002263 Expr *Object, Expr **Args, unsigned NumArgs,
2264 OverloadCandidateSet& CandidateSet) {
2265 CandidateSet.push_back(OverloadCandidate());
2266 OverloadCandidate& Candidate = CandidateSet.back();
2267 Candidate.Function = 0;
2268 Candidate.Surrogate = Conversion;
2269 Candidate.Viable = true;
2270 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002271 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002272 Candidate.Conversions.resize(NumArgs + 1);
2273
2274 // Determine the implicit conversion sequence for the implicit
2275 // object parameter.
2276 ImplicitConversionSequence ObjectInit
2277 = TryObjectArgumentInitialization(Object, Conversion);
2278 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2279 Candidate.Viable = false;
2280 return;
2281 }
2282
2283 // The first conversion is actually a user-defined conversion whose
2284 // first conversion is ObjectInit's standard conversion (which is
2285 // effectively a reference binding). Record it as such.
2286 Candidate.Conversions[0].ConversionKind
2287 = ImplicitConversionSequence::UserDefinedConversion;
2288 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2289 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2290 Candidate.Conversions[0].UserDefined.After
2291 = Candidate.Conversions[0].UserDefined.Before;
2292 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2293
2294 // Find the
2295 unsigned NumArgsInProto = Proto->getNumArgs();
2296
2297 // (C++ 13.3.2p2): A candidate function having fewer than m
2298 // parameters is viable only if it has an ellipsis in its parameter
2299 // list (8.3.5).
2300 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2301 Candidate.Viable = false;
2302 return;
2303 }
2304
2305 // Function types don't have any default arguments, so just check if
2306 // we have enough arguments.
2307 if (NumArgs < NumArgsInProto) {
2308 // Not enough arguments.
2309 Candidate.Viable = false;
2310 return;
2311 }
2312
2313 // Determine the implicit conversion sequences for each of the
2314 // arguments.
2315 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2316 if (ArgIdx < NumArgsInProto) {
2317 // (C++ 13.3.2p3): for F to be a viable function, there shall
2318 // exist for each argument an implicit conversion sequence
2319 // (13.3.3.1) that converts that argument to the corresponding
2320 // parameter of F.
2321 QualType ParamType = Proto->getArgType(ArgIdx);
2322 Candidate.Conversions[ArgIdx + 1]
2323 = TryCopyInitialization(Args[ArgIdx], ParamType,
2324 /*SuppressUserConversions=*/false);
2325 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2326 == ImplicitConversionSequence::BadConversion) {
2327 Candidate.Viable = false;
2328 break;
2329 }
2330 } else {
2331 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2332 // argument for which there is no corresponding parameter is
2333 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2334 Candidate.Conversions[ArgIdx + 1].ConversionKind
2335 = ImplicitConversionSequence::EllipsisConversion;
2336 }
2337 }
2338}
2339
Douglas Gregor063daf62009-03-13 18:40:31 +00002340// FIXME: This will eventually be removed, once we've migrated all of
2341// the operator overloading logic over to the scheme used by binary
2342// operators, which works for template instantiation.
2343void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002344 SourceLocation OpLoc,
Douglas Gregor96176b32008-11-18 23:14:02 +00002345 Expr **Args, unsigned NumArgs,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002346 OverloadCandidateSet& CandidateSet,
2347 SourceRange OpRange) {
Douglas Gregor063daf62009-03-13 18:40:31 +00002348
2349 FunctionSet Functions;
2350
2351 QualType T1 = Args[0]->getType();
2352 QualType T2;
2353 if (NumArgs > 1)
2354 T2 = Args[1]->getType();
2355
2356 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2357 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
2358 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2359 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2360 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2361 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2362}
2363
2364/// \brief Add overload candidates for overloaded operators that are
2365/// member functions.
2366///
2367/// Add the overloaded operator candidates that are member functions
2368/// for the operator Op that was used in an operator expression such
2369/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2370/// CandidateSet will store the added overload candidates. (C++
2371/// [over.match.oper]).
2372void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2373 SourceLocation OpLoc,
2374 Expr **Args, unsigned NumArgs,
2375 OverloadCandidateSet& CandidateSet,
2376 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002377 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2378
2379 // C++ [over.match.oper]p3:
2380 // For a unary operator @ with an operand of a type whose
2381 // cv-unqualified version is T1, and for a binary operator @ with
2382 // a left operand of a type whose cv-unqualified version is T1 and
2383 // a right operand of a type whose cv-unqualified version is T2,
2384 // three sets of candidate functions, designated member
2385 // candidates, non-member candidates and built-in candidates, are
2386 // constructed as follows:
2387 QualType T1 = Args[0]->getType();
2388 QualType T2;
2389 if (NumArgs > 1)
2390 T2 = Args[1]->getType();
2391
2392 // -- If T1 is a class type, the set of member candidates is the
2393 // result of the qualified lookup of T1::operator@
2394 // (13.3.1.1.1); otherwise, the set of member candidates is
2395 // empty.
Douglas Gregor063daf62009-03-13 18:40:31 +00002396 // FIXME: Lookup in base classes, too!
Douglas Gregor96176b32008-11-18 23:14:02 +00002397 if (const RecordType *T1Rec = T1->getAsRecordType()) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002398 DeclContext::lookup_const_iterator Oper, OperEnd;
Douglas Gregor6ab35242009-04-09 21:40:53 +00002399 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(Context, OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002400 Oper != OperEnd; ++Oper)
2401 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2402 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor96176b32008-11-18 23:14:02 +00002403 /*SuppressUserConversions=*/false);
Douglas Gregor96176b32008-11-18 23:14:02 +00002404 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002405}
2406
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002407/// AddBuiltinCandidate - Add a candidate for a built-in
2408/// operator. ResultTy and ParamTys are the result and parameter types
2409/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002410/// arguments being passed to the candidate. IsAssignmentOperator
2411/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002412/// operator. NumContextualBoolArguments is the number of arguments
2413/// (at the beginning of the argument list) that will be contextually
2414/// converted to bool.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002415void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2416 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002417 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002418 bool IsAssignmentOperator,
2419 unsigned NumContextualBoolArguments) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002420 // Add this candidate
2421 CandidateSet.push_back(OverloadCandidate());
2422 OverloadCandidate& Candidate = CandidateSet.back();
2423 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00002424 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002425 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002426 Candidate.BuiltinTypes.ResultTy = ResultTy;
2427 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2428 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2429
2430 // Determine the implicit conversion sequences for each of the
2431 // arguments.
2432 Candidate.Viable = true;
2433 Candidate.Conversions.resize(NumArgs);
2434 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002435 // C++ [over.match.oper]p4:
2436 // For the built-in assignment operators, conversions of the
2437 // left operand are restricted as follows:
2438 // -- no temporaries are introduced to hold the left operand, and
2439 // -- no user-defined conversions are applied to the left
2440 // operand to achieve a type match with the left-most
2441 // parameter of a built-in candidate.
2442 //
2443 // We block these conversions by turning off user-defined
2444 // conversions, since that is the only way that initialization of
2445 // a reference to a non-class type can occur from something that
2446 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002447 if (ArgIdx < NumContextualBoolArguments) {
2448 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2449 "Contextual conversion to bool requires bool type");
2450 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2451 } else {
2452 Candidate.Conversions[ArgIdx]
2453 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2454 ArgIdx == 0 && IsAssignmentOperator);
2455 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002456 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002457 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002458 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002459 break;
2460 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002461 }
2462}
2463
2464/// BuiltinCandidateTypeSet - A set of types that will be used for the
2465/// candidate operator functions for built-in operators (C++
2466/// [over.built]). The types are separated into pointer types and
2467/// enumeration types.
2468class BuiltinCandidateTypeSet {
2469 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002470 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002471
2472 /// PointerTypes - The set of pointer types that will be used in the
2473 /// built-in candidates.
2474 TypeSet PointerTypes;
2475
2476 /// EnumerationTypes - The set of enumeration types that will be
2477 /// used in the built-in candidates.
2478 TypeSet EnumerationTypes;
2479
2480 /// Context - The AST context in which we will build the type sets.
2481 ASTContext &Context;
2482
2483 bool AddWithMoreQualifiedTypeVariants(QualType Ty);
2484
2485public:
2486 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002487 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002488
2489 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2490
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002491 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2492 bool AllowExplicitConversions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002493
2494 /// pointer_begin - First pointer type found;
2495 iterator pointer_begin() { return PointerTypes.begin(); }
2496
2497 /// pointer_end - Last pointer type found;
2498 iterator pointer_end() { return PointerTypes.end(); }
2499
2500 /// enumeration_begin - First enumeration type found;
2501 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2502
2503 /// enumeration_end - Last enumeration type found;
2504 iterator enumeration_end() { return EnumerationTypes.end(); }
2505};
2506
2507/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2508/// the set of pointer types along with any more-qualified variants of
2509/// that type. For example, if @p Ty is "int const *", this routine
2510/// will add "int const *", "int const volatile *", "int const
2511/// restrict *", and "int const volatile restrict *" to the set of
2512/// pointer types. Returns true if the add of @p Ty itself succeeded,
2513/// false otherwise.
2514bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) {
2515 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002516 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002517 return false;
2518
2519 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2520 QualType PointeeTy = PointerTy->getPointeeType();
2521 // FIXME: Optimize this so that we don't keep trying to add the same types.
2522
2523 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
2524 // with all pointer conversions that don't cast away constness?
2525 if (!PointeeTy.isConstQualified())
2526 AddWithMoreQualifiedTypeVariants
2527 (Context.getPointerType(PointeeTy.withConst()));
2528 if (!PointeeTy.isVolatileQualified())
2529 AddWithMoreQualifiedTypeVariants
2530 (Context.getPointerType(PointeeTy.withVolatile()));
2531 if (!PointeeTy.isRestrictQualified())
2532 AddWithMoreQualifiedTypeVariants
2533 (Context.getPointerType(PointeeTy.withRestrict()));
2534 }
2535
2536 return true;
2537}
2538
2539/// AddTypesConvertedFrom - Add each of the types to which the type @p
2540/// Ty can be implicit converted to the given set of @p Types. We're
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002541/// primarily interested in pointer types and enumeration types.
2542/// AllowUserConversions is true if we should look at the conversion
2543/// functions of a class type, and AllowExplicitConversions if we
2544/// should also include the explicit conversion functions of a class
2545/// type.
2546void
2547BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2548 bool AllowUserConversions,
2549 bool AllowExplicitConversions) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002550 // Only deal with canonical types.
2551 Ty = Context.getCanonicalType(Ty);
2552
2553 // Look through reference types; they aren't part of the type of an
2554 // expression for the purposes of conversions.
2555 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2556 Ty = RefTy->getPointeeType();
2557
2558 // We don't care about qualifiers on the type.
2559 Ty = Ty.getUnqualifiedType();
2560
2561 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2562 QualType PointeeTy = PointerTy->getPointeeType();
2563
2564 // Insert our type, and its more-qualified variants, into the set
2565 // of types.
2566 if (!AddWithMoreQualifiedTypeVariants(Ty))
2567 return;
2568
2569 // Add 'cv void*' to our set of types.
2570 if (!Ty->isVoidType()) {
2571 QualType QualVoid
2572 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2573 AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2574 }
2575
2576 // If this is a pointer to a class type, add pointers to its bases
2577 // (with the same level of cv-qualification as the original
2578 // derived class, of course).
2579 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2580 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2581 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2582 Base != ClassDecl->bases_end(); ++Base) {
2583 QualType BaseTy = Context.getCanonicalType(Base->getType());
2584 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2585
2586 // Add the pointer type, recursively, so that we get all of
2587 // the indirect base classes, too.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002588 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002589 }
2590 }
2591 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00002592 EnumerationTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002593 } else if (AllowUserConversions) {
2594 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2595 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2596 // FIXME: Visit conversion functions in the base classes, too.
2597 OverloadedFunctionDecl *Conversions
2598 = ClassDecl->getConversionFunctions();
2599 for (OverloadedFunctionDecl::function_iterator Func
2600 = Conversions->function_begin();
2601 Func != Conversions->function_end(); ++Func) {
2602 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002603 if (AllowExplicitConversions || !Conv->isExplicit())
2604 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002605 }
2606 }
2607 }
2608}
2609
Douglas Gregor74253732008-11-19 15:42:04 +00002610/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2611/// operator overloads to the candidate set (C++ [over.built]), based
2612/// on the operator @p Op and the arguments given. For example, if the
2613/// operator is a binary '+', this routine might add "int
2614/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002615void
Douglas Gregor74253732008-11-19 15:42:04 +00002616Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2617 Expr **Args, unsigned NumArgs,
2618 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002619 // The set of "promoted arithmetic types", which are the arithmetic
2620 // types are that preserved by promotion (C++ [over.built]p2). Note
2621 // that the first few of these types are the promoted integral
2622 // types; these types need to be first.
2623 // FIXME: What about complex?
2624 const unsigned FirstIntegralType = 0;
2625 const unsigned LastIntegralType = 13;
2626 const unsigned FirstPromotedIntegralType = 7,
2627 LastPromotedIntegralType = 13;
2628 const unsigned FirstPromotedArithmeticType = 7,
2629 LastPromotedArithmeticType = 16;
2630 const unsigned NumArithmeticTypes = 16;
2631 QualType ArithmeticTypes[NumArithmeticTypes] = {
2632 Context.BoolTy, Context.CharTy, Context.WCharTy,
2633 Context.SignedCharTy, Context.ShortTy,
2634 Context.UnsignedCharTy, Context.UnsignedShortTy,
2635 Context.IntTy, Context.LongTy, Context.LongLongTy,
2636 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2637 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2638 };
2639
2640 // Find all of the types that the arguments can convert to, but only
2641 // if the operator we're looking at has built-in operator candidates
2642 // that make use of these types.
2643 BuiltinCandidateTypeSet CandidateTypes(Context);
2644 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2645 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00002646 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002647 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00002648 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
2649 (Op == OO_Star && NumArgs == 1)) {
2650 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002651 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2652 true,
2653 (Op == OO_Exclaim ||
2654 Op == OO_AmpAmp ||
2655 Op == OO_PipePipe));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002656 }
2657
2658 bool isComparison = false;
2659 switch (Op) {
2660 case OO_None:
2661 case NUM_OVERLOADED_OPERATORS:
2662 assert(false && "Expected an overloaded operator");
2663 break;
2664
Douglas Gregor74253732008-11-19 15:42:04 +00002665 case OO_Star: // '*' is either unary or binary
2666 if (NumArgs == 1)
2667 goto UnaryStar;
2668 else
2669 goto BinaryStar;
2670 break;
2671
2672 case OO_Plus: // '+' is either unary or binary
2673 if (NumArgs == 1)
2674 goto UnaryPlus;
2675 else
2676 goto BinaryPlus;
2677 break;
2678
2679 case OO_Minus: // '-' is either unary or binary
2680 if (NumArgs == 1)
2681 goto UnaryMinus;
2682 else
2683 goto BinaryMinus;
2684 break;
2685
2686 case OO_Amp: // '&' is either unary or binary
2687 if (NumArgs == 1)
2688 goto UnaryAmp;
2689 else
2690 goto BinaryAmp;
2691
2692 case OO_PlusPlus:
2693 case OO_MinusMinus:
2694 // C++ [over.built]p3:
2695 //
2696 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2697 // is either volatile or empty, there exist candidate operator
2698 // functions of the form
2699 //
2700 // VQ T& operator++(VQ T&);
2701 // T operator++(VQ T&, int);
2702 //
2703 // C++ [over.built]p4:
2704 //
2705 // For every pair (T, VQ), where T is an arithmetic type other
2706 // than bool, and VQ is either volatile or empty, there exist
2707 // candidate operator functions of the form
2708 //
2709 // VQ T& operator--(VQ T&);
2710 // T operator--(VQ T&, int);
2711 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2712 Arith < NumArithmeticTypes; ++Arith) {
2713 QualType ArithTy = ArithmeticTypes[Arith];
2714 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002715 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00002716
2717 // Non-volatile version.
2718 if (NumArgs == 1)
2719 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2720 else
2721 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2722
2723 // Volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002724 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregor74253732008-11-19 15:42:04 +00002725 if (NumArgs == 1)
2726 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2727 else
2728 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2729 }
2730
2731 // C++ [over.built]p5:
2732 //
2733 // For every pair (T, VQ), where T is a cv-qualified or
2734 // cv-unqualified object type, and VQ is either volatile or
2735 // empty, there exist candidate operator functions of the form
2736 //
2737 // T*VQ& operator++(T*VQ&);
2738 // T*VQ& operator--(T*VQ&);
2739 // T* operator++(T*VQ&, int);
2740 // T* operator--(T*VQ&, int);
2741 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2742 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2743 // Skip pointer types that aren't pointers to object types.
Douglas Gregorbad0e652009-03-24 20:32:41 +00002744 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00002745 continue;
2746
2747 QualType ParamTypes[2] = {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002748 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00002749 };
2750
2751 // Without volatile
2752 if (NumArgs == 1)
2753 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2754 else
2755 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2756
2757 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2758 // With volatile
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002759 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor74253732008-11-19 15:42:04 +00002760 if (NumArgs == 1)
2761 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2762 else
2763 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2764 }
2765 }
2766 break;
2767
2768 UnaryStar:
2769 // C++ [over.built]p6:
2770 // For every cv-qualified or cv-unqualified object type T, there
2771 // exist candidate operator functions of the form
2772 //
2773 // T& operator*(T*);
2774 //
2775 // C++ [over.built]p7:
2776 // For every function type T, there exist candidate operator
2777 // functions of the form
2778 // T& operator*(T*);
2779 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2780 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2781 QualType ParamTy = *Ptr;
2782 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002783 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00002784 &ParamTy, Args, 1, CandidateSet);
2785 }
2786 break;
2787
2788 UnaryPlus:
2789 // C++ [over.built]p8:
2790 // For every type T, there exist candidate operator functions of
2791 // the form
2792 //
2793 // T* operator+(T*);
2794 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2795 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2796 QualType ParamTy = *Ptr;
2797 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2798 }
2799
2800 // Fall through
2801
2802 UnaryMinus:
2803 // C++ [over.built]p9:
2804 // For every promoted arithmetic type T, there exist candidate
2805 // operator functions of the form
2806 //
2807 // T operator+(T);
2808 // T operator-(T);
2809 for (unsigned Arith = FirstPromotedArithmeticType;
2810 Arith < LastPromotedArithmeticType; ++Arith) {
2811 QualType ArithTy = ArithmeticTypes[Arith];
2812 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2813 }
2814 break;
2815
2816 case OO_Tilde:
2817 // C++ [over.built]p10:
2818 // For every promoted integral type T, there exist candidate
2819 // operator functions of the form
2820 //
2821 // T operator~(T);
2822 for (unsigned Int = FirstPromotedIntegralType;
2823 Int < LastPromotedIntegralType; ++Int) {
2824 QualType IntTy = ArithmeticTypes[Int];
2825 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2826 }
2827 break;
2828
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002829 case OO_New:
2830 case OO_Delete:
2831 case OO_Array_New:
2832 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002833 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00002834 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002835 break;
2836
2837 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00002838 UnaryAmp:
2839 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002840 // C++ [over.match.oper]p3:
2841 // -- For the operator ',', the unary operator '&', or the
2842 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002843 break;
2844
2845 case OO_Less:
2846 case OO_Greater:
2847 case OO_LessEqual:
2848 case OO_GreaterEqual:
2849 case OO_EqualEqual:
2850 case OO_ExclaimEqual:
2851 // C++ [over.built]p15:
2852 //
2853 // For every pointer or enumeration type T, there exist
2854 // candidate operator functions of the form
2855 //
2856 // bool operator<(T, T);
2857 // bool operator>(T, T);
2858 // bool operator<=(T, T);
2859 // bool operator>=(T, T);
2860 // bool operator==(T, T);
2861 // bool operator!=(T, T);
2862 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2863 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2864 QualType ParamTypes[2] = { *Ptr, *Ptr };
2865 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2866 }
2867 for (BuiltinCandidateTypeSet::iterator Enum
2868 = CandidateTypes.enumeration_begin();
2869 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2870 QualType ParamTypes[2] = { *Enum, *Enum };
2871 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2872 }
2873
2874 // Fall through.
2875 isComparison = true;
2876
Douglas Gregor74253732008-11-19 15:42:04 +00002877 BinaryPlus:
2878 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002879 if (!isComparison) {
2880 // We didn't fall through, so we must have OO_Plus or OO_Minus.
2881
2882 // C++ [over.built]p13:
2883 //
2884 // For every cv-qualified or cv-unqualified object type T
2885 // there exist candidate operator functions of the form
2886 //
2887 // T* operator+(T*, ptrdiff_t);
2888 // T& operator[](T*, ptrdiff_t); [BELOW]
2889 // T* operator-(T*, ptrdiff_t);
2890 // T* operator+(ptrdiff_t, T*);
2891 // T& operator[](ptrdiff_t, T*); [BELOW]
2892 //
2893 // C++ [over.built]p14:
2894 //
2895 // For every T, where T is a pointer to object type, there
2896 // exist candidate operator functions of the form
2897 //
2898 // ptrdiff_t operator-(T, T);
2899 for (BuiltinCandidateTypeSet::iterator Ptr
2900 = CandidateTypes.pointer_begin();
2901 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2902 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2903
2904 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
2905 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2906
2907 if (Op == OO_Plus) {
2908 // T* operator+(ptrdiff_t, T*);
2909 ParamTypes[0] = ParamTypes[1];
2910 ParamTypes[1] = *Ptr;
2911 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2912 } else {
2913 // ptrdiff_t operator-(T, T);
2914 ParamTypes[1] = *Ptr;
2915 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
2916 Args, 2, CandidateSet);
2917 }
2918 }
2919 }
2920 // Fall through
2921
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002922 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00002923 BinaryStar:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002924 // C++ [over.built]p12:
2925 //
2926 // For every pair of promoted arithmetic types L and R, there
2927 // exist candidate operator functions of the form
2928 //
2929 // LR operator*(L, R);
2930 // LR operator/(L, R);
2931 // LR operator+(L, R);
2932 // LR operator-(L, R);
2933 // bool operator<(L, R);
2934 // bool operator>(L, R);
2935 // bool operator<=(L, R);
2936 // bool operator>=(L, R);
2937 // bool operator==(L, R);
2938 // bool operator!=(L, R);
2939 //
2940 // where LR is the result of the usual arithmetic conversions
2941 // between types L and R.
2942 for (unsigned Left = FirstPromotedArithmeticType;
2943 Left < LastPromotedArithmeticType; ++Left) {
2944 for (unsigned Right = FirstPromotedArithmeticType;
2945 Right < LastPromotedArithmeticType; ++Right) {
2946 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2947 QualType Result
2948 = isComparison? Context.BoolTy
2949 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2950 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2951 }
2952 }
2953 break;
2954
2955 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00002956 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002957 case OO_Caret:
2958 case OO_Pipe:
2959 case OO_LessLess:
2960 case OO_GreaterGreater:
2961 // C++ [over.built]p17:
2962 //
2963 // For every pair of promoted integral types L and R, there
2964 // exist candidate operator functions of the form
2965 //
2966 // LR operator%(L, R);
2967 // LR operator&(L, R);
2968 // LR operator^(L, R);
2969 // LR operator|(L, R);
2970 // L operator<<(L, R);
2971 // L operator>>(L, R);
2972 //
2973 // where LR is the result of the usual arithmetic conversions
2974 // between types L and R.
2975 for (unsigned Left = FirstPromotedIntegralType;
2976 Left < LastPromotedIntegralType; ++Left) {
2977 for (unsigned Right = FirstPromotedIntegralType;
2978 Right < LastPromotedIntegralType; ++Right) {
2979 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2980 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
2981 ? LandR[0]
2982 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2983 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2984 }
2985 }
2986 break;
2987
2988 case OO_Equal:
2989 // C++ [over.built]p20:
2990 //
2991 // For every pair (T, VQ), where T is an enumeration or
2992 // (FIXME:) pointer to member type and VQ is either volatile or
2993 // empty, there exist candidate operator functions of the form
2994 //
2995 // VQ T& operator=(VQ T&, T);
2996 for (BuiltinCandidateTypeSet::iterator Enum
2997 = CandidateTypes.enumeration_begin();
2998 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2999 QualType ParamTypes[2];
3000
3001 // T& operator=(T&, T)
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003002 ParamTypes[0] = Context.getLValueReferenceType(*Enum);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003003 ParamTypes[1] = *Enum;
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003004 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003005 /*IsAssignmentOperator=*/false);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003006
Douglas Gregor74253732008-11-19 15:42:04 +00003007 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
3008 // volatile T& operator=(volatile T&, T)
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003009 ParamTypes[0] = Context.getLValueReferenceType((*Enum).withVolatile());
Douglas Gregor74253732008-11-19 15:42:04 +00003010 ParamTypes[1] = *Enum;
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003011 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003012 /*IsAssignmentOperator=*/false);
Douglas Gregor74253732008-11-19 15:42:04 +00003013 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003014 }
3015 // Fall through.
3016
3017 case OO_PlusEqual:
3018 case OO_MinusEqual:
3019 // C++ [over.built]p19:
3020 //
3021 // For every pair (T, VQ), where T is any type and VQ is either
3022 // volatile or empty, there exist candidate operator functions
3023 // of the form
3024 //
3025 // T*VQ& operator=(T*VQ&, T*);
3026 //
3027 // C++ [over.built]p21:
3028 //
3029 // For every pair (T, VQ), where T is a cv-qualified or
3030 // cv-unqualified object type and VQ is either volatile or
3031 // empty, there exist candidate operator functions of the form
3032 //
3033 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3034 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3035 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3036 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3037 QualType ParamTypes[2];
3038 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3039
3040 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003041 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003042 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3043 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003044
Douglas Gregor74253732008-11-19 15:42:04 +00003045 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3046 // volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003047 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003048 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3049 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00003050 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003051 }
3052 // Fall through.
3053
3054 case OO_StarEqual:
3055 case OO_SlashEqual:
3056 // C++ [over.built]p18:
3057 //
3058 // For every triple (L, VQ, R), where L is an arithmetic type,
3059 // VQ is either volatile or empty, and R is a promoted
3060 // arithmetic type, there exist candidate operator functions of
3061 // the form
3062 //
3063 // VQ L& operator=(VQ L&, R);
3064 // VQ L& operator*=(VQ L&, R);
3065 // VQ L& operator/=(VQ L&, R);
3066 // VQ L& operator+=(VQ L&, R);
3067 // VQ L& operator-=(VQ L&, R);
3068 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3069 for (unsigned Right = FirstPromotedArithmeticType;
3070 Right < LastPromotedArithmeticType; ++Right) {
3071 QualType ParamTypes[2];
3072 ParamTypes[1] = ArithmeticTypes[Right];
3073
3074 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003075 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003076 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3077 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003078
3079 // Add this built-in operator as a candidate (VQ is 'volatile').
3080 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003081 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003082 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3083 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003084 }
3085 }
3086 break;
3087
3088 case OO_PercentEqual:
3089 case OO_LessLessEqual:
3090 case OO_GreaterGreaterEqual:
3091 case OO_AmpEqual:
3092 case OO_CaretEqual:
3093 case OO_PipeEqual:
3094 // C++ [over.built]p22:
3095 //
3096 // For every triple (L, VQ, R), where L is an integral type, VQ
3097 // is either volatile or empty, and R is a promoted integral
3098 // type, there exist candidate operator functions of the form
3099 //
3100 // VQ L& operator%=(VQ L&, R);
3101 // VQ L& operator<<=(VQ L&, R);
3102 // VQ L& operator>>=(VQ L&, R);
3103 // VQ L& operator&=(VQ L&, R);
3104 // VQ L& operator^=(VQ L&, R);
3105 // VQ L& operator|=(VQ L&, R);
3106 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3107 for (unsigned Right = FirstPromotedIntegralType;
3108 Right < LastPromotedIntegralType; ++Right) {
3109 QualType ParamTypes[2];
3110 ParamTypes[1] = ArithmeticTypes[Right];
3111
3112 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003113 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003114 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3115
3116 // Add this built-in operator as a candidate (VQ is 'volatile').
3117 ParamTypes[0] = ArithmeticTypes[Left];
3118 ParamTypes[0].addVolatile();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003119 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003120 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3121 }
3122 }
3123 break;
3124
Douglas Gregor74253732008-11-19 15:42:04 +00003125 case OO_Exclaim: {
3126 // C++ [over.operator]p23:
3127 //
3128 // There also exist candidate operator functions of the form
3129 //
3130 // bool operator!(bool);
3131 // bool operator&&(bool, bool); [BELOW]
3132 // bool operator||(bool, bool); [BELOW]
3133 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003134 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3135 /*IsAssignmentOperator=*/false,
3136 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00003137 break;
3138 }
3139
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003140 case OO_AmpAmp:
3141 case OO_PipePipe: {
3142 // C++ [over.operator]p23:
3143 //
3144 // There also exist candidate operator functions of the form
3145 //
Douglas Gregor74253732008-11-19 15:42:04 +00003146 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003147 // bool operator&&(bool, bool);
3148 // bool operator||(bool, bool);
3149 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003150 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3151 /*IsAssignmentOperator=*/false,
3152 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003153 break;
3154 }
3155
3156 case OO_Subscript:
3157 // C++ [over.built]p13:
3158 //
3159 // For every cv-qualified or cv-unqualified object type T there
3160 // exist candidate operator functions of the form
3161 //
3162 // T* operator+(T*, ptrdiff_t); [ABOVE]
3163 // T& operator[](T*, ptrdiff_t);
3164 // T* operator-(T*, ptrdiff_t); [ABOVE]
3165 // T* operator+(ptrdiff_t, T*); [ABOVE]
3166 // T& operator[](ptrdiff_t, T*);
3167 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3168 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3169 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3170 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003171 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003172
3173 // T& operator[](T*, ptrdiff_t)
3174 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3175
3176 // T& operator[](ptrdiff_t, T*);
3177 ParamTypes[0] = ParamTypes[1];
3178 ParamTypes[1] = *Ptr;
3179 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3180 }
3181 break;
3182
3183 case OO_ArrowStar:
3184 // FIXME: No support for pointer-to-members yet.
3185 break;
3186 }
3187}
3188
Douglas Gregorfa047642009-02-04 00:32:51 +00003189/// \brief Add function candidates found via argument-dependent lookup
3190/// to the set of overloading candidates.
3191///
3192/// This routine performs argument-dependent name lookup based on the
3193/// given function name (which may also be an operator name) and adds
3194/// all of the overload candidates found by ADL to the overload
3195/// candidate set (C++ [basic.lookup.argdep]).
3196void
3197Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3198 Expr **Args, unsigned NumArgs,
3199 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003200 FunctionSet Functions;
Douglas Gregorfa047642009-02-04 00:32:51 +00003201
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003202 // Record all of the function candidates that we've already
3203 // added to the overload set, so that we don't add those same
3204 // candidates a second time.
3205 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3206 CandEnd = CandidateSet.end();
3207 Cand != CandEnd; ++Cand)
3208 if (Cand->Function)
3209 Functions.insert(Cand->Function);
Douglas Gregorfa047642009-02-04 00:32:51 +00003210
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003211 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregorfa047642009-02-04 00:32:51 +00003212
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003213 // Erase all of the candidates we already knew about.
3214 // FIXME: This is suboptimal. Is there a better way?
3215 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3216 CandEnd = CandidateSet.end();
3217 Cand != CandEnd; ++Cand)
3218 if (Cand->Function)
3219 Functions.erase(Cand->Function);
3220
3221 // For each of the ADL candidates we found, add it to the overload
3222 // set.
3223 for (FunctionSet::iterator Func = Functions.begin(),
3224 FuncEnd = Functions.end();
3225 Func != FuncEnd; ++Func)
3226 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
Douglas Gregorfa047642009-02-04 00:32:51 +00003227}
3228
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003229/// isBetterOverloadCandidate - Determines whether the first overload
3230/// candidate is a better candidate than the second (C++ 13.3.3p1).
3231bool
3232Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3233 const OverloadCandidate& Cand2)
3234{
3235 // Define viable functions to be better candidates than non-viable
3236 // functions.
3237 if (!Cand2.Viable)
3238 return Cand1.Viable;
3239 else if (!Cand1.Viable)
3240 return false;
3241
Douglas Gregor88a35142008-12-22 05:46:06 +00003242 // C++ [over.match.best]p1:
3243 //
3244 // -- if F is a static member function, ICS1(F) is defined such
3245 // that ICS1(F) is neither better nor worse than ICS1(G) for
3246 // any function G, and, symmetrically, ICS1(G) is neither
3247 // better nor worse than ICS1(F).
3248 unsigned StartArg = 0;
3249 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3250 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003251
3252 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
3253 // function than another viable function F2 if for all arguments i,
3254 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
3255 // then...
3256 unsigned NumArgs = Cand1.Conversions.size();
3257 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3258 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003259 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003260 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3261 Cand2.Conversions[ArgIdx])) {
3262 case ImplicitConversionSequence::Better:
3263 // Cand1 has a better conversion sequence.
3264 HasBetterConversion = true;
3265 break;
3266
3267 case ImplicitConversionSequence::Worse:
3268 // Cand1 can't be better than Cand2.
3269 return false;
3270
3271 case ImplicitConversionSequence::Indistinguishable:
3272 // Do nothing.
3273 break;
3274 }
3275 }
3276
3277 if (HasBetterConversion)
3278 return true;
3279
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003280 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
3281 // implemented, but they require template support.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003282
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003283 // C++ [over.match.best]p1b4:
3284 //
3285 // -- the context is an initialization by user-defined conversion
3286 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3287 // from the return type of F1 to the destination type (i.e.,
3288 // the type of the entity being initialized) is a better
3289 // conversion sequence than the standard conversion sequence
3290 // from the return type of F2 to the destination type.
Douglas Gregor447b69e2008-11-19 03:25:36 +00003291 if (Cand1.Function && Cand2.Function &&
3292 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003293 isa<CXXConversionDecl>(Cand2.Function)) {
3294 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3295 Cand2.FinalConversion)) {
3296 case ImplicitConversionSequence::Better:
3297 // Cand1 has a better conversion sequence.
3298 return true;
3299
3300 case ImplicitConversionSequence::Worse:
3301 // Cand1 can't be better than Cand2.
3302 return false;
3303
3304 case ImplicitConversionSequence::Indistinguishable:
3305 // Do nothing
3306 break;
3307 }
3308 }
3309
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003310 return false;
3311}
3312
3313/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
3314/// within an overload candidate set. If overloading is successful,
3315/// the result will be OR_Success and Best will be set to point to the
3316/// best viable function within the candidate set. Otherwise, one of
3317/// several kinds of errors will be returned; see
3318/// Sema::OverloadingResult.
3319Sema::OverloadingResult
3320Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
3321 OverloadCandidateSet::iterator& Best)
3322{
3323 // Find the best viable function.
3324 Best = CandidateSet.end();
3325 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3326 Cand != CandidateSet.end(); ++Cand) {
3327 if (Cand->Viable) {
3328 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3329 Best = Cand;
3330 }
3331 }
3332
3333 // If we didn't find any viable functions, abort.
3334 if (Best == CandidateSet.end())
3335 return OR_No_Viable_Function;
3336
3337 // Make sure that this function is better than every other viable
3338 // function. If not, we have an ambiguity.
3339 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3340 Cand != CandidateSet.end(); ++Cand) {
3341 if (Cand->Viable &&
3342 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003343 !isBetterOverloadCandidate(*Best, *Cand)) {
3344 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003345 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003346 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003347 }
3348
3349 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003350 if (Best->Function &&
3351 (Best->Function->isDeleted() ||
3352 Best->Function->getAttr<UnavailableAttr>()))
3353 return OR_Deleted;
3354
3355 // If Best refers to a function that is either deleted (C++0x) or
3356 // unavailable (Clang extension) report an error.
3357
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003358 return OR_Success;
3359}
3360
3361/// PrintOverloadCandidates - When overload resolution fails, prints
3362/// diagnostic messages containing the candidates in the candidate
3363/// set. If OnlyViable is true, only viable candidates will be printed.
3364void
3365Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3366 bool OnlyViable)
3367{
3368 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3369 LastCand = CandidateSet.end();
3370 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003371 if (Cand->Viable || !OnlyViable) {
3372 if (Cand->Function) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003373 if (Cand->Function->isDeleted() ||
3374 Cand->Function->getAttr<UnavailableAttr>()) {
3375 // Deleted or "unavailable" function.
3376 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3377 << Cand->Function->isDeleted();
3378 } else {
3379 // Normal function
3380 // FIXME: Give a better reason!
3381 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3382 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003383 } else if (Cand->IsSurrogate) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003384 // Desugar the type of the surrogate down to a function type,
3385 // retaining as many typedefs as possible while still showing
3386 // the function type (and, therefore, its parameter types).
3387 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003388 bool isLValueReference = false;
3389 bool isRValueReference = false;
Douglas Gregor621b3932008-11-21 02:54:28 +00003390 bool isPointer = false;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003391 if (const LValueReferenceType *FnTypeRef =
3392 FnType->getAsLValueReferenceType()) {
Douglas Gregor621b3932008-11-21 02:54:28 +00003393 FnType = FnTypeRef->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003394 isLValueReference = true;
3395 } else if (const RValueReferenceType *FnTypeRef =
3396 FnType->getAsRValueReferenceType()) {
3397 FnType = FnTypeRef->getPointeeType();
3398 isRValueReference = true;
Douglas Gregor621b3932008-11-21 02:54:28 +00003399 }
3400 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
3401 FnType = FnTypePtr->getPointeeType();
3402 isPointer = true;
3403 }
3404 // Desugar down to a function type.
3405 FnType = QualType(FnType->getAsFunctionType(), 0);
3406 // Reconstruct the pointer/reference as appropriate.
3407 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003408 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3409 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor621b3932008-11-21 02:54:28 +00003410
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003411 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003412 << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003413 } else {
3414 // FIXME: We need to get the identifier in here
3415 // FIXME: Do we want the error message to point at the
3416 // operator? (built-ins won't have a location)
3417 QualType FnType
3418 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3419 Cand->BuiltinTypes.ParamTypes,
3420 Cand->Conversions.size(),
3421 false, 0);
3422
Chris Lattnerd1625842008-11-24 06:25:27 +00003423 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003424 }
3425 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003426 }
3427}
3428
Douglas Gregor904eed32008-11-10 20:40:00 +00003429/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3430/// an overloaded function (C++ [over.over]), where @p From is an
3431/// expression with overloaded function type and @p ToType is the type
3432/// we're trying to resolve to. For example:
3433///
3434/// @code
3435/// int f(double);
3436/// int f(int);
3437///
3438/// int (*pfd)(double) = f; // selects f(double)
3439/// @endcode
3440///
3441/// This routine returns the resulting FunctionDecl if it could be
3442/// resolved, and NULL otherwise. When @p Complain is true, this
3443/// routine will emit diagnostics if there is an error.
3444FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00003445Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor904eed32008-11-10 20:40:00 +00003446 bool Complain) {
3447 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00003448 bool IsMember = false;
Daniel Dunbarbb710012009-02-26 19:13:44 +00003449 if (const PointerType *ToTypePtr = ToType->getAsPointerType())
Douglas Gregor904eed32008-11-10 20:40:00 +00003450 FunctionType = ToTypePtr->getPointeeType();
Daniel Dunbarbb710012009-02-26 19:13:44 +00003451 else if (const ReferenceType *ToTypeRef = ToType->getAsReferenceType())
3452 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00003453 else if (const MemberPointerType *MemTypePtr =
3454 ToType->getAsMemberPointerType()) {
3455 FunctionType = MemTypePtr->getPointeeType();
3456 IsMember = true;
3457 }
Douglas Gregor904eed32008-11-10 20:40:00 +00003458
3459 // We only look at pointers or references to functions.
3460 if (!FunctionType->isFunctionType())
3461 return 0;
3462
3463 // Find the actual overloaded function declaration.
3464 OverloadedFunctionDecl *Ovl = 0;
3465
3466 // C++ [over.over]p1:
3467 // [...] [Note: any redundant set of parentheses surrounding the
3468 // overloaded function name is ignored (5.1). ]
3469 Expr *OvlExpr = From->IgnoreParens();
3470
3471 // C++ [over.over]p1:
3472 // [...] The overloaded function name can be preceded by the &
3473 // operator.
3474 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3475 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3476 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3477 }
3478
3479 // Try to dig out the overloaded function.
3480 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
3481 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
3482
3483 // If there's no overloaded function declaration, we're done.
3484 if (!Ovl)
3485 return 0;
3486
3487 // Look through all of the overloaded functions, searching for one
3488 // whose type matches exactly.
3489 // FIXME: When templates or using declarations come along, we'll actually
3490 // have to deal with duplicates, partial ordering, etc. For now, we
3491 // can just do a simple search.
3492 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
3493 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
3494 Fun != Ovl->function_end(); ++Fun) {
3495 // C++ [over.over]p3:
3496 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00003497 // targets of type "pointer-to-function" or "reference-to-function."
3498 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00003499 // type "pointer-to-member-function."
3500 // Note that according to DR 247, the containing class does not matter.
3501 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3502 // Skip non-static functions when converting to pointer, and static
3503 // when converting to member pointer.
3504 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00003505 continue;
Sebastian Redl33b399a2009-02-04 21:23:32 +00003506 } else if (IsMember)
3507 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00003508
3509 if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
3510 return *Fun;
3511 }
3512
3513 return 0;
3514}
3515
Douglas Gregorf6b89692008-11-26 05:54:23 +00003516/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00003517/// (which eventually refers to the declaration Func) and the call
3518/// arguments Args/NumArgs, attempt to resolve the function call down
3519/// to a specific function. If overload resolution succeeds, returns
3520/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00003521/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00003522/// arguments and Fn, and returns NULL.
Douglas Gregorfa047642009-02-04 00:32:51 +00003523FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor17330012009-02-04 15:01:18 +00003524 DeclarationName UnqualifiedName,
Douglas Gregor0a396682008-11-26 06:01:48 +00003525 SourceLocation LParenLoc,
3526 Expr **Args, unsigned NumArgs,
3527 SourceLocation *CommaLocs,
Douglas Gregorfa047642009-02-04 00:32:51 +00003528 SourceLocation RParenLoc,
Douglas Gregor17330012009-02-04 15:01:18 +00003529 bool &ArgumentDependentLookup) {
Douglas Gregorf6b89692008-11-26 05:54:23 +00003530 OverloadCandidateSet CandidateSet;
Douglas Gregor17330012009-02-04 15:01:18 +00003531
3532 // Add the functions denoted by Callee to the set of candidate
3533 // functions. While we're doing so, track whether argument-dependent
3534 // lookup still applies, per:
3535 //
3536 // C++0x [basic.lookup.argdep]p3:
3537 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3538 // and let Y be the lookup set produced by argument dependent
3539 // lookup (defined as follows). If X contains
3540 //
3541 // -- a declaration of a class member, or
3542 //
3543 // -- a block-scope function declaration that is not a
3544 // using-declaration, or
3545 //
3546 // -- a declaration that is neither a function or a function
3547 // template
3548 //
3549 // then Y is empty.
Douglas Gregorfa047642009-02-04 00:32:51 +00003550 if (OverloadedFunctionDecl *Ovl
Douglas Gregor17330012009-02-04 15:01:18 +00003551 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
3552 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3553 FuncEnd = Ovl->function_end();
3554 Func != FuncEnd; ++Func) {
3555 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
3556
3557 if ((*Func)->getDeclContext()->isRecord() ||
3558 (*Func)->getDeclContext()->isFunctionOrMethod())
3559 ArgumentDependentLookup = false;
3560 }
3561 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
3562 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
3563
3564 if (Func->getDeclContext()->isRecord() ||
3565 Func->getDeclContext()->isFunctionOrMethod())
3566 ArgumentDependentLookup = false;
3567 }
3568
3569 if (Callee)
3570 UnqualifiedName = Callee->getDeclName();
3571
Douglas Gregorfa047642009-02-04 00:32:51 +00003572 if (ArgumentDependentLookup)
Douglas Gregor17330012009-02-04 15:01:18 +00003573 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregorfa047642009-02-04 00:32:51 +00003574 CandidateSet);
3575
Douglas Gregorf6b89692008-11-26 05:54:23 +00003576 OverloadCandidateSet::iterator Best;
3577 switch (BestViableFunction(CandidateSet, Best)) {
Douglas Gregor0a396682008-11-26 06:01:48 +00003578 case OR_Success:
3579 return Best->Function;
Douglas Gregorf6b89692008-11-26 05:54:23 +00003580
3581 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00003582 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00003583 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00003584 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00003585 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3586 break;
3587
3588 case OR_Ambiguous:
3589 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor17330012009-02-04 15:01:18 +00003590 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00003591 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3592 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003593
3594 case OR_Deleted:
3595 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
3596 << Best->Function->isDeleted()
3597 << UnqualifiedName
3598 << Fn->getSourceRange();
3599 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3600 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00003601 }
3602
3603 // Overload resolution failed. Destroy all of the subexpressions and
3604 // return NULL.
3605 Fn->Destroy(Context);
3606 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3607 Args[Arg]->Destroy(Context);
3608 return 0;
3609}
3610
Douglas Gregorbc736fc2009-03-13 23:49:33 +00003611/// \brief Create a unary operation that may resolve to an overloaded
3612/// operator.
3613///
3614/// \param OpLoc The location of the operator itself (e.g., '*').
3615///
3616/// \param OpcIn The UnaryOperator::Opcode that describes this
3617/// operator.
3618///
3619/// \param Functions The set of non-member functions that will be
3620/// considered by overload resolution. The caller needs to build this
3621/// set based on the context using, e.g.,
3622/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
3623/// set should not contain any member functions; those will be added
3624/// by CreateOverloadedUnaryOp().
3625///
3626/// \param input The input argument.
3627Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
3628 unsigned OpcIn,
3629 FunctionSet &Functions,
3630 ExprArg input) {
3631 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
3632 Expr *Input = (Expr *)input.get();
3633
3634 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
3635 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
3636 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3637
3638 Expr *Args[2] = { Input, 0 };
3639 unsigned NumArgs = 1;
3640
3641 // For post-increment and post-decrement, add the implicit '0' as
3642 // the second argument, so that we know this is a post-increment or
3643 // post-decrement.
3644 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
3645 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
3646 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
3647 SourceLocation());
3648 NumArgs = 2;
3649 }
3650
3651 if (Input->isTypeDependent()) {
3652 OverloadedFunctionDecl *Overloads
3653 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
3654 for (FunctionSet::iterator Func = Functions.begin(),
3655 FuncEnd = Functions.end();
3656 Func != FuncEnd; ++Func)
3657 Overloads->addOverload(*Func);
3658
3659 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
3660 OpLoc, false, false);
3661
3662 input.release();
3663 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
3664 &Args[0], NumArgs,
3665 Context.DependentTy,
3666 OpLoc));
3667 }
3668
3669 // Build an empty overload set.
3670 OverloadCandidateSet CandidateSet;
3671
3672 // Add the candidates from the given function set.
3673 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
3674
3675 // Add operator candidates that are member functions.
3676 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
3677
3678 // Add builtin operator candidates.
3679 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
3680
3681 // Perform overload resolution.
3682 OverloadCandidateSet::iterator Best;
3683 switch (BestViableFunction(CandidateSet, Best)) {
3684 case OR_Success: {
3685 // We found a built-in operator or an overloaded operator.
3686 FunctionDecl *FnDecl = Best->Function;
3687
3688 if (FnDecl) {
3689 // We matched an overloaded operator. Build a call to that
3690 // operator.
3691
3692 // Convert the arguments.
3693 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3694 if (PerformObjectArgumentInitialization(Input, Method))
3695 return ExprError();
3696 } else {
3697 // Convert the arguments.
3698 if (PerformCopyInitialization(Input,
3699 FnDecl->getParamDecl(0)->getType(),
3700 "passing"))
3701 return ExprError();
3702 }
3703
3704 // Determine the result type
3705 QualType ResultTy
3706 = FnDecl->getType()->getAsFunctionType()->getResultType();
3707 ResultTy = ResultTy.getNonReferenceType();
3708
3709 // Build the actual expression node.
3710 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3711 SourceLocation());
3712 UsualUnaryConversions(FnExpr);
3713
3714 input.release();
3715 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
3716 &Input, 1, ResultTy,
3717 OpLoc));
3718 } else {
3719 // We matched a built-in operator. Convert the arguments, then
3720 // break out so that we will build the appropriate built-in
3721 // operator node.
3722 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3723 Best->Conversions[0], "passing"))
3724 return ExprError();
3725
3726 break;
3727 }
3728 }
3729
3730 case OR_No_Viable_Function:
3731 // No viable function; fall through to handling this as a
3732 // built-in operator, which will produce an error message for us.
3733 break;
3734
3735 case OR_Ambiguous:
3736 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3737 << UnaryOperator::getOpcodeStr(Opc)
3738 << Input->getSourceRange();
3739 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3740 return ExprError();
3741
3742 case OR_Deleted:
3743 Diag(OpLoc, diag::err_ovl_deleted_oper)
3744 << Best->Function->isDeleted()
3745 << UnaryOperator::getOpcodeStr(Opc)
3746 << Input->getSourceRange();
3747 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3748 return ExprError();
3749 }
3750
3751 // Either we found no viable overloaded operator or we matched a
3752 // built-in operator. In either case, fall through to trying to
3753 // build a built-in operation.
3754 input.release();
3755 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
3756}
3757
Douglas Gregor063daf62009-03-13 18:40:31 +00003758/// \brief Create a binary operation that may resolve to an overloaded
3759/// operator.
3760///
3761/// \param OpLoc The location of the operator itself (e.g., '+').
3762///
3763/// \param OpcIn The BinaryOperator::Opcode that describes this
3764/// operator.
3765///
3766/// \param Functions The set of non-member functions that will be
3767/// considered by overload resolution. The caller needs to build this
3768/// set based on the context using, e.g.,
3769/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
3770/// set should not contain any member functions; those will be added
3771/// by CreateOverloadedBinOp().
3772///
3773/// \param LHS Left-hand argument.
3774/// \param RHS Right-hand argument.
3775Sema::OwningExprResult
3776Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
3777 unsigned OpcIn,
3778 FunctionSet &Functions,
3779 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00003780 Expr *Args[2] = { LHS, RHS };
3781
3782 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
3783 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
3784 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3785
3786 // If either side is type-dependent, create an appropriate dependent
3787 // expression.
3788 if (LHS->isTypeDependent() || RHS->isTypeDependent()) {
3789 // .* cannot be overloaded.
3790 if (Opc == BinaryOperator::PtrMemD)
3791 return Owned(new (Context) BinaryOperator(LHS, RHS, Opc,
3792 Context.DependentTy, OpLoc));
3793
3794 OverloadedFunctionDecl *Overloads
3795 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
3796 for (FunctionSet::iterator Func = Functions.begin(),
3797 FuncEnd = Functions.end();
3798 Func != FuncEnd; ++Func)
3799 Overloads->addOverload(*Func);
3800
3801 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
3802 OpLoc, false, false);
3803
3804 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
3805 Args, 2,
3806 Context.DependentTy,
3807 OpLoc));
3808 }
3809
3810 // If this is the .* operator, which is not overloadable, just
3811 // create a built-in binary operator.
3812 if (Opc == BinaryOperator::PtrMemD)
3813 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
3814
3815 // If this is one of the assignment operators, we only perform
3816 // overload resolution if the left-hand side is a class or
3817 // enumeration type (C++ [expr.ass]p3).
3818 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3819 !LHS->getType()->isOverloadableType())
3820 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
3821
Douglas Gregorbc736fc2009-03-13 23:49:33 +00003822 // Build an empty overload set.
3823 OverloadCandidateSet CandidateSet;
Douglas Gregor063daf62009-03-13 18:40:31 +00003824
3825 // Add the candidates from the given function set.
3826 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
3827
3828 // Add operator candidates that are member functions.
3829 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
3830
3831 // Add builtin operator candidates.
3832 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
3833
3834 // Perform overload resolution.
3835 OverloadCandidateSet::iterator Best;
3836 switch (BestViableFunction(CandidateSet, Best)) {
3837 case OR_Success: {
3838 // We found a built-in operator or an overloaded operator.
3839 FunctionDecl *FnDecl = Best->Function;
3840
3841 if (FnDecl) {
3842 // We matched an overloaded operator. Build a call to that
3843 // operator.
3844
3845 // Convert the arguments.
3846 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3847 if (PerformObjectArgumentInitialization(LHS, Method) ||
3848 PerformCopyInitialization(RHS, FnDecl->getParamDecl(0)->getType(),
3849 "passing"))
3850 return ExprError();
3851 } else {
3852 // Convert the arguments.
3853 if (PerformCopyInitialization(LHS, FnDecl->getParamDecl(0)->getType(),
3854 "passing") ||
3855 PerformCopyInitialization(RHS, FnDecl->getParamDecl(1)->getType(),
3856 "passing"))
3857 return ExprError();
3858 }
3859
3860 // Determine the result type
3861 QualType ResultTy
3862 = FnDecl->getType()->getAsFunctionType()->getResultType();
3863 ResultTy = ResultTy.getNonReferenceType();
3864
3865 // Build the actual expression node.
3866 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3867 SourceLocation());
3868 UsualUnaryConversions(FnExpr);
3869
3870 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
3871 Args, 2, ResultTy,
3872 OpLoc));
3873 } else {
3874 // We matched a built-in operator. Convert the arguments, then
3875 // break out so that we will build the appropriate built-in
3876 // operator node.
3877 if (PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
3878 Best->Conversions[0], "passing") ||
3879 PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
3880 Best->Conversions[1], "passing"))
3881 return ExprError();
3882
3883 break;
3884 }
3885 }
3886
3887 case OR_No_Viable_Function:
3888 // No viable function; fall through to handling this as a
3889 // built-in operator, which will produce an error message for us.
3890 break;
3891
3892 case OR_Ambiguous:
3893 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3894 << BinaryOperator::getOpcodeStr(Opc)
3895 << LHS->getSourceRange() << RHS->getSourceRange();
3896 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3897 return ExprError();
3898
3899 case OR_Deleted:
3900 Diag(OpLoc, diag::err_ovl_deleted_oper)
3901 << Best->Function->isDeleted()
3902 << BinaryOperator::getOpcodeStr(Opc)
3903 << LHS->getSourceRange() << RHS->getSourceRange();
3904 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3905 return ExprError();
3906 }
3907
3908 // Either we found no viable overloaded operator or we matched a
3909 // built-in operator. In either case, try to build a built-in
3910 // operation.
3911 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
3912}
3913
Douglas Gregor88a35142008-12-22 05:46:06 +00003914/// BuildCallToMemberFunction - Build a call to a member
3915/// function. MemExpr is the expression that refers to the member
3916/// function (and includes the object parameter), Args/NumArgs are the
3917/// arguments to the function call (not including the object
3918/// parameter). The caller needs to validate that the member
3919/// expression refers to a member function or an overloaded member
3920/// function.
3921Sema::ExprResult
3922Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
3923 SourceLocation LParenLoc, Expr **Args,
3924 unsigned NumArgs, SourceLocation *CommaLocs,
3925 SourceLocation RParenLoc) {
3926 // Dig out the member expression. This holds both the object
3927 // argument and the member function we're referring to.
3928 MemberExpr *MemExpr = 0;
3929 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
3930 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
3931 else
3932 MemExpr = dyn_cast<MemberExpr>(MemExprE);
3933 assert(MemExpr && "Building member call without member expression");
3934
3935 // Extract the object argument.
3936 Expr *ObjectArg = MemExpr->getBase();
3937 if (MemExpr->isArrow())
Ted Kremenek8189cde2009-02-07 01:47:29 +00003938 ObjectArg = new (Context) UnaryOperator(ObjectArg, UnaryOperator::Deref,
3939 ObjectArg->getType()->getAsPointerType()->getPointeeType(),
Douglas Gregor611a8c42009-02-19 00:52:42 +00003940 ObjectArg->getLocStart());
Douglas Gregor88a35142008-12-22 05:46:06 +00003941 CXXMethodDecl *Method = 0;
3942 if (OverloadedFunctionDecl *Ovl
3943 = dyn_cast<OverloadedFunctionDecl>(MemExpr->getMemberDecl())) {
3944 // Add overload candidates
3945 OverloadCandidateSet CandidateSet;
3946 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3947 FuncEnd = Ovl->function_end();
3948 Func != FuncEnd; ++Func) {
3949 assert(isa<CXXMethodDecl>(*Func) && "Function is not a method");
3950 Method = cast<CXXMethodDecl>(*Func);
3951 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
3952 /*SuppressUserConversions=*/false);
3953 }
3954
3955 OverloadCandidateSet::iterator Best;
3956 switch (BestViableFunction(CandidateSet, Best)) {
3957 case OR_Success:
3958 Method = cast<CXXMethodDecl>(Best->Function);
3959 break;
3960
3961 case OR_No_Viable_Function:
3962 Diag(MemExpr->getSourceRange().getBegin(),
3963 diag::err_ovl_no_viable_member_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00003964 << Ovl->getDeclName() << MemExprE->getSourceRange();
Douglas Gregor88a35142008-12-22 05:46:06 +00003965 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3966 // FIXME: Leaking incoming expressions!
3967 return true;
3968
3969 case OR_Ambiguous:
3970 Diag(MemExpr->getSourceRange().getBegin(),
3971 diag::err_ovl_ambiguous_member_call)
3972 << Ovl->getDeclName() << MemExprE->getSourceRange();
3973 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3974 // FIXME: Leaking incoming expressions!
3975 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003976
3977 case OR_Deleted:
3978 Diag(MemExpr->getSourceRange().getBegin(),
3979 diag::err_ovl_deleted_member_call)
3980 << Best->Function->isDeleted()
3981 << Ovl->getDeclName() << MemExprE->getSourceRange();
3982 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3983 // FIXME: Leaking incoming expressions!
3984 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003985 }
3986
3987 FixOverloadedFunctionReference(MemExpr, Method);
3988 } else {
3989 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
3990 }
3991
3992 assert(Method && "Member call to something that isn't a method?");
Ted Kremenek8189cde2009-02-07 01:47:29 +00003993 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek668bf912009-02-09 20:51:47 +00003994 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
3995 NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003996 Method->getResultType().getNonReferenceType(),
3997 RParenLoc));
3998
3999 // Convert the object argument (for a non-static member function call).
4000 if (!Method->isStatic() &&
4001 PerformObjectArgumentInitialization(ObjectArg, Method))
4002 return true;
4003 MemExpr->setBase(ObjectArg);
4004
4005 // Convert the rest of the arguments
Douglas Gregor72564e72009-02-26 23:50:07 +00004006 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Douglas Gregor88a35142008-12-22 05:46:06 +00004007 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
4008 RParenLoc))
4009 return true;
4010
Sebastian Redl0eb23302009-01-19 00:08:26 +00004011 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregor88a35142008-12-22 05:46:06 +00004012}
4013
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004014/// BuildCallToObjectOfClassType - Build a call to an object of class
4015/// type (C++ [over.call.object]), which can end up invoking an
4016/// overloaded function call operator (@c operator()) or performing a
4017/// user-defined conversion on the object argument.
Douglas Gregor88a35142008-12-22 05:46:06 +00004018Sema::ExprResult
Douglas Gregor5c37de72008-12-06 00:22:45 +00004019Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
4020 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004021 Expr **Args, unsigned NumArgs,
4022 SourceLocation *CommaLocs,
4023 SourceLocation RParenLoc) {
4024 assert(Object->getType()->isRecordType() && "Requires object type argument");
4025 const RecordType *Record = Object->getType()->getAsRecordType();
4026
4027 // C++ [over.call.object]p1:
4028 // If the primary-expression E in the function call syntax
4029 // evaluates to a class object of type “cv T”, then the set of
4030 // candidate functions includes at least the function call
4031 // operators of T. The function call operators of T are obtained by
4032 // ordinary lookup of the name operator() in the context of
4033 // (E).operator().
4034 OverloadCandidateSet CandidateSet;
Douglas Gregor44b43212008-12-11 16:49:14 +00004035 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004036 DeclContext::lookup_const_iterator Oper, OperEnd;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004037 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(Context, OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004038 Oper != OperEnd; ++Oper)
4039 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
4040 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004041
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004042 // C++ [over.call.object]p2:
4043 // In addition, for each conversion function declared in T of the
4044 // form
4045 //
4046 // operator conversion-type-id () cv-qualifier;
4047 //
4048 // where cv-qualifier is the same cv-qualification as, or a
4049 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00004050 // denotes the type "pointer to function of (P1,...,Pn) returning
4051 // R", or the type "reference to pointer to function of
4052 // (P1,...,Pn) returning R", or the type "reference to function
4053 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004054 // is also considered as a candidate function. Similarly,
4055 // surrogate call functions are added to the set of candidate
4056 // functions for each conversion function declared in an
4057 // accessible base class provided the function is not hidden
4058 // within T by another intervening declaration.
4059 //
4060 // FIXME: Look in base classes for more conversion operators!
4061 OverloadedFunctionDecl *Conversions
4062 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor621b3932008-11-21 02:54:28 +00004063 for (OverloadedFunctionDecl::function_iterator
4064 Func = Conversions->function_begin(),
4065 FuncEnd = Conversions->function_end();
4066 Func != FuncEnd; ++Func) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004067 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
4068
4069 // Strip the reference type (if any) and then the pointer type (if
4070 // any) to get down to what might be a function type.
4071 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4072 if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
4073 ConvType = ConvPtrType->getPointeeType();
4074
Douglas Gregor72564e72009-02-26 23:50:07 +00004075 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004076 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4077 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004078
4079 // Perform overload resolution.
4080 OverloadCandidateSet::iterator Best;
4081 switch (BestViableFunction(CandidateSet, Best)) {
4082 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004083 // Overload resolution succeeded; we'll build the appropriate call
4084 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004085 break;
4086
4087 case OR_No_Viable_Function:
Sebastian Redle4c452c2008-11-22 13:44:36 +00004088 Diag(Object->getSourceRange().getBegin(),
4089 diag::err_ovl_no_viable_object_call)
Chris Lattner4330d652009-02-17 07:29:20 +00004090 << Object->getType() << Object->getSourceRange();
Sebastian Redle4c452c2008-11-22 13:44:36 +00004091 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004092 break;
4093
4094 case OR_Ambiguous:
4095 Diag(Object->getSourceRange().getBegin(),
4096 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00004097 << Object->getType() << Object->getSourceRange();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004098 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4099 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004100
4101 case OR_Deleted:
4102 Diag(Object->getSourceRange().getBegin(),
4103 diag::err_ovl_deleted_object_call)
4104 << Best->Function->isDeleted()
4105 << Object->getType() << Object->getSourceRange();
4106 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4107 break;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004108 }
4109
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004110 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004111 // We had an error; delete all of the subexpressions and return
4112 // the error.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004113 Object->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004114 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek8189cde2009-02-07 01:47:29 +00004115 Args[ArgIdx]->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004116 return true;
4117 }
4118
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004119 if (Best->Function == 0) {
4120 // Since there is no function declaration, this is one of the
4121 // surrogate candidates. Dig out the conversion function.
4122 CXXConversionDecl *Conv
4123 = cast<CXXConversionDecl>(
4124 Best->Conversions[0].UserDefined.ConversionFunction);
4125
4126 // We selected one of the surrogate functions that converts the
4127 // object parameter to a function pointer. Perform the conversion
4128 // on the object argument, then let ActOnCallExpr finish the job.
4129 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl0eb23302009-01-19 00:08:26 +00004130 ImpCastExprToType(Object,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004131 Conv->getConversionType().getNonReferenceType(),
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004132 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00004133 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4134 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4135 CommaLocs, RParenLoc).release();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004136 }
4137
4138 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4139 // that calls this method, using Object for the implicit object
4140 // parameter and passing along the remaining arguments.
4141 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor72564e72009-02-26 23:50:07 +00004142 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004143
4144 unsigned NumArgsInProto = Proto->getNumArgs();
4145 unsigned NumArgsToCheck = NumArgs;
4146
4147 // Build the full argument list for the method call (the
4148 // implicit object parameter is placed at the beginning of the
4149 // list).
4150 Expr **MethodArgs;
4151 if (NumArgs < NumArgsInProto) {
4152 NumArgsToCheck = NumArgsInProto;
4153 MethodArgs = new Expr*[NumArgsInProto + 1];
4154 } else {
4155 MethodArgs = new Expr*[NumArgs + 1];
4156 }
4157 MethodArgs[0] = Object;
4158 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4159 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
4160
Ted Kremenek8189cde2009-02-07 01:47:29 +00004161 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
4162 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004163 UsualUnaryConversions(NewFn);
4164
4165 // Once we've built TheCall, all of the expressions are properly
4166 // owned.
4167 QualType ResultTy = Method->getResultType().getNonReferenceType();
Ted Kremenek8189cde2009-02-07 01:47:29 +00004168 ExprOwningPtr<CXXOperatorCallExpr>
Douglas Gregor063daf62009-03-13 18:40:31 +00004169 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
4170 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00004171 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004172 delete [] MethodArgs;
4173
Douglas Gregor518fda12009-01-13 05:10:00 +00004174 // We may have default arguments. If so, we need to allocate more
4175 // slots in the call for them.
4176 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00004177 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00004178 else if (NumArgs > NumArgsInProto)
4179 NumArgsToCheck = NumArgsInProto;
4180
Chris Lattner312531a2009-04-12 08:11:20 +00004181 bool IsError = false;
4182
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004183 // Initialize the implicit object parameter.
Chris Lattner312531a2009-04-12 08:11:20 +00004184 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004185 TheCall->setArg(0, Object);
4186
Chris Lattner312531a2009-04-12 08:11:20 +00004187
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004188 // Check the argument types.
4189 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004190 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00004191 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004192 Arg = Args[i];
Douglas Gregor518fda12009-01-13 05:10:00 +00004193
4194 // Pass the argument.
4195 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner312531a2009-04-12 08:11:20 +00004196 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor518fda12009-01-13 05:10:00 +00004197 } else {
Ted Kremenek8189cde2009-02-07 01:47:29 +00004198 Arg = new (Context) CXXDefaultArgExpr(Method->getParamDecl(i));
Douglas Gregor518fda12009-01-13 05:10:00 +00004199 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004200
4201 TheCall->setArg(i + 1, Arg);
4202 }
4203
4204 // If this is a variadic call, handle args passed through "...".
4205 if (Proto->isVariadic()) {
4206 // Promote the arguments (C99 6.5.2.2p7).
4207 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4208 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00004209 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004210 TheCall->setArg(i + 1, Arg);
4211 }
4212 }
4213
Chris Lattner312531a2009-04-12 08:11:20 +00004214 if (IsError) return true;
4215
Sebastian Redl0eb23302009-01-19 00:08:26 +00004216 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00004217}
4218
Douglas Gregor8ba10742008-11-20 16:27:02 +00004219/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
4220/// (if one exists), where @c Base is an expression of class type and
4221/// @c Member is the name of the member we're trying to find.
4222Action::ExprResult
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004223Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
Douglas Gregor8ba10742008-11-20 16:27:02 +00004224 SourceLocation MemberLoc,
4225 IdentifierInfo &Member) {
4226 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
4227
4228 // C++ [over.ref]p1:
4229 //
4230 // [...] An expression x->m is interpreted as (x.operator->())->m
4231 // for a class object x of type T if T::operator->() exists and if
4232 // the operator is selected as the best match function by the
4233 // overload resolution mechanism (13.3).
4234 // FIXME: look in base classes.
4235 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4236 OverloadCandidateSet CandidateSet;
4237 const RecordType *BaseRecord = Base->getType()->getAsRecordType();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004238
4239 DeclContext::lookup_const_iterator Oper, OperEnd;
Douglas Gregor6ab35242009-04-09 21:40:53 +00004240 for (llvm::tie(Oper, OperEnd)
4241 = BaseRecord->getDecl()->lookup(Context, OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00004242 Oper != OperEnd; ++Oper)
4243 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00004244 /*SuppressUserConversions=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00004245
Ted Kremenek8189cde2009-02-07 01:47:29 +00004246 ExprOwningPtr<Expr> BasePtr(this, Base);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00004247
Douglas Gregor8ba10742008-11-20 16:27:02 +00004248 // Perform overload resolution.
4249 OverloadCandidateSet::iterator Best;
4250 switch (BestViableFunction(CandidateSet, Best)) {
4251 case OR_Success:
4252 // Overload resolution succeeded; we'll build the call below.
4253 break;
4254
4255 case OR_No_Viable_Function:
4256 if (CandidateSet.empty())
4257 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattnerd1625842008-11-24 06:25:27 +00004258 << BasePtr->getType() << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004259 else
4260 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Chris Lattner4330d652009-02-17 07:29:20 +00004261 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004262 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00004263 return true;
4264
4265 case OR_Ambiguous:
4266 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Chris Lattnerd1625842008-11-24 06:25:27 +00004267 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004268 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregor8ba10742008-11-20 16:27:02 +00004269 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004270
4271 case OR_Deleted:
4272 Diag(OpLoc, diag::err_ovl_deleted_oper)
4273 << Best->Function->isDeleted()
4274 << "operator->" << BasePtr->getSourceRange();
4275 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4276 return true;
Douglas Gregor8ba10742008-11-20 16:27:02 +00004277 }
4278
4279 // Convert the object parameter.
4280 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00004281 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregor8ba10742008-11-20 16:27:02 +00004282 return true;
Douglas Gregorfc195ef2008-11-21 03:04:22 +00004283
4284 // No concerns about early exits now.
4285 BasePtr.take();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004286
4287 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004288 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4289 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00004290 UsualUnaryConversions(FnExpr);
Douglas Gregor063daf62009-03-13 18:40:31 +00004291 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregor8ba10742008-11-20 16:27:02 +00004292 Method->getResultType().getNonReferenceType(),
4293 OpLoc);
Sebastian Redl0eb23302009-01-19 00:08:26 +00004294 return ActOnMemberReferenceExpr(S, ExprArg(*this, Base), OpLoc, tok::arrow,
Chris Lattnerb28317a2009-03-28 19:18:32 +00004295 MemberLoc, Member, DeclPtrTy()).release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00004296}
4297
Douglas Gregor904eed32008-11-10 20:40:00 +00004298/// FixOverloadedFunctionReference - E is an expression that refers to
4299/// a C++ overloaded function (possibly with some parentheses and
4300/// perhaps a '&' around it). We have resolved the overloaded function
4301/// to the function declaration Fn, so patch up the expression E to
4302/// refer (possibly indirectly) to Fn.
4303void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4304 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4305 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4306 E->setType(PE->getSubExpr()->getType());
4307 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
4308 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
4309 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00004310 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4311 if (Method->isStatic()) {
4312 // Do nothing: static member functions aren't any different
4313 // from non-member functions.
4314 }
4315 else if (QualifiedDeclRefExpr *DRE
4316 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4317 // We have taken the address of a pointer to member
4318 // function. Perform the computation here so that we get the
4319 // appropriate pointer to member type.
4320 DRE->setDecl(Fn);
4321 DRE->setType(Fn->getType());
4322 QualType ClassType
4323 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
4324 E->setType(Context.getMemberPointerType(Fn->getType(),
4325 ClassType.getTypePtr()));
4326 return;
4327 }
4328 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004329 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregora35284b2009-02-11 00:19:33 +00004330 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregor904eed32008-11-10 20:40:00 +00004331 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
4332 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
4333 "Expected overloaded function");
4334 DR->setDecl(Fn);
4335 E->setType(Fn->getType());
Douglas Gregor88a35142008-12-22 05:46:06 +00004336 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4337 MemExpr->setMemberDecl(Fn);
4338 E->setType(Fn->getType());
Douglas Gregor904eed32008-11-10 20:40:00 +00004339 } else {
4340 assert(false && "Invalid reference to overloaded function");
4341 }
4342}
4343
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004344} // end namespace clang