blob: e1939d329e923e9f106010565599c3295b6ad971 [file] [log] [blame]
Douglas Gregord2baafd2008-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 Gregorbb461502008-10-24 04:54:22 +000015#include "SemaInherit.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregor70d26122008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
Douglas Gregor10f3c502008-11-19 21:05:33 +000020#include "clang/AST/ExprCXX.h"
Douglas Gregor70d26122008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Douglas Gregor3d4492e2008-11-13 20:12:29 +000022#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregorddfd9d52008-12-23 00:26:44 +000023#include "llvm/ADT/STLExtras.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000024#include "llvm/Support/Compiler.h"
25#include <algorithm>
26
27namespace clang {
28
29/// GetConversionCategory - Retrieve the implicit conversion
30/// category corresponding to the given implicit conversion kind.
31ImplicitConversionCategory
32GetConversionCategory(ImplicitConversionKind Kind) {
33 static const ImplicitConversionCategory
34 Category[(int)ICK_Num_Conversion_Kinds] = {
35 ICC_Identity,
36 ICC_Lvalue_Transformation,
37 ICC_Lvalue_Transformation,
38 ICC_Lvalue_Transformation,
39 ICC_Qualification_Adjustment,
40 ICC_Promotion,
41 ICC_Promotion,
42 ICC_Conversion,
43 ICC_Conversion,
44 ICC_Conversion,
45 ICC_Conversion,
46 ICC_Conversion,
Douglas Gregor2aecd1f2008-10-29 02:00:59 +000047 ICC_Conversion,
Douglas Gregorfcb19192009-02-11 23:02:49 +000048 ICC_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000049 ICC_Conversion
50 };
51 return Category[(int)Kind];
52}
53
54/// GetConversionRank - Retrieve the implicit conversion rank
55/// corresponding to the given implicit conversion kind.
56ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
57 static const ImplicitConversionRank
58 Rank[(int)ICK_Num_Conversion_Kinds] = {
59 ICR_Exact_Match,
60 ICR_Exact_Match,
61 ICR_Exact_Match,
62 ICR_Exact_Match,
63 ICR_Exact_Match,
64 ICR_Promotion,
65 ICR_Promotion,
66 ICR_Conversion,
67 ICR_Conversion,
68 ICR_Conversion,
69 ICR_Conversion,
70 ICR_Conversion,
Douglas Gregor2aecd1f2008-10-29 02:00:59 +000071 ICR_Conversion,
Douglas Gregorfcb19192009-02-11 23:02:49 +000072 ICR_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000073 ICR_Conversion
74 };
75 return Rank[(int)Kind];
76}
77
78/// GetImplicitConversionName - Return the name of this kind of
79/// implicit conversion.
80const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
81 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
82 "No conversion",
83 "Lvalue-to-rvalue",
84 "Array-to-pointer",
85 "Function-to-pointer",
86 "Qualification",
87 "Integral promotion",
88 "Floating point promotion",
89 "Integral conversion",
90 "Floating conversion",
91 "Floating-integral conversion",
92 "Pointer conversion",
93 "Pointer-to-member conversion",
Douglas Gregor2aecd1f2008-10-29 02:00:59 +000094 "Boolean conversion",
Douglas Gregorfcb19192009-02-11 23:02:49 +000095 "Compatible-types conversion",
Douglas Gregor2aecd1f2008-10-29 02:00:59 +000096 "Derived-to-base conversion"
Douglas Gregord2baafd2008-10-21 16:13:35 +000097 };
98 return Name[Kind];
99}
100
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000101/// StandardConversionSequence - Set the standard conversion
102/// sequence to the identity conversion.
103void StandardConversionSequence::setAsIdentityConversion() {
104 First = ICK_Identity;
105 Second = ICK_Identity;
106 Third = ICK_Identity;
107 Deprecated = false;
108 ReferenceBinding = false;
109 DirectBinding = false;
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000110 CopyConstructor = 0;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000111}
112
Douglas Gregord2baafd2008-10-21 16:13:35 +0000113/// getRank - Retrieve the rank of this standard conversion sequence
114/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
115/// implicit conversions.
116ImplicitConversionRank StandardConversionSequence::getRank() const {
117 ImplicitConversionRank Rank = ICR_Exact_Match;
118 if (GetConversionRank(First) > Rank)
119 Rank = GetConversionRank(First);
120 if (GetConversionRank(Second) > Rank)
121 Rank = GetConversionRank(Second);
122 if (GetConversionRank(Third) > Rank)
123 Rank = GetConversionRank(Third);
124 return Rank;
125}
126
127/// isPointerConversionToBool - Determines whether this conversion is
128/// a conversion of a pointer or pointer-to-member to bool. This is
129/// used as part of the ranking of standard conversion sequences
130/// (C++ 13.3.3.2p4).
131bool StandardConversionSequence::isPointerConversionToBool() const
132{
133 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
134 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
135
136 // Note that FromType has not necessarily been transformed by the
137 // array-to-pointer or function-to-pointer implicit conversions, so
138 // check for their presence as well as checking whether FromType is
139 // a pointer.
140 if (ToType->isBooleanType() &&
Douglas Gregor80402cf2008-12-23 00:53:59 +0000141 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregord2baafd2008-10-21 16:13:35 +0000142 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
143 return true;
144
145 return false;
146}
147
Douglas Gregor14046502008-10-23 00:40:37 +0000148/// isPointerConversionToVoidPointer - Determines whether this
149/// conversion is a conversion of a pointer to a void pointer. This is
150/// used as part of the ranking of standard conversion sequences (C++
151/// 13.3.3.2p4).
152bool
153StandardConversionSequence::
154isPointerConversionToVoidPointer(ASTContext& Context) const
155{
156 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
157 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
158
159 // Note that FromType has not necessarily been transformed by the
160 // array-to-pointer implicit conversion, so check for its presence
161 // and redo the conversion to get a pointer.
162 if (First == ICK_Array_To_Pointer)
163 FromType = Context.getArrayDecayedType(FromType);
164
165 if (Second == ICK_Pointer_Conversion)
166 if (const PointerType* ToPtrType = ToType->getAsPointerType())
167 return ToPtrType->getPointeeType()->isVoidType();
168
169 return false;
170}
171
Douglas Gregord2baafd2008-10-21 16:13:35 +0000172/// DebugPrint - Print this standard conversion sequence to standard
173/// error. Useful for debugging overloading issues.
174void StandardConversionSequence::DebugPrint() const {
175 bool PrintedSomething = false;
176 if (First != ICK_Identity) {
177 fprintf(stderr, "%s", GetImplicitConversionName(First));
178 PrintedSomething = true;
179 }
180
181 if (Second != ICK_Identity) {
182 if (PrintedSomething) {
183 fprintf(stderr, " -> ");
184 }
185 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000186
187 if (CopyConstructor) {
188 fprintf(stderr, " (by copy constructor)");
189 } else if (DirectBinding) {
190 fprintf(stderr, " (direct reference binding)");
191 } else if (ReferenceBinding) {
192 fprintf(stderr, " (reference binding)");
193 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000194 PrintedSomething = true;
195 }
196
197 if (Third != ICK_Identity) {
198 if (PrintedSomething) {
199 fprintf(stderr, " -> ");
200 }
201 fprintf(stderr, "%s", GetImplicitConversionName(Third));
202 PrintedSomething = true;
203 }
204
205 if (!PrintedSomething) {
206 fprintf(stderr, "No conversions required");
207 }
208}
209
210/// DebugPrint - Print this user-defined conversion sequence to standard
211/// error. Useful for debugging overloading issues.
212void UserDefinedConversionSequence::DebugPrint() const {
213 if (Before.First || Before.Second || Before.Third) {
214 Before.DebugPrint();
215 fprintf(stderr, " -> ");
216 }
Chris Lattner271d4c22008-11-24 05:29:24 +0000217 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregord2baafd2008-10-21 16:13:35 +0000218 if (After.First || After.Second || After.Third) {
219 fprintf(stderr, " -> ");
220 After.DebugPrint();
221 }
222}
223
224/// DebugPrint - Print this implicit conversion sequence to standard
225/// error. Useful for debugging overloading issues.
226void ImplicitConversionSequence::DebugPrint() const {
227 switch (ConversionKind) {
228 case StandardConversion:
229 fprintf(stderr, "Standard conversion: ");
230 Standard.DebugPrint();
231 break;
232 case UserDefinedConversion:
233 fprintf(stderr, "User-defined conversion: ");
234 UserDefined.DebugPrint();
235 break;
236 case EllipsisConversion:
237 fprintf(stderr, "Ellipsis conversion");
238 break;
239 case BadConversion:
240 fprintf(stderr, "Bad conversion");
241 break;
242 }
243
244 fprintf(stderr, "\n");
245}
246
247// IsOverload - Determine whether the given New declaration is an
248// overload of the Old declaration. This routine returns false if New
249// and Old cannot be overloaded, e.g., if they are functions with the
250// same signature (C++ 1.3.10) or if the Old declaration isn't a
251// function (or overload set). When it does return false and Old is an
252// OverloadedFunctionDecl, MatchedDecl will be set to point to the
253// FunctionDecl that New cannot be overloaded with.
254//
255// Example: Given the following input:
256//
257// void f(int, float); // #1
258// void f(int, int); // #2
259// int f(int, int); // #3
260//
261// When we process #1, there is no previous declaration of "f",
262// so IsOverload will not be used.
263//
264// When we process #2, Old is a FunctionDecl for #1. By comparing the
265// parameter types, we see that #1 and #2 are overloaded (since they
266// have different signatures), so this routine returns false;
267// MatchedDecl is unchanged.
268//
269// When we process #3, Old is an OverloadedFunctionDecl containing #1
270// and #2. We compare the signatures of #3 to #1 (they're overloaded,
271// so we do nothing) and then #3 to #2. Since the signatures of #3 and
272// #2 are identical (return types of functions are not part of the
273// signature), IsOverload returns false and MatchedDecl will be set to
274// point to the FunctionDecl for #2.
275bool
276Sema::IsOverload(FunctionDecl *New, Decl* OldD,
277 OverloadedFunctionDecl::function_iterator& MatchedDecl)
278{
279 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
280 // Is this new function an overload of every function in the
281 // overload set?
282 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
283 FuncEnd = Ovl->function_end();
284 for (; Func != FuncEnd; ++Func) {
285 if (!IsOverload(New, *Func, MatchedDecl)) {
286 MatchedDecl = Func;
287 return false;
288 }
289 }
290
291 // This function overloads every function in the overload set.
292 return true;
293 } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
294 // Is the function New an overload of the function Old?
295 QualType OldQType = Context.getCanonicalType(Old->getType());
296 QualType NewQType = Context.getCanonicalType(New->getType());
297
298 // Compare the signatures (C++ 1.3.10) of the two functions to
299 // determine whether they are overloads. If we find any mismatch
300 // in the signature, they are overloads.
301
302 // If either of these functions is a K&R-style function (no
303 // prototype), then we consider them to have matching signatures.
304 if (isa<FunctionTypeNoProto>(OldQType.getTypePtr()) ||
305 isa<FunctionTypeNoProto>(NewQType.getTypePtr()))
306 return false;
307
308 FunctionTypeProto* OldType = cast<FunctionTypeProto>(OldQType.getTypePtr());
309 FunctionTypeProto* NewType = cast<FunctionTypeProto>(NewQType.getTypePtr());
310
311 // The signature of a function includes the types of its
312 // parameters (C++ 1.3.10), which includes the presence or absence
313 // of the ellipsis; see C++ DR 357).
314 if (OldQType != NewQType &&
315 (OldType->getNumArgs() != NewType->getNumArgs() ||
316 OldType->isVariadic() != NewType->isVariadic() ||
317 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
318 NewType->arg_type_begin())))
319 return true;
320
321 // If the function is a class member, its signature includes the
322 // cv-qualifiers (if any) on the function itself.
323 //
324 // As part of this, also check whether one of the member functions
325 // is static, in which case they are not overloads (C++
326 // 13.1p2). While not part of the definition of the signature,
327 // this check is important to determine whether these functions
328 // can be overloaded.
329 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
330 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
331 if (OldMethod && NewMethod &&
332 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregora7b56a32008-11-21 15:36:28 +0000333 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregord2baafd2008-10-21 16:13:35 +0000334 return true;
335
336 // The signatures match; this is not an overload.
337 return false;
338 } else {
339 // (C++ 13p1):
340 // Only function declarations can be overloaded; object and type
341 // declarations cannot be overloaded.
342 return false;
343 }
344}
345
Douglas Gregor81c29152008-10-29 00:13:59 +0000346/// TryImplicitConversion - Attempt to perform an implicit conversion
347/// from the given expression (Expr) to the given type (ToType). This
348/// function returns an implicit conversion sequence that can be used
349/// to perform the initialization. Given
Douglas Gregord2baafd2008-10-21 16:13:35 +0000350///
351/// void f(float f);
352/// void g(int i) { f(i); }
353///
354/// this routine would produce an implicit conversion sequence to
355/// describe the initialization of f from i, which will be a standard
356/// conversion sequence containing an lvalue-to-rvalue conversion (C++
357/// 4.1) followed by a floating-integral conversion (C++ 4.9).
358//
359/// Note that this routine only determines how the conversion can be
360/// performed; it does not actually perform the conversion. As such,
361/// it will not produce any diagnostics if no conversion is available,
362/// but will instead return an implicit conversion sequence of kind
363/// "BadConversion".
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000364///
365/// If @p SuppressUserConversions, then user-defined conversions are
366/// not permitted.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000367/// If @p AllowExplicit, then explicit user-defined conversions are
368/// permitted.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000369ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000370Sema::TryImplicitConversion(Expr* From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000371 bool SuppressUserConversions,
Douglas Gregorb206cc42009-01-30 23:27:23 +0000372 bool AllowExplicit)
Douglas Gregord2baafd2008-10-21 16:13:35 +0000373{
374 ImplicitConversionSequence ICS;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000375 if (IsStandardConversion(From, ToType, ICS.Standard))
376 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000377 else if (getLangOptions().CPlusPlus &&
378 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregorb206cc42009-01-30 23:27:23 +0000379 !SuppressUserConversions, AllowExplicit)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000380 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregore640ab62008-11-03 17:51:48 +0000381 // C++ [over.ics.user]p4:
382 // A conversion of an expression of class type to the same class
383 // type is given Exact Match rank, and a conversion of an
384 // expression of class type to a base class of that type is
385 // given Conversion rank, in spite of the fact that a copy
386 // constructor (i.e., a user-defined conversion function) is
387 // called for those cases.
388 if (CXXConstructorDecl *Constructor
389 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Douglas Gregord9176392009-02-02 22:11:10 +0000390 QualType FromCanon
391 = Context.getCanonicalType(From->getType().getUnqualifiedType());
392 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
393 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000394 // Turn this into a "standard" conversion sequence, so that it
395 // gets ranked with standard conversion sequences.
Douglas Gregore640ab62008-11-03 17:51:48 +0000396 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
397 ICS.Standard.setAsIdentityConversion();
398 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
399 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000400 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregord9176392009-02-02 22:11:10 +0000401 if (ToCanon != FromCanon)
Douglas Gregore640ab62008-11-03 17:51:48 +0000402 ICS.Standard.Second = ICK_Derived_To_Base;
403 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000404 }
Douglas Gregorb206cc42009-01-30 23:27:23 +0000405
406 // C++ [over.best.ics]p4:
407 // However, when considering the argument of a user-defined
408 // conversion function that is a candidate by 13.3.1.3 when
409 // invoked for the copying of the temporary in the second step
410 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
411 // 13.3.1.6 in all cases, only standard conversion sequences and
412 // ellipsis conversion sequences are allowed.
413 if (SuppressUserConversions &&
414 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
415 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregore640ab62008-11-03 17:51:48 +0000416 } else
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000417 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000418
419 return ICS;
420}
421
422/// IsStandardConversion - Determines whether there is a standard
423/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
424/// expression From to the type ToType. Standard conversion sequences
425/// only consider non-class types; for conversions that involve class
426/// types, use TryImplicitConversion. If a conversion exists, SCS will
427/// contain the standard conversion sequence required to perform this
428/// conversion and this routine will return true. Otherwise, this
429/// routine will return false and the value of SCS is unspecified.
430bool
431Sema::IsStandardConversion(Expr* From, QualType ToType,
432 StandardConversionSequence &SCS)
433{
Douglas Gregord2baafd2008-10-21 16:13:35 +0000434 QualType FromType = From->getType();
435
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000436 // Standard conversions (C++ [conv])
Douglas Gregor70d26122008-11-12 17:17:38 +0000437 SCS.setAsIdentityConversion();
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000438 SCS.Deprecated = false;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000439 SCS.IncompatibleObjC = false;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000440 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000441 SCS.CopyConstructor = 0;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000442
Douglas Gregorfcb19192009-02-11 23:02:49 +0000443 // There are no standard conversions for class types in C++, so
444 // abort early. When overloading in C, however, we do permit
445 if (FromType->isRecordType() || ToType->isRecordType()) {
446 if (getLangOptions().CPlusPlus)
447 return false;
448
449 // When we're overloading in C, we allow, as standard conversions,
450 }
451
Douglas Gregord2baafd2008-10-21 16:13:35 +0000452 // The first conversion can be an lvalue-to-rvalue conversion,
453 // array-to-pointer conversion, or function-to-pointer conversion
454 // (C++ 4p1).
455
456 // Lvalue-to-rvalue conversion (C++ 4.1):
457 // An lvalue (3.10) of a non-function, non-array type T can be
458 // converted to an rvalue.
459 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
460 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor45014fd2008-11-10 20:40:00 +0000461 !FromType->isFunctionType() && !FromType->isArrayType() &&
462 !FromType->isOverloadType()) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000463 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000464
465 // If T is a non-class type, the type of the rvalue is the
466 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorfcb19192009-02-11 23:02:49 +0000467 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
468 // just strip the qualifiers because they don't matter.
469
470 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000471 FromType = FromType.getUnqualifiedType();
Douglas Gregord2baafd2008-10-21 16:13:35 +0000472 }
473 // Array-to-pointer conversion (C++ 4.2)
474 else if (FromType->isArrayType()) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000475 SCS.First = ICK_Array_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000476
477 // An lvalue or rvalue of type "array of N T" or "array of unknown
478 // bound of T" can be converted to an rvalue of type "pointer to
479 // T" (C++ 4.2p1).
480 FromType = Context.getArrayDecayedType(FromType);
481
482 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
483 // This conversion is deprecated. (C++ D.4).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000484 SCS.Deprecated = true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000485
486 // For the purpose of ranking in overload resolution
487 // (13.3.3.1.1), this conversion is considered an
488 // array-to-pointer conversion followed by a qualification
489 // conversion (4.4). (C++ 4.2p2)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000490 SCS.Second = ICK_Identity;
491 SCS.Third = ICK_Qualification;
492 SCS.ToTypePtr = ToType.getAsOpaquePtr();
493 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000494 }
495 }
496 // Function-to-pointer conversion (C++ 4.3).
497 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000498 SCS.First = ICK_Function_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000499
500 // An lvalue of function type T can be converted to an rvalue of
501 // type "pointer to T." The result is a pointer to the
502 // function. (C++ 4.3p1).
503 FromType = Context.getPointerType(FromType);
Sebastian Redl7434fc32009-02-04 21:23:32 +0000504 }
Douglas Gregor45014fd2008-11-10 20:40:00 +0000505 // Address of overloaded function (C++ [over.over]).
506 else if (FunctionDecl *Fn
507 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
508 SCS.First = ICK_Function_To_Pointer;
509
510 // We were able to resolve the address of the overloaded function,
511 // so we can convert to the type of that function.
512 FromType = Fn->getType();
513 if (ToType->isReferenceType())
514 FromType = Context.getReferenceType(FromType);
Sebastian Redl7434fc32009-02-04 21:23:32 +0000515 else if (ToType->isMemberPointerType()) {
516 // Resolve address only succeeds if both sides are member pointers,
517 // but it doesn't have to be the same class. See DR 247.
518 // Note that this means that the type of &Derived::fn can be
519 // Ret (Base::*)(Args) if the fn overload actually found is from the
520 // base class, even if it was brought into the derived class via a
521 // using declaration. The standard isn't clear on this issue at all.
522 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
523 FromType = Context.getMemberPointerType(FromType,
524 Context.getTypeDeclType(M->getParent()).getTypePtr());
525 } else
Douglas Gregor45014fd2008-11-10 20:40:00 +0000526 FromType = Context.getPointerType(FromType);
527 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000528 // We don't require any conversions for the first step.
529 else {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000530 SCS.First = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000531 }
532
533 // The second conversion can be an integral promotion, floating
534 // point promotion, integral conversion, floating point conversion,
535 // floating-integral conversion, pointer conversion,
536 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorfcb19192009-02-11 23:02:49 +0000537 // For overloading in C, this can also be a "compatible-type"
538 // conversion.
Douglas Gregor6fd35572008-12-19 17:40:08 +0000539 bool IncompatibleObjC = false;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000540 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000541 // The unqualified versions of the types are the same: there's no
542 // conversion to do.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000543 SCS.Second = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000544 }
545 // Integral promotion (C++ 4.5).
546 else if (IsIntegralPromotion(From, FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000547 SCS.Second = ICK_Integral_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000548 FromType = ToType.getUnqualifiedType();
549 }
550 // Floating point promotion (C++ 4.6).
551 else if (IsFloatingPointPromotion(FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000552 SCS.Second = ICK_Floating_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000553 FromType = ToType.getUnqualifiedType();
554 }
555 // Integral conversions (C++ 4.7).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000556 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000557 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000558 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000559 SCS.Second = ICK_Integral_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000560 FromType = ToType.getUnqualifiedType();
561 }
562 // Floating point conversions (C++ 4.8).
563 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000564 SCS.Second = ICK_Floating_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000565 FromType = ToType.getUnqualifiedType();
566 }
567 // Floating-integral conversions (C++ 4.9).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000568 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000569 else if ((FromType->isFloatingType() &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000570 ToType->isIntegralType() && !ToType->isBooleanType() &&
571 !ToType->isEnumeralType()) ||
Douglas Gregord2baafd2008-10-21 16:13:35 +0000572 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
573 ToType->isFloatingType())) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000574 SCS.Second = ICK_Floating_Integral;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000575 FromType = ToType.getUnqualifiedType();
576 }
577 // Pointer conversions (C++ 4.10).
Douglas Gregor6fd35572008-12-19 17:40:08 +0000578 else if (IsPointerConversion(From, FromType, ToType, FromType,
579 IncompatibleObjC)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000580 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000581 SCS.IncompatibleObjC = IncompatibleObjC;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000582 }
Sebastian Redlba387562009-01-25 19:43:20 +0000583 // Pointer to member conversions (4.11).
584 else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
585 SCS.Second = ICK_Pointer_Member;
586 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000587 // Boolean conversions (C++ 4.12).
Douglas Gregord2baafd2008-10-21 16:13:35 +0000588 else if (ToType->isBooleanType() &&
589 (FromType->isArithmeticType() ||
590 FromType->isEnumeralType() ||
Douglas Gregor80402cf2008-12-23 00:53:59 +0000591 FromType->isPointerType() ||
Sebastian Redlba387562009-01-25 19:43:20 +0000592 FromType->isBlockPointerType() ||
593 FromType->isMemberPointerType())) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000594 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000595 FromType = Context.BoolTy;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000596 }
597 // Compatible conversions (Clang extension for C function overloading)
598 else if (!getLangOptions().CPlusPlus &&
599 Context.typesAreCompatible(ToType, FromType)) {
600 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000601 } else {
602 // No second conversion required.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000603 SCS.Second = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000604 }
605
Douglas Gregor81c29152008-10-29 00:13:59 +0000606 QualType CanonFrom;
607 QualType CanonTo;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000608 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor6573cfd2008-10-21 23:43:52 +0000609 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000610 SCS.Third = ICK_Qualification;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000611 FromType = ToType;
Douglas Gregor81c29152008-10-29 00:13:59 +0000612 CanonFrom = Context.getCanonicalType(FromType);
613 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000614 } else {
615 // No conversion required
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000616 SCS.Third = ICK_Identity;
617
618 // C++ [over.best.ics]p6:
619 // [...] Any difference in top-level cv-qualification is
620 // subsumed by the initialization itself and does not constitute
621 // a conversion. [...]
Douglas Gregor81c29152008-10-29 00:13:59 +0000622 CanonFrom = Context.getCanonicalType(FromType);
623 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000624 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor81c29152008-10-29 00:13:59 +0000625 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
626 FromType = ToType;
627 CanonFrom = CanonTo;
628 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000629 }
630
631 // If we have not converted the argument type to the parameter type,
632 // this is a bad conversion sequence.
Douglas Gregor81c29152008-10-29 00:13:59 +0000633 if (CanonFrom != CanonTo)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000634 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000635
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000636 SCS.ToTypePtr = FromType.getAsOpaquePtr();
637 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000638}
639
640/// IsIntegralPromotion - Determines whether the conversion from the
641/// expression From (whose potentially-adjusted type is FromType) to
642/// ToType is an integral promotion (C++ 4.5). If so, returns true and
643/// sets PromotedType to the promoted type.
644bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
645{
646 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redl12aee862008-11-04 15:59:10 +0000647 // All integers are built-in.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000648 if (!To) {
649 return false;
650 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000651
652 // An rvalue of type char, signed char, unsigned char, short int, or
653 // unsigned short int can be converted to an rvalue of type int if
654 // int can represent all the values of the source type; otherwise,
655 // the source rvalue can be converted to an rvalue of type unsigned
656 // int (C++ 4.5p1).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000657 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000658 if (// We can promote any signed, promotable integer type to an int
659 (FromType->isSignedIntegerType() ||
660 // We can promote any unsigned integer type whose size is
661 // less than int to an int.
662 (!FromType->isSignedIntegerType() &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000663 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000664 return To->getKind() == BuiltinType::Int;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000665 }
666
Douglas Gregord2baafd2008-10-21 16:13:35 +0000667 return To->getKind() == BuiltinType::UInt;
668 }
669
670 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
671 // can be converted to an rvalue of the first of the following types
672 // that can represent all the values of its underlying type: int,
673 // unsigned int, long, or unsigned long (C++ 4.5p2).
674 if ((FromType->isEnumeralType() || FromType->isWideCharType())
675 && ToType->isIntegerType()) {
676 // Determine whether the type we're converting from is signed or
677 // unsigned.
678 bool FromIsSigned;
679 uint64_t FromSize = Context.getTypeSize(FromType);
680 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
681 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
682 FromIsSigned = UnderlyingType->isSignedIntegerType();
683 } else {
684 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
685 FromIsSigned = true;
686 }
687
688 // The types we'll try to promote to, in the appropriate
689 // order. Try each of these types.
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000690 QualType PromoteTypes[6] = {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000691 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000692 Context.LongTy, Context.UnsignedLongTy ,
693 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregord2baafd2008-10-21 16:13:35 +0000694 };
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000695 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000696 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
697 if (FromSize < ToSize ||
698 (FromSize == ToSize &&
699 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
700 // We found the type that we can promote to. If this is the
701 // type we wanted, we have a promotion. Otherwise, no
702 // promotion.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000703 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregord2baafd2008-10-21 16:13:35 +0000704 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
705 }
706 }
707 }
708
709 // An rvalue for an integral bit-field (9.6) can be converted to an
710 // rvalue of type int if int can represent all the values of the
711 // bit-field; otherwise, it can be converted to unsigned int if
712 // unsigned int can represent all the values of the bit-field. If
713 // the bit-field is larger yet, no integral promotion applies to
714 // it. If the bit-field has an enumerated type, it is treated as any
715 // other value of that type for promotion purposes (C++ 4.5p3).
716 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) {
717 using llvm::APSInt;
Douglas Gregor82d44772008-12-20 23:49:58 +0000718 if (FieldDecl *MemberDecl = dyn_cast<FieldDecl>(MemRef->getMemberDecl())) {
719 APSInt BitWidth;
720 if (MemberDecl->isBitField() &&
721 FromType->isIntegralType() && !FromType->isEnumeralType() &&
722 From->isIntegerConstantExpr(BitWidth, Context)) {
723 APSInt ToSize(Context.getTypeSize(ToType));
724
725 // Are we promoting to an int from a bitfield that fits in an int?
726 if (BitWidth < ToSize ||
727 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
728 return To->getKind() == BuiltinType::Int;
729 }
730
731 // Are we promoting to an unsigned int from an unsigned bitfield
732 // that fits into an unsigned int?
733 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
734 return To->getKind() == BuiltinType::UInt;
735 }
736
737 return false;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000738 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000739 }
740 }
741
742 // An rvalue of type bool can be converted to an rvalue of type int,
743 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000744 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000745 return true;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000746 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000747
748 return false;
749}
750
751/// IsFloatingPointPromotion - Determines whether the conversion from
752/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
753/// returns true and sets PromotedType to the promoted type.
754bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
755{
756 /// An rvalue of type float can be converted to an rvalue of type
757 /// double. (C++ 4.6p1).
758 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
759 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType())
760 if (FromBuiltin->getKind() == BuiltinType::Float &&
761 ToBuiltin->getKind() == BuiltinType::Double)
762 return true;
763
764 return false;
765}
766
Douglas Gregor24a90a52008-11-26 23:31:11 +0000767/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
768/// the pointer type FromPtr to a pointer to type ToPointee, with the
769/// same type qualifiers as FromPtr has on its pointee type. ToType,
770/// if non-empty, will be a pointer to ToType that may or may not have
771/// the right set of qualifiers on its pointee.
772static QualType
773BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
774 QualType ToPointee, QualType ToType,
775 ASTContext &Context) {
776 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
777 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
778 unsigned Quals = CanonFromPointee.getCVRQualifiers();
779
780 // Exact qualifier match -> return the pointer type we're converting to.
781 if (CanonToPointee.getCVRQualifiers() == Quals) {
782 // ToType is exactly what we need. Return it.
783 if (ToType.getTypePtr())
784 return ToType;
785
786 // Build a pointer to ToPointee. It has the right qualifiers
787 // already.
788 return Context.getPointerType(ToPointee);
789 }
790
791 // Just build a canonical type that has the right qualifiers.
792 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
793}
794
Douglas Gregord2baafd2008-10-21 16:13:35 +0000795/// IsPointerConversion - Determines whether the conversion of the
796/// expression From, which has the (possibly adjusted) type FromType,
797/// can be converted to the type ToType via a pointer conversion (C++
798/// 4.10). If so, returns true and places the converted type (that
799/// might differ from ToType in its cv-qualifiers at some level) into
800/// ConvertedType.
Douglas Gregor9036ef72008-11-27 00:15:41 +0000801///
Douglas Gregor3f5a00c2008-11-27 01:19:21 +0000802/// This routine also supports conversions to and from block pointers
803/// and conversions with Objective-C's 'id', 'id<protocols...>', and
804/// pointers to interfaces. FIXME: Once we've determined the
805/// appropriate overloading rules for Objective-C, we may want to
806/// split the Objective-C checks into a different routine; however,
807/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor6fd35572008-12-19 17:40:08 +0000808/// conversions, so for now they live here. IncompatibleObjC will be
809/// set if the conversion is an allowed Objective-C conversion that
810/// should result in a warning.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000811bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Douglas Gregor6fd35572008-12-19 17:40:08 +0000812 QualType& ConvertedType,
813 bool &IncompatibleObjC)
Douglas Gregord2baafd2008-10-21 16:13:35 +0000814{
Douglas Gregor6fd35572008-12-19 17:40:08 +0000815 IncompatibleObjC = false;
Douglas Gregor932778b2008-12-19 19:13:09 +0000816 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
817 return true;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000818
Douglas Gregorf1d75712008-12-22 20:51:52 +0000819 // Conversion from a null pointer constant to any Objective-C pointer type.
820 if (Context.isObjCObjectPointerType(ToType) &&
821 From->isNullPointerConstant(Context)) {
822 ConvertedType = ToType;
823 return true;
824 }
825
Douglas Gregor9036ef72008-11-27 00:15:41 +0000826 // Blocks: Block pointers can be converted to void*.
827 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
828 ToType->getAsPointerType()->getPointeeType()->isVoidType()) {
829 ConvertedType = ToType;
830 return true;
831 }
832 // Blocks: A null pointer constant can be converted to a block
833 // pointer type.
834 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
835 ConvertedType = ToType;
836 return true;
837 }
838
Douglas Gregord2baafd2008-10-21 16:13:35 +0000839 const PointerType* ToTypePtr = ToType->getAsPointerType();
840 if (!ToTypePtr)
841 return false;
842
843 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
844 if (From->isNullPointerConstant(Context)) {
845 ConvertedType = ToType;
846 return true;
847 }
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000848
Douglas Gregor24a90a52008-11-26 23:31:11 +0000849 // Beyond this point, both types need to be pointers.
850 const PointerType *FromTypePtr = FromType->getAsPointerType();
851 if (!FromTypePtr)
852 return false;
853
854 QualType FromPointeeType = FromTypePtr->getPointeeType();
855 QualType ToPointeeType = ToTypePtr->getPointeeType();
856
Douglas Gregord2baafd2008-10-21 16:13:35 +0000857 // An rvalue of type "pointer to cv T," where T is an object type,
858 // can be converted to an rvalue of type "pointer to cv void" (C++
859 // 4.10p2).
Douglas Gregor932778b2008-12-19 19:13:09 +0000860 if (FromPointeeType->isIncompleteOrObjectType() &&
861 ToPointeeType->isVoidType()) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000862 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
863 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000864 ToType, Context);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000865 return true;
866 }
867
Douglas Gregorfcb19192009-02-11 23:02:49 +0000868 // When we're overloading in C, we allow a special kind of pointer
869 // conversion for compatible-but-not-identical pointee types.
870 if (!getLangOptions().CPlusPlus &&
871 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
872 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
873 ToPointeeType,
874 ToType, Context);
875 return true;
876 }
877
Douglas Gregor14046502008-10-23 00:40:37 +0000878 // C++ [conv.ptr]p3:
879 //
880 // An rvalue of type "pointer to cv D," where D is a class type,
881 // can be converted to an rvalue of type "pointer to cv B," where
882 // B is a base class (clause 10) of D. If B is an inaccessible
883 // (clause 11) or ambiguous (10.2) base class of D, a program that
884 // necessitates this conversion is ill-formed. The result of the
885 // conversion is a pointer to the base class sub-object of the
886 // derived class object. The null pointer value is converted to
887 // the null pointer value of the destination type.
888 //
Douglas Gregorbb461502008-10-24 04:54:22 +0000889 // Note that we do not check for ambiguity or inaccessibility
890 // here. That is handled by CheckPointerConversion.
Douglas Gregorfcb19192009-02-11 23:02:49 +0000891 if (getLangOptions().CPlusPlus &&
892 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor24a90a52008-11-26 23:31:11 +0000893 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000894 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
895 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000896 ToType, Context);
897 return true;
898 }
Douglas Gregor14046502008-10-23 00:40:37 +0000899
Douglas Gregor932778b2008-12-19 19:13:09 +0000900 return false;
901}
902
903/// isObjCPointerConversion - Determines whether this is an
904/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
905/// with the same arguments and return values.
906bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
907 QualType& ConvertedType,
908 bool &IncompatibleObjC) {
909 if (!getLangOptions().ObjC1)
910 return false;
911
912 // Conversions with Objective-C's id<...>.
913 if ((FromType->isObjCQualifiedIdType() || ToType->isObjCQualifiedIdType()) &&
914 ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) {
915 ConvertedType = ToType;
916 return true;
917 }
918
Douglas Gregor80402cf2008-12-23 00:53:59 +0000919 // Beyond this point, both types need to be pointers or block pointers.
920 QualType ToPointeeType;
Douglas Gregor932778b2008-12-19 19:13:09 +0000921 const PointerType* ToTypePtr = ToType->getAsPointerType();
Douglas Gregor80402cf2008-12-23 00:53:59 +0000922 if (ToTypePtr)
923 ToPointeeType = ToTypePtr->getPointeeType();
924 else if (const BlockPointerType *ToBlockPtr = ToType->getAsBlockPointerType())
925 ToPointeeType = ToBlockPtr->getPointeeType();
926 else
Douglas Gregor932778b2008-12-19 19:13:09 +0000927 return false;
928
Douglas Gregor80402cf2008-12-23 00:53:59 +0000929 QualType FromPointeeType;
Douglas Gregor932778b2008-12-19 19:13:09 +0000930 const PointerType *FromTypePtr = FromType->getAsPointerType();
Douglas Gregor80402cf2008-12-23 00:53:59 +0000931 if (FromTypePtr)
932 FromPointeeType = FromTypePtr->getPointeeType();
933 else if (const BlockPointerType *FromBlockPtr
934 = FromType->getAsBlockPointerType())
935 FromPointeeType = FromBlockPtr->getPointeeType();
936 else
Douglas Gregor932778b2008-12-19 19:13:09 +0000937 return false;
938
Douglas Gregor24a90a52008-11-26 23:31:11 +0000939 // Objective C++: We're able to convert from a pointer to an
940 // interface to a pointer to a different interface.
941 const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType();
942 const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType();
943 if (FromIface && ToIface &&
944 Context.canAssignObjCInterfaces(ToIface, FromIface)) {
Douglas Gregor80402cf2008-12-23 00:53:59 +0000945 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000946 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000947 ToType, Context);
948 return true;
949 }
950
Douglas Gregor6fd35572008-12-19 17:40:08 +0000951 if (FromIface && ToIface &&
952 Context.canAssignObjCInterfaces(FromIface, ToIface)) {
953 // Okay: this is some kind of implicit downcast of Objective-C
954 // interfaces, which is permitted. However, we're going to
955 // complain about it.
956 IncompatibleObjC = true;
Douglas Gregor80402cf2008-12-23 00:53:59 +0000957 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor6fd35572008-12-19 17:40:08 +0000958 ToPointeeType,
959 ToType, Context);
960 return true;
961 }
962
Douglas Gregor24a90a52008-11-26 23:31:11 +0000963 // Objective C++: We're able to convert between "id" and a pointer
964 // to any interface (in both directions).
965 if ((FromIface && Context.isObjCIdType(ToPointeeType))
966 || (ToIface && Context.isObjCIdType(FromPointeeType))) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000967 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
968 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000969 ToType, Context);
970 return true;
971 }
Douglas Gregor14046502008-10-23 00:40:37 +0000972
Douglas Gregord0c653a2008-12-18 23:43:31 +0000973 // Objective C++: Allow conversions between the Objective-C "id" and
974 // "Class", in either direction.
975 if ((Context.isObjCIdType(FromPointeeType) &&
976 Context.isObjCClassType(ToPointeeType)) ||
977 (Context.isObjCClassType(FromPointeeType) &&
978 Context.isObjCIdType(ToPointeeType))) {
979 ConvertedType = ToType;
980 return true;
981 }
982
Douglas Gregor932778b2008-12-19 19:13:09 +0000983 // If we have pointers to pointers, recursively check whether this
984 // is an Objective-C conversion.
985 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
986 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
987 IncompatibleObjC)) {
988 // We always complain about this conversion.
989 IncompatibleObjC = true;
990 ConvertedType = ToType;
991 return true;
992 }
993
Douglas Gregor80402cf2008-12-23 00:53:59 +0000994 // If we have pointers to functions or blocks, check whether the only
Douglas Gregor932778b2008-12-19 19:13:09 +0000995 // differences in the argument and result types are in Objective-C
996 // pointer conversions. If so, we permit the conversion (but
997 // complain about it).
998 const FunctionTypeProto *FromFunctionType
999 = FromPointeeType->getAsFunctionTypeProto();
1000 const FunctionTypeProto *ToFunctionType
1001 = ToPointeeType->getAsFunctionTypeProto();
1002 if (FromFunctionType && ToFunctionType) {
1003 // If the function types are exactly the same, this isn't an
1004 // Objective-C pointer conversion.
1005 if (Context.getCanonicalType(FromPointeeType)
1006 == Context.getCanonicalType(ToPointeeType))
1007 return false;
1008
1009 // Perform the quick checks that will tell us whether these
1010 // function types are obviously different.
1011 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1012 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1013 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1014 return false;
1015
1016 bool HasObjCConversion = false;
1017 if (Context.getCanonicalType(FromFunctionType->getResultType())
1018 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1019 // Okay, the types match exactly. Nothing to do.
1020 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1021 ToFunctionType->getResultType(),
1022 ConvertedType, IncompatibleObjC)) {
1023 // Okay, we have an Objective-C pointer conversion.
1024 HasObjCConversion = true;
1025 } else {
1026 // Function types are too different. Abort.
1027 return false;
1028 }
1029
1030 // Check argument types.
1031 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1032 ArgIdx != NumArgs; ++ArgIdx) {
1033 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1034 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1035 if (Context.getCanonicalType(FromArgType)
1036 == Context.getCanonicalType(ToArgType)) {
1037 // Okay, the types match exactly. Nothing to do.
1038 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1039 ConvertedType, IncompatibleObjC)) {
1040 // Okay, we have an Objective-C pointer conversion.
1041 HasObjCConversion = true;
1042 } else {
1043 // Argument types are too different. Abort.
1044 return false;
1045 }
1046 }
1047
1048 if (HasObjCConversion) {
1049 // We had an Objective-C conversion. Allow this pointer
1050 // conversion, but complain about it.
1051 ConvertedType = ToType;
1052 IncompatibleObjC = true;
1053 return true;
1054 }
1055 }
1056
Sebastian Redlba387562009-01-25 19:43:20 +00001057 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001058}
1059
Douglas Gregorbb461502008-10-24 04:54:22 +00001060/// CheckPointerConversion - Check the pointer conversion from the
1061/// expression From to the type ToType. This routine checks for
1062/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
1063/// conversions for which IsPointerConversion has already returned
1064/// true. It returns true and produces a diagnostic if there was an
1065/// error, or returns false otherwise.
1066bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1067 QualType FromType = From->getType();
1068
1069 if (const PointerType *FromPtrType = FromType->getAsPointerType())
1070 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
Douglas Gregorbb461502008-10-24 04:54:22 +00001071 QualType FromPointeeType = FromPtrType->getPointeeType(),
1072 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregord0c653a2008-12-18 23:43:31 +00001073
1074 // Objective-C++ conversions are always okay.
1075 // FIXME: We should have a different class of conversions for
1076 // the Objective-C++ implicit conversions.
1077 if (Context.isObjCIdType(FromPointeeType) ||
1078 Context.isObjCIdType(ToPointeeType) ||
1079 Context.isObjCClassType(FromPointeeType) ||
1080 Context.isObjCClassType(ToPointeeType))
1081 return false;
1082
Douglas Gregorbb461502008-10-24 04:54:22 +00001083 if (FromPointeeType->isRecordType() &&
1084 ToPointeeType->isRecordType()) {
1085 // We must have a derived-to-base conversion. Check an
1086 // ambiguous or inaccessible conversion.
Douglas Gregor651d1cc2008-10-24 16:17:19 +00001087 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1088 From->getExprLoc(),
1089 From->getSourceRange());
Douglas Gregorbb461502008-10-24 04:54:22 +00001090 }
1091 }
1092
1093 return false;
1094}
1095
Sebastian Redlba387562009-01-25 19:43:20 +00001096/// IsMemberPointerConversion - Determines whether the conversion of the
1097/// expression From, which has the (possibly adjusted) type FromType, can be
1098/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1099/// If so, returns true and places the converted type (that might differ from
1100/// ToType in its cv-qualifiers at some level) into ConvertedType.
1101bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1102 QualType ToType, QualType &ConvertedType)
1103{
1104 const MemberPointerType *ToTypePtr = ToType->getAsMemberPointerType();
1105 if (!ToTypePtr)
1106 return false;
1107
1108 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1109 if (From->isNullPointerConstant(Context)) {
1110 ConvertedType = ToType;
1111 return true;
1112 }
1113
1114 // Otherwise, both types have to be member pointers.
1115 const MemberPointerType *FromTypePtr = FromType->getAsMemberPointerType();
1116 if (!FromTypePtr)
1117 return false;
1118
1119 // A pointer to member of B can be converted to a pointer to member of D,
1120 // where D is derived from B (C++ 4.11p2).
1121 QualType FromClass(FromTypePtr->getClass(), 0);
1122 QualType ToClass(ToTypePtr->getClass(), 0);
1123 // FIXME: What happens when these are dependent? Is this function even called?
1124
1125 if (IsDerivedFrom(ToClass, FromClass)) {
1126 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1127 ToClass.getTypePtr());
1128 return true;
1129 }
1130
1131 return false;
1132}
1133
1134/// CheckMemberPointerConversion - Check the member pointer conversion from the
1135/// expression From to the type ToType. This routine checks for ambiguous or
1136/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1137/// for which IsMemberPointerConversion has already returned true. It returns
1138/// true and produces a diagnostic if there was an error, or returns false
1139/// otherwise.
1140bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType) {
1141 QualType FromType = From->getType();
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001142 const MemberPointerType *FromPtrType = FromType->getAsMemberPointerType();
1143 if (!FromPtrType)
1144 return false;
Sebastian Redlba387562009-01-25 19:43:20 +00001145
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001146 const MemberPointerType *ToPtrType = ToType->getAsMemberPointerType();
1147 assert(ToPtrType && "No member pointer cast has a target type "
1148 "that is not a member pointer.");
Sebastian Redlba387562009-01-25 19:43:20 +00001149
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001150 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1151 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redlba387562009-01-25 19:43:20 +00001152
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001153 // FIXME: What about dependent types?
1154 assert(FromClass->isRecordType() && "Pointer into non-class.");
1155 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redlba387562009-01-25 19:43:20 +00001156
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001157 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1158 /*DetectVirtual=*/true);
1159 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1160 assert(DerivationOkay &&
1161 "Should not have been called if derivation isn't OK.");
1162 (void)DerivationOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001163
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001164 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1165 getUnqualifiedType())) {
1166 // Derivation is ambiguous. Redo the check to find the exact paths.
1167 Paths.clear();
1168 Paths.setRecordingPaths(true);
1169 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1170 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1171 (void)StillOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001172
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001173 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1174 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1175 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1176 return true;
Sebastian Redlba387562009-01-25 19:43:20 +00001177 }
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001178
1179 if (const CXXRecordType *VBase = Paths.getDetectedVirtual()) {
1180 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1181 << FromClass << ToClass << QualType(VBase, 0)
1182 << From->getSourceRange();
1183 return true;
1184 }
1185
Sebastian Redlba387562009-01-25 19:43:20 +00001186 return false;
1187}
1188
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001189/// IsQualificationConversion - Determines whether the conversion from
1190/// an rvalue of type FromType to ToType is a qualification conversion
1191/// (C++ 4.4).
1192bool
1193Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1194{
1195 FromType = Context.getCanonicalType(FromType);
1196 ToType = Context.getCanonicalType(ToType);
1197
1198 // If FromType and ToType are the same type, this is not a
1199 // qualification conversion.
1200 if (FromType == ToType)
1201 return false;
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001202
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001203 // (C++ 4.4p4):
1204 // A conversion can add cv-qualifiers at levels other than the first
1205 // in multi-level pointers, subject to the following rules: [...]
1206 bool PreviousToQualsIncludeConst = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001207 bool UnwrappedAnyPointer = false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001208 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001209 // Within each iteration of the loop, we check the qualifiers to
1210 // determine if this still looks like a qualification
1211 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001212 // pointers or pointers-to-members and do it all again
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001213 // until there are no more pointers or pointers-to-members left to
1214 // unwrap.
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001215 UnwrappedAnyPointer = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001216
1217 // -- for every j > 0, if const is in cv 1,j then const is in cv
1218 // 2,j, and similarly for volatile.
Douglas Gregore5db4f72008-10-22 00:38:21 +00001219 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001220 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001221
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001222 // -- if the cv 1,j and cv 2,j are different, then const is in
1223 // every cv for 0 < k < j.
1224 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001225 && !PreviousToQualsIncludeConst)
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001226 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001227
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001228 // Keep track of whether all prior cv-qualifiers in the "to" type
1229 // include const.
1230 PreviousToQualsIncludeConst
1231 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001232 }
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001233
1234 // We are left with FromType and ToType being the pointee types
1235 // after unwrapping the original FromType and ToType the same number
1236 // of types. If we unwrapped any pointers, and if FromType and
1237 // ToType have the same unqualified type (since we checked
1238 // qualifiers above), then this is a qualification conversion.
1239 return UnwrappedAnyPointer &&
1240 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1241}
1242
Douglas Gregorb206cc42009-01-30 23:27:23 +00001243/// Determines whether there is a user-defined conversion sequence
1244/// (C++ [over.ics.user]) that converts expression From to the type
1245/// ToType. If such a conversion exists, User will contain the
1246/// user-defined conversion sequence that performs such a conversion
1247/// and this routine will return true. Otherwise, this routine returns
1248/// false and User is unspecified.
1249///
1250/// \param AllowConversionFunctions true if the conversion should
1251/// consider conversion functions at all. If false, only constructors
1252/// will be considered.
1253///
1254/// \param AllowExplicit true if the conversion should consider C++0x
1255/// "explicit" conversion functions as well as non-explicit conversion
1256/// functions (C++0x [class.conv.fct]p2).
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001257bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001258 UserDefinedConversionSequence& User,
Douglas Gregorb206cc42009-01-30 23:27:23 +00001259 bool AllowConversionFunctions,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001260 bool AllowExplicit)
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001261{
1262 OverloadCandidateSet CandidateSet;
1263 if (const CXXRecordType *ToRecordType
1264 = dyn_cast_or_null<CXXRecordType>(ToType->getAsRecordType())) {
1265 // C++ [over.match.ctor]p1:
1266 // When objects of class type are direct-initialized (8.5), or
1267 // copy-initialized from an expression of the same or a
1268 // derived class type (8.5), overload resolution selects the
1269 // constructor. [...] For copy-initialization, the candidate
1270 // functions are all the converting constructors (12.3.1) of
1271 // that class. The argument list is the expression-list within
1272 // the parentheses of the initializer.
1273 CXXRecordDecl *ToRecordDecl = ToRecordType->getDecl();
Douglas Gregorb9213832008-12-15 21:24:18 +00001274 DeclarationName ConstructorName
1275 = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor036b5a02009-01-13 00:11:19 +00001276 Context.getCanonicalType(ToType).getUnqualifiedType());
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001277 DeclContext::lookup_iterator Con, ConEnd;
Steve Naroffab63fd62009-01-08 17:28:14 +00001278 for (llvm::tie(Con, ConEnd) = ToRecordDecl->lookup(ConstructorName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001279 Con != ConEnd; ++Con) {
1280 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001281 if (Constructor->isConvertingConstructor())
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001282 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1283 /*SuppressUserConversions=*/true);
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001284 }
1285 }
1286
Douglas Gregorb206cc42009-01-30 23:27:23 +00001287 if (!AllowConversionFunctions) {
1288 // Don't allow any conversion functions to enter the overload set.
1289 } else if (const CXXRecordType *FromRecordType
1290 = dyn_cast_or_null<CXXRecordType>(
1291 From->getType()->getAsRecordType())) {
Douglas Gregor60714f92008-11-07 22:36:19 +00001292 // Add all of the conversion functions as candidates.
1293 // FIXME: Look for conversions in base classes!
1294 CXXRecordDecl *FromRecordDecl = FromRecordType->getDecl();
1295 OverloadedFunctionDecl *Conversions
1296 = FromRecordDecl->getConversionFunctions();
1297 for (OverloadedFunctionDecl::function_iterator Func
1298 = Conversions->function_begin();
1299 Func != Conversions->function_end(); ++Func) {
1300 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001301 if (AllowExplicit || !Conv->isExplicit())
1302 AddConversionCandidate(Conv, From, ToType, CandidateSet);
Douglas Gregor60714f92008-11-07 22:36:19 +00001303 }
1304 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001305
1306 OverloadCandidateSet::iterator Best;
1307 switch (BestViableFunction(CandidateSet, Best)) {
1308 case OR_Success:
1309 // Record the standard conversion we used and the conversion function.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001310 if (CXXConstructorDecl *Constructor
1311 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1312 // C++ [over.ics.user]p1:
1313 // If the user-defined conversion is specified by a
1314 // constructor (12.3.1), the initial standard conversion
1315 // sequence converts the source type to the type required by
1316 // the argument of the constructor.
1317 //
1318 // FIXME: What about ellipsis conversions?
1319 QualType ThisType = Constructor->getThisType(Context);
1320 User.Before = Best->Conversions[0].Standard;
1321 User.ConversionFunction = Constructor;
1322 User.After.setAsIdentityConversion();
1323 User.After.FromTypePtr
1324 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
1325 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1326 return true;
Douglas Gregor60714f92008-11-07 22:36:19 +00001327 } else if (CXXConversionDecl *Conversion
1328 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1329 // C++ [over.ics.user]p1:
1330 //
1331 // [...] If the user-defined conversion is specified by a
1332 // conversion function (12.3.2), the initial standard
1333 // conversion sequence converts the source type to the
1334 // implicit object parameter of the conversion function.
1335 User.Before = Best->Conversions[0].Standard;
1336 User.ConversionFunction = Conversion;
1337
1338 // C++ [over.ics.user]p2:
1339 // The second standard conversion sequence converts the
1340 // result of the user-defined conversion to the target type
1341 // for the sequence. Since an implicit conversion sequence
1342 // is an initialization, the special rules for
1343 // initialization by user-defined conversion apply when
1344 // selecting the best user-defined conversion for a
1345 // user-defined conversion sequence (see 13.3.3 and
1346 // 13.3.3.1).
1347 User.After = Best->FinalConversion;
1348 return true;
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001349 } else {
Douglas Gregor60714f92008-11-07 22:36:19 +00001350 assert(false && "Not a constructor or conversion function?");
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001351 return false;
1352 }
1353
1354 case OR_No_Viable_Function:
1355 // No conversion here! We're done.
1356 return false;
1357
1358 case OR_Ambiguous:
1359 // FIXME: See C++ [over.best.ics]p10 for the handling of
1360 // ambiguous conversion sequences.
1361 return false;
1362 }
1363
1364 return false;
1365}
1366
Douglas Gregord2baafd2008-10-21 16:13:35 +00001367/// CompareImplicitConversionSequences - Compare two implicit
1368/// conversion sequences to determine whether one is better than the
1369/// other or if they are indistinguishable (C++ 13.3.3.2).
1370ImplicitConversionSequence::CompareKind
1371Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1372 const ImplicitConversionSequence& ICS2)
1373{
1374 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1375 // conversion sequences (as defined in 13.3.3.1)
1376 // -- a standard conversion sequence (13.3.3.1.1) is a better
1377 // conversion sequence than a user-defined conversion sequence or
1378 // an ellipsis conversion sequence, and
1379 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1380 // conversion sequence than an ellipsis conversion sequence
1381 // (13.3.3.1.3).
1382 //
1383 if (ICS1.ConversionKind < ICS2.ConversionKind)
1384 return ImplicitConversionSequence::Better;
1385 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1386 return ImplicitConversionSequence::Worse;
1387
1388 // Two implicit conversion sequences of the same form are
1389 // indistinguishable conversion sequences unless one of the
1390 // following rules apply: (C++ 13.3.3.2p3):
1391 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1392 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1393 else if (ICS1.ConversionKind ==
1394 ImplicitConversionSequence::UserDefinedConversion) {
1395 // User-defined conversion sequence U1 is a better conversion
1396 // sequence than another user-defined conversion sequence U2 if
1397 // they contain the same user-defined conversion function or
1398 // constructor and if the second standard conversion sequence of
1399 // U1 is better than the second standard conversion sequence of
1400 // U2 (C++ 13.3.3.2p3).
1401 if (ICS1.UserDefined.ConversionFunction ==
1402 ICS2.UserDefined.ConversionFunction)
1403 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1404 ICS2.UserDefined.After);
1405 }
1406
1407 return ImplicitConversionSequence::Indistinguishable;
1408}
1409
1410/// CompareStandardConversionSequences - Compare two standard
1411/// conversion sequences to determine whether one is better than the
1412/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1413ImplicitConversionSequence::CompareKind
1414Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1415 const StandardConversionSequence& SCS2)
1416{
1417 // Standard conversion sequence S1 is a better conversion sequence
1418 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1419
1420 // -- S1 is a proper subsequence of S2 (comparing the conversion
1421 // sequences in the canonical form defined by 13.3.3.1.1,
1422 // excluding any Lvalue Transformation; the identity conversion
1423 // sequence is considered to be a subsequence of any
1424 // non-identity conversion sequence) or, if not that,
1425 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1426 // Neither is a proper subsequence of the other. Do nothing.
1427 ;
1428 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1429 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1430 (SCS1.Second == ICK_Identity &&
1431 SCS1.Third == ICK_Identity))
1432 // SCS1 is a proper subsequence of SCS2.
1433 return ImplicitConversionSequence::Better;
1434 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1435 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1436 (SCS2.Second == ICK_Identity &&
1437 SCS2.Third == ICK_Identity))
1438 // SCS2 is a proper subsequence of SCS1.
1439 return ImplicitConversionSequence::Worse;
1440
1441 // -- the rank of S1 is better than the rank of S2 (by the rules
1442 // defined below), or, if not that,
1443 ImplicitConversionRank Rank1 = SCS1.getRank();
1444 ImplicitConversionRank Rank2 = SCS2.getRank();
1445 if (Rank1 < Rank2)
1446 return ImplicitConversionSequence::Better;
1447 else if (Rank2 < Rank1)
1448 return ImplicitConversionSequence::Worse;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001449
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001450 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1451 // are indistinguishable unless one of the following rules
1452 // applies:
1453
1454 // A conversion that is not a conversion of a pointer, or
1455 // pointer to member, to bool is better than another conversion
1456 // that is such a conversion.
1457 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1458 return SCS2.isPointerConversionToBool()
1459 ? ImplicitConversionSequence::Better
1460 : ImplicitConversionSequence::Worse;
1461
Douglas Gregor14046502008-10-23 00:40:37 +00001462 // C++ [over.ics.rank]p4b2:
1463 //
1464 // If class B is derived directly or indirectly from class A,
Douglas Gregor0e343382008-10-29 14:50:44 +00001465 // conversion of B* to A* is better than conversion of B* to
1466 // void*, and conversion of A* to void* is better than conversion
1467 // of B* to void*.
Douglas Gregor14046502008-10-23 00:40:37 +00001468 bool SCS1ConvertsToVoid
1469 = SCS1.isPointerConversionToVoidPointer(Context);
1470 bool SCS2ConvertsToVoid
1471 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregor0e343382008-10-29 14:50:44 +00001472 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1473 // Exactly one of the conversion sequences is a conversion to
1474 // a void pointer; it's the worse conversion.
Douglas Gregor14046502008-10-23 00:40:37 +00001475 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1476 : ImplicitConversionSequence::Worse;
Douglas Gregor0e343382008-10-29 14:50:44 +00001477 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1478 // Neither conversion sequence converts to a void pointer; compare
1479 // their derived-to-base conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001480 if (ImplicitConversionSequence::CompareKind DerivedCK
1481 = CompareDerivedToBaseConversions(SCS1, SCS2))
1482 return DerivedCK;
Douglas Gregor0e343382008-10-29 14:50:44 +00001483 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1484 // Both conversion sequences are conversions to void
1485 // pointers. Compare the source types to determine if there's an
1486 // inheritance relationship in their sources.
1487 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1488 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1489
1490 // Adjust the types we're converting from via the array-to-pointer
1491 // conversion, if we need to.
1492 if (SCS1.First == ICK_Array_To_Pointer)
1493 FromType1 = Context.getArrayDecayedType(FromType1);
1494 if (SCS2.First == ICK_Array_To_Pointer)
1495 FromType2 = Context.getArrayDecayedType(FromType2);
1496
1497 QualType FromPointee1
1498 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1499 QualType FromPointee2
1500 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1501
1502 if (IsDerivedFrom(FromPointee2, FromPointee1))
1503 return ImplicitConversionSequence::Better;
1504 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1505 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001506
1507 // Objective-C++: If one interface is more specific than the
1508 // other, it is the better one.
1509 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1510 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1511 if (FromIface1 && FromIface1) {
1512 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1513 return ImplicitConversionSequence::Better;
1514 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1515 return ImplicitConversionSequence::Worse;
1516 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001517 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001518
1519 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1520 // bullet 3).
Douglas Gregor14046502008-10-23 00:40:37 +00001521 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001522 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor14046502008-10-23 00:40:37 +00001523 return QualCK;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001524
Douglas Gregor0e343382008-10-29 14:50:44 +00001525 // C++ [over.ics.rank]p3b4:
1526 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1527 // which the references refer are the same type except for
1528 // top-level cv-qualifiers, and the type to which the reference
1529 // initialized by S2 refers is more cv-qualified than the type
1530 // to which the reference initialized by S1 refers.
1531 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1532 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1533 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1534 T1 = Context.getCanonicalType(T1);
1535 T2 = Context.getCanonicalType(T2);
1536 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1537 if (T2.isMoreQualifiedThan(T1))
1538 return ImplicitConversionSequence::Better;
1539 else if (T1.isMoreQualifiedThan(T2))
1540 return ImplicitConversionSequence::Worse;
1541 }
1542 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001543
1544 return ImplicitConversionSequence::Indistinguishable;
1545}
1546
1547/// CompareQualificationConversions - Compares two standard conversion
1548/// sequences to determine whether they can be ranked based on their
1549/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1550ImplicitConversionSequence::CompareKind
1551Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1552 const StandardConversionSequence& SCS2)
1553{
Douglas Gregor4459bbe2008-10-22 15:04:37 +00001554 // C++ 13.3.3.2p3:
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001555 // -- S1 and S2 differ only in their qualification conversion and
1556 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1557 // cv-qualification signature of type T1 is a proper subset of
1558 // the cv-qualification signature of type T2, and S1 is not the
1559 // deprecated string literal array-to-pointer conversion (4.2).
1560 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1561 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1562 return ImplicitConversionSequence::Indistinguishable;
1563
1564 // FIXME: the example in the standard doesn't use a qualification
1565 // conversion (!)
1566 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1567 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1568 T1 = Context.getCanonicalType(T1);
1569 T2 = Context.getCanonicalType(T2);
1570
1571 // If the types are the same, we won't learn anything by unwrapped
1572 // them.
1573 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1574 return ImplicitConversionSequence::Indistinguishable;
1575
1576 ImplicitConversionSequence::CompareKind Result
1577 = ImplicitConversionSequence::Indistinguishable;
1578 while (UnwrapSimilarPointerTypes(T1, T2)) {
1579 // Within each iteration of the loop, we check the qualifiers to
1580 // determine if this still looks like a qualification
1581 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001582 // pointers or pointers-to-members and do it all again
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001583 // until there are no more pointers or pointers-to-members left
1584 // to unwrap. This essentially mimics what
1585 // IsQualificationConversion does, but here we're checking for a
1586 // strict subset of qualifiers.
1587 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1588 // The qualifiers are the same, so this doesn't tell us anything
1589 // about how the sequences rank.
1590 ;
1591 else if (T2.isMoreQualifiedThan(T1)) {
1592 // T1 has fewer qualifiers, so it could be the better sequence.
1593 if (Result == ImplicitConversionSequence::Worse)
1594 // Neither has qualifiers that are a subset of the other's
1595 // qualifiers.
1596 return ImplicitConversionSequence::Indistinguishable;
1597
1598 Result = ImplicitConversionSequence::Better;
1599 } else if (T1.isMoreQualifiedThan(T2)) {
1600 // T2 has fewer qualifiers, so it could be the better sequence.
1601 if (Result == ImplicitConversionSequence::Better)
1602 // Neither has qualifiers that are a subset of the other's
1603 // qualifiers.
1604 return ImplicitConversionSequence::Indistinguishable;
1605
1606 Result = ImplicitConversionSequence::Worse;
1607 } else {
1608 // Qualifiers are disjoint.
1609 return ImplicitConversionSequence::Indistinguishable;
1610 }
1611
1612 // If the types after this point are equivalent, we're done.
1613 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1614 break;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001615 }
1616
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001617 // Check that the winning standard conversion sequence isn't using
1618 // the deprecated string literal array to pointer conversion.
1619 switch (Result) {
1620 case ImplicitConversionSequence::Better:
1621 if (SCS1.Deprecated)
1622 Result = ImplicitConversionSequence::Indistinguishable;
1623 break;
1624
1625 case ImplicitConversionSequence::Indistinguishable:
1626 break;
1627
1628 case ImplicitConversionSequence::Worse:
1629 if (SCS2.Deprecated)
1630 Result = ImplicitConversionSequence::Indistinguishable;
1631 break;
1632 }
1633
1634 return Result;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001635}
1636
Douglas Gregor14046502008-10-23 00:40:37 +00001637/// CompareDerivedToBaseConversions - Compares two standard conversion
1638/// sequences to determine whether they can be ranked based on their
Douglas Gregor24a90a52008-11-26 23:31:11 +00001639/// various kinds of derived-to-base conversions (C++
1640/// [over.ics.rank]p4b3). As part of these checks, we also look at
1641/// conversions between Objective-C interface types.
Douglas Gregor14046502008-10-23 00:40:37 +00001642ImplicitConversionSequence::CompareKind
1643Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1644 const StandardConversionSequence& SCS2) {
1645 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1646 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1647 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1648 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1649
1650 // Adjust the types we're converting from via the array-to-pointer
1651 // conversion, if we need to.
1652 if (SCS1.First == ICK_Array_To_Pointer)
1653 FromType1 = Context.getArrayDecayedType(FromType1);
1654 if (SCS2.First == ICK_Array_To_Pointer)
1655 FromType2 = Context.getArrayDecayedType(FromType2);
1656
1657 // Canonicalize all of the types.
1658 FromType1 = Context.getCanonicalType(FromType1);
1659 ToType1 = Context.getCanonicalType(ToType1);
1660 FromType2 = Context.getCanonicalType(FromType2);
1661 ToType2 = Context.getCanonicalType(ToType2);
1662
Douglas Gregor0e343382008-10-29 14:50:44 +00001663 // C++ [over.ics.rank]p4b3:
Douglas Gregor14046502008-10-23 00:40:37 +00001664 //
1665 // If class B is derived directly or indirectly from class A and
1666 // class C is derived directly or indirectly from B,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001667 //
1668 // For Objective-C, we let A, B, and C also be Objective-C
1669 // interfaces.
Douglas Gregor0e343382008-10-29 14:50:44 +00001670
1671 // Compare based on pointer conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001672 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor3f5a00c2008-11-27 01:19:21 +00001673 SCS2.Second == ICK_Pointer_Conversion &&
1674 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1675 FromType1->isPointerType() && FromType2->isPointerType() &&
1676 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregor14046502008-10-23 00:40:37 +00001677 QualType FromPointee1
1678 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1679 QualType ToPointee1
1680 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1681 QualType FromPointee2
1682 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1683 QualType ToPointee2
1684 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregor24a90a52008-11-26 23:31:11 +00001685
1686 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1687 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1688 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1689 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1690
Douglas Gregor0e343382008-10-29 14:50:44 +00001691 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor14046502008-10-23 00:40:37 +00001692 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1693 if (IsDerivedFrom(ToPointee1, ToPointee2))
1694 return ImplicitConversionSequence::Better;
1695 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1696 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001697
1698 if (ToIface1 && ToIface2) {
1699 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1700 return ImplicitConversionSequence::Better;
1701 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1702 return ImplicitConversionSequence::Worse;
1703 }
Douglas Gregor14046502008-10-23 00:40:37 +00001704 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001705
1706 // -- conversion of B* to A* is better than conversion of C* to A*,
1707 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1708 if (IsDerivedFrom(FromPointee2, FromPointee1))
1709 return ImplicitConversionSequence::Better;
1710 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1711 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001712
1713 if (FromIface1 && FromIface2) {
1714 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1715 return ImplicitConversionSequence::Better;
1716 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1717 return ImplicitConversionSequence::Worse;
1718 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001719 }
Douglas Gregor14046502008-10-23 00:40:37 +00001720 }
1721
Douglas Gregor0e343382008-10-29 14:50:44 +00001722 // Compare based on reference bindings.
1723 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1724 SCS1.Second == ICK_Derived_To_Base) {
1725 // -- binding of an expression of type C to a reference of type
1726 // B& is better than binding an expression of type C to a
1727 // reference of type A&,
1728 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1729 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1730 if (IsDerivedFrom(ToType1, ToType2))
1731 return ImplicitConversionSequence::Better;
1732 else if (IsDerivedFrom(ToType2, ToType1))
1733 return ImplicitConversionSequence::Worse;
1734 }
1735
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001736 // -- binding of an expression of type B to a reference of type
1737 // A& is better than binding an expression of type C to a
1738 // reference of type A&,
Douglas Gregor0e343382008-10-29 14:50:44 +00001739 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1740 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1741 if (IsDerivedFrom(FromType2, FromType1))
1742 return ImplicitConversionSequence::Better;
1743 else if (IsDerivedFrom(FromType1, FromType2))
1744 return ImplicitConversionSequence::Worse;
1745 }
1746 }
1747
1748
1749 // FIXME: conversion of A::* to B::* is better than conversion of
1750 // A::* to C::*,
1751
1752 // FIXME: conversion of B::* to C::* is better than conversion of
1753 // A::* to C::*, and
1754
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001755 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1756 SCS1.Second == ICK_Derived_To_Base) {
1757 // -- conversion of C to B is better than conversion of C to A,
1758 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1759 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1760 if (IsDerivedFrom(ToType1, ToType2))
1761 return ImplicitConversionSequence::Better;
1762 else if (IsDerivedFrom(ToType2, ToType1))
1763 return ImplicitConversionSequence::Worse;
1764 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001765
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001766 // -- conversion of B to A is better than conversion of C to A.
1767 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1768 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1769 if (IsDerivedFrom(FromType2, FromType1))
1770 return ImplicitConversionSequence::Better;
1771 else if (IsDerivedFrom(FromType1, FromType2))
1772 return ImplicitConversionSequence::Worse;
1773 }
1774 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001775
Douglas Gregor14046502008-10-23 00:40:37 +00001776 return ImplicitConversionSequence::Indistinguishable;
1777}
1778
Douglas Gregor81c29152008-10-29 00:13:59 +00001779/// TryCopyInitialization - Try to copy-initialize a value of type
1780/// ToType from the expression From. Return the implicit conversion
1781/// sequence required to pass this argument, which may be a bad
1782/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001783/// a parameter of this type). If @p SuppressUserConversions, then we
1784/// do not permit any user-defined conversion sequences.
Douglas Gregor81c29152008-10-29 00:13:59 +00001785ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001786Sema::TryCopyInitialization(Expr *From, QualType ToType,
1787 bool SuppressUserConversions) {
Douglas Gregorfcb19192009-02-11 23:02:49 +00001788 if (ToType->isReferenceType()) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001789 ImplicitConversionSequence ICS;
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001790 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions);
Douglas Gregor81c29152008-10-29 00:13:59 +00001791 return ICS;
1792 } else {
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001793 return TryImplicitConversion(From, ToType, SuppressUserConversions);
Douglas Gregor81c29152008-10-29 00:13:59 +00001794 }
1795}
1796
1797/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1798/// type ToType. Returns true (and emits a diagnostic) if there was
1799/// an error, returns false if the initialization succeeded.
1800bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1801 const char* Flavor) {
1802 if (!getLangOptions().CPlusPlus) {
1803 // In C, argument passing is the same as performing an assignment.
1804 QualType FromType = From->getType();
1805 AssignConvertType ConvTy =
1806 CheckSingleAssignmentConstraints(ToType, From);
1807
1808 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1809 FromType, From, Flavor);
Douglas Gregor81c29152008-10-29 00:13:59 +00001810 }
Chris Lattner271d4c22008-11-24 05:29:24 +00001811
1812 if (ToType->isReferenceType())
1813 return CheckReferenceInit(From, ToType);
1814
Douglas Gregor6fd35572008-12-19 17:40:08 +00001815 if (!PerformImplicitConversion(From, ToType, Flavor))
Chris Lattner271d4c22008-11-24 05:29:24 +00001816 return false;
1817
1818 return Diag(From->getSourceRange().getBegin(),
1819 diag::err_typecheck_convert_incompatible)
1820 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001821}
1822
Douglas Gregor5ed15042008-11-18 23:14:02 +00001823/// TryObjectArgumentInitialization - Try to initialize the object
1824/// parameter of the given member function (@c Method) from the
1825/// expression @p From.
1826ImplicitConversionSequence
1827Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1828 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1829 unsigned MethodQuals = Method->getTypeQualifiers();
1830 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1831
1832 // Set up the conversion sequence as a "bad" conversion, to allow us
1833 // to exit early.
1834 ImplicitConversionSequence ICS;
1835 ICS.Standard.setAsIdentityConversion();
1836 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1837
1838 // We need to have an object of class type.
1839 QualType FromType = From->getType();
1840 if (!FromType->isRecordType())
1841 return ICS;
1842
1843 // The implicit object parmeter is has the type "reference to cv X",
1844 // where X is the class of which the function is a member
1845 // (C++ [over.match.funcs]p4). However, when finding an implicit
1846 // conversion sequence for the argument, we are not allowed to
1847 // create temporaries or perform user-defined conversions
1848 // (C++ [over.match.funcs]p5). We perform a simplified version of
1849 // reference binding here, that allows class rvalues to bind to
1850 // non-constant references.
1851
1852 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1853 // with the implicit object parameter (C++ [over.match.funcs]p5).
1854 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1855 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1856 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1857 return ICS;
1858
1859 // Check that we have either the same type or a derived type. It
1860 // affects the conversion rank.
1861 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1862 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1863 ICS.Standard.Second = ICK_Identity;
1864 else if (IsDerivedFrom(FromType, ClassType))
1865 ICS.Standard.Second = ICK_Derived_To_Base;
1866 else
1867 return ICS;
1868
1869 // Success. Mark this as a reference binding.
1870 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1871 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1872 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1873 ICS.Standard.ReferenceBinding = true;
1874 ICS.Standard.DirectBinding = true;
1875 return ICS;
1876}
1877
1878/// PerformObjectArgumentInitialization - Perform initialization of
1879/// the implicit object parameter for the given Method with the given
1880/// expression.
1881bool
1882Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
1883 QualType ImplicitParamType
1884 = Method->getThisType(Context)->getAsPointerType()->getPointeeType();
1885 ImplicitConversionSequence ICS
1886 = TryObjectArgumentInitialization(From, Method);
1887 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
1888 return Diag(From->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001889 diag::err_implicit_object_parameter_init)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001890 << ImplicitParamType << From->getType() << From->getSourceRange();
Douglas Gregor5ed15042008-11-18 23:14:02 +00001891
1892 if (ICS.Standard.Second == ICK_Derived_To_Base &&
1893 CheckDerivedToBaseConversion(From->getType(), ImplicitParamType,
1894 From->getSourceRange().getBegin(),
1895 From->getSourceRange()))
1896 return true;
1897
1898 ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true);
1899 return false;
1900}
1901
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001902/// TryContextuallyConvertToBool - Attempt to contextually convert the
1903/// expression From to bool (C++0x [conv]p3).
1904ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
1905 return TryImplicitConversion(From, Context.BoolTy, false, true);
1906}
1907
1908/// PerformContextuallyConvertToBool - Perform a contextual conversion
1909/// of the expression From to bool (C++0x [conv]p3).
1910bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
1911 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
1912 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
1913 return false;
1914
1915 return Diag(From->getSourceRange().getBegin(),
1916 diag::err_typecheck_bool_condition)
1917 << From->getType() << From->getSourceRange();
1918}
1919
Douglas Gregord2baafd2008-10-21 16:13:35 +00001920/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001921/// candidate functions, using the given function call arguments. If
1922/// @p SuppressUserConversions, then don't allow user-defined
1923/// conversions via constructors or conversion operators.
Douglas Gregord2baafd2008-10-21 16:13:35 +00001924void
1925Sema::AddOverloadCandidate(FunctionDecl *Function,
1926 Expr **Args, unsigned NumArgs,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001927 OverloadCandidateSet& CandidateSet,
1928 bool SuppressUserConversions)
Douglas Gregord2baafd2008-10-21 16:13:35 +00001929{
1930 const FunctionTypeProto* Proto
1931 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType());
1932 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregor60714f92008-11-07 22:36:19 +00001933 assert(!isa<CXXConversionDecl>(Function) &&
1934 "Use AddConversionCandidate for conversion functions");
Douglas Gregord2baafd2008-10-21 16:13:35 +00001935
Douglas Gregor3257fb52008-12-22 05:46:06 +00001936 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
1937 // If we get here, it's because we're calling a member function
1938 // that is named without a member access expression (e.g.,
1939 // "this->f") that was either written explicitly or created
1940 // implicitly. This can happen with a qualified call to a member
1941 // function, e.g., X::f(). We use a NULL object as the implied
1942 // object argument (C++ [over.call.func]p3).
1943 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
1944 SuppressUserConversions);
1945 return;
1946 }
1947
1948
Douglas Gregord2baafd2008-10-21 16:13:35 +00001949 // Add this candidate
1950 CandidateSet.push_back(OverloadCandidate());
1951 OverloadCandidate& Candidate = CandidateSet.back();
1952 Candidate.Function = Function;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001953 Candidate.Viable = true;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00001954 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001955 Candidate.IgnoreObjectArgument = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001956
1957 unsigned NumArgsInProto = Proto->getNumArgs();
1958
1959 // (C++ 13.3.2p2): A candidate function having fewer than m
1960 // parameters is viable only if it has an ellipsis in its parameter
1961 // list (8.3.5).
1962 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1963 Candidate.Viable = false;
1964 return;
1965 }
1966
1967 // (C++ 13.3.2p2): A candidate function having more than m parameters
1968 // is viable only if the (m+1)st parameter has a default argument
1969 // (8.3.6). For the purposes of overload resolution, the
1970 // parameter list is truncated on the right, so that there are
1971 // exactly m parameters.
1972 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
1973 if (NumArgs < MinRequiredArgs) {
1974 // Not enough arguments.
1975 Candidate.Viable = false;
1976 return;
1977 }
1978
1979 // Determine the implicit conversion sequences for each of the
1980 // arguments.
Douglas Gregord2baafd2008-10-21 16:13:35 +00001981 Candidate.Conversions.resize(NumArgs);
1982 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1983 if (ArgIdx < NumArgsInProto) {
1984 // (C++ 13.3.2p3): for F to be a viable function, there shall
1985 // exist for each argument an implicit conversion sequence
1986 // (13.3.3.1) that converts that argument to the corresponding
1987 // parameter of F.
1988 QualType ParamType = Proto->getArgType(ArgIdx);
1989 Candidate.Conversions[ArgIdx]
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001990 = TryCopyInitialization(Args[ArgIdx], ParamType,
1991 SuppressUserConversions);
Douglas Gregord2baafd2008-10-21 16:13:35 +00001992 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00001993 == ImplicitConversionSequence::BadConversion) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00001994 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00001995 break;
1996 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001997 } else {
1998 // (C++ 13.3.2p2): For the purposes of overload resolution, any
1999 // argument for which there is no corresponding parameter is
2000 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2001 Candidate.Conversions[ArgIdx].ConversionKind
2002 = ImplicitConversionSequence::EllipsisConversion;
2003 }
2004 }
2005}
2006
Douglas Gregor5ed15042008-11-18 23:14:02 +00002007/// AddMethodCandidate - Adds the given C++ member function to the set
2008/// of candidate functions, using the given function call arguments
2009/// and the object argument (@c Object). For example, in a call
2010/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2011/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2012/// allow user-defined conversions via constructors or conversion
2013/// operators.
2014void
2015Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2016 Expr **Args, unsigned NumArgs,
2017 OverloadCandidateSet& CandidateSet,
2018 bool SuppressUserConversions)
2019{
2020 const FunctionTypeProto* Proto
2021 = dyn_cast<FunctionTypeProto>(Method->getType()->getAsFunctionType());
2022 assert(Proto && "Methods without a prototype cannot be overloaded");
2023 assert(!isa<CXXConversionDecl>(Method) &&
2024 "Use AddConversionCandidate for conversion functions");
2025
2026 // Add this candidate
2027 CandidateSet.push_back(OverloadCandidate());
2028 OverloadCandidate& Candidate = CandidateSet.back();
2029 Candidate.Function = Method;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002030 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002031 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +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 = Method->getMinRequiredArguments();
2049 if (NumArgs < MinRequiredArgs) {
2050 // Not enough arguments.
2051 Candidate.Viable = false;
2052 return;
2053 }
2054
2055 Candidate.Viable = true;
2056 Candidate.Conversions.resize(NumArgs + 1);
2057
Douglas Gregor3257fb52008-12-22 05:46:06 +00002058 if (Method->isStatic() || !Object)
2059 // The implicit object argument is ignored.
2060 Candidate.IgnoreObjectArgument = true;
2061 else {
2062 // Determine the implicit conversion sequence for the object
2063 // parameter.
2064 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2065 if (Candidate.Conversions[0].ConversionKind
2066 == ImplicitConversionSequence::BadConversion) {
2067 Candidate.Viable = false;
2068 return;
2069 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002070 }
2071
2072 // Determine the implicit conversion sequences for each of the
2073 // arguments.
2074 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2075 if (ArgIdx < NumArgsInProto) {
2076 // (C++ 13.3.2p3): for F to be a viable function, there shall
2077 // exist for each argument an implicit conversion sequence
2078 // (13.3.3.1) that converts that argument to the corresponding
2079 // parameter of F.
2080 QualType ParamType = Proto->getArgType(ArgIdx);
2081 Candidate.Conversions[ArgIdx + 1]
2082 = TryCopyInitialization(Args[ArgIdx], ParamType,
2083 SuppressUserConversions);
2084 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2085 == ImplicitConversionSequence::BadConversion) {
2086 Candidate.Viable = false;
2087 break;
2088 }
2089 } else {
2090 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2091 // argument for which there is no corresponding parameter is
2092 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2093 Candidate.Conversions[ArgIdx + 1].ConversionKind
2094 = ImplicitConversionSequence::EllipsisConversion;
2095 }
2096 }
2097}
2098
Douglas Gregor60714f92008-11-07 22:36:19 +00002099/// AddConversionCandidate - Add a C++ conversion function as a
2100/// candidate in the candidate set (C++ [over.match.conv],
2101/// C++ [over.match.copy]). From is the expression we're converting from,
2102/// and ToType is the type that we're eventually trying to convert to
2103/// (which may or may not be the same type as the type that the
2104/// conversion function produces).
2105void
2106Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2107 Expr *From, QualType ToType,
2108 OverloadCandidateSet& CandidateSet) {
2109 // Add this candidate
2110 CandidateSet.push_back(OverloadCandidate());
2111 OverloadCandidate& Candidate = CandidateSet.back();
2112 Candidate.Function = Conversion;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002113 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002114 Candidate.IgnoreObjectArgument = false;
Douglas Gregor60714f92008-11-07 22:36:19 +00002115 Candidate.FinalConversion.setAsIdentityConversion();
2116 Candidate.FinalConversion.FromTypePtr
2117 = Conversion->getConversionType().getAsOpaquePtr();
2118 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2119
Douglas Gregor5ed15042008-11-18 23:14:02 +00002120 // Determine the implicit conversion sequence for the implicit
2121 // object parameter.
Douglas Gregor60714f92008-11-07 22:36:19 +00002122 Candidate.Viable = true;
2123 Candidate.Conversions.resize(1);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002124 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregor60714f92008-11-07 22:36:19 +00002125
Douglas Gregor60714f92008-11-07 22:36:19 +00002126 if (Candidate.Conversions[0].ConversionKind
2127 == ImplicitConversionSequence::BadConversion) {
2128 Candidate.Viable = false;
2129 return;
2130 }
2131
2132 // To determine what the conversion from the result of calling the
2133 // conversion function to the type we're eventually trying to
2134 // convert to (ToType), we need to synthesize a call to the
2135 // conversion function and attempt copy initialization from it. This
2136 // makes sure that we get the right semantics with respect to
2137 // lvalues/rvalues and the type. Fortunately, we can allocate this
2138 // call on the stack and we don't need its arguments to be
2139 // well-formed.
2140 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2141 SourceLocation());
2142 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregor70d26122008-11-12 17:17:38 +00002143 &ConversionRef, false);
Ted Kremenek362abcd2009-02-09 20:51:47 +00002144
2145 // Note that it is safe to allocate CallExpr on the stack here because
2146 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2147 // allocator).
2148 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregor60714f92008-11-07 22:36:19 +00002149 Conversion->getConversionType().getNonReferenceType(),
2150 SourceLocation());
2151 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2152 switch (ICS.ConversionKind) {
2153 case ImplicitConversionSequence::StandardConversion:
2154 Candidate.FinalConversion = ICS.Standard;
2155 break;
2156
2157 case ImplicitConversionSequence::BadConversion:
2158 Candidate.Viable = false;
2159 break;
2160
2161 default:
2162 assert(false &&
2163 "Can only end up with a standard conversion sequence or failure");
2164 }
2165}
2166
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002167/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2168/// converts the given @c Object to a function pointer via the
2169/// conversion function @c Conversion, and then attempts to call it
2170/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2171/// the type of function that we'll eventually be calling.
2172void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
2173 const FunctionTypeProto *Proto,
2174 Expr *Object, Expr **Args, unsigned NumArgs,
2175 OverloadCandidateSet& CandidateSet) {
2176 CandidateSet.push_back(OverloadCandidate());
2177 OverloadCandidate& Candidate = CandidateSet.back();
2178 Candidate.Function = 0;
2179 Candidate.Surrogate = Conversion;
2180 Candidate.Viable = true;
2181 Candidate.IsSurrogate = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002182 Candidate.IgnoreObjectArgument = false;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002183 Candidate.Conversions.resize(NumArgs + 1);
2184
2185 // Determine the implicit conversion sequence for the implicit
2186 // object parameter.
2187 ImplicitConversionSequence ObjectInit
2188 = TryObjectArgumentInitialization(Object, Conversion);
2189 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2190 Candidate.Viable = false;
2191 return;
2192 }
2193
2194 // The first conversion is actually a user-defined conversion whose
2195 // first conversion is ObjectInit's standard conversion (which is
2196 // effectively a reference binding). Record it as such.
2197 Candidate.Conversions[0].ConversionKind
2198 = ImplicitConversionSequence::UserDefinedConversion;
2199 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2200 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2201 Candidate.Conversions[0].UserDefined.After
2202 = Candidate.Conversions[0].UserDefined.Before;
2203 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2204
2205 // Find the
2206 unsigned NumArgsInProto = Proto->getNumArgs();
2207
2208 // (C++ 13.3.2p2): A candidate function having fewer than m
2209 // parameters is viable only if it has an ellipsis in its parameter
2210 // list (8.3.5).
2211 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2212 Candidate.Viable = false;
2213 return;
2214 }
2215
2216 // Function types don't have any default arguments, so just check if
2217 // we have enough arguments.
2218 if (NumArgs < NumArgsInProto) {
2219 // Not enough arguments.
2220 Candidate.Viable = false;
2221 return;
2222 }
2223
2224 // Determine the implicit conversion sequences for each of the
2225 // arguments.
2226 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2227 if (ArgIdx < NumArgsInProto) {
2228 // (C++ 13.3.2p3): for F to be a viable function, there shall
2229 // exist for each argument an implicit conversion sequence
2230 // (13.3.3.1) that converts that argument to the corresponding
2231 // parameter of F.
2232 QualType ParamType = Proto->getArgType(ArgIdx);
2233 Candidate.Conversions[ArgIdx + 1]
2234 = TryCopyInitialization(Args[ArgIdx], ParamType,
2235 /*SuppressUserConversions=*/false);
2236 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2237 == ImplicitConversionSequence::BadConversion) {
2238 Candidate.Viable = false;
2239 break;
2240 }
2241 } else {
2242 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2243 // argument for which there is no corresponding parameter is
2244 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2245 Candidate.Conversions[ArgIdx + 1].ConversionKind
2246 = ImplicitConversionSequence::EllipsisConversion;
2247 }
2248 }
2249}
2250
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002251/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2252/// an acceptable non-member overloaded operator for a call whose
2253/// arguments have types T1 (and, if non-empty, T2). This routine
2254/// implements the check in C++ [over.match.oper]p3b2 concerning
2255/// enumeration types.
2256static bool
2257IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2258 QualType T1, QualType T2,
2259 ASTContext &Context) {
2260 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2261 return true;
2262
2263 const FunctionTypeProto *Proto = Fn->getType()->getAsFunctionTypeProto();
2264 if (Proto->getNumArgs() < 1)
2265 return false;
2266
2267 if (T1->isEnumeralType()) {
2268 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
2269 if (Context.getCanonicalType(T1).getUnqualifiedType()
2270 == Context.getCanonicalType(ArgType).getUnqualifiedType())
2271 return true;
2272 }
2273
2274 if (Proto->getNumArgs() < 2)
2275 return false;
2276
2277 if (!T2.isNull() && T2->isEnumeralType()) {
2278 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
2279 if (Context.getCanonicalType(T2).getUnqualifiedType()
2280 == Context.getCanonicalType(ArgType).getUnqualifiedType())
2281 return true;
2282 }
2283
2284 return false;
2285}
2286
Douglas Gregor5ed15042008-11-18 23:14:02 +00002287/// AddOperatorCandidates - Add the overloaded operator candidates for
2288/// the operator Op that was used in an operator expression such as "x
2289/// Op y". S is the scope in which the expression occurred (used for
2290/// name lookup of the operator), Args/NumArgs provides the operator
2291/// arguments, and CandidateSet will store the added overload
2292/// candidates. (C++ [over.match.oper]).
Douglas Gregor48a87322009-02-04 16:44:47 +00002293bool Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
2294 SourceLocation OpLoc,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002295 Expr **Args, unsigned NumArgs,
Douglas Gregor48a87322009-02-04 16:44:47 +00002296 OverloadCandidateSet& CandidateSet,
2297 SourceRange OpRange) {
Douglas Gregor5ed15042008-11-18 23:14:02 +00002298 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2299
2300 // C++ [over.match.oper]p3:
2301 // For a unary operator @ with an operand of a type whose
2302 // cv-unqualified version is T1, and for a binary operator @ with
2303 // a left operand of a type whose cv-unqualified version is T1 and
2304 // a right operand of a type whose cv-unqualified version is T2,
2305 // three sets of candidate functions, designated member
2306 // candidates, non-member candidates and built-in candidates, are
2307 // constructed as follows:
2308 QualType T1 = Args[0]->getType();
2309 QualType T2;
2310 if (NumArgs > 1)
2311 T2 = Args[1]->getType();
2312
2313 // -- If T1 is a class type, the set of member candidates is the
2314 // result of the qualified lookup of T1::operator@
2315 // (13.3.1.1.1); otherwise, the set of member candidates is
2316 // empty.
2317 if (const RecordType *T1Rec = T1->getAsRecordType()) {
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002318 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroffab63fd62009-01-08 17:28:14 +00002319 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002320 Oper != OperEnd; ++Oper)
2321 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2322 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002323 /*SuppressUserConversions=*/false);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002324 }
2325
2326 // -- The set of non-member candidates is the result of the
2327 // unqualified lookup of operator@ in the context of the
2328 // expression according to the usual rules for name lookup in
2329 // unqualified function calls (3.4.2) except that all member
2330 // functions are ignored. However, if no operand has a class
2331 // type, only those non-member functions in the lookup set
2332 // that have a first parameter of type T1 or “reference to
2333 // (possibly cv-qualified) T1”, when T1 is an enumeration
2334 // type, or (if there is a right operand) a second parameter
2335 // of type T2 or “reference to (possibly cv-qualified) T2”,
2336 // when T2 is an enumeration type, are candidate functions.
Douglas Gregor48a87322009-02-04 16:44:47 +00002337 LookupResult Operators = LookupName(S, OpName, LookupOperatorName);
2338
2339 if (Operators.isAmbiguous())
2340 return DiagnoseAmbiguousLookup(Operators, OpName, OpLoc, OpRange);
2341 else if (Operators) {
2342 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2343 Op != OpEnd; ++Op) {
2344 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op))
2345 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
2346 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2347 /*SuppressUserConversions=*/false);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002348 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002349 }
2350
Douglas Gregor48a87322009-02-04 16:44:47 +00002351 // Since the set of non-member candidates corresponds to
2352 // *unqualified* lookup of the operator name, we also perform
2353 // argument-dependent lookup (C++ [basic.lookup.argdep]).
2354 AddArgumentDependentLookupCandidates(OpName, Args, NumArgs, CandidateSet);
2355
Douglas Gregor5ed15042008-11-18 23:14:02 +00002356 // Add builtin overload candidates (C++ [over.built]).
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002357 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
Douglas Gregor48a87322009-02-04 16:44:47 +00002358
2359 return false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002360}
2361
Douglas Gregor70d26122008-11-12 17:17:38 +00002362/// AddBuiltinCandidate - Add a candidate for a built-in
2363/// operator. ResultTy and ParamTys are the result and parameter types
2364/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorab141112009-01-13 00:52:54 +00002365/// arguments being passed to the candidate. IsAssignmentOperator
2366/// should be true when this built-in candidate is an assignment
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002367/// operator. NumContextualBoolArguments is the number of arguments
2368/// (at the beginning of the argument list) that will be contextually
2369/// converted to bool.
Douglas Gregor70d26122008-11-12 17:17:38 +00002370void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2371 Expr **Args, unsigned NumArgs,
Douglas Gregorab141112009-01-13 00:52:54 +00002372 OverloadCandidateSet& CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002373 bool IsAssignmentOperator,
2374 unsigned NumContextualBoolArguments) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002375 // Add this candidate
2376 CandidateSet.push_back(OverloadCandidate());
2377 OverloadCandidate& Candidate = CandidateSet.back();
2378 Candidate.Function = 0;
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00002379 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002380 Candidate.IgnoreObjectArgument = false;
Douglas Gregor70d26122008-11-12 17:17:38 +00002381 Candidate.BuiltinTypes.ResultTy = ResultTy;
2382 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2383 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2384
2385 // Determine the implicit conversion sequences for each of the
2386 // arguments.
2387 Candidate.Viable = true;
2388 Candidate.Conversions.resize(NumArgs);
2389 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorab141112009-01-13 00:52:54 +00002390 // C++ [over.match.oper]p4:
2391 // For the built-in assignment operators, conversions of the
2392 // left operand are restricted as follows:
2393 // -- no temporaries are introduced to hold the left operand, and
2394 // -- no user-defined conversions are applied to the left
2395 // operand to achieve a type match with the left-most
2396 // parameter of a built-in candidate.
2397 //
2398 // We block these conversions by turning off user-defined
2399 // conversions, since that is the only way that initialization of
2400 // a reference to a non-class type can occur from something that
2401 // is not of the same type.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002402 if (ArgIdx < NumContextualBoolArguments) {
2403 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2404 "Contextual conversion to bool requires bool type");
2405 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2406 } else {
2407 Candidate.Conversions[ArgIdx]
2408 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2409 ArgIdx == 0 && IsAssignmentOperator);
2410 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002411 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002412 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002413 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002414 break;
2415 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002416 }
2417}
2418
2419/// BuiltinCandidateTypeSet - A set of types that will be used for the
2420/// candidate operator functions for built-in operators (C++
2421/// [over.built]). The types are separated into pointer types and
2422/// enumeration types.
2423class BuiltinCandidateTypeSet {
2424 /// TypeSet - A set of types.
Douglas Gregor3d4492e2008-11-13 20:12:29 +00002425 typedef llvm::SmallPtrSet<void*, 8> TypeSet;
Douglas Gregor70d26122008-11-12 17:17:38 +00002426
2427 /// PointerTypes - The set of pointer types that will be used in the
2428 /// built-in candidates.
2429 TypeSet PointerTypes;
2430
2431 /// EnumerationTypes - The set of enumeration types that will be
2432 /// used in the built-in candidates.
2433 TypeSet EnumerationTypes;
2434
2435 /// Context - The AST context in which we will build the type sets.
2436 ASTContext &Context;
2437
2438 bool AddWithMoreQualifiedTypeVariants(QualType Ty);
2439
2440public:
2441 /// iterator - Iterates through the types that are part of the set.
Douglas Gregor3d4492e2008-11-13 20:12:29 +00002442 class iterator {
2443 TypeSet::iterator Base;
2444
2445 public:
2446 typedef QualType value_type;
2447 typedef QualType reference;
2448 typedef QualType pointer;
2449 typedef std::ptrdiff_t difference_type;
2450 typedef std::input_iterator_tag iterator_category;
2451
2452 iterator(TypeSet::iterator B) : Base(B) { }
2453
2454 iterator& operator++() {
2455 ++Base;
2456 return *this;
2457 }
2458
2459 iterator operator++(int) {
2460 iterator tmp(*this);
2461 ++(*this);
2462 return tmp;
2463 }
2464
2465 reference operator*() const {
2466 return QualType::getFromOpaquePtr(*Base);
2467 }
2468
2469 pointer operator->() const {
2470 return **this;
2471 }
2472
2473 friend bool operator==(iterator LHS, iterator RHS) {
2474 return LHS.Base == RHS.Base;
2475 }
2476
2477 friend bool operator!=(iterator LHS, iterator RHS) {
2478 return LHS.Base != RHS.Base;
2479 }
2480 };
Douglas Gregor70d26122008-11-12 17:17:38 +00002481
2482 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2483
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002484 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2485 bool AllowExplicitConversions);
Douglas Gregor70d26122008-11-12 17:17:38 +00002486
2487 /// pointer_begin - First pointer type found;
2488 iterator pointer_begin() { return PointerTypes.begin(); }
2489
2490 /// pointer_end - Last pointer type found;
2491 iterator pointer_end() { return PointerTypes.end(); }
2492
2493 /// enumeration_begin - First enumeration type found;
2494 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2495
2496 /// enumeration_end - Last enumeration type found;
2497 iterator enumeration_end() { return EnumerationTypes.end(); }
2498};
2499
2500/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2501/// the set of pointer types along with any more-qualified variants of
2502/// that type. For example, if @p Ty is "int const *", this routine
2503/// will add "int const *", "int const volatile *", "int const
2504/// restrict *", and "int const volatile restrict *" to the set of
2505/// pointer types. Returns true if the add of @p Ty itself succeeded,
2506/// false otherwise.
2507bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) {
2508 // Insert this type.
Douglas Gregor3d4492e2008-11-13 20:12:29 +00002509 if (!PointerTypes.insert(Ty.getAsOpaquePtr()))
Douglas Gregor70d26122008-11-12 17:17:38 +00002510 return false;
2511
2512 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2513 QualType PointeeTy = PointerTy->getPointeeType();
2514 // FIXME: Optimize this so that we don't keep trying to add the same types.
2515
2516 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
2517 // with all pointer conversions that don't cast away constness?
2518 if (!PointeeTy.isConstQualified())
2519 AddWithMoreQualifiedTypeVariants
2520 (Context.getPointerType(PointeeTy.withConst()));
2521 if (!PointeeTy.isVolatileQualified())
2522 AddWithMoreQualifiedTypeVariants
2523 (Context.getPointerType(PointeeTy.withVolatile()));
2524 if (!PointeeTy.isRestrictQualified())
2525 AddWithMoreQualifiedTypeVariants
2526 (Context.getPointerType(PointeeTy.withRestrict()));
2527 }
2528
2529 return true;
2530}
2531
2532/// AddTypesConvertedFrom - Add each of the types to which the type @p
2533/// Ty can be implicit converted to the given set of @p Types. We're
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002534/// primarily interested in pointer types and enumeration types.
2535/// AllowUserConversions is true if we should look at the conversion
2536/// functions of a class type, and AllowExplicitConversions if we
2537/// should also include the explicit conversion functions of a class
2538/// type.
2539void
2540BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2541 bool AllowUserConversions,
2542 bool AllowExplicitConversions) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002543 // Only deal with canonical types.
2544 Ty = Context.getCanonicalType(Ty);
2545
2546 // Look through reference types; they aren't part of the type of an
2547 // expression for the purposes of conversions.
2548 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2549 Ty = RefTy->getPointeeType();
2550
2551 // We don't care about qualifiers on the type.
2552 Ty = Ty.getUnqualifiedType();
2553
2554 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2555 QualType PointeeTy = PointerTy->getPointeeType();
2556
2557 // Insert our type, and its more-qualified variants, into the set
2558 // of types.
2559 if (!AddWithMoreQualifiedTypeVariants(Ty))
2560 return;
2561
2562 // Add 'cv void*' to our set of types.
2563 if (!Ty->isVoidType()) {
2564 QualType QualVoid
2565 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2566 AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2567 }
2568
2569 // If this is a pointer to a class type, add pointers to its bases
2570 // (with the same level of cv-qualification as the original
2571 // derived class, of course).
2572 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2573 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2574 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2575 Base != ClassDecl->bases_end(); ++Base) {
2576 QualType BaseTy = Context.getCanonicalType(Base->getType());
2577 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2578
2579 // Add the pointer type, recursively, so that we get all of
2580 // the indirect base classes, too.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002581 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002582 }
2583 }
2584 } else if (Ty->isEnumeralType()) {
Douglas Gregor3d4492e2008-11-13 20:12:29 +00002585 EnumerationTypes.insert(Ty.getAsOpaquePtr());
Douglas Gregor70d26122008-11-12 17:17:38 +00002586 } else if (AllowUserConversions) {
2587 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2588 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2589 // FIXME: Visit conversion functions in the base classes, too.
2590 OverloadedFunctionDecl *Conversions
2591 = ClassDecl->getConversionFunctions();
2592 for (OverloadedFunctionDecl::function_iterator Func
2593 = Conversions->function_begin();
2594 Func != Conversions->function_end(); ++Func) {
2595 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002596 if (AllowExplicitConversions || !Conv->isExplicit())
2597 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002598 }
2599 }
2600 }
2601}
2602
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002603/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2604/// operator overloads to the candidate set (C++ [over.built]), based
2605/// on the operator @p Op and the arguments given. For example, if the
2606/// operator is a binary '+', this routine might add "int
2607/// operator+(int, int)" to cover integer addition.
Douglas Gregor70d26122008-11-12 17:17:38 +00002608void
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002609Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2610 Expr **Args, unsigned NumArgs,
2611 OverloadCandidateSet& CandidateSet) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002612 // The set of "promoted arithmetic types", which are the arithmetic
2613 // types are that preserved by promotion (C++ [over.built]p2). Note
2614 // that the first few of these types are the promoted integral
2615 // types; these types need to be first.
2616 // FIXME: What about complex?
2617 const unsigned FirstIntegralType = 0;
2618 const unsigned LastIntegralType = 13;
2619 const unsigned FirstPromotedIntegralType = 7,
2620 LastPromotedIntegralType = 13;
2621 const unsigned FirstPromotedArithmeticType = 7,
2622 LastPromotedArithmeticType = 16;
2623 const unsigned NumArithmeticTypes = 16;
2624 QualType ArithmeticTypes[NumArithmeticTypes] = {
2625 Context.BoolTy, Context.CharTy, Context.WCharTy,
2626 Context.SignedCharTy, Context.ShortTy,
2627 Context.UnsignedCharTy, Context.UnsignedShortTy,
2628 Context.IntTy, Context.LongTy, Context.LongLongTy,
2629 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2630 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2631 };
2632
2633 // Find all of the types that the arguments can convert to, but only
2634 // if the operator we're looking at has built-in operator candidates
2635 // that make use of these types.
2636 BuiltinCandidateTypeSet CandidateTypes(Context);
2637 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2638 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002639 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregor70d26122008-11-12 17:17:38 +00002640 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002641 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
2642 (Op == OO_Star && NumArgs == 1)) {
2643 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002644 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2645 true,
2646 (Op == OO_Exclaim ||
2647 Op == OO_AmpAmp ||
2648 Op == OO_PipePipe));
Douglas Gregor70d26122008-11-12 17:17:38 +00002649 }
2650
2651 bool isComparison = false;
2652 switch (Op) {
2653 case OO_None:
2654 case NUM_OVERLOADED_OPERATORS:
2655 assert(false && "Expected an overloaded operator");
2656 break;
2657
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002658 case OO_Star: // '*' is either unary or binary
2659 if (NumArgs == 1)
2660 goto UnaryStar;
2661 else
2662 goto BinaryStar;
2663 break;
2664
2665 case OO_Plus: // '+' is either unary or binary
2666 if (NumArgs == 1)
2667 goto UnaryPlus;
2668 else
2669 goto BinaryPlus;
2670 break;
2671
2672 case OO_Minus: // '-' is either unary or binary
2673 if (NumArgs == 1)
2674 goto UnaryMinus;
2675 else
2676 goto BinaryMinus;
2677 break;
2678
2679 case OO_Amp: // '&' is either unary or binary
2680 if (NumArgs == 1)
2681 goto UnaryAmp;
2682 else
2683 goto BinaryAmp;
2684
2685 case OO_PlusPlus:
2686 case OO_MinusMinus:
2687 // C++ [over.built]p3:
2688 //
2689 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2690 // is either volatile or empty, there exist candidate operator
2691 // functions of the form
2692 //
2693 // VQ T& operator++(VQ T&);
2694 // T operator++(VQ T&, int);
2695 //
2696 // C++ [over.built]p4:
2697 //
2698 // For every pair (T, VQ), where T is an arithmetic type other
2699 // than bool, and VQ is either volatile or empty, there exist
2700 // candidate operator functions of the form
2701 //
2702 // VQ T& operator--(VQ T&);
2703 // T operator--(VQ T&, int);
2704 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2705 Arith < NumArithmeticTypes; ++Arith) {
2706 QualType ArithTy = ArithmeticTypes[Arith];
2707 QualType ParamTypes[2]
2708 = { Context.getReferenceType(ArithTy), Context.IntTy };
2709
2710 // Non-volatile version.
2711 if (NumArgs == 1)
2712 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2713 else
2714 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2715
2716 // Volatile version
2717 ParamTypes[0] = Context.getReferenceType(ArithTy.withVolatile());
2718 if (NumArgs == 1)
2719 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2720 else
2721 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2722 }
2723
2724 // C++ [over.built]p5:
2725 //
2726 // For every pair (T, VQ), where T is a cv-qualified or
2727 // cv-unqualified object type, and VQ is either volatile or
2728 // empty, there exist candidate operator functions of the form
2729 //
2730 // T*VQ& operator++(T*VQ&);
2731 // T*VQ& operator--(T*VQ&);
2732 // T* operator++(T*VQ&, int);
2733 // T* operator--(T*VQ&, int);
2734 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2735 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2736 // Skip pointer types that aren't pointers to object types.
Douglas Gregor24a90a52008-11-26 23:31:11 +00002737 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002738 continue;
2739
2740 QualType ParamTypes[2] = {
2741 Context.getReferenceType(*Ptr), Context.IntTy
2742 };
2743
2744 // Without volatile
2745 if (NumArgs == 1)
2746 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2747 else
2748 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2749
2750 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2751 // With volatile
2752 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2753 if (NumArgs == 1)
2754 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2755 else
2756 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2757 }
2758 }
2759 break;
2760
2761 UnaryStar:
2762 // C++ [over.built]p6:
2763 // For every cv-qualified or cv-unqualified object type T, there
2764 // exist candidate operator functions of the form
2765 //
2766 // T& operator*(T*);
2767 //
2768 // C++ [over.built]p7:
2769 // For every function type T, there exist candidate operator
2770 // functions of the form
2771 // T& operator*(T*);
2772 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2773 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2774 QualType ParamTy = *Ptr;
2775 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
2776 AddBuiltinCandidate(Context.getReferenceType(PointeeTy),
2777 &ParamTy, Args, 1, CandidateSet);
2778 }
2779 break;
2780
2781 UnaryPlus:
2782 // C++ [over.built]p8:
2783 // For every type T, there exist candidate operator functions of
2784 // the form
2785 //
2786 // T* operator+(T*);
2787 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2788 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2789 QualType ParamTy = *Ptr;
2790 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2791 }
2792
2793 // Fall through
2794
2795 UnaryMinus:
2796 // C++ [over.built]p9:
2797 // For every promoted arithmetic type T, there exist candidate
2798 // operator functions of the form
2799 //
2800 // T operator+(T);
2801 // T operator-(T);
2802 for (unsigned Arith = FirstPromotedArithmeticType;
2803 Arith < LastPromotedArithmeticType; ++Arith) {
2804 QualType ArithTy = ArithmeticTypes[Arith];
2805 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2806 }
2807 break;
2808
2809 case OO_Tilde:
2810 // C++ [over.built]p10:
2811 // For every promoted integral type T, there exist candidate
2812 // operator functions of the form
2813 //
2814 // T operator~(T);
2815 for (unsigned Int = FirstPromotedIntegralType;
2816 Int < LastPromotedIntegralType; ++Int) {
2817 QualType IntTy = ArithmeticTypes[Int];
2818 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2819 }
2820 break;
2821
Douglas Gregor70d26122008-11-12 17:17:38 +00002822 case OO_New:
2823 case OO_Delete:
2824 case OO_Array_New:
2825 case OO_Array_Delete:
Douglas Gregor70d26122008-11-12 17:17:38 +00002826 case OO_Call:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002827 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregor70d26122008-11-12 17:17:38 +00002828 break;
2829
2830 case OO_Comma:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002831 UnaryAmp:
2832 case OO_Arrow:
Douglas Gregor70d26122008-11-12 17:17:38 +00002833 // C++ [over.match.oper]p3:
2834 // -- For the operator ',', the unary operator '&', or the
2835 // operator '->', the built-in candidates set is empty.
Douglas Gregor70d26122008-11-12 17:17:38 +00002836 break;
2837
2838 case OO_Less:
2839 case OO_Greater:
2840 case OO_LessEqual:
2841 case OO_GreaterEqual:
2842 case OO_EqualEqual:
2843 case OO_ExclaimEqual:
2844 // C++ [over.built]p15:
2845 //
2846 // For every pointer or enumeration type T, there exist
2847 // candidate operator functions of the form
2848 //
2849 // bool operator<(T, T);
2850 // bool operator>(T, T);
2851 // bool operator<=(T, T);
2852 // bool operator>=(T, T);
2853 // bool operator==(T, T);
2854 // bool operator!=(T, T);
2855 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2856 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2857 QualType ParamTypes[2] = { *Ptr, *Ptr };
2858 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2859 }
2860 for (BuiltinCandidateTypeSet::iterator Enum
2861 = CandidateTypes.enumeration_begin();
2862 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2863 QualType ParamTypes[2] = { *Enum, *Enum };
2864 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2865 }
2866
2867 // Fall through.
2868 isComparison = true;
2869
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002870 BinaryPlus:
2871 BinaryMinus:
Douglas Gregor70d26122008-11-12 17:17:38 +00002872 if (!isComparison) {
2873 // We didn't fall through, so we must have OO_Plus or OO_Minus.
2874
2875 // C++ [over.built]p13:
2876 //
2877 // For every cv-qualified or cv-unqualified object type T
2878 // there exist candidate operator functions of the form
2879 //
2880 // T* operator+(T*, ptrdiff_t);
2881 // T& operator[](T*, ptrdiff_t); [BELOW]
2882 // T* operator-(T*, ptrdiff_t);
2883 // T* operator+(ptrdiff_t, T*);
2884 // T& operator[](ptrdiff_t, T*); [BELOW]
2885 //
2886 // C++ [over.built]p14:
2887 //
2888 // For every T, where T is a pointer to object type, there
2889 // exist candidate operator functions of the form
2890 //
2891 // ptrdiff_t operator-(T, T);
2892 for (BuiltinCandidateTypeSet::iterator Ptr
2893 = CandidateTypes.pointer_begin();
2894 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2895 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2896
2897 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
2898 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2899
2900 if (Op == OO_Plus) {
2901 // T* operator+(ptrdiff_t, T*);
2902 ParamTypes[0] = ParamTypes[1];
2903 ParamTypes[1] = *Ptr;
2904 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2905 } else {
2906 // ptrdiff_t operator-(T, T);
2907 ParamTypes[1] = *Ptr;
2908 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
2909 Args, 2, CandidateSet);
2910 }
2911 }
2912 }
2913 // Fall through
2914
Douglas Gregor70d26122008-11-12 17:17:38 +00002915 case OO_Slash:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002916 BinaryStar:
Douglas Gregor70d26122008-11-12 17:17:38 +00002917 // C++ [over.built]p12:
2918 //
2919 // For every pair of promoted arithmetic types L and R, there
2920 // exist candidate operator functions of the form
2921 //
2922 // LR operator*(L, R);
2923 // LR operator/(L, R);
2924 // LR operator+(L, R);
2925 // LR operator-(L, R);
2926 // bool operator<(L, R);
2927 // bool operator>(L, R);
2928 // bool operator<=(L, R);
2929 // bool operator>=(L, R);
2930 // bool operator==(L, R);
2931 // bool operator!=(L, R);
2932 //
2933 // where LR is the result of the usual arithmetic conversions
2934 // between types L and R.
2935 for (unsigned Left = FirstPromotedArithmeticType;
2936 Left < LastPromotedArithmeticType; ++Left) {
2937 for (unsigned Right = FirstPromotedArithmeticType;
2938 Right < LastPromotedArithmeticType; ++Right) {
2939 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2940 QualType Result
2941 = isComparison? Context.BoolTy
2942 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2943 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2944 }
2945 }
2946 break;
2947
2948 case OO_Percent:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002949 BinaryAmp:
Douglas Gregor70d26122008-11-12 17:17:38 +00002950 case OO_Caret:
2951 case OO_Pipe:
2952 case OO_LessLess:
2953 case OO_GreaterGreater:
2954 // C++ [over.built]p17:
2955 //
2956 // For every pair of promoted integral types L and R, there
2957 // exist candidate operator functions of the form
2958 //
2959 // LR operator%(L, R);
2960 // LR operator&(L, R);
2961 // LR operator^(L, R);
2962 // LR operator|(L, R);
2963 // L operator<<(L, R);
2964 // L operator>>(L, R);
2965 //
2966 // where LR is the result of the usual arithmetic conversions
2967 // between types L and R.
2968 for (unsigned Left = FirstPromotedIntegralType;
2969 Left < LastPromotedIntegralType; ++Left) {
2970 for (unsigned Right = FirstPromotedIntegralType;
2971 Right < LastPromotedIntegralType; ++Right) {
2972 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2973 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
2974 ? LandR[0]
2975 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2976 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2977 }
2978 }
2979 break;
2980
2981 case OO_Equal:
2982 // C++ [over.built]p20:
2983 //
2984 // For every pair (T, VQ), where T is an enumeration or
2985 // (FIXME:) pointer to member type and VQ is either volatile or
2986 // empty, there exist candidate operator functions of the form
2987 //
2988 // VQ T& operator=(VQ T&, T);
2989 for (BuiltinCandidateTypeSet::iterator Enum
2990 = CandidateTypes.enumeration_begin();
2991 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2992 QualType ParamTypes[2];
2993
2994 // T& operator=(T&, T)
2995 ParamTypes[0] = Context.getReferenceType(*Enum);
2996 ParamTypes[1] = *Enum;
Douglas Gregorab141112009-01-13 00:52:54 +00002997 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002998 /*IsAssignmentOperator=*/false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002999
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003000 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
3001 // volatile T& operator=(volatile T&, T)
3002 ParamTypes[0] = Context.getReferenceType((*Enum).withVolatile());
3003 ParamTypes[1] = *Enum;
Douglas Gregorab141112009-01-13 00:52:54 +00003004 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003005 /*IsAssignmentOperator=*/false);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003006 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003007 }
3008 // Fall through.
3009
3010 case OO_PlusEqual:
3011 case OO_MinusEqual:
3012 // C++ [over.built]p19:
3013 //
3014 // For every pair (T, VQ), where T is any type and VQ is either
3015 // volatile or empty, there exist candidate operator functions
3016 // of the form
3017 //
3018 // T*VQ& operator=(T*VQ&, T*);
3019 //
3020 // C++ [over.built]p21:
3021 //
3022 // For every pair (T, VQ), where T is a cv-qualified or
3023 // cv-unqualified object type and VQ is either volatile or
3024 // empty, there exist candidate operator functions of the form
3025 //
3026 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3027 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3028 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3029 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3030 QualType ParamTypes[2];
3031 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3032
3033 // non-volatile version
3034 ParamTypes[0] = Context.getReferenceType(*Ptr);
Douglas Gregorab141112009-01-13 00:52:54 +00003035 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3036 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003037
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003038 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3039 // volatile version
3040 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
Douglas Gregorab141112009-01-13 00:52:54 +00003041 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3042 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003043 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003044 }
3045 // Fall through.
3046
3047 case OO_StarEqual:
3048 case OO_SlashEqual:
3049 // C++ [over.built]p18:
3050 //
3051 // For every triple (L, VQ, R), where L is an arithmetic type,
3052 // VQ is either volatile or empty, and R is a promoted
3053 // arithmetic type, there exist candidate operator functions of
3054 // the form
3055 //
3056 // VQ L& operator=(VQ L&, R);
3057 // VQ L& operator*=(VQ L&, R);
3058 // VQ L& operator/=(VQ L&, R);
3059 // VQ L& operator+=(VQ L&, R);
3060 // VQ L& operator-=(VQ L&, R);
3061 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3062 for (unsigned Right = FirstPromotedArithmeticType;
3063 Right < LastPromotedArithmeticType; ++Right) {
3064 QualType ParamTypes[2];
3065 ParamTypes[1] = ArithmeticTypes[Right];
3066
3067 // Add this built-in operator as a candidate (VQ is empty).
3068 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
Douglas Gregorab141112009-01-13 00:52:54 +00003069 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3070 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003071
3072 // Add this built-in operator as a candidate (VQ is 'volatile').
3073 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
3074 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
Douglas Gregorab141112009-01-13 00:52:54 +00003075 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3076 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003077 }
3078 }
3079 break;
3080
3081 case OO_PercentEqual:
3082 case OO_LessLessEqual:
3083 case OO_GreaterGreaterEqual:
3084 case OO_AmpEqual:
3085 case OO_CaretEqual:
3086 case OO_PipeEqual:
3087 // C++ [over.built]p22:
3088 //
3089 // For every triple (L, VQ, R), where L is an integral type, VQ
3090 // is either volatile or empty, and R is a promoted integral
3091 // type, there exist candidate operator functions of the form
3092 //
3093 // VQ L& operator%=(VQ L&, R);
3094 // VQ L& operator<<=(VQ L&, R);
3095 // VQ L& operator>>=(VQ L&, R);
3096 // VQ L& operator&=(VQ L&, R);
3097 // VQ L& operator^=(VQ L&, R);
3098 // VQ L& operator|=(VQ L&, R);
3099 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3100 for (unsigned Right = FirstPromotedIntegralType;
3101 Right < LastPromotedIntegralType; ++Right) {
3102 QualType ParamTypes[2];
3103 ParamTypes[1] = ArithmeticTypes[Right];
3104
3105 // Add this built-in operator as a candidate (VQ is empty).
Douglas Gregor70d26122008-11-12 17:17:38 +00003106 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
3107 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3108
3109 // Add this built-in operator as a candidate (VQ is 'volatile').
3110 ParamTypes[0] = ArithmeticTypes[Left];
3111 ParamTypes[0].addVolatile();
3112 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
3113 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3114 }
3115 }
3116 break;
3117
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003118 case OO_Exclaim: {
3119 // C++ [over.operator]p23:
3120 //
3121 // There also exist candidate operator functions of the form
3122 //
3123 // bool operator!(bool);
3124 // bool operator&&(bool, bool); [BELOW]
3125 // bool operator||(bool, bool); [BELOW]
3126 QualType ParamTy = Context.BoolTy;
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003127 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3128 /*IsAssignmentOperator=*/false,
3129 /*NumContextualBoolArguments=*/1);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003130 break;
3131 }
3132
Douglas Gregor70d26122008-11-12 17:17:38 +00003133 case OO_AmpAmp:
3134 case OO_PipePipe: {
3135 // C++ [over.operator]p23:
3136 //
3137 // There also exist candidate operator functions of the form
3138 //
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003139 // bool operator!(bool); [ABOVE]
Douglas Gregor70d26122008-11-12 17:17:38 +00003140 // bool operator&&(bool, bool);
3141 // bool operator||(bool, bool);
3142 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003143 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3144 /*IsAssignmentOperator=*/false,
3145 /*NumContextualBoolArguments=*/2);
Douglas Gregor70d26122008-11-12 17:17:38 +00003146 break;
3147 }
3148
3149 case OO_Subscript:
3150 // C++ [over.built]p13:
3151 //
3152 // For every cv-qualified or cv-unqualified object type T there
3153 // exist candidate operator functions of the form
3154 //
3155 // T* operator+(T*, ptrdiff_t); [ABOVE]
3156 // T& operator[](T*, ptrdiff_t);
3157 // T* operator-(T*, ptrdiff_t); [ABOVE]
3158 // T* operator+(ptrdiff_t, T*); [ABOVE]
3159 // T& operator[](ptrdiff_t, T*);
3160 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3161 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3162 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3163 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
3164 QualType ResultTy = Context.getReferenceType(PointeeType);
3165
3166 // T& operator[](T*, ptrdiff_t)
3167 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3168
3169 // T& operator[](ptrdiff_t, T*);
3170 ParamTypes[0] = ParamTypes[1];
3171 ParamTypes[1] = *Ptr;
3172 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3173 }
3174 break;
3175
3176 case OO_ArrowStar:
3177 // FIXME: No support for pointer-to-members yet.
3178 break;
3179 }
3180}
3181
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003182/// \brief Add function candidates found via argument-dependent lookup
3183/// to the set of overloading candidates.
3184///
3185/// This routine performs argument-dependent name lookup based on the
3186/// given function name (which may also be an operator name) and adds
3187/// all of the overload candidates found by ADL to the overload
3188/// candidate set (C++ [basic.lookup.argdep]).
3189void
3190Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3191 Expr **Args, unsigned NumArgs,
3192 OverloadCandidateSet& CandidateSet) {
3193 // Find all of the associated namespaces and classes based on the
3194 // arguments we have.
3195 AssociatedNamespaceSet AssociatedNamespaces;
3196 AssociatedClassSet AssociatedClasses;
3197 FindAssociatedClassesAndNamespaces(Args, NumArgs,
3198 AssociatedNamespaces, AssociatedClasses);
3199
3200 // C++ [basic.lookup.argdep]p3:
3201 //
3202 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3203 // and let Y be the lookup set produced by argument dependent
3204 // lookup (defined as follows). If X contains [...] then Y is
3205 // empty. Otherwise Y is the set of declarations found in the
3206 // namespaces associated with the argument types as described
3207 // below. The set of declarations found by the lookup of the name
3208 // is the union of X and Y.
3209 //
3210 // Here, we compute Y and add its members to the overloaded
3211 // candidate set.
3212 llvm::SmallPtrSet<FunctionDecl *, 16> KnownCandidates;
3213 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
3214 NSEnd = AssociatedNamespaces.end();
3215 NS != NSEnd; ++NS) {
3216 // When considering an associated namespace, the lookup is the
3217 // same as the lookup performed when the associated namespace is
3218 // used as a qualifier (3.4.3.2) except that:
3219 //
3220 // -- Any using-directives in the associated namespace are
3221 // ignored.
3222 //
3223 // -- FIXME: Any namespace-scope friend functions declared in
3224 // associated classes are visible within their respective
3225 // namespaces even if they are not visible during an ordinary
3226 // lookup (11.4).
3227 DeclContext::lookup_iterator I, E;
3228 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
3229 FunctionDecl *Func = dyn_cast<FunctionDecl>(*I);
3230 if (!Func)
3231 break;
3232
3233 if (KnownCandidates.empty()) {
3234 // Record all of the function candidates that we've already
3235 // added to the overload set, so that we don't add those same
3236 // candidates a second time.
3237 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3238 CandEnd = CandidateSet.end();
3239 Cand != CandEnd; ++Cand)
3240 KnownCandidates.insert(Cand->Function);
3241 }
3242
3243 // If we haven't seen this function before, add it as a
3244 // candidate.
3245 if (KnownCandidates.insert(Func))
3246 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
3247 }
3248 }
3249}
3250
Douglas Gregord2baafd2008-10-21 16:13:35 +00003251/// isBetterOverloadCandidate - Determines whether the first overload
3252/// candidate is a better candidate than the second (C++ 13.3.3p1).
3253bool
3254Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3255 const OverloadCandidate& Cand2)
3256{
3257 // Define viable functions to be better candidates than non-viable
3258 // functions.
3259 if (!Cand2.Viable)
3260 return Cand1.Viable;
3261 else if (!Cand1.Viable)
3262 return false;
3263
Douglas Gregor3257fb52008-12-22 05:46:06 +00003264 // C++ [over.match.best]p1:
3265 //
3266 // -- if F is a static member function, ICS1(F) is defined such
3267 // that ICS1(F) is neither better nor worse than ICS1(G) for
3268 // any function G, and, symmetrically, ICS1(G) is neither
3269 // better nor worse than ICS1(F).
3270 unsigned StartArg = 0;
3271 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3272 StartArg = 1;
Douglas Gregord2baafd2008-10-21 16:13:35 +00003273
3274 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
3275 // function than another viable function F2 if for all arguments i,
3276 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
3277 // then...
3278 unsigned NumArgs = Cand1.Conversions.size();
3279 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3280 bool HasBetterConversion = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00003281 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00003282 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3283 Cand2.Conversions[ArgIdx])) {
3284 case ImplicitConversionSequence::Better:
3285 // Cand1 has a better conversion sequence.
3286 HasBetterConversion = true;
3287 break;
3288
3289 case ImplicitConversionSequence::Worse:
3290 // Cand1 can't be better than Cand2.
3291 return false;
3292
3293 case ImplicitConversionSequence::Indistinguishable:
3294 // Do nothing.
3295 break;
3296 }
3297 }
3298
3299 if (HasBetterConversion)
3300 return true;
3301
Douglas Gregor70d26122008-11-12 17:17:38 +00003302 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
3303 // implemented, but they require template support.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003304
Douglas Gregor60714f92008-11-07 22:36:19 +00003305 // C++ [over.match.best]p1b4:
3306 //
3307 // -- the context is an initialization by user-defined conversion
3308 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3309 // from the return type of F1 to the destination type (i.e.,
3310 // the type of the entity being initialized) is a better
3311 // conversion sequence than the standard conversion sequence
3312 // from the return type of F2 to the destination type.
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003313 if (Cand1.Function && Cand2.Function &&
3314 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregor60714f92008-11-07 22:36:19 +00003315 isa<CXXConversionDecl>(Cand2.Function)) {
3316 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3317 Cand2.FinalConversion)) {
3318 case ImplicitConversionSequence::Better:
3319 // Cand1 has a better conversion sequence.
3320 return true;
3321
3322 case ImplicitConversionSequence::Worse:
3323 // Cand1 can't be better than Cand2.
3324 return false;
3325
3326 case ImplicitConversionSequence::Indistinguishable:
3327 // Do nothing
3328 break;
3329 }
3330 }
3331
Douglas Gregord2baafd2008-10-21 16:13:35 +00003332 return false;
3333}
3334
3335/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
3336/// within an overload candidate set. If overloading is successful,
3337/// the result will be OR_Success and Best will be set to point to the
3338/// best viable function within the candidate set. Otherwise, one of
3339/// several kinds of errors will be returned; see
3340/// Sema::OverloadingResult.
3341Sema::OverloadingResult
3342Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
3343 OverloadCandidateSet::iterator& Best)
3344{
3345 // Find the best viable function.
3346 Best = CandidateSet.end();
3347 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3348 Cand != CandidateSet.end(); ++Cand) {
3349 if (Cand->Viable) {
3350 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3351 Best = Cand;
3352 }
3353 }
3354
3355 // If we didn't find any viable functions, abort.
3356 if (Best == CandidateSet.end())
3357 return OR_No_Viable_Function;
3358
3359 // Make sure that this function is better than every other viable
3360 // function. If not, we have an ambiguity.
3361 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3362 Cand != CandidateSet.end(); ++Cand) {
3363 if (Cand->Viable &&
3364 Cand != Best &&
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003365 !isBetterOverloadCandidate(*Best, *Cand)) {
3366 Best = CandidateSet.end();
Douglas Gregord2baafd2008-10-21 16:13:35 +00003367 return OR_Ambiguous;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003368 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003369 }
3370
3371 // Best is the best viable function.
3372 return OR_Success;
3373}
3374
3375/// PrintOverloadCandidates - When overload resolution fails, prints
3376/// diagnostic messages containing the candidates in the candidate
3377/// set. If OnlyViable is true, only viable candidates will be printed.
3378void
3379Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3380 bool OnlyViable)
3381{
3382 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3383 LastCand = CandidateSet.end();
3384 for (; Cand != LastCand; ++Cand) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003385 if (Cand->Viable || !OnlyViable) {
3386 if (Cand->Function) {
3387 // Normal function
3388 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003389 } else if (Cand->IsSurrogate) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003390 // Desugar the type of the surrogate down to a function type,
3391 // retaining as many typedefs as possible while still showing
3392 // the function type (and, therefore, its parameter types).
3393 QualType FnType = Cand->Surrogate->getConversionType();
3394 bool isReference = false;
3395 bool isPointer = false;
3396 if (const ReferenceType *FnTypeRef = FnType->getAsReferenceType()) {
3397 FnType = FnTypeRef->getPointeeType();
3398 isReference = true;
3399 }
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);
3408 if (isReference) FnType = Context.getReferenceType(FnType);
3409
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003410 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003411 << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003412 } else {
3413 // FIXME: We need to get the identifier in here
3414 // FIXME: Do we want the error message to point at the
3415 // operator? (built-ins won't have a location)
3416 QualType FnType
3417 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3418 Cand->BuiltinTypes.ParamTypes,
3419 Cand->Conversions.size(),
3420 false, 0);
3421
Chris Lattner4bfd2232008-11-24 06:25:27 +00003422 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003423 }
3424 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003425 }
3426}
3427
Douglas Gregor45014fd2008-11-10 20:40:00 +00003428/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3429/// an overloaded function (C++ [over.over]), where @p From is an
3430/// expression with overloaded function type and @p ToType is the type
3431/// we're trying to resolve to. For example:
3432///
3433/// @code
3434/// int f(double);
3435/// int f(int);
3436///
3437/// int (*pfd)(double) = f; // selects f(double)
3438/// @endcode
3439///
3440/// This routine returns the resulting FunctionDecl if it could be
3441/// resolved, and NULL otherwise. When @p Complain is true, this
3442/// routine will emit diagnostics if there is an error.
3443FunctionDecl *
Sebastian Redl7434fc32009-02-04 21:23:32 +00003444Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor45014fd2008-11-10 20:40:00 +00003445 bool Complain) {
3446 QualType FunctionType = ToType;
Sebastian Redl7434fc32009-02-04 21:23:32 +00003447 bool IsMember = false;
Douglas Gregor45014fd2008-11-10 20:40:00 +00003448 if (const PointerLikeType *ToTypePtr = ToType->getAsPointerLikeType())
3449 FunctionType = ToTypePtr->getPointeeType();
Sebastian Redl7434fc32009-02-04 21:23:32 +00003450 else if (const MemberPointerType *MemTypePtr =
3451 ToType->getAsMemberPointerType()) {
3452 FunctionType = MemTypePtr->getPointeeType();
3453 IsMember = true;
3454 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003455
3456 // We only look at pointers or references to functions.
3457 if (!FunctionType->isFunctionType())
3458 return 0;
3459
3460 // Find the actual overloaded function declaration.
3461 OverloadedFunctionDecl *Ovl = 0;
3462
3463 // C++ [over.over]p1:
3464 // [...] [Note: any redundant set of parentheses surrounding the
3465 // overloaded function name is ignored (5.1). ]
3466 Expr *OvlExpr = From->IgnoreParens();
3467
3468 // C++ [over.over]p1:
3469 // [...] The overloaded function name can be preceded by the &
3470 // operator.
3471 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3472 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3473 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3474 }
3475
3476 // Try to dig out the overloaded function.
3477 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
3478 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
3479
3480 // If there's no overloaded function declaration, we're done.
3481 if (!Ovl)
3482 return 0;
3483
3484 // Look through all of the overloaded functions, searching for one
3485 // whose type matches exactly.
3486 // FIXME: When templates or using declarations come along, we'll actually
3487 // have to deal with duplicates, partial ordering, etc. For now, we
3488 // can just do a simple search.
3489 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
3490 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
3491 Fun != Ovl->function_end(); ++Fun) {
3492 // C++ [over.over]p3:
3493 // Non-member functions and static member functions match
Sebastian Redl3a75abf2009-02-05 12:33:33 +00003494 // targets of type "pointer-to-function" or "reference-to-function."
3495 // Nonstatic member functions match targets of
Sebastian Redl7434fc32009-02-04 21:23:32 +00003496 // type "pointer-to-member-function."
3497 // Note that according to DR 247, the containing class does not matter.
3498 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3499 // Skip non-static functions when converting to pointer, and static
3500 // when converting to member pointer.
3501 if (Method->isStatic() == IsMember)
Douglas Gregor45014fd2008-11-10 20:40:00 +00003502 continue;
Sebastian Redl7434fc32009-02-04 21:23:32 +00003503 } else if (IsMember)
3504 continue;
Douglas Gregor45014fd2008-11-10 20:40:00 +00003505
3506 if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
3507 return *Fun;
3508 }
3509
3510 return 0;
3511}
3512
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003513/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003514/// (which eventually refers to the declaration Func) and the call
3515/// arguments Args/NumArgs, attempt to resolve the function call down
3516/// to a specific function. If overload resolution succeeds, returns
3517/// the function declaration produced by overload
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003518/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003519/// arguments and Fn, and returns NULL.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003520FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003521 DeclarationName UnqualifiedName,
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003522 SourceLocation LParenLoc,
3523 Expr **Args, unsigned NumArgs,
3524 SourceLocation *CommaLocs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003525 SourceLocation RParenLoc,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003526 bool &ArgumentDependentLookup) {
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003527 OverloadCandidateSet CandidateSet;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003528
3529 // Add the functions denoted by Callee to the set of candidate
3530 // functions. While we're doing so, track whether argument-dependent
3531 // lookup still applies, per:
3532 //
3533 // C++0x [basic.lookup.argdep]p3:
3534 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3535 // and let Y be the lookup set produced by argument dependent
3536 // lookup (defined as follows). If X contains
3537 //
3538 // -- a declaration of a class member, or
3539 //
3540 // -- a block-scope function declaration that is not a
3541 // using-declaration, or
3542 //
3543 // -- a declaration that is neither a function or a function
3544 // template
3545 //
3546 // then Y is empty.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003547 if (OverloadedFunctionDecl *Ovl
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003548 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
3549 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3550 FuncEnd = Ovl->function_end();
3551 Func != FuncEnd; ++Func) {
3552 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
3553
3554 if ((*Func)->getDeclContext()->isRecord() ||
3555 (*Func)->getDeclContext()->isFunctionOrMethod())
3556 ArgumentDependentLookup = false;
3557 }
3558 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
3559 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
3560
3561 if (Func->getDeclContext()->isRecord() ||
3562 Func->getDeclContext()->isFunctionOrMethod())
3563 ArgumentDependentLookup = false;
3564 }
3565
3566 if (Callee)
3567 UnqualifiedName = Callee->getDeclName();
3568
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003569 if (ArgumentDependentLookup)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003570 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003571 CandidateSet);
3572
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003573 OverloadCandidateSet::iterator Best;
3574 switch (BestViableFunction(CandidateSet, Best)) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003575 case OR_Success:
3576 return Best->Function;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003577
3578 case OR_No_Viable_Function:
3579 Diag(Fn->getSourceRange().getBegin(),
3580 diag::err_ovl_no_viable_function_in_call)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003581 << UnqualifiedName << (unsigned)CandidateSet.size()
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003582 << Fn->getSourceRange();
3583 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3584 break;
3585
3586 case OR_Ambiguous:
3587 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003588 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003589 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3590 break;
3591 }
3592
3593 // Overload resolution failed. Destroy all of the subexpressions and
3594 // return NULL.
3595 Fn->Destroy(Context);
3596 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3597 Args[Arg]->Destroy(Context);
3598 return 0;
3599}
3600
Douglas Gregor3257fb52008-12-22 05:46:06 +00003601/// BuildCallToMemberFunction - Build a call to a member
3602/// function. MemExpr is the expression that refers to the member
3603/// function (and includes the object parameter), Args/NumArgs are the
3604/// arguments to the function call (not including the object
3605/// parameter). The caller needs to validate that the member
3606/// expression refers to a member function or an overloaded member
3607/// function.
3608Sema::ExprResult
3609Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
3610 SourceLocation LParenLoc, Expr **Args,
3611 unsigned NumArgs, SourceLocation *CommaLocs,
3612 SourceLocation RParenLoc) {
3613 // Dig out the member expression. This holds both the object
3614 // argument and the member function we're referring to.
3615 MemberExpr *MemExpr = 0;
3616 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
3617 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
3618 else
3619 MemExpr = dyn_cast<MemberExpr>(MemExprE);
3620 assert(MemExpr && "Building member call without member expression");
3621
3622 // Extract the object argument.
3623 Expr *ObjectArg = MemExpr->getBase();
3624 if (MemExpr->isArrow())
Ted Kremenek0c97e042009-02-07 01:47:29 +00003625 ObjectArg = new (Context) UnaryOperator(ObjectArg, UnaryOperator::Deref,
3626 ObjectArg->getType()->getAsPointerType()->getPointeeType(),
3627 SourceLocation());
Douglas Gregor3257fb52008-12-22 05:46:06 +00003628 CXXMethodDecl *Method = 0;
3629 if (OverloadedFunctionDecl *Ovl
3630 = dyn_cast<OverloadedFunctionDecl>(MemExpr->getMemberDecl())) {
3631 // Add overload candidates
3632 OverloadCandidateSet CandidateSet;
3633 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3634 FuncEnd = Ovl->function_end();
3635 Func != FuncEnd; ++Func) {
3636 assert(isa<CXXMethodDecl>(*Func) && "Function is not a method");
3637 Method = cast<CXXMethodDecl>(*Func);
3638 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
3639 /*SuppressUserConversions=*/false);
3640 }
3641
3642 OverloadCandidateSet::iterator Best;
3643 switch (BestViableFunction(CandidateSet, Best)) {
3644 case OR_Success:
3645 Method = cast<CXXMethodDecl>(Best->Function);
3646 break;
3647
3648 case OR_No_Viable_Function:
3649 Diag(MemExpr->getSourceRange().getBegin(),
3650 diag::err_ovl_no_viable_member_function_in_call)
3651 << Ovl->getDeclName() << (unsigned)CandidateSet.size()
3652 << MemExprE->getSourceRange();
3653 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3654 // FIXME: Leaking incoming expressions!
3655 return true;
3656
3657 case OR_Ambiguous:
3658 Diag(MemExpr->getSourceRange().getBegin(),
3659 diag::err_ovl_ambiguous_member_call)
3660 << Ovl->getDeclName() << MemExprE->getSourceRange();
3661 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3662 // FIXME: Leaking incoming expressions!
3663 return true;
3664 }
3665
3666 FixOverloadedFunctionReference(MemExpr, Method);
3667 } else {
3668 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
3669 }
3670
3671 assert(Method && "Member call to something that isn't a method?");
Ted Kremenek0c97e042009-02-07 01:47:29 +00003672 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek362abcd2009-02-09 20:51:47 +00003673 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
3674 NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00003675 Method->getResultType().getNonReferenceType(),
3676 RParenLoc));
3677
3678 // Convert the object argument (for a non-static member function call).
3679 if (!Method->isStatic() &&
3680 PerformObjectArgumentInitialization(ObjectArg, Method))
3681 return true;
3682 MemExpr->setBase(ObjectArg);
3683
3684 // Convert the rest of the arguments
3685 const FunctionTypeProto *Proto = cast<FunctionTypeProto>(Method->getType());
3686 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
3687 RParenLoc))
3688 return true;
3689
Sebastian Redl8b769972009-01-19 00:08:26 +00003690 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregor3257fb52008-12-22 05:46:06 +00003691}
3692
Douglas Gregor10f3c502008-11-19 21:05:33 +00003693/// BuildCallToObjectOfClassType - Build a call to an object of class
3694/// type (C++ [over.call.object]), which can end up invoking an
3695/// overloaded function call operator (@c operator()) or performing a
3696/// user-defined conversion on the object argument.
Douglas Gregor3257fb52008-12-22 05:46:06 +00003697Sema::ExprResult
Douglas Gregora133e262008-12-06 00:22:45 +00003698Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
3699 SourceLocation LParenLoc,
Douglas Gregor10f3c502008-11-19 21:05:33 +00003700 Expr **Args, unsigned NumArgs,
3701 SourceLocation *CommaLocs,
3702 SourceLocation RParenLoc) {
3703 assert(Object->getType()->isRecordType() && "Requires object type argument");
3704 const RecordType *Record = Object->getType()->getAsRecordType();
3705
3706 // C++ [over.call.object]p1:
3707 // If the primary-expression E in the function call syntax
3708 // evaluates to a class object of type “cv T”, then the set of
3709 // candidate functions includes at least the function call
3710 // operators of T. The function call operators of T are obtained by
3711 // ordinary lookup of the name operator() in the context of
3712 // (E).operator().
3713 OverloadCandidateSet CandidateSet;
Douglas Gregor8acb7272008-12-11 16:49:14 +00003714 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003715 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroffab63fd62009-01-08 17:28:14 +00003716 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003717 Oper != OperEnd; ++Oper)
3718 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
3719 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00003720
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003721 // C++ [over.call.object]p2:
3722 // In addition, for each conversion function declared in T of the
3723 // form
3724 //
3725 // operator conversion-type-id () cv-qualifier;
3726 //
3727 // where cv-qualifier is the same cv-qualification as, or a
3728 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregor261afa72008-11-20 13:33:37 +00003729 // denotes the type "pointer to function of (P1,...,Pn) returning
3730 // R", or the type "reference to pointer to function of
3731 // (P1,...,Pn) returning R", or the type "reference to function
3732 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003733 // is also considered as a candidate function. Similarly,
3734 // surrogate call functions are added to the set of candidate
3735 // functions for each conversion function declared in an
3736 // accessible base class provided the function is not hidden
3737 // within T by another intervening declaration.
3738 //
3739 // FIXME: Look in base classes for more conversion operators!
3740 OverloadedFunctionDecl *Conversions
3741 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003742 for (OverloadedFunctionDecl::function_iterator
3743 Func = Conversions->function_begin(),
3744 FuncEnd = Conversions->function_end();
3745 Func != FuncEnd; ++Func) {
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003746 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
3747
3748 // Strip the reference type (if any) and then the pointer type (if
3749 // any) to get down to what might be a function type.
3750 QualType ConvType = Conv->getConversionType().getNonReferenceType();
3751 if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
3752 ConvType = ConvPtrType->getPointeeType();
3753
3754 if (const FunctionTypeProto *Proto = ConvType->getAsFunctionTypeProto())
3755 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
3756 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00003757
3758 // Perform overload resolution.
3759 OverloadCandidateSet::iterator Best;
3760 switch (BestViableFunction(CandidateSet, Best)) {
3761 case OR_Success:
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003762 // Overload resolution succeeded; we'll build the appropriate call
3763 // below.
Douglas Gregor10f3c502008-11-19 21:05:33 +00003764 break;
3765
3766 case OR_No_Viable_Function:
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00003767 Diag(Object->getSourceRange().getBegin(),
3768 diag::err_ovl_no_viable_object_call)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003769 << Object->getType() << (unsigned)CandidateSet.size()
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00003770 << Object->getSourceRange();
3771 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00003772 break;
3773
3774 case OR_Ambiguous:
3775 Diag(Object->getSourceRange().getBegin(),
3776 diag::err_ovl_ambiguous_object_call)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003777 << Object->getType() << Object->getSourceRange();
Douglas Gregor10f3c502008-11-19 21:05:33 +00003778 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3779 break;
3780 }
3781
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003782 if (Best == CandidateSet.end()) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00003783 // We had an error; delete all of the subexpressions and return
3784 // the error.
Ted Kremenek0c97e042009-02-07 01:47:29 +00003785 Object->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00003786 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek0c97e042009-02-07 01:47:29 +00003787 Args[ArgIdx]->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00003788 return true;
3789 }
3790
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003791 if (Best->Function == 0) {
3792 // Since there is no function declaration, this is one of the
3793 // surrogate candidates. Dig out the conversion function.
3794 CXXConversionDecl *Conv
3795 = cast<CXXConversionDecl>(
3796 Best->Conversions[0].UserDefined.ConversionFunction);
3797
3798 // We selected one of the surrogate functions that converts the
3799 // object parameter to a function pointer. Perform the conversion
3800 // on the object argument, then let ActOnCallExpr finish the job.
3801 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl8b769972009-01-19 00:08:26 +00003802 ImpCastExprToType(Object,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003803 Conv->getConversionType().getNonReferenceType(),
3804 Conv->getConversionType()->isReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00003805 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
3806 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
3807 CommaLocs, RParenLoc).release();
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003808 }
3809
3810 // We found an overloaded operator(). Build a CXXOperatorCallExpr
3811 // that calls this method, using Object for the implicit object
3812 // parameter and passing along the remaining arguments.
3813 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor10f3c502008-11-19 21:05:33 +00003814 const FunctionTypeProto *Proto = Method->getType()->getAsFunctionTypeProto();
3815
3816 unsigned NumArgsInProto = Proto->getNumArgs();
3817 unsigned NumArgsToCheck = NumArgs;
3818
3819 // Build the full argument list for the method call (the
3820 // implicit object parameter is placed at the beginning of the
3821 // list).
3822 Expr **MethodArgs;
3823 if (NumArgs < NumArgsInProto) {
3824 NumArgsToCheck = NumArgsInProto;
3825 MethodArgs = new Expr*[NumArgsInProto + 1];
3826 } else {
3827 MethodArgs = new Expr*[NumArgs + 1];
3828 }
3829 MethodArgs[0] = Object;
3830 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3831 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
3832
Ted Kremenek0c97e042009-02-07 01:47:29 +00003833 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
3834 SourceLocation());
Douglas Gregor10f3c502008-11-19 21:05:33 +00003835 UsualUnaryConversions(NewFn);
3836
3837 // Once we've built TheCall, all of the expressions are properly
3838 // owned.
3839 QualType ResultTy = Method->getResultType().getNonReferenceType();
Ted Kremenek0c97e042009-02-07 01:47:29 +00003840 ExprOwningPtr<CXXOperatorCallExpr>
Ted Kremenek362abcd2009-02-09 20:51:47 +00003841 TheCall(this, new (Context) CXXOperatorCallExpr(Context, NewFn, MethodArgs,
Ted Kremenek0c97e042009-02-07 01:47:29 +00003842 NumArgs + 1,
3843 ResultTy, RParenLoc));
Douglas Gregor10f3c502008-11-19 21:05:33 +00003844 delete [] MethodArgs;
3845
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00003846 // We may have default arguments. If so, we need to allocate more
3847 // slots in the call for them.
3848 if (NumArgs < NumArgsInProto)
Ted Kremenek0c97e042009-02-07 01:47:29 +00003849 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00003850 else if (NumArgs > NumArgsInProto)
3851 NumArgsToCheck = NumArgsInProto;
3852
Douglas Gregor10f3c502008-11-19 21:05:33 +00003853 // Initialize the implicit object parameter.
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00003854 if (PerformObjectArgumentInitialization(Object, Method))
Douglas Gregor10f3c502008-11-19 21:05:33 +00003855 return true;
3856 TheCall->setArg(0, Object);
3857
3858 // Check the argument types.
3859 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00003860 Expr *Arg;
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00003861 if (i < NumArgs) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00003862 Arg = Args[i];
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00003863
3864 // Pass the argument.
3865 QualType ProtoArgType = Proto->getArgType(i);
3866 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3867 return true;
3868 } else {
Ted Kremenek0c97e042009-02-07 01:47:29 +00003869 Arg = new (Context) CXXDefaultArgExpr(Method->getParamDecl(i));
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00003870 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00003871
3872 TheCall->setArg(i + 1, Arg);
3873 }
3874
3875 // If this is a variadic call, handle args passed through "...".
3876 if (Proto->isVariadic()) {
3877 // Promote the arguments (C99 6.5.2.2p7).
3878 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3879 Expr *Arg = Args[i];
Anders Carlssonfde627e2009-01-13 05:48:52 +00003880
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00003881 DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor10f3c502008-11-19 21:05:33 +00003882 TheCall->setArg(i + 1, Arg);
3883 }
3884 }
3885
Sebastian Redl8b769972009-01-19 00:08:26 +00003886 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregor10f3c502008-11-19 21:05:33 +00003887}
3888
Douglas Gregor7f3fec52008-11-20 16:27:02 +00003889/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
3890/// (if one exists), where @c Base is an expression of class type and
3891/// @c Member is the name of the member we're trying to find.
3892Action::ExprResult
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003893Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00003894 SourceLocation MemberLoc,
3895 IdentifierInfo &Member) {
3896 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
3897
3898 // C++ [over.ref]p1:
3899 //
3900 // [...] An expression x->m is interpreted as (x.operator->())->m
3901 // for a class object x of type T if T::operator->() exists and if
3902 // the operator is selected as the best match function by the
3903 // overload resolution mechanism (13.3).
3904 // FIXME: look in base classes.
3905 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
3906 OverloadCandidateSet CandidateSet;
3907 const RecordType *BaseRecord = Base->getType()->getAsRecordType();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003908
3909 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroffab63fd62009-01-08 17:28:14 +00003910 for (llvm::tie(Oper, OperEnd) = BaseRecord->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003911 Oper != OperEnd; ++Oper)
3912 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00003913 /*SuppressUserConversions=*/false);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00003914
Ted Kremenek0c97e042009-02-07 01:47:29 +00003915 ExprOwningPtr<Expr> BasePtr(this, Base);
Douglas Gregor9c690e92008-11-21 03:04:22 +00003916
Douglas Gregor7f3fec52008-11-20 16:27:02 +00003917 // Perform overload resolution.
3918 OverloadCandidateSet::iterator Best;
3919 switch (BestViableFunction(CandidateSet, Best)) {
3920 case OR_Success:
3921 // Overload resolution succeeded; we'll build the call below.
3922 break;
3923
3924 case OR_No_Viable_Function:
3925 if (CandidateSet.empty())
3926 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003927 << BasePtr->getType() << BasePtr->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00003928 else
3929 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00003930 << "operator->" << (unsigned)CandidateSet.size()
3931 << BasePtr->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00003932 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00003933 return true;
3934
3935 case OR_Ambiguous:
3936 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003937 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00003938 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00003939 return true;
3940 }
3941
3942 // Convert the object parameter.
3943 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9c690e92008-11-21 03:04:22 +00003944 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregor7f3fec52008-11-20 16:27:02 +00003945 return true;
Douglas Gregor9c690e92008-11-21 03:04:22 +00003946
3947 // No concerns about early exits now.
3948 BasePtr.take();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00003949
3950 // Build the operator call.
Ted Kremenek0c97e042009-02-07 01:47:29 +00003951 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
3952 SourceLocation());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00003953 UsualUnaryConversions(FnExpr);
Ted Kremenek362abcd2009-02-09 20:51:47 +00003954 Base = new (Context) CXXOperatorCallExpr(Context, FnExpr, &Base, 1,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00003955 Method->getResultType().getNonReferenceType(),
3956 OpLoc);
Sebastian Redl8b769972009-01-19 00:08:26 +00003957 return ActOnMemberReferenceExpr(S, ExprArg(*this, Base), OpLoc, tok::arrow,
3958 MemberLoc, Member).release();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00003959}
3960
Douglas Gregor45014fd2008-11-10 20:40:00 +00003961/// FixOverloadedFunctionReference - E is an expression that refers to
3962/// a C++ overloaded function (possibly with some parentheses and
3963/// perhaps a '&' around it). We have resolved the overloaded function
3964/// to the function declaration Fn, so patch up the expression E to
3965/// refer (possibly indirectly) to Fn.
3966void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
3967 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
3968 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
3969 E->setType(PE->getSubExpr()->getType());
3970 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
3971 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
3972 "Can only take the address of an overloaded function");
Douglas Gregor3f411962009-02-11 01:18:59 +00003973 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
3974 if (Method->isStatic()) {
3975 // Do nothing: static member functions aren't any different
3976 // from non-member functions.
3977 }
3978 else if (QualifiedDeclRefExpr *DRE
3979 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
3980 // We have taken the address of a pointer to member
3981 // function. Perform the computation here so that we get the
3982 // appropriate pointer to member type.
3983 DRE->setDecl(Fn);
3984 DRE->setType(Fn->getType());
3985 QualType ClassType
3986 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
3987 E->setType(Context.getMemberPointerType(Fn->getType(),
3988 ClassType.getTypePtr()));
3989 return;
3990 }
3991 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003992 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregor2eedd992009-02-11 00:19:33 +00003993 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregor45014fd2008-11-10 20:40:00 +00003994 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
3995 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
3996 "Expected overloaded function");
3997 DR->setDecl(Fn);
3998 E->setType(Fn->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00003999 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4000 MemExpr->setMemberDecl(Fn);
4001 E->setType(Fn->getType());
Douglas Gregor45014fd2008-11-10 20:40:00 +00004002 } else {
4003 assert(false && "Invalid reference to overloaded function");
4004 }
4005}
4006
Douglas Gregord2baafd2008-10-21 16:13:35 +00004007} // end namespace clang