blob: 9f88a87474048ff5742a3ab0059c95e9212c398d [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,
Douglas Gregore819caf2009-02-12 00:15:05 +000042 ICC_Promotion,
43 ICC_Conversion,
44 ICC_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000045 ICC_Conversion,
46 ICC_Conversion,
47 ICC_Conversion,
48 ICC_Conversion,
49 ICC_Conversion,
Douglas Gregor2aecd1f2008-10-29 02:00:59 +000050 ICC_Conversion,
Douglas Gregorfcb19192009-02-11 23:02:49 +000051 ICC_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000052 ICC_Conversion
53 };
54 return Category[(int)Kind];
55}
56
57/// GetConversionRank - Retrieve the implicit conversion rank
58/// corresponding to the given implicit conversion kind.
59ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
60 static const ImplicitConversionRank
61 Rank[(int)ICK_Num_Conversion_Kinds] = {
62 ICR_Exact_Match,
63 ICR_Exact_Match,
64 ICR_Exact_Match,
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Promotion,
68 ICR_Promotion,
Douglas Gregore819caf2009-02-12 00:15:05 +000069 ICR_Promotion,
70 ICR_Conversion,
71 ICR_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000072 ICR_Conversion,
73 ICR_Conversion,
74 ICR_Conversion,
75 ICR_Conversion,
76 ICR_Conversion,
Douglas Gregor2aecd1f2008-10-29 02:00:59 +000077 ICR_Conversion,
Douglas Gregorfcb19192009-02-11 23:02:49 +000078 ICR_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000079 ICR_Conversion
80 };
81 return Rank[(int)Kind];
82}
83
84/// GetImplicitConversionName - Return the name of this kind of
85/// implicit conversion.
86const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
87 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
88 "No conversion",
89 "Lvalue-to-rvalue",
90 "Array-to-pointer",
91 "Function-to-pointer",
92 "Qualification",
93 "Integral promotion",
94 "Floating point promotion",
Douglas Gregore819caf2009-02-12 00:15:05 +000095 "Complex promotion",
Douglas Gregord2baafd2008-10-21 16:13:35 +000096 "Integral conversion",
97 "Floating conversion",
Douglas Gregore819caf2009-02-12 00:15:05 +000098 "Complex conversion",
Douglas Gregord2baafd2008-10-21 16:13:35 +000099 "Floating-integral conversion",
Douglas Gregore819caf2009-02-12 00:15:05 +0000100 "Complex-real conversion",
Douglas Gregord2baafd2008-10-21 16:13:35 +0000101 "Pointer conversion",
102 "Pointer-to-member conversion",
Douglas Gregor2aecd1f2008-10-29 02:00:59 +0000103 "Boolean conversion",
Douglas Gregorfcb19192009-02-11 23:02:49 +0000104 "Compatible-types conversion",
Douglas Gregor2aecd1f2008-10-29 02:00:59 +0000105 "Derived-to-base conversion"
Douglas Gregord2baafd2008-10-21 16:13:35 +0000106 };
107 return Name[Kind];
108}
109
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000110/// StandardConversionSequence - Set the standard conversion
111/// sequence to the identity conversion.
112void StandardConversionSequence::setAsIdentityConversion() {
113 First = ICK_Identity;
114 Second = ICK_Identity;
115 Third = ICK_Identity;
116 Deprecated = false;
117 ReferenceBinding = false;
118 DirectBinding = false;
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000119 CopyConstructor = 0;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000120}
121
Douglas Gregord2baafd2008-10-21 16:13:35 +0000122/// getRank - Retrieve the rank of this standard conversion sequence
123/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
124/// implicit conversions.
125ImplicitConversionRank StandardConversionSequence::getRank() const {
126 ImplicitConversionRank Rank = ICR_Exact_Match;
127 if (GetConversionRank(First) > Rank)
128 Rank = GetConversionRank(First);
129 if (GetConversionRank(Second) > Rank)
130 Rank = GetConversionRank(Second);
131 if (GetConversionRank(Third) > Rank)
132 Rank = GetConversionRank(Third);
133 return Rank;
134}
135
136/// isPointerConversionToBool - Determines whether this conversion is
137/// a conversion of a pointer or pointer-to-member to bool. This is
138/// used as part of the ranking of standard conversion sequences
139/// (C++ 13.3.3.2p4).
140bool StandardConversionSequence::isPointerConversionToBool() const
141{
142 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
143 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
144
145 // Note that FromType has not necessarily been transformed by the
146 // array-to-pointer or function-to-pointer implicit conversions, so
147 // check for their presence as well as checking whether FromType is
148 // a pointer.
149 if (ToType->isBooleanType() &&
Douglas Gregor80402cf2008-12-23 00:53:59 +0000150 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregord2baafd2008-10-21 16:13:35 +0000151 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
152 return true;
153
154 return false;
155}
156
Douglas Gregor14046502008-10-23 00:40:37 +0000157/// isPointerConversionToVoidPointer - Determines whether this
158/// conversion is a conversion of a pointer to a void pointer. This is
159/// used as part of the ranking of standard conversion sequences (C++
160/// 13.3.3.2p4).
161bool
162StandardConversionSequence::
163isPointerConversionToVoidPointer(ASTContext& Context) const
164{
165 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
166 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
167
168 // Note that FromType has not necessarily been transformed by the
169 // array-to-pointer implicit conversion, so check for its presence
170 // and redo the conversion to get a pointer.
171 if (First == ICK_Array_To_Pointer)
172 FromType = Context.getArrayDecayedType(FromType);
173
174 if (Second == ICK_Pointer_Conversion)
175 if (const PointerType* ToPtrType = ToType->getAsPointerType())
176 return ToPtrType->getPointeeType()->isVoidType();
177
178 return false;
179}
180
Douglas Gregord2baafd2008-10-21 16:13:35 +0000181/// DebugPrint - Print this standard conversion sequence to standard
182/// error. Useful for debugging overloading issues.
183void StandardConversionSequence::DebugPrint() const {
184 bool PrintedSomething = false;
185 if (First != ICK_Identity) {
186 fprintf(stderr, "%s", GetImplicitConversionName(First));
187 PrintedSomething = true;
188 }
189
190 if (Second != ICK_Identity) {
191 if (PrintedSomething) {
192 fprintf(stderr, " -> ");
193 }
194 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000195
196 if (CopyConstructor) {
197 fprintf(stderr, " (by copy constructor)");
198 } else if (DirectBinding) {
199 fprintf(stderr, " (direct reference binding)");
200 } else if (ReferenceBinding) {
201 fprintf(stderr, " (reference binding)");
202 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000203 PrintedSomething = true;
204 }
205
206 if (Third != ICK_Identity) {
207 if (PrintedSomething) {
208 fprintf(stderr, " -> ");
209 }
210 fprintf(stderr, "%s", GetImplicitConversionName(Third));
211 PrintedSomething = true;
212 }
213
214 if (!PrintedSomething) {
215 fprintf(stderr, "No conversions required");
216 }
217}
218
219/// DebugPrint - Print this user-defined conversion sequence to standard
220/// error. Useful for debugging overloading issues.
221void UserDefinedConversionSequence::DebugPrint() const {
222 if (Before.First || Before.Second || Before.Third) {
223 Before.DebugPrint();
224 fprintf(stderr, " -> ");
225 }
Chris Lattner271d4c22008-11-24 05:29:24 +0000226 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregord2baafd2008-10-21 16:13:35 +0000227 if (After.First || After.Second || After.Third) {
228 fprintf(stderr, " -> ");
229 After.DebugPrint();
230 }
231}
232
233/// DebugPrint - Print this implicit conversion sequence to standard
234/// error. Useful for debugging overloading issues.
235void ImplicitConversionSequence::DebugPrint() const {
236 switch (ConversionKind) {
237 case StandardConversion:
238 fprintf(stderr, "Standard conversion: ");
239 Standard.DebugPrint();
240 break;
241 case UserDefinedConversion:
242 fprintf(stderr, "User-defined conversion: ");
243 UserDefined.DebugPrint();
244 break;
245 case EllipsisConversion:
246 fprintf(stderr, "Ellipsis conversion");
247 break;
248 case BadConversion:
249 fprintf(stderr, "Bad conversion");
250 break;
251 }
252
253 fprintf(stderr, "\n");
254}
255
256// IsOverload - Determine whether the given New declaration is an
257// overload of the Old declaration. This routine returns false if New
258// and Old cannot be overloaded, e.g., if they are functions with the
259// same signature (C++ 1.3.10) or if the Old declaration isn't a
260// function (or overload set). When it does return false and Old is an
261// OverloadedFunctionDecl, MatchedDecl will be set to point to the
262// FunctionDecl that New cannot be overloaded with.
263//
264// Example: Given the following input:
265//
266// void f(int, float); // #1
267// void f(int, int); // #2
268// int f(int, int); // #3
269//
270// When we process #1, there is no previous declaration of "f",
271// so IsOverload will not be used.
272//
273// When we process #2, Old is a FunctionDecl for #1. By comparing the
274// parameter types, we see that #1 and #2 are overloaded (since they
275// have different signatures), so this routine returns false;
276// MatchedDecl is unchanged.
277//
278// When we process #3, Old is an OverloadedFunctionDecl containing #1
279// and #2. We compare the signatures of #3 to #1 (they're overloaded,
280// so we do nothing) and then #3 to #2. Since the signatures of #3 and
281// #2 are identical (return types of functions are not part of the
282// signature), IsOverload returns false and MatchedDecl will be set to
283// point to the FunctionDecl for #2.
284bool
285Sema::IsOverload(FunctionDecl *New, Decl* OldD,
286 OverloadedFunctionDecl::function_iterator& MatchedDecl)
287{
288 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
289 // Is this new function an overload of every function in the
290 // overload set?
291 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
292 FuncEnd = Ovl->function_end();
293 for (; Func != FuncEnd; ++Func) {
294 if (!IsOverload(New, *Func, MatchedDecl)) {
295 MatchedDecl = Func;
296 return false;
297 }
298 }
299
300 // This function overloads every function in the overload set.
301 return true;
302 } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
303 // Is the function New an overload of the function Old?
304 QualType OldQType = Context.getCanonicalType(Old->getType());
305 QualType NewQType = Context.getCanonicalType(New->getType());
306
307 // Compare the signatures (C++ 1.3.10) of the two functions to
308 // determine whether they are overloads. If we find any mismatch
309 // in the signature, they are overloads.
310
311 // If either of these functions is a K&R-style function (no
312 // prototype), then we consider them to have matching signatures.
Douglas Gregor4fa58902009-02-26 23:50:07 +0000313 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
314 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
Douglas Gregord2baafd2008-10-21 16:13:35 +0000315 return false;
316
Douglas Gregor4fa58902009-02-26 23:50:07 +0000317 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType.getTypePtr());
318 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType.getTypePtr());
Douglas Gregord2baafd2008-10-21 16:13:35 +0000319
320 // The signature of a function includes the types of its
321 // parameters (C++ 1.3.10), which includes the presence or absence
322 // of the ellipsis; see C++ DR 357).
323 if (OldQType != NewQType &&
324 (OldType->getNumArgs() != NewType->getNumArgs() ||
325 OldType->isVariadic() != NewType->isVariadic() ||
326 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
327 NewType->arg_type_begin())))
328 return true;
329
330 // If the function is a class member, its signature includes the
331 // cv-qualifiers (if any) on the function itself.
332 //
333 // As part of this, also check whether one of the member functions
334 // is static, in which case they are not overloads (C++
335 // 13.1p2). While not part of the definition of the signature,
336 // this check is important to determine whether these functions
337 // can be overloaded.
338 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
339 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
340 if (OldMethod && NewMethod &&
341 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregora7b56a32008-11-21 15:36:28 +0000342 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregord2baafd2008-10-21 16:13:35 +0000343 return true;
344
345 // The signatures match; this is not an overload.
346 return false;
347 } else {
348 // (C++ 13p1):
349 // Only function declarations can be overloaded; object and type
350 // declarations cannot be overloaded.
351 return false;
352 }
353}
354
Douglas Gregor81c29152008-10-29 00:13:59 +0000355/// TryImplicitConversion - Attempt to perform an implicit conversion
356/// from the given expression (Expr) to the given type (ToType). This
357/// function returns an implicit conversion sequence that can be used
358/// to perform the initialization. Given
Douglas Gregord2baafd2008-10-21 16:13:35 +0000359///
360/// void f(float f);
361/// void g(int i) { f(i); }
362///
363/// this routine would produce an implicit conversion sequence to
364/// describe the initialization of f from i, which will be a standard
365/// conversion sequence containing an lvalue-to-rvalue conversion (C++
366/// 4.1) followed by a floating-integral conversion (C++ 4.9).
367//
368/// Note that this routine only determines how the conversion can be
369/// performed; it does not actually perform the conversion. As such,
370/// it will not produce any diagnostics if no conversion is available,
371/// but will instead return an implicit conversion sequence of kind
372/// "BadConversion".
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000373///
374/// If @p SuppressUserConversions, then user-defined conversions are
375/// not permitted.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000376/// If @p AllowExplicit, then explicit user-defined conversions are
377/// permitted.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000378ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000379Sema::TryImplicitConversion(Expr* From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000380 bool SuppressUserConversions,
Douglas Gregorb206cc42009-01-30 23:27:23 +0000381 bool AllowExplicit)
Douglas Gregord2baafd2008-10-21 16:13:35 +0000382{
383 ImplicitConversionSequence ICS;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000384 if (IsStandardConversion(From, ToType, ICS.Standard))
385 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000386 else if (getLangOptions().CPlusPlus &&
387 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregorb206cc42009-01-30 23:27:23 +0000388 !SuppressUserConversions, AllowExplicit)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000389 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregore640ab62008-11-03 17:51:48 +0000390 // C++ [over.ics.user]p4:
391 // A conversion of an expression of class type to the same class
392 // type is given Exact Match rank, and a conversion of an
393 // expression of class type to a base class of that type is
394 // given Conversion rank, in spite of the fact that a copy
395 // constructor (i.e., a user-defined conversion function) is
396 // called for those cases.
397 if (CXXConstructorDecl *Constructor
398 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Douglas Gregord9176392009-02-02 22:11:10 +0000399 QualType FromCanon
400 = Context.getCanonicalType(From->getType().getUnqualifiedType());
401 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
402 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000403 // Turn this into a "standard" conversion sequence, so that it
404 // gets ranked with standard conversion sequences.
Douglas Gregore640ab62008-11-03 17:51:48 +0000405 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
406 ICS.Standard.setAsIdentityConversion();
407 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
408 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000409 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregord9176392009-02-02 22:11:10 +0000410 if (ToCanon != FromCanon)
Douglas Gregore640ab62008-11-03 17:51:48 +0000411 ICS.Standard.Second = ICK_Derived_To_Base;
412 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000413 }
Douglas Gregorb206cc42009-01-30 23:27:23 +0000414
415 // C++ [over.best.ics]p4:
416 // However, when considering the argument of a user-defined
417 // conversion function that is a candidate by 13.3.1.3 when
418 // invoked for the copying of the temporary in the second step
419 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
420 // 13.3.1.6 in all cases, only standard conversion sequences and
421 // ellipsis conversion sequences are allowed.
422 if (SuppressUserConversions &&
423 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
424 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregore640ab62008-11-03 17:51:48 +0000425 } else
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000426 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000427
428 return ICS;
429}
430
431/// IsStandardConversion - Determines whether there is a standard
432/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
433/// expression From to the type ToType. Standard conversion sequences
434/// only consider non-class types; for conversions that involve class
435/// types, use TryImplicitConversion. If a conversion exists, SCS will
436/// contain the standard conversion sequence required to perform this
437/// conversion and this routine will return true. Otherwise, this
438/// routine will return false and the value of SCS is unspecified.
439bool
440Sema::IsStandardConversion(Expr* From, QualType ToType,
441 StandardConversionSequence &SCS)
442{
Douglas Gregord2baafd2008-10-21 16:13:35 +0000443 QualType FromType = From->getType();
444
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000445 // Standard conversions (C++ [conv])
Douglas Gregor70d26122008-11-12 17:17:38 +0000446 SCS.setAsIdentityConversion();
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000447 SCS.Deprecated = false;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000448 SCS.IncompatibleObjC = false;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000449 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000450 SCS.CopyConstructor = 0;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000451
Douglas Gregorfcb19192009-02-11 23:02:49 +0000452 // There are no standard conversions for class types in C++, so
453 // abort early. When overloading in C, however, we do permit
454 if (FromType->isRecordType() || ToType->isRecordType()) {
455 if (getLangOptions().CPlusPlus)
456 return false;
457
458 // When we're overloading in C, we allow, as standard conversions,
459 }
460
Douglas Gregord2baafd2008-10-21 16:13:35 +0000461 // The first conversion can be an lvalue-to-rvalue conversion,
462 // array-to-pointer conversion, or function-to-pointer conversion
463 // (C++ 4p1).
464
465 // Lvalue-to-rvalue conversion (C++ 4.1):
466 // An lvalue (3.10) of a non-function, non-array type T can be
467 // converted to an rvalue.
468 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
469 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor45014fd2008-11-10 20:40:00 +0000470 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000471 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000472 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000473
474 // If T is a non-class type, the type of the rvalue is the
475 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorfcb19192009-02-11 23:02:49 +0000476 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
477 // just strip the qualifiers because they don't matter.
478
479 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000480 FromType = FromType.getUnqualifiedType();
Douglas Gregord2baafd2008-10-21 16:13:35 +0000481 }
482 // Array-to-pointer conversion (C++ 4.2)
483 else if (FromType->isArrayType()) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000484 SCS.First = ICK_Array_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000485
486 // An lvalue or rvalue of type "array of N T" or "array of unknown
487 // bound of T" can be converted to an rvalue of type "pointer to
488 // T" (C++ 4.2p1).
489 FromType = Context.getArrayDecayedType(FromType);
490
491 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
492 // This conversion is deprecated. (C++ D.4).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000493 SCS.Deprecated = true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000494
495 // For the purpose of ranking in overload resolution
496 // (13.3.3.1.1), this conversion is considered an
497 // array-to-pointer conversion followed by a qualification
498 // conversion (4.4). (C++ 4.2p2)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000499 SCS.Second = ICK_Identity;
500 SCS.Third = ICK_Qualification;
501 SCS.ToTypePtr = ToType.getAsOpaquePtr();
502 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000503 }
504 }
505 // Function-to-pointer conversion (C++ 4.3).
506 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000507 SCS.First = ICK_Function_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000508
509 // An lvalue of function type T can be converted to an rvalue of
510 // type "pointer to T." The result is a pointer to the
511 // function. (C++ 4.3p1).
512 FromType = Context.getPointerType(FromType);
Sebastian Redl7434fc32009-02-04 21:23:32 +0000513 }
Douglas Gregor45014fd2008-11-10 20:40:00 +0000514 // Address of overloaded function (C++ [over.over]).
515 else if (FunctionDecl *Fn
516 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
517 SCS.First = ICK_Function_To_Pointer;
518
519 // We were able to resolve the address of the overloaded function,
520 // so we can convert to the type of that function.
521 FromType = Fn->getType();
Sebastian Redlce6fff02009-03-16 23:22:08 +0000522 if (ToType->isLValueReferenceType())
523 FromType = Context.getLValueReferenceType(FromType);
524 else if (ToType->isRValueReferenceType())
525 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl7434fc32009-02-04 21:23:32 +0000526 else if (ToType->isMemberPointerType()) {
527 // Resolve address only succeeds if both sides are member pointers,
528 // but it doesn't have to be the same class. See DR 247.
529 // Note that this means that the type of &Derived::fn can be
530 // Ret (Base::*)(Args) if the fn overload actually found is from the
531 // base class, even if it was brought into the derived class via a
532 // using declaration. The standard isn't clear on this issue at all.
533 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
534 FromType = Context.getMemberPointerType(FromType,
535 Context.getTypeDeclType(M->getParent()).getTypePtr());
536 } else
Douglas Gregor45014fd2008-11-10 20:40:00 +0000537 FromType = Context.getPointerType(FromType);
538 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000539 // We don't require any conversions for the first step.
540 else {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000541 SCS.First = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000542 }
543
544 // The second conversion can be an integral promotion, floating
545 // point promotion, integral conversion, floating point conversion,
546 // floating-integral conversion, pointer conversion,
547 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorfcb19192009-02-11 23:02:49 +0000548 // For overloading in C, this can also be a "compatible-type"
549 // conversion.
Douglas Gregor6fd35572008-12-19 17:40:08 +0000550 bool IncompatibleObjC = false;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000551 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000552 // The unqualified versions of the types are the same: there's no
553 // conversion to do.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000554 SCS.Second = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000555 }
556 // Integral promotion (C++ 4.5).
557 else if (IsIntegralPromotion(From, FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000558 SCS.Second = ICK_Integral_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000559 FromType = ToType.getUnqualifiedType();
560 }
561 // Floating point promotion (C++ 4.6).
562 else if (IsFloatingPointPromotion(FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000563 SCS.Second = ICK_Floating_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000564 FromType = ToType.getUnqualifiedType();
565 }
Douglas Gregore819caf2009-02-12 00:15:05 +0000566 // Complex promotion (Clang extension)
567 else if (IsComplexPromotion(FromType, ToType)) {
568 SCS.Second = ICK_Complex_Promotion;
569 FromType = ToType.getUnqualifiedType();
570 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000571 // Integral conversions (C++ 4.7).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000572 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000573 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000574 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000575 SCS.Second = ICK_Integral_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000576 FromType = ToType.getUnqualifiedType();
577 }
578 // Floating point conversions (C++ 4.8).
579 else if (FromType->isFloatingType() && ToType->isFloatingType()) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000580 SCS.Second = ICK_Floating_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000581 FromType = ToType.getUnqualifiedType();
582 }
Douglas Gregore819caf2009-02-12 00:15:05 +0000583 // Complex conversions (C99 6.3.1.6)
584 else if (FromType->isComplexType() && ToType->isComplexType()) {
585 SCS.Second = ICK_Complex_Conversion;
586 FromType = ToType.getUnqualifiedType();
587 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000588 // Floating-integral conversions (C++ 4.9).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000589 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000590 else if ((FromType->isFloatingType() &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000591 ToType->isIntegralType() && !ToType->isBooleanType() &&
592 !ToType->isEnumeralType()) ||
Douglas Gregord2baafd2008-10-21 16:13:35 +0000593 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
594 ToType->isFloatingType())) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000595 SCS.Second = ICK_Floating_Integral;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000596 FromType = ToType.getUnqualifiedType();
597 }
Douglas Gregore819caf2009-02-12 00:15:05 +0000598 // Complex-real conversions (C99 6.3.1.7)
599 else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
600 (ToType->isComplexType() && FromType->isArithmeticType())) {
601 SCS.Second = ICK_Complex_Real;
602 FromType = ToType.getUnqualifiedType();
603 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000604 // Pointer conversions (C++ 4.10).
Douglas Gregor6fd35572008-12-19 17:40:08 +0000605 else if (IsPointerConversion(From, FromType, ToType, FromType,
606 IncompatibleObjC)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000607 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000608 SCS.IncompatibleObjC = IncompatibleObjC;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000609 }
Sebastian Redlba387562009-01-25 19:43:20 +0000610 // Pointer to member conversions (4.11).
611 else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
612 SCS.Second = ICK_Pointer_Member;
613 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000614 // Boolean conversions (C++ 4.12).
Douglas Gregord2baafd2008-10-21 16:13:35 +0000615 else if (ToType->isBooleanType() &&
616 (FromType->isArithmeticType() ||
617 FromType->isEnumeralType() ||
Douglas Gregor80402cf2008-12-23 00:53:59 +0000618 FromType->isPointerType() ||
Sebastian Redlba387562009-01-25 19:43:20 +0000619 FromType->isBlockPointerType() ||
620 FromType->isMemberPointerType())) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000621 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000622 FromType = Context.BoolTy;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000623 }
624 // Compatible conversions (Clang extension for C function overloading)
625 else if (!getLangOptions().CPlusPlus &&
626 Context.typesAreCompatible(ToType, FromType)) {
627 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000628 } else {
629 // No second conversion required.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000630 SCS.Second = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000631 }
632
Douglas Gregor81c29152008-10-29 00:13:59 +0000633 QualType CanonFrom;
634 QualType CanonTo;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000635 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor6573cfd2008-10-21 23:43:52 +0000636 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000637 SCS.Third = ICK_Qualification;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000638 FromType = ToType;
Douglas Gregor81c29152008-10-29 00:13:59 +0000639 CanonFrom = Context.getCanonicalType(FromType);
640 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000641 } else {
642 // No conversion required
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000643 SCS.Third = ICK_Identity;
644
645 // C++ [over.best.ics]p6:
646 // [...] Any difference in top-level cv-qualification is
647 // subsumed by the initialization itself and does not constitute
648 // a conversion. [...]
Douglas Gregor81c29152008-10-29 00:13:59 +0000649 CanonFrom = Context.getCanonicalType(FromType);
650 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000651 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor81c29152008-10-29 00:13:59 +0000652 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
653 FromType = ToType;
654 CanonFrom = CanonTo;
655 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000656 }
657
658 // If we have not converted the argument type to the parameter type,
659 // this is a bad conversion sequence.
Douglas Gregor81c29152008-10-29 00:13:59 +0000660 if (CanonFrom != CanonTo)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000661 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000662
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000663 SCS.ToTypePtr = FromType.getAsOpaquePtr();
664 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000665}
666
667/// IsIntegralPromotion - Determines whether the conversion from the
668/// expression From (whose potentially-adjusted type is FromType) to
669/// ToType is an integral promotion (C++ 4.5). If so, returns true and
670/// sets PromotedType to the promoted type.
671bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
672{
673 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redl12aee862008-11-04 15:59:10 +0000674 // All integers are built-in.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000675 if (!To) {
676 return false;
677 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000678
679 // An rvalue of type char, signed char, unsigned char, short int, or
680 // unsigned short int can be converted to an rvalue of type int if
681 // int can represent all the values of the source type; otherwise,
682 // the source rvalue can be converted to an rvalue of type unsigned
683 // int (C++ 4.5p1).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000684 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000685 if (// We can promote any signed, promotable integer type to an int
686 (FromType->isSignedIntegerType() ||
687 // We can promote any unsigned integer type whose size is
688 // less than int to an int.
689 (!FromType->isSignedIntegerType() &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000690 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000691 return To->getKind() == BuiltinType::Int;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000692 }
693
Douglas Gregord2baafd2008-10-21 16:13:35 +0000694 return To->getKind() == BuiltinType::UInt;
695 }
696
697 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
698 // can be converted to an rvalue of the first of the following types
699 // that can represent all the values of its underlying type: int,
700 // unsigned int, long, or unsigned long (C++ 4.5p2).
701 if ((FromType->isEnumeralType() || FromType->isWideCharType())
702 && ToType->isIntegerType()) {
703 // Determine whether the type we're converting from is signed or
704 // unsigned.
705 bool FromIsSigned;
706 uint64_t FromSize = Context.getTypeSize(FromType);
707 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
708 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
709 FromIsSigned = UnderlyingType->isSignedIntegerType();
710 } else {
711 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
712 FromIsSigned = true;
713 }
714
715 // The types we'll try to promote to, in the appropriate
716 // order. Try each of these types.
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000717 QualType PromoteTypes[6] = {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000718 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000719 Context.LongTy, Context.UnsignedLongTy ,
720 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregord2baafd2008-10-21 16:13:35 +0000721 };
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000722 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000723 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
724 if (FromSize < ToSize ||
725 (FromSize == ToSize &&
726 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
727 // We found the type that we can promote to. If this is the
728 // type we wanted, we have a promotion. Otherwise, no
729 // promotion.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000730 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregord2baafd2008-10-21 16:13:35 +0000731 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
732 }
733 }
734 }
735
736 // An rvalue for an integral bit-field (9.6) can be converted to an
737 // rvalue of type int if int can represent all the values of the
738 // bit-field; otherwise, it can be converted to unsigned int if
739 // unsigned int can represent all the values of the bit-field. If
740 // the bit-field is larger yet, no integral promotion applies to
741 // it. If the bit-field has an enumerated type, it is treated as any
742 // other value of that type for promotion purposes (C++ 4.5p3).
Douglas Gregor4ff48512009-02-12 00:26:06 +0000743 // FIXME: We should delay checking of bit-fields until we actually
744 // perform the conversion.
745 if (MemberExpr *MemRef = dyn_cast_or_null<MemberExpr>(From)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000746 using llvm::APSInt;
Douglas Gregor82d44772008-12-20 23:49:58 +0000747 if (FieldDecl *MemberDecl = dyn_cast<FieldDecl>(MemRef->getMemberDecl())) {
748 APSInt BitWidth;
749 if (MemberDecl->isBitField() &&
750 FromType->isIntegralType() && !FromType->isEnumeralType() &&
751 From->isIntegerConstantExpr(BitWidth, Context)) {
752 APSInt ToSize(Context.getTypeSize(ToType));
753
754 // Are we promoting to an int from a bitfield that fits in an int?
755 if (BitWidth < ToSize ||
756 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
757 return To->getKind() == BuiltinType::Int;
758 }
759
760 // Are we promoting to an unsigned int from an unsigned bitfield
761 // that fits into an unsigned int?
762 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
763 return To->getKind() == BuiltinType::UInt;
764 }
765
766 return false;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000767 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000768 }
769 }
770
771 // An rvalue of type bool can be converted to an rvalue of type int,
772 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000773 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000774 return true;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000775 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000776
777 return false;
778}
779
780/// IsFloatingPointPromotion - Determines whether the conversion from
781/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
782/// returns true and sets PromotedType to the promoted type.
783bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
784{
785 /// An rvalue of type float can be converted to an rvalue of type
786 /// double. (C++ 4.6p1).
787 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
Douglas Gregore819caf2009-02-12 00:15:05 +0000788 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000789 if (FromBuiltin->getKind() == BuiltinType::Float &&
790 ToBuiltin->getKind() == BuiltinType::Double)
791 return true;
792
Douglas Gregore819caf2009-02-12 00:15:05 +0000793 // C99 6.3.1.5p1:
794 // When a float is promoted to double or long double, or a
795 // double is promoted to long double [...].
796 if (!getLangOptions().CPlusPlus &&
797 (FromBuiltin->getKind() == BuiltinType::Float ||
798 FromBuiltin->getKind() == BuiltinType::Double) &&
799 (ToBuiltin->getKind() == BuiltinType::LongDouble))
800 return true;
801 }
802
Douglas Gregord2baafd2008-10-21 16:13:35 +0000803 return false;
804}
805
Douglas Gregore819caf2009-02-12 00:15:05 +0000806/// \brief Determine if a conversion is a complex promotion.
807///
808/// A complex promotion is defined as a complex -> complex conversion
809/// where the conversion between the underlying real types is a
Douglas Gregor4ff48512009-02-12 00:26:06 +0000810/// floating-point or integral promotion.
Douglas Gregore819caf2009-02-12 00:15:05 +0000811bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
812 const ComplexType *FromComplex = FromType->getAsComplexType();
813 if (!FromComplex)
814 return false;
815
816 const ComplexType *ToComplex = ToType->getAsComplexType();
817 if (!ToComplex)
818 return false;
819
820 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor4ff48512009-02-12 00:26:06 +0000821 ToComplex->getElementType()) ||
822 IsIntegralPromotion(0, FromComplex->getElementType(),
823 ToComplex->getElementType());
Douglas Gregore819caf2009-02-12 00:15:05 +0000824}
825
Douglas Gregor24a90a52008-11-26 23:31:11 +0000826/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
827/// the pointer type FromPtr to a pointer to type ToPointee, with the
828/// same type qualifiers as FromPtr has on its pointee type. ToType,
829/// if non-empty, will be a pointer to ToType that may or may not have
830/// the right set of qualifiers on its pointee.
831static QualType
832BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
833 QualType ToPointee, QualType ToType,
834 ASTContext &Context) {
835 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
836 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
837 unsigned Quals = CanonFromPointee.getCVRQualifiers();
838
839 // Exact qualifier match -> return the pointer type we're converting to.
840 if (CanonToPointee.getCVRQualifiers() == Quals) {
841 // ToType is exactly what we need. Return it.
842 if (ToType.getTypePtr())
843 return ToType;
844
845 // Build a pointer to ToPointee. It has the right qualifiers
846 // already.
847 return Context.getPointerType(ToPointee);
848 }
849
850 // Just build a canonical type that has the right qualifiers.
851 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
852}
853
Douglas Gregord2baafd2008-10-21 16:13:35 +0000854/// IsPointerConversion - Determines whether the conversion of the
855/// expression From, which has the (possibly adjusted) type FromType,
856/// can be converted to the type ToType via a pointer conversion (C++
857/// 4.10). If so, returns true and places the converted type (that
858/// might differ from ToType in its cv-qualifiers at some level) into
859/// ConvertedType.
Douglas Gregor9036ef72008-11-27 00:15:41 +0000860///
Douglas Gregor3f5a00c2008-11-27 01:19:21 +0000861/// This routine also supports conversions to and from block pointers
862/// and conversions with Objective-C's 'id', 'id<protocols...>', and
863/// pointers to interfaces. FIXME: Once we've determined the
864/// appropriate overloading rules for Objective-C, we may want to
865/// split the Objective-C checks into a different routine; however,
866/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor6fd35572008-12-19 17:40:08 +0000867/// conversions, so for now they live here. IncompatibleObjC will be
868/// set if the conversion is an allowed Objective-C conversion that
869/// should result in a warning.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000870bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Douglas Gregor6fd35572008-12-19 17:40:08 +0000871 QualType& ConvertedType,
872 bool &IncompatibleObjC)
Douglas Gregord2baafd2008-10-21 16:13:35 +0000873{
Douglas Gregor6fd35572008-12-19 17:40:08 +0000874 IncompatibleObjC = false;
Douglas Gregor932778b2008-12-19 19:13:09 +0000875 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
876 return true;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000877
Douglas Gregorf1d75712008-12-22 20:51:52 +0000878 // Conversion from a null pointer constant to any Objective-C pointer type.
879 if (Context.isObjCObjectPointerType(ToType) &&
880 From->isNullPointerConstant(Context)) {
881 ConvertedType = ToType;
882 return true;
883 }
884
Douglas Gregor9036ef72008-11-27 00:15:41 +0000885 // Blocks: Block pointers can be converted to void*.
886 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
887 ToType->getAsPointerType()->getPointeeType()->isVoidType()) {
888 ConvertedType = ToType;
889 return true;
890 }
891 // Blocks: A null pointer constant can be converted to a block
892 // pointer type.
893 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
894 ConvertedType = ToType;
895 return true;
896 }
897
Douglas Gregord2baafd2008-10-21 16:13:35 +0000898 const PointerType* ToTypePtr = ToType->getAsPointerType();
899 if (!ToTypePtr)
900 return false;
901
902 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
903 if (From->isNullPointerConstant(Context)) {
904 ConvertedType = ToType;
905 return true;
906 }
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000907
Douglas Gregor24a90a52008-11-26 23:31:11 +0000908 // Beyond this point, both types need to be pointers.
909 const PointerType *FromTypePtr = FromType->getAsPointerType();
910 if (!FromTypePtr)
911 return false;
912
913 QualType FromPointeeType = FromTypePtr->getPointeeType();
914 QualType ToPointeeType = ToTypePtr->getPointeeType();
915
Douglas Gregord2baafd2008-10-21 16:13:35 +0000916 // An rvalue of type "pointer to cv T," where T is an object type,
917 // can be converted to an rvalue of type "pointer to cv void" (C++
918 // 4.10p2).
Douglas Gregor932778b2008-12-19 19:13:09 +0000919 if (FromPointeeType->isIncompleteOrObjectType() &&
920 ToPointeeType->isVoidType()) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000921 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
922 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000923 ToType, Context);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000924 return true;
925 }
926
Douglas Gregorfcb19192009-02-11 23:02:49 +0000927 // When we're overloading in C, we allow a special kind of pointer
928 // conversion for compatible-but-not-identical pointee types.
929 if (!getLangOptions().CPlusPlus &&
930 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
931 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
932 ToPointeeType,
933 ToType, Context);
934 return true;
935 }
936
Douglas Gregor14046502008-10-23 00:40:37 +0000937 // C++ [conv.ptr]p3:
938 //
939 // An rvalue of type "pointer to cv D," where D is a class type,
940 // can be converted to an rvalue of type "pointer to cv B," where
941 // B is a base class (clause 10) of D. If B is an inaccessible
942 // (clause 11) or ambiguous (10.2) base class of D, a program that
943 // necessitates this conversion is ill-formed. The result of the
944 // conversion is a pointer to the base class sub-object of the
945 // derived class object. The null pointer value is converted to
946 // the null pointer value of the destination type.
947 //
Douglas Gregorbb461502008-10-24 04:54:22 +0000948 // Note that we do not check for ambiguity or inaccessibility
949 // here. That is handled by CheckPointerConversion.
Douglas Gregorfcb19192009-02-11 23:02:49 +0000950 if (getLangOptions().CPlusPlus &&
951 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor24a90a52008-11-26 23:31:11 +0000952 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000953 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
954 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000955 ToType, Context);
956 return true;
957 }
Douglas Gregor14046502008-10-23 00:40:37 +0000958
Douglas Gregor932778b2008-12-19 19:13:09 +0000959 return false;
960}
961
962/// isObjCPointerConversion - Determines whether this is an
963/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
964/// with the same arguments and return values.
965bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
966 QualType& ConvertedType,
967 bool &IncompatibleObjC) {
968 if (!getLangOptions().ObjC1)
969 return false;
970
971 // Conversions with Objective-C's id<...>.
972 if ((FromType->isObjCQualifiedIdType() || ToType->isObjCQualifiedIdType()) &&
973 ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) {
974 ConvertedType = ToType;
975 return true;
976 }
977
Douglas Gregor80402cf2008-12-23 00:53:59 +0000978 // Beyond this point, both types need to be pointers or block pointers.
979 QualType ToPointeeType;
Douglas Gregor932778b2008-12-19 19:13:09 +0000980 const PointerType* ToTypePtr = ToType->getAsPointerType();
Douglas Gregor80402cf2008-12-23 00:53:59 +0000981 if (ToTypePtr)
982 ToPointeeType = ToTypePtr->getPointeeType();
983 else if (const BlockPointerType *ToBlockPtr = ToType->getAsBlockPointerType())
984 ToPointeeType = ToBlockPtr->getPointeeType();
985 else
Douglas Gregor932778b2008-12-19 19:13:09 +0000986 return false;
987
Douglas Gregor80402cf2008-12-23 00:53:59 +0000988 QualType FromPointeeType;
Douglas Gregor932778b2008-12-19 19:13:09 +0000989 const PointerType *FromTypePtr = FromType->getAsPointerType();
Douglas Gregor80402cf2008-12-23 00:53:59 +0000990 if (FromTypePtr)
991 FromPointeeType = FromTypePtr->getPointeeType();
992 else if (const BlockPointerType *FromBlockPtr
993 = FromType->getAsBlockPointerType())
994 FromPointeeType = FromBlockPtr->getPointeeType();
995 else
Douglas Gregor932778b2008-12-19 19:13:09 +0000996 return false;
997
Douglas Gregor24a90a52008-11-26 23:31:11 +0000998 // Objective C++: We're able to convert from a pointer to an
999 // interface to a pointer to a different interface.
1000 const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType();
1001 const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType();
1002 if (FromIface && ToIface &&
1003 Context.canAssignObjCInterfaces(ToIface, FromIface)) {
Douglas Gregor80402cf2008-12-23 00:53:59 +00001004 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor8bb7ad82008-11-27 00:52:49 +00001005 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001006 ToType, Context);
1007 return true;
1008 }
1009
Douglas Gregor6fd35572008-12-19 17:40:08 +00001010 if (FromIface && ToIface &&
1011 Context.canAssignObjCInterfaces(FromIface, ToIface)) {
1012 // Okay: this is some kind of implicit downcast of Objective-C
1013 // interfaces, which is permitted. However, we're going to
1014 // complain about it.
1015 IncompatibleObjC = true;
Douglas Gregor80402cf2008-12-23 00:53:59 +00001016 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor6fd35572008-12-19 17:40:08 +00001017 ToPointeeType,
1018 ToType, Context);
1019 return true;
1020 }
1021
Douglas Gregor24a90a52008-11-26 23:31:11 +00001022 // Objective C++: We're able to convert between "id" and a pointer
1023 // to any interface (in both directions).
Steve Naroff17c03822009-02-12 17:52:19 +00001024 if ((FromIface && Context.isObjCIdStructType(ToPointeeType))
1025 || (ToIface && Context.isObjCIdStructType(FromPointeeType))) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +00001026 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1027 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001028 ToType, Context);
1029 return true;
1030 }
Douglas Gregor14046502008-10-23 00:40:37 +00001031
Douglas Gregord0c653a2008-12-18 23:43:31 +00001032 // Objective C++: Allow conversions between the Objective-C "id" and
1033 // "Class", in either direction.
Steve Naroff17c03822009-02-12 17:52:19 +00001034 if ((Context.isObjCIdStructType(FromPointeeType) &&
1035 Context.isObjCClassStructType(ToPointeeType)) ||
1036 (Context.isObjCClassStructType(FromPointeeType) &&
1037 Context.isObjCIdStructType(ToPointeeType))) {
Douglas Gregord0c653a2008-12-18 23:43:31 +00001038 ConvertedType = ToType;
1039 return true;
1040 }
1041
Douglas Gregor932778b2008-12-19 19:13:09 +00001042 // If we have pointers to pointers, recursively check whether this
1043 // is an Objective-C conversion.
1044 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1045 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1046 IncompatibleObjC)) {
1047 // We always complain about this conversion.
1048 IncompatibleObjC = true;
1049 ConvertedType = ToType;
1050 return true;
1051 }
1052
Douglas Gregor80402cf2008-12-23 00:53:59 +00001053 // If we have pointers to functions or blocks, check whether the only
Douglas Gregor932778b2008-12-19 19:13:09 +00001054 // differences in the argument and result types are in Objective-C
1055 // pointer conversions. If so, we permit the conversion (but
1056 // complain about it).
Douglas Gregor4fa58902009-02-26 23:50:07 +00001057 const FunctionProtoType *FromFunctionType
1058 = FromPointeeType->getAsFunctionProtoType();
1059 const FunctionProtoType *ToFunctionType
1060 = ToPointeeType->getAsFunctionProtoType();
Douglas Gregor932778b2008-12-19 19:13:09 +00001061 if (FromFunctionType && ToFunctionType) {
1062 // If the function types are exactly the same, this isn't an
1063 // Objective-C pointer conversion.
1064 if (Context.getCanonicalType(FromPointeeType)
1065 == Context.getCanonicalType(ToPointeeType))
1066 return false;
1067
1068 // Perform the quick checks that will tell us whether these
1069 // function types are obviously different.
1070 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1071 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1072 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1073 return false;
1074
1075 bool HasObjCConversion = false;
1076 if (Context.getCanonicalType(FromFunctionType->getResultType())
1077 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1078 // Okay, the types match exactly. Nothing to do.
1079 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1080 ToFunctionType->getResultType(),
1081 ConvertedType, IncompatibleObjC)) {
1082 // Okay, we have an Objective-C pointer conversion.
1083 HasObjCConversion = true;
1084 } else {
1085 // Function types are too different. Abort.
1086 return false;
1087 }
1088
1089 // Check argument types.
1090 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1091 ArgIdx != NumArgs; ++ArgIdx) {
1092 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1093 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1094 if (Context.getCanonicalType(FromArgType)
1095 == Context.getCanonicalType(ToArgType)) {
1096 // Okay, the types match exactly. Nothing to do.
1097 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1098 ConvertedType, IncompatibleObjC)) {
1099 // Okay, we have an Objective-C pointer conversion.
1100 HasObjCConversion = true;
1101 } else {
1102 // Argument types are too different. Abort.
1103 return false;
1104 }
1105 }
1106
1107 if (HasObjCConversion) {
1108 // We had an Objective-C conversion. Allow this pointer
1109 // conversion, but complain about it.
1110 ConvertedType = ToType;
1111 IncompatibleObjC = true;
1112 return true;
1113 }
1114 }
1115
Sebastian Redlba387562009-01-25 19:43:20 +00001116 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001117}
1118
Douglas Gregorbb461502008-10-24 04:54:22 +00001119/// CheckPointerConversion - Check the pointer conversion from the
1120/// expression From to the type ToType. This routine checks for
1121/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
1122/// conversions for which IsPointerConversion has already returned
1123/// true. It returns true and produces a diagnostic if there was an
1124/// error, or returns false otherwise.
1125bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1126 QualType FromType = From->getType();
1127
1128 if (const PointerType *FromPtrType = FromType->getAsPointerType())
1129 if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
Douglas Gregorbb461502008-10-24 04:54:22 +00001130 QualType FromPointeeType = FromPtrType->getPointeeType(),
1131 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregord0c653a2008-12-18 23:43:31 +00001132
1133 // Objective-C++ conversions are always okay.
1134 // FIXME: We should have a different class of conversions for
1135 // the Objective-C++ implicit conversions.
Steve Naroff17c03822009-02-12 17:52:19 +00001136 if (Context.isObjCIdStructType(FromPointeeType) ||
1137 Context.isObjCIdStructType(ToPointeeType) ||
1138 Context.isObjCClassStructType(FromPointeeType) ||
1139 Context.isObjCClassStructType(ToPointeeType))
Douglas Gregord0c653a2008-12-18 23:43:31 +00001140 return false;
1141
Douglas Gregorbb461502008-10-24 04:54:22 +00001142 if (FromPointeeType->isRecordType() &&
1143 ToPointeeType->isRecordType()) {
1144 // We must have a derived-to-base conversion. Check an
1145 // ambiguous or inaccessible conversion.
Douglas Gregor651d1cc2008-10-24 16:17:19 +00001146 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1147 From->getExprLoc(),
1148 From->getSourceRange());
Douglas Gregorbb461502008-10-24 04:54:22 +00001149 }
1150 }
1151
1152 return false;
1153}
1154
Sebastian Redlba387562009-01-25 19:43:20 +00001155/// IsMemberPointerConversion - Determines whether the conversion of the
1156/// expression From, which has the (possibly adjusted) type FromType, can be
1157/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1158/// If so, returns true and places the converted type (that might differ from
1159/// ToType in its cv-qualifiers at some level) into ConvertedType.
1160bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1161 QualType ToType, QualType &ConvertedType)
1162{
1163 const MemberPointerType *ToTypePtr = ToType->getAsMemberPointerType();
1164 if (!ToTypePtr)
1165 return false;
1166
1167 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1168 if (From->isNullPointerConstant(Context)) {
1169 ConvertedType = ToType;
1170 return true;
1171 }
1172
1173 // Otherwise, both types have to be member pointers.
1174 const MemberPointerType *FromTypePtr = FromType->getAsMemberPointerType();
1175 if (!FromTypePtr)
1176 return false;
1177
1178 // A pointer to member of B can be converted to a pointer to member of D,
1179 // where D is derived from B (C++ 4.11p2).
1180 QualType FromClass(FromTypePtr->getClass(), 0);
1181 QualType ToClass(ToTypePtr->getClass(), 0);
1182 // FIXME: What happens when these are dependent? Is this function even called?
1183
1184 if (IsDerivedFrom(ToClass, FromClass)) {
1185 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1186 ToClass.getTypePtr());
1187 return true;
1188 }
1189
1190 return false;
1191}
1192
1193/// CheckMemberPointerConversion - Check the member pointer conversion from the
1194/// expression From to the type ToType. This routine checks for ambiguous or
1195/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1196/// for which IsMemberPointerConversion has already returned true. It returns
1197/// true and produces a diagnostic if there was an error, or returns false
1198/// otherwise.
1199bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType) {
1200 QualType FromType = From->getType();
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001201 const MemberPointerType *FromPtrType = FromType->getAsMemberPointerType();
1202 if (!FromPtrType)
1203 return false;
Sebastian Redlba387562009-01-25 19:43:20 +00001204
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001205 const MemberPointerType *ToPtrType = ToType->getAsMemberPointerType();
1206 assert(ToPtrType && "No member pointer cast has a target type "
1207 "that is not a member pointer.");
Sebastian Redlba387562009-01-25 19:43:20 +00001208
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001209 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1210 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redlba387562009-01-25 19:43:20 +00001211
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001212 // FIXME: What about dependent types?
1213 assert(FromClass->isRecordType() && "Pointer into non-class.");
1214 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redlba387562009-01-25 19:43:20 +00001215
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001216 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1217 /*DetectVirtual=*/true);
1218 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1219 assert(DerivationOkay &&
1220 "Should not have been called if derivation isn't OK.");
1221 (void)DerivationOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001222
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001223 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1224 getUnqualifiedType())) {
1225 // Derivation is ambiguous. Redo the check to find the exact paths.
1226 Paths.clear();
1227 Paths.setRecordingPaths(true);
1228 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1229 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1230 (void)StillOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001231
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001232 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1233 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1234 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1235 return true;
Sebastian Redlba387562009-01-25 19:43:20 +00001236 }
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001237
Douglas Gregor2e047592009-02-28 01:32:25 +00001238 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001239 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1240 << FromClass << ToClass << QualType(VBase, 0)
1241 << From->getSourceRange();
1242 return true;
1243 }
1244
Sebastian Redlba387562009-01-25 19:43:20 +00001245 return false;
1246}
1247
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001248/// IsQualificationConversion - Determines whether the conversion from
1249/// an rvalue of type FromType to ToType is a qualification conversion
1250/// (C++ 4.4).
1251bool
1252Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1253{
1254 FromType = Context.getCanonicalType(FromType);
1255 ToType = Context.getCanonicalType(ToType);
1256
1257 // If FromType and ToType are the same type, this is not a
1258 // qualification conversion.
1259 if (FromType == ToType)
1260 return false;
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001261
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001262 // (C++ 4.4p4):
1263 // A conversion can add cv-qualifiers at levels other than the first
1264 // in multi-level pointers, subject to the following rules: [...]
1265 bool PreviousToQualsIncludeConst = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001266 bool UnwrappedAnyPointer = false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001267 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001268 // Within each iteration of the loop, we check the qualifiers to
1269 // determine if this still looks like a qualification
1270 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001271 // pointers or pointers-to-members and do it all again
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001272 // until there are no more pointers or pointers-to-members left to
1273 // unwrap.
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001274 UnwrappedAnyPointer = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001275
1276 // -- for every j > 0, if const is in cv 1,j then const is in cv
1277 // 2,j, and similarly for volatile.
Douglas Gregore5db4f72008-10-22 00:38:21 +00001278 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001279 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001280
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001281 // -- if the cv 1,j and cv 2,j are different, then const is in
1282 // every cv for 0 < k < j.
1283 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001284 && !PreviousToQualsIncludeConst)
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001285 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001286
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001287 // Keep track of whether all prior cv-qualifiers in the "to" type
1288 // include const.
1289 PreviousToQualsIncludeConst
1290 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001291 }
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001292
1293 // We are left with FromType and ToType being the pointee types
1294 // after unwrapping the original FromType and ToType the same number
1295 // of types. If we unwrapped any pointers, and if FromType and
1296 // ToType have the same unqualified type (since we checked
1297 // qualifiers above), then this is a qualification conversion.
1298 return UnwrappedAnyPointer &&
1299 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1300}
1301
Douglas Gregorb206cc42009-01-30 23:27:23 +00001302/// Determines whether there is a user-defined conversion sequence
1303/// (C++ [over.ics.user]) that converts expression From to the type
1304/// ToType. If such a conversion exists, User will contain the
1305/// user-defined conversion sequence that performs such a conversion
1306/// and this routine will return true. Otherwise, this routine returns
1307/// false and User is unspecified.
1308///
1309/// \param AllowConversionFunctions true if the conversion should
1310/// consider conversion functions at all. If false, only constructors
1311/// will be considered.
1312///
1313/// \param AllowExplicit true if the conversion should consider C++0x
1314/// "explicit" conversion functions as well as non-explicit conversion
1315/// functions (C++0x [class.conv.fct]p2).
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001316bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001317 UserDefinedConversionSequence& User,
Douglas Gregorb206cc42009-01-30 23:27:23 +00001318 bool AllowConversionFunctions,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001319 bool AllowExplicit)
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001320{
1321 OverloadCandidateSet CandidateSet;
Douglas Gregor2e047592009-02-28 01:32:25 +00001322 if (const RecordType *ToRecordType = ToType->getAsRecordType()) {
1323 if (CXXRecordDecl *ToRecordDecl
1324 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1325 // C++ [over.match.ctor]p1:
1326 // When objects of class type are direct-initialized (8.5), or
1327 // copy-initialized from an expression of the same or a
1328 // derived class type (8.5), overload resolution selects the
1329 // constructor. [...] For copy-initialization, the candidate
1330 // functions are all the converting constructors (12.3.1) of
1331 // that class. The argument list is the expression-list within
1332 // the parentheses of the initializer.
1333 DeclarationName ConstructorName
1334 = Context.DeclarationNames.getCXXConstructorName(
1335 Context.getCanonicalType(ToType).getUnqualifiedType());
1336 DeclContext::lookup_iterator Con, ConEnd;
1337 for (llvm::tie(Con, ConEnd) = ToRecordDecl->lookup(ConstructorName);
1338 Con != ConEnd; ++Con) {
1339 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1340 if (Constructor->isConvertingConstructor())
1341 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1342 /*SuppressUserConversions=*/true);
1343 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001344 }
1345 }
1346
Douglas Gregorb206cc42009-01-30 23:27:23 +00001347 if (!AllowConversionFunctions) {
1348 // Don't allow any conversion functions to enter the overload set.
Douglas Gregor2e047592009-02-28 01:32:25 +00001349 } else if (const RecordType *FromRecordType
1350 = From->getType()->getAsRecordType()) {
1351 if (CXXRecordDecl *FromRecordDecl
1352 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1353 // Add all of the conversion functions as candidates.
1354 // FIXME: Look for conversions in base classes!
1355 OverloadedFunctionDecl *Conversions
1356 = FromRecordDecl->getConversionFunctions();
1357 for (OverloadedFunctionDecl::function_iterator Func
1358 = Conversions->function_begin();
1359 Func != Conversions->function_end(); ++Func) {
1360 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1361 if (AllowExplicit || !Conv->isExplicit())
1362 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1363 }
Douglas Gregor60714f92008-11-07 22:36:19 +00001364 }
1365 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001366
1367 OverloadCandidateSet::iterator Best;
1368 switch (BestViableFunction(CandidateSet, Best)) {
1369 case OR_Success:
1370 // Record the standard conversion we used and the conversion function.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001371 if (CXXConstructorDecl *Constructor
1372 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1373 // C++ [over.ics.user]p1:
1374 // If the user-defined conversion is specified by a
1375 // constructor (12.3.1), the initial standard conversion
1376 // sequence converts the source type to the type required by
1377 // the argument of the constructor.
1378 //
1379 // FIXME: What about ellipsis conversions?
1380 QualType ThisType = Constructor->getThisType(Context);
1381 User.Before = Best->Conversions[0].Standard;
1382 User.ConversionFunction = Constructor;
1383 User.After.setAsIdentityConversion();
1384 User.After.FromTypePtr
1385 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
1386 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1387 return true;
Douglas Gregor60714f92008-11-07 22:36:19 +00001388 } else if (CXXConversionDecl *Conversion
1389 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1390 // C++ [over.ics.user]p1:
1391 //
1392 // [...] If the user-defined conversion is specified by a
1393 // conversion function (12.3.2), the initial standard
1394 // conversion sequence converts the source type to the
1395 // implicit object parameter of the conversion function.
1396 User.Before = Best->Conversions[0].Standard;
1397 User.ConversionFunction = Conversion;
1398
1399 // C++ [over.ics.user]p2:
1400 // The second standard conversion sequence converts the
1401 // result of the user-defined conversion to the target type
1402 // for the sequence. Since an implicit conversion sequence
1403 // is an initialization, the special rules for
1404 // initialization by user-defined conversion apply when
1405 // selecting the best user-defined conversion for a
1406 // user-defined conversion sequence (see 13.3.3 and
1407 // 13.3.3.1).
1408 User.After = Best->FinalConversion;
1409 return true;
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001410 } else {
Douglas Gregor60714f92008-11-07 22:36:19 +00001411 assert(false && "Not a constructor or conversion function?");
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001412 return false;
1413 }
1414
1415 case OR_No_Viable_Function:
Douglas Gregoraa57e862009-02-18 21:56:37 +00001416 case OR_Deleted:
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001417 // No conversion here! We're done.
1418 return false;
1419
1420 case OR_Ambiguous:
1421 // FIXME: See C++ [over.best.ics]p10 for the handling of
1422 // ambiguous conversion sequences.
1423 return false;
1424 }
1425
1426 return false;
1427}
1428
Douglas Gregord2baafd2008-10-21 16:13:35 +00001429/// CompareImplicitConversionSequences - Compare two implicit
1430/// conversion sequences to determine whether one is better than the
1431/// other or if they are indistinguishable (C++ 13.3.3.2).
1432ImplicitConversionSequence::CompareKind
1433Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1434 const ImplicitConversionSequence& ICS2)
1435{
1436 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1437 // conversion sequences (as defined in 13.3.3.1)
1438 // -- a standard conversion sequence (13.3.3.1.1) is a better
1439 // conversion sequence than a user-defined conversion sequence or
1440 // an ellipsis conversion sequence, and
1441 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1442 // conversion sequence than an ellipsis conversion sequence
1443 // (13.3.3.1.3).
1444 //
1445 if (ICS1.ConversionKind < ICS2.ConversionKind)
1446 return ImplicitConversionSequence::Better;
1447 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1448 return ImplicitConversionSequence::Worse;
1449
1450 // Two implicit conversion sequences of the same form are
1451 // indistinguishable conversion sequences unless one of the
1452 // following rules apply: (C++ 13.3.3.2p3):
1453 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1454 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1455 else if (ICS1.ConversionKind ==
1456 ImplicitConversionSequence::UserDefinedConversion) {
1457 // User-defined conversion sequence U1 is a better conversion
1458 // sequence than another user-defined conversion sequence U2 if
1459 // they contain the same user-defined conversion function or
1460 // constructor and if the second standard conversion sequence of
1461 // U1 is better than the second standard conversion sequence of
1462 // U2 (C++ 13.3.3.2p3).
1463 if (ICS1.UserDefined.ConversionFunction ==
1464 ICS2.UserDefined.ConversionFunction)
1465 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1466 ICS2.UserDefined.After);
1467 }
1468
1469 return ImplicitConversionSequence::Indistinguishable;
1470}
1471
1472/// CompareStandardConversionSequences - Compare two standard
1473/// conversion sequences to determine whether one is better than the
1474/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1475ImplicitConversionSequence::CompareKind
1476Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1477 const StandardConversionSequence& SCS2)
1478{
1479 // Standard conversion sequence S1 is a better conversion sequence
1480 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1481
1482 // -- S1 is a proper subsequence of S2 (comparing the conversion
1483 // sequences in the canonical form defined by 13.3.3.1.1,
1484 // excluding any Lvalue Transformation; the identity conversion
1485 // sequence is considered to be a subsequence of any
1486 // non-identity conversion sequence) or, if not that,
1487 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1488 // Neither is a proper subsequence of the other. Do nothing.
1489 ;
1490 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1491 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1492 (SCS1.Second == ICK_Identity &&
1493 SCS1.Third == ICK_Identity))
1494 // SCS1 is a proper subsequence of SCS2.
1495 return ImplicitConversionSequence::Better;
1496 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1497 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1498 (SCS2.Second == ICK_Identity &&
1499 SCS2.Third == ICK_Identity))
1500 // SCS2 is a proper subsequence of SCS1.
1501 return ImplicitConversionSequence::Worse;
1502
1503 // -- the rank of S1 is better than the rank of S2 (by the rules
1504 // defined below), or, if not that,
1505 ImplicitConversionRank Rank1 = SCS1.getRank();
1506 ImplicitConversionRank Rank2 = SCS2.getRank();
1507 if (Rank1 < Rank2)
1508 return ImplicitConversionSequence::Better;
1509 else if (Rank2 < Rank1)
1510 return ImplicitConversionSequence::Worse;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001511
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001512 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1513 // are indistinguishable unless one of the following rules
1514 // applies:
1515
1516 // A conversion that is not a conversion of a pointer, or
1517 // pointer to member, to bool is better than another conversion
1518 // that is such a conversion.
1519 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1520 return SCS2.isPointerConversionToBool()
1521 ? ImplicitConversionSequence::Better
1522 : ImplicitConversionSequence::Worse;
1523
Douglas Gregor14046502008-10-23 00:40:37 +00001524 // C++ [over.ics.rank]p4b2:
1525 //
1526 // If class B is derived directly or indirectly from class A,
Douglas Gregor0e343382008-10-29 14:50:44 +00001527 // conversion of B* to A* is better than conversion of B* to
1528 // void*, and conversion of A* to void* is better than conversion
1529 // of B* to void*.
Douglas Gregor14046502008-10-23 00:40:37 +00001530 bool SCS1ConvertsToVoid
1531 = SCS1.isPointerConversionToVoidPointer(Context);
1532 bool SCS2ConvertsToVoid
1533 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregor0e343382008-10-29 14:50:44 +00001534 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1535 // Exactly one of the conversion sequences is a conversion to
1536 // a void pointer; it's the worse conversion.
Douglas Gregor14046502008-10-23 00:40:37 +00001537 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1538 : ImplicitConversionSequence::Worse;
Douglas Gregor0e343382008-10-29 14:50:44 +00001539 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1540 // Neither conversion sequence converts to a void pointer; compare
1541 // their derived-to-base conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001542 if (ImplicitConversionSequence::CompareKind DerivedCK
1543 = CompareDerivedToBaseConversions(SCS1, SCS2))
1544 return DerivedCK;
Douglas Gregor0e343382008-10-29 14:50:44 +00001545 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1546 // Both conversion sequences are conversions to void
1547 // pointers. Compare the source types to determine if there's an
1548 // inheritance relationship in their sources.
1549 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1550 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1551
1552 // Adjust the types we're converting from via the array-to-pointer
1553 // conversion, if we need to.
1554 if (SCS1.First == ICK_Array_To_Pointer)
1555 FromType1 = Context.getArrayDecayedType(FromType1);
1556 if (SCS2.First == ICK_Array_To_Pointer)
1557 FromType2 = Context.getArrayDecayedType(FromType2);
1558
1559 QualType FromPointee1
1560 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1561 QualType FromPointee2
1562 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1563
1564 if (IsDerivedFrom(FromPointee2, FromPointee1))
1565 return ImplicitConversionSequence::Better;
1566 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1567 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001568
1569 // Objective-C++: If one interface is more specific than the
1570 // other, it is the better one.
1571 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1572 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1573 if (FromIface1 && FromIface1) {
1574 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1575 return ImplicitConversionSequence::Better;
1576 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1577 return ImplicitConversionSequence::Worse;
1578 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001579 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001580
1581 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1582 // bullet 3).
Douglas Gregor14046502008-10-23 00:40:37 +00001583 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001584 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor14046502008-10-23 00:40:37 +00001585 return QualCK;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001586
Douglas Gregor0e343382008-10-29 14:50:44 +00001587 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1588 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1589 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001590 // C++0x [over.ics.rank]p3b4:
1591 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1592 // implicit object parameter of a non-static member function declared
1593 // without a ref-qualifier, and S1 binds an rvalue reference to an
1594 // rvalue and S2 binds an lvalue reference.
1595 // FIXME: We have far too little information for this check. We don't know
1596 // if the bound object is an rvalue. We don't know if the binding type is
1597 // an rvalue or lvalue reference. We don't know if we're dealing with the
1598 // implicit object parameter, or if the member function in this case has
1599 // a ref qualifier.
1600
1601 // C++ [over.ics.rank]p3b4:
1602 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1603 // which the references refer are the same type except for
1604 // top-level cv-qualifiers, and the type to which the reference
1605 // initialized by S2 refers is more cv-qualified than the type
1606 // to which the reference initialized by S1 refers.
Douglas Gregor0e343382008-10-29 14:50:44 +00001607 T1 = Context.getCanonicalType(T1);
1608 T2 = Context.getCanonicalType(T2);
1609 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1610 if (T2.isMoreQualifiedThan(T1))
1611 return ImplicitConversionSequence::Better;
1612 else if (T1.isMoreQualifiedThan(T2))
1613 return ImplicitConversionSequence::Worse;
1614 }
1615 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001616
1617 return ImplicitConversionSequence::Indistinguishable;
1618}
1619
1620/// CompareQualificationConversions - Compares two standard conversion
1621/// sequences to determine whether they can be ranked based on their
1622/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1623ImplicitConversionSequence::CompareKind
1624Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1625 const StandardConversionSequence& SCS2)
1626{
Douglas Gregor4459bbe2008-10-22 15:04:37 +00001627 // C++ 13.3.3.2p3:
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001628 // -- S1 and S2 differ only in their qualification conversion and
1629 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1630 // cv-qualification signature of type T1 is a proper subset of
1631 // the cv-qualification signature of type T2, and S1 is not the
1632 // deprecated string literal array-to-pointer conversion (4.2).
1633 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1634 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1635 return ImplicitConversionSequence::Indistinguishable;
1636
1637 // FIXME: the example in the standard doesn't use a qualification
1638 // conversion (!)
1639 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1640 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1641 T1 = Context.getCanonicalType(T1);
1642 T2 = Context.getCanonicalType(T2);
1643
1644 // If the types are the same, we won't learn anything by unwrapped
1645 // them.
1646 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1647 return ImplicitConversionSequence::Indistinguishable;
1648
1649 ImplicitConversionSequence::CompareKind Result
1650 = ImplicitConversionSequence::Indistinguishable;
1651 while (UnwrapSimilarPointerTypes(T1, T2)) {
1652 // Within each iteration of the loop, we check the qualifiers to
1653 // determine if this still looks like a qualification
1654 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001655 // pointers or pointers-to-members and do it all again
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001656 // until there are no more pointers or pointers-to-members left
1657 // to unwrap. This essentially mimics what
1658 // IsQualificationConversion does, but here we're checking for a
1659 // strict subset of qualifiers.
1660 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1661 // The qualifiers are the same, so this doesn't tell us anything
1662 // about how the sequences rank.
1663 ;
1664 else if (T2.isMoreQualifiedThan(T1)) {
1665 // T1 has fewer qualifiers, so it could be the better sequence.
1666 if (Result == ImplicitConversionSequence::Worse)
1667 // Neither has qualifiers that are a subset of the other's
1668 // qualifiers.
1669 return ImplicitConversionSequence::Indistinguishable;
1670
1671 Result = ImplicitConversionSequence::Better;
1672 } else if (T1.isMoreQualifiedThan(T2)) {
1673 // T2 has fewer qualifiers, so it could be the better sequence.
1674 if (Result == ImplicitConversionSequence::Better)
1675 // Neither has qualifiers that are a subset of the other's
1676 // qualifiers.
1677 return ImplicitConversionSequence::Indistinguishable;
1678
1679 Result = ImplicitConversionSequence::Worse;
1680 } else {
1681 // Qualifiers are disjoint.
1682 return ImplicitConversionSequence::Indistinguishable;
1683 }
1684
1685 // If the types after this point are equivalent, we're done.
1686 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1687 break;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001688 }
1689
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001690 // Check that the winning standard conversion sequence isn't using
1691 // the deprecated string literal array to pointer conversion.
1692 switch (Result) {
1693 case ImplicitConversionSequence::Better:
1694 if (SCS1.Deprecated)
1695 Result = ImplicitConversionSequence::Indistinguishable;
1696 break;
1697
1698 case ImplicitConversionSequence::Indistinguishable:
1699 break;
1700
1701 case ImplicitConversionSequence::Worse:
1702 if (SCS2.Deprecated)
1703 Result = ImplicitConversionSequence::Indistinguishable;
1704 break;
1705 }
1706
1707 return Result;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001708}
1709
Douglas Gregor14046502008-10-23 00:40:37 +00001710/// CompareDerivedToBaseConversions - Compares two standard conversion
1711/// sequences to determine whether they can be ranked based on their
Douglas Gregor24a90a52008-11-26 23:31:11 +00001712/// various kinds of derived-to-base conversions (C++
1713/// [over.ics.rank]p4b3). As part of these checks, we also look at
1714/// conversions between Objective-C interface types.
Douglas Gregor14046502008-10-23 00:40:37 +00001715ImplicitConversionSequence::CompareKind
1716Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1717 const StandardConversionSequence& SCS2) {
1718 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1719 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1720 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1721 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1722
1723 // Adjust the types we're converting from via the array-to-pointer
1724 // conversion, if we need to.
1725 if (SCS1.First == ICK_Array_To_Pointer)
1726 FromType1 = Context.getArrayDecayedType(FromType1);
1727 if (SCS2.First == ICK_Array_To_Pointer)
1728 FromType2 = Context.getArrayDecayedType(FromType2);
1729
1730 // Canonicalize all of the types.
1731 FromType1 = Context.getCanonicalType(FromType1);
1732 ToType1 = Context.getCanonicalType(ToType1);
1733 FromType2 = Context.getCanonicalType(FromType2);
1734 ToType2 = Context.getCanonicalType(ToType2);
1735
Douglas Gregor0e343382008-10-29 14:50:44 +00001736 // C++ [over.ics.rank]p4b3:
Douglas Gregor14046502008-10-23 00:40:37 +00001737 //
1738 // If class B is derived directly or indirectly from class A and
1739 // class C is derived directly or indirectly from B,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001740 //
1741 // For Objective-C, we let A, B, and C also be Objective-C
1742 // interfaces.
Douglas Gregor0e343382008-10-29 14:50:44 +00001743
1744 // Compare based on pointer conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001745 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor3f5a00c2008-11-27 01:19:21 +00001746 SCS2.Second == ICK_Pointer_Conversion &&
1747 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1748 FromType1->isPointerType() && FromType2->isPointerType() &&
1749 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregor14046502008-10-23 00:40:37 +00001750 QualType FromPointee1
1751 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1752 QualType ToPointee1
1753 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1754 QualType FromPointee2
1755 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1756 QualType ToPointee2
1757 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
Douglas Gregor24a90a52008-11-26 23:31:11 +00001758
1759 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1760 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1761 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1762 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1763
Douglas Gregor0e343382008-10-29 14:50:44 +00001764 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor14046502008-10-23 00:40:37 +00001765 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1766 if (IsDerivedFrom(ToPointee1, ToPointee2))
1767 return ImplicitConversionSequence::Better;
1768 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1769 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001770
1771 if (ToIface1 && ToIface2) {
1772 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1773 return ImplicitConversionSequence::Better;
1774 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1775 return ImplicitConversionSequence::Worse;
1776 }
Douglas Gregor14046502008-10-23 00:40:37 +00001777 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001778
1779 // -- conversion of B* to A* is better than conversion of C* to A*,
1780 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1781 if (IsDerivedFrom(FromPointee2, FromPointee1))
1782 return ImplicitConversionSequence::Better;
1783 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1784 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001785
1786 if (FromIface1 && FromIface2) {
1787 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1788 return ImplicitConversionSequence::Better;
1789 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1790 return ImplicitConversionSequence::Worse;
1791 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001792 }
Douglas Gregor14046502008-10-23 00:40:37 +00001793 }
1794
Douglas Gregor0e343382008-10-29 14:50:44 +00001795 // Compare based on reference bindings.
1796 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1797 SCS1.Second == ICK_Derived_To_Base) {
1798 // -- binding of an expression of type C to a reference of type
1799 // B& is better than binding an expression of type C to a
1800 // reference of type A&,
1801 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1802 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1803 if (IsDerivedFrom(ToType1, ToType2))
1804 return ImplicitConversionSequence::Better;
1805 else if (IsDerivedFrom(ToType2, ToType1))
1806 return ImplicitConversionSequence::Worse;
1807 }
1808
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001809 // -- binding of an expression of type B to a reference of type
1810 // A& is better than binding an expression of type C to a
1811 // reference of type A&,
Douglas Gregor0e343382008-10-29 14:50:44 +00001812 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1813 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1814 if (IsDerivedFrom(FromType2, FromType1))
1815 return ImplicitConversionSequence::Better;
1816 else if (IsDerivedFrom(FromType1, FromType2))
1817 return ImplicitConversionSequence::Worse;
1818 }
1819 }
1820
1821
1822 // FIXME: conversion of A::* to B::* is better than conversion of
1823 // A::* to C::*,
1824
1825 // FIXME: conversion of B::* to C::* is better than conversion of
1826 // A::* to C::*, and
1827
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001828 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1829 SCS1.Second == ICK_Derived_To_Base) {
1830 // -- conversion of C to B is better than conversion of C to A,
1831 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1832 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1833 if (IsDerivedFrom(ToType1, ToType2))
1834 return ImplicitConversionSequence::Better;
1835 else if (IsDerivedFrom(ToType2, ToType1))
1836 return ImplicitConversionSequence::Worse;
1837 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001838
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001839 // -- conversion of B to A is better than conversion of C to A.
1840 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1841 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1842 if (IsDerivedFrom(FromType2, FromType1))
1843 return ImplicitConversionSequence::Better;
1844 else if (IsDerivedFrom(FromType1, FromType2))
1845 return ImplicitConversionSequence::Worse;
1846 }
1847 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001848
Douglas Gregor14046502008-10-23 00:40:37 +00001849 return ImplicitConversionSequence::Indistinguishable;
1850}
1851
Douglas Gregor81c29152008-10-29 00:13:59 +00001852/// TryCopyInitialization - Try to copy-initialize a value of type
1853/// ToType from the expression From. Return the implicit conversion
1854/// sequence required to pass this argument, which may be a bad
1855/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001856/// a parameter of this type). If @p SuppressUserConversions, then we
1857/// do not permit any user-defined conversion sequences.
Douglas Gregor81c29152008-10-29 00:13:59 +00001858ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001859Sema::TryCopyInitialization(Expr *From, QualType ToType,
1860 bool SuppressUserConversions) {
Douglas Gregorfcb19192009-02-11 23:02:49 +00001861 if (ToType->isReferenceType()) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001862 ImplicitConversionSequence ICS;
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001863 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions);
Douglas Gregor81c29152008-10-29 00:13:59 +00001864 return ICS;
1865 } else {
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001866 return TryImplicitConversion(From, ToType, SuppressUserConversions);
Douglas Gregor81c29152008-10-29 00:13:59 +00001867 }
1868}
1869
1870/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1871/// type ToType. Returns true (and emits a diagnostic) if there was
1872/// an error, returns false if the initialization succeeded.
1873bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1874 const char* Flavor) {
1875 if (!getLangOptions().CPlusPlus) {
1876 // In C, argument passing is the same as performing an assignment.
1877 QualType FromType = From->getType();
1878 AssignConvertType ConvTy =
1879 CheckSingleAssignmentConstraints(ToType, From);
1880
1881 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1882 FromType, From, Flavor);
Douglas Gregor81c29152008-10-29 00:13:59 +00001883 }
Chris Lattner271d4c22008-11-24 05:29:24 +00001884
1885 if (ToType->isReferenceType())
1886 return CheckReferenceInit(From, ToType);
1887
Douglas Gregor6fd35572008-12-19 17:40:08 +00001888 if (!PerformImplicitConversion(From, ToType, Flavor))
Chris Lattner271d4c22008-11-24 05:29:24 +00001889 return false;
1890
1891 return Diag(From->getSourceRange().getBegin(),
1892 diag::err_typecheck_convert_incompatible)
1893 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001894}
1895
Douglas Gregor5ed15042008-11-18 23:14:02 +00001896/// TryObjectArgumentInitialization - Try to initialize the object
1897/// parameter of the given member function (@c Method) from the
1898/// expression @p From.
1899ImplicitConversionSequence
1900Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1901 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1902 unsigned MethodQuals = Method->getTypeQualifiers();
1903 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1904
1905 // Set up the conversion sequence as a "bad" conversion, to allow us
1906 // to exit early.
1907 ImplicitConversionSequence ICS;
1908 ICS.Standard.setAsIdentityConversion();
1909 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1910
1911 // We need to have an object of class type.
1912 QualType FromType = From->getType();
1913 if (!FromType->isRecordType())
1914 return ICS;
1915
1916 // The implicit object parmeter is has the type "reference to cv X",
1917 // where X is the class of which the function is a member
1918 // (C++ [over.match.funcs]p4). However, when finding an implicit
1919 // conversion sequence for the argument, we are not allowed to
1920 // create temporaries or perform user-defined conversions
1921 // (C++ [over.match.funcs]p5). We perform a simplified version of
1922 // reference binding here, that allows class rvalues to bind to
1923 // non-constant references.
1924
1925 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1926 // with the implicit object parameter (C++ [over.match.funcs]p5).
1927 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1928 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1929 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1930 return ICS;
1931
1932 // Check that we have either the same type or a derived type. It
1933 // affects the conversion rank.
1934 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1935 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1936 ICS.Standard.Second = ICK_Identity;
1937 else if (IsDerivedFrom(FromType, ClassType))
1938 ICS.Standard.Second = ICK_Derived_To_Base;
1939 else
1940 return ICS;
1941
1942 // Success. Mark this as a reference binding.
1943 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1944 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1945 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1946 ICS.Standard.ReferenceBinding = true;
1947 ICS.Standard.DirectBinding = true;
1948 return ICS;
1949}
1950
1951/// PerformObjectArgumentInitialization - Perform initialization of
1952/// the implicit object parameter for the given Method with the given
1953/// expression.
1954bool
1955Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
1956 QualType ImplicitParamType
1957 = Method->getThisType(Context)->getAsPointerType()->getPointeeType();
1958 ImplicitConversionSequence ICS
1959 = TryObjectArgumentInitialization(From, Method);
1960 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
1961 return Diag(From->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001962 diag::err_implicit_object_parameter_init)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001963 << ImplicitParamType << From->getType() << From->getSourceRange();
Douglas Gregor5ed15042008-11-18 23:14:02 +00001964
1965 if (ICS.Standard.Second == ICK_Derived_To_Base &&
1966 CheckDerivedToBaseConversion(From->getType(), ImplicitParamType,
1967 From->getSourceRange().getBegin(),
1968 From->getSourceRange()))
1969 return true;
1970
1971 ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true);
1972 return false;
1973}
1974
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001975/// TryContextuallyConvertToBool - Attempt to contextually convert the
1976/// expression From to bool (C++0x [conv]p3).
1977ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
1978 return TryImplicitConversion(From, Context.BoolTy, false, true);
1979}
1980
1981/// PerformContextuallyConvertToBool - Perform a contextual conversion
1982/// of the expression From to bool (C++0x [conv]p3).
1983bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
1984 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
1985 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
1986 return false;
1987
1988 return Diag(From->getSourceRange().getBegin(),
1989 diag::err_typecheck_bool_condition)
1990 << From->getType() << From->getSourceRange();
1991}
1992
Douglas Gregord2baafd2008-10-21 16:13:35 +00001993/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001994/// candidate functions, using the given function call arguments. If
1995/// @p SuppressUserConversions, then don't allow user-defined
1996/// conversions via constructors or conversion operators.
Douglas Gregord2baafd2008-10-21 16:13:35 +00001997void
1998Sema::AddOverloadCandidate(FunctionDecl *Function,
1999 Expr **Args, unsigned NumArgs,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002000 OverloadCandidateSet& CandidateSet,
2001 bool SuppressUserConversions)
Douglas Gregord2baafd2008-10-21 16:13:35 +00002002{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002003 const FunctionProtoType* Proto
2004 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
Douglas Gregord2baafd2008-10-21 16:13:35 +00002005 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregor60714f92008-11-07 22:36:19 +00002006 assert(!isa<CXXConversionDecl>(Function) &&
2007 "Use AddConversionCandidate for conversion functions");
Douglas Gregord2baafd2008-10-21 16:13:35 +00002008
Douglas Gregor3257fb52008-12-22 05:46:06 +00002009 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2010 // If we get here, it's because we're calling a member function
2011 // that is named without a member access expression (e.g.,
2012 // "this->f") that was either written explicitly or created
2013 // implicitly. This can happen with a qualified call to a member
2014 // function, e.g., X::f(). We use a NULL object as the implied
2015 // object argument (C++ [over.call.func]p3).
2016 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2017 SuppressUserConversions);
2018 return;
2019 }
2020
2021
Douglas Gregord2baafd2008-10-21 16:13:35 +00002022 // Add this candidate
2023 CandidateSet.push_back(OverloadCandidate());
2024 OverloadCandidate& Candidate = CandidateSet.back();
2025 Candidate.Function = Function;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002026 Candidate.Viable = true;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002027 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002028 Candidate.IgnoreObjectArgument = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00002029
2030 unsigned NumArgsInProto = Proto->getNumArgs();
2031
2032 // (C++ 13.3.2p2): A candidate function having fewer than m
2033 // parameters is viable only if it has an ellipsis in its parameter
2034 // list (8.3.5).
2035 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2036 Candidate.Viable = false;
2037 return;
2038 }
2039
2040 // (C++ 13.3.2p2): A candidate function having more than m parameters
2041 // is viable only if the (m+1)st parameter has a default argument
2042 // (8.3.6). For the purposes of overload resolution, the
2043 // parameter list is truncated on the right, so that there are
2044 // exactly m parameters.
2045 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2046 if (NumArgs < MinRequiredArgs) {
2047 // Not enough arguments.
2048 Candidate.Viable = false;
2049 return;
2050 }
2051
2052 // Determine the implicit conversion sequences for each of the
2053 // arguments.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002054 Candidate.Conversions.resize(NumArgs);
2055 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2056 if (ArgIdx < NumArgsInProto) {
2057 // (C++ 13.3.2p3): for F to be a viable function, there shall
2058 // exist for each argument an implicit conversion sequence
2059 // (13.3.3.1) that converts that argument to the corresponding
2060 // parameter of F.
2061 QualType ParamType = Proto->getArgType(ArgIdx);
2062 Candidate.Conversions[ArgIdx]
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002063 = TryCopyInitialization(Args[ArgIdx], ParamType,
2064 SuppressUserConversions);
Douglas Gregord2baafd2008-10-21 16:13:35 +00002065 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002066 == ImplicitConversionSequence::BadConversion) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00002067 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002068 break;
2069 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002070 } else {
2071 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2072 // argument for which there is no corresponding parameter is
2073 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2074 Candidate.Conversions[ArgIdx].ConversionKind
2075 = ImplicitConversionSequence::EllipsisConversion;
2076 }
2077 }
2078}
2079
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002080/// \brief Add all of the function declarations in the given function set to
2081/// the overload canddiate set.
2082void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2083 Expr **Args, unsigned NumArgs,
2084 OverloadCandidateSet& CandidateSet,
2085 bool SuppressUserConversions) {
2086 for (FunctionSet::const_iterator F = Functions.begin(),
2087 FEnd = Functions.end();
2088 F != FEnd; ++F)
2089 AddOverloadCandidate(*F, Args, NumArgs, CandidateSet,
2090 SuppressUserConversions);
2091}
2092
Douglas Gregor5ed15042008-11-18 23:14:02 +00002093/// AddMethodCandidate - Adds the given C++ member function to the set
2094/// of candidate functions, using the given function call arguments
2095/// and the object argument (@c Object). For example, in a call
2096/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2097/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2098/// allow user-defined conversions via constructors or conversion
2099/// operators.
2100void
2101Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2102 Expr **Args, unsigned NumArgs,
2103 OverloadCandidateSet& CandidateSet,
2104 bool SuppressUserConversions)
2105{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002106 const FunctionProtoType* Proto
2107 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00002108 assert(Proto && "Methods without a prototype cannot be overloaded");
2109 assert(!isa<CXXConversionDecl>(Method) &&
2110 "Use AddConversionCandidate for conversion functions");
2111
2112 // Add this candidate
2113 CandidateSet.push_back(OverloadCandidate());
2114 OverloadCandidate& Candidate = CandidateSet.back();
2115 Candidate.Function = Method;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002116 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002117 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002118
2119 unsigned NumArgsInProto = Proto->getNumArgs();
2120
2121 // (C++ 13.3.2p2): A candidate function having fewer than m
2122 // parameters is viable only if it has an ellipsis in its parameter
2123 // list (8.3.5).
2124 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2125 Candidate.Viable = false;
2126 return;
2127 }
2128
2129 // (C++ 13.3.2p2): A candidate function having more than m parameters
2130 // is viable only if the (m+1)st parameter has a default argument
2131 // (8.3.6). For the purposes of overload resolution, the
2132 // parameter list is truncated on the right, so that there are
2133 // exactly m parameters.
2134 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2135 if (NumArgs < MinRequiredArgs) {
2136 // Not enough arguments.
2137 Candidate.Viable = false;
2138 return;
2139 }
2140
2141 Candidate.Viable = true;
2142 Candidate.Conversions.resize(NumArgs + 1);
2143
Douglas Gregor3257fb52008-12-22 05:46:06 +00002144 if (Method->isStatic() || !Object)
2145 // The implicit object argument is ignored.
2146 Candidate.IgnoreObjectArgument = true;
2147 else {
2148 // Determine the implicit conversion sequence for the object
2149 // parameter.
2150 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2151 if (Candidate.Conversions[0].ConversionKind
2152 == ImplicitConversionSequence::BadConversion) {
2153 Candidate.Viable = false;
2154 return;
2155 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002156 }
2157
2158 // Determine the implicit conversion sequences for each of the
2159 // arguments.
2160 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2161 if (ArgIdx < NumArgsInProto) {
2162 // (C++ 13.3.2p3): for F to be a viable function, there shall
2163 // exist for each argument an implicit conversion sequence
2164 // (13.3.3.1) that converts that argument to the corresponding
2165 // parameter of F.
2166 QualType ParamType = Proto->getArgType(ArgIdx);
2167 Candidate.Conversions[ArgIdx + 1]
2168 = TryCopyInitialization(Args[ArgIdx], ParamType,
2169 SuppressUserConversions);
2170 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2171 == ImplicitConversionSequence::BadConversion) {
2172 Candidate.Viable = false;
2173 break;
2174 }
2175 } else {
2176 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2177 // argument for which there is no corresponding parameter is
2178 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2179 Candidate.Conversions[ArgIdx + 1].ConversionKind
2180 = ImplicitConversionSequence::EllipsisConversion;
2181 }
2182 }
2183}
2184
Douglas Gregor60714f92008-11-07 22:36:19 +00002185/// AddConversionCandidate - Add a C++ conversion function as a
2186/// candidate in the candidate set (C++ [over.match.conv],
2187/// C++ [over.match.copy]). From is the expression we're converting from,
2188/// and ToType is the type that we're eventually trying to convert to
2189/// (which may or may not be the same type as the type that the
2190/// conversion function produces).
2191void
2192Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2193 Expr *From, QualType ToType,
2194 OverloadCandidateSet& CandidateSet) {
2195 // Add this candidate
2196 CandidateSet.push_back(OverloadCandidate());
2197 OverloadCandidate& Candidate = CandidateSet.back();
2198 Candidate.Function = Conversion;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002199 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002200 Candidate.IgnoreObjectArgument = false;
Douglas Gregor60714f92008-11-07 22:36:19 +00002201 Candidate.FinalConversion.setAsIdentityConversion();
2202 Candidate.FinalConversion.FromTypePtr
2203 = Conversion->getConversionType().getAsOpaquePtr();
2204 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2205
Douglas Gregor5ed15042008-11-18 23:14:02 +00002206 // Determine the implicit conversion sequence for the implicit
2207 // object parameter.
Douglas Gregor60714f92008-11-07 22:36:19 +00002208 Candidate.Viable = true;
2209 Candidate.Conversions.resize(1);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002210 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregor60714f92008-11-07 22:36:19 +00002211
Douglas Gregor60714f92008-11-07 22:36:19 +00002212 if (Candidate.Conversions[0].ConversionKind
2213 == ImplicitConversionSequence::BadConversion) {
2214 Candidate.Viable = false;
2215 return;
2216 }
2217
2218 // To determine what the conversion from the result of calling the
2219 // conversion function to the type we're eventually trying to
2220 // convert to (ToType), we need to synthesize a call to the
2221 // conversion function and attempt copy initialization from it. This
2222 // makes sure that we get the right semantics with respect to
2223 // lvalues/rvalues and the type. Fortunately, we can allocate this
2224 // call on the stack and we don't need its arguments to be
2225 // well-formed.
2226 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2227 SourceLocation());
2228 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Douglas Gregor70d26122008-11-12 17:17:38 +00002229 &ConversionRef, false);
Ted Kremenek362abcd2009-02-09 20:51:47 +00002230
2231 // Note that it is safe to allocate CallExpr on the stack here because
2232 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2233 // allocator).
2234 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregor60714f92008-11-07 22:36:19 +00002235 Conversion->getConversionType().getNonReferenceType(),
2236 SourceLocation());
2237 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2238 switch (ICS.ConversionKind) {
2239 case ImplicitConversionSequence::StandardConversion:
2240 Candidate.FinalConversion = ICS.Standard;
2241 break;
2242
2243 case ImplicitConversionSequence::BadConversion:
2244 Candidate.Viable = false;
2245 break;
2246
2247 default:
2248 assert(false &&
2249 "Can only end up with a standard conversion sequence or failure");
2250 }
2251}
2252
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002253/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2254/// converts the given @c Object to a function pointer via the
2255/// conversion function @c Conversion, and then attempts to call it
2256/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2257/// the type of function that we'll eventually be calling.
2258void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002259 const FunctionProtoType *Proto,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002260 Expr *Object, Expr **Args, unsigned NumArgs,
2261 OverloadCandidateSet& CandidateSet) {
2262 CandidateSet.push_back(OverloadCandidate());
2263 OverloadCandidate& Candidate = CandidateSet.back();
2264 Candidate.Function = 0;
2265 Candidate.Surrogate = Conversion;
2266 Candidate.Viable = true;
2267 Candidate.IsSurrogate = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002268 Candidate.IgnoreObjectArgument = false;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002269 Candidate.Conversions.resize(NumArgs + 1);
2270
2271 // Determine the implicit conversion sequence for the implicit
2272 // object parameter.
2273 ImplicitConversionSequence ObjectInit
2274 = TryObjectArgumentInitialization(Object, Conversion);
2275 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2276 Candidate.Viable = false;
2277 return;
2278 }
2279
2280 // The first conversion is actually a user-defined conversion whose
2281 // first conversion is ObjectInit's standard conversion (which is
2282 // effectively a reference binding). Record it as such.
2283 Candidate.Conversions[0].ConversionKind
2284 = ImplicitConversionSequence::UserDefinedConversion;
2285 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2286 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2287 Candidate.Conversions[0].UserDefined.After
2288 = Candidate.Conversions[0].UserDefined.Before;
2289 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2290
2291 // Find the
2292 unsigned NumArgsInProto = Proto->getNumArgs();
2293
2294 // (C++ 13.3.2p2): A candidate function having fewer than m
2295 // parameters is viable only if it has an ellipsis in its parameter
2296 // list (8.3.5).
2297 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2298 Candidate.Viable = false;
2299 return;
2300 }
2301
2302 // Function types don't have any default arguments, so just check if
2303 // we have enough arguments.
2304 if (NumArgs < NumArgsInProto) {
2305 // Not enough arguments.
2306 Candidate.Viable = false;
2307 return;
2308 }
2309
2310 // Determine the implicit conversion sequences for each of the
2311 // arguments.
2312 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2313 if (ArgIdx < NumArgsInProto) {
2314 // (C++ 13.3.2p3): for F to be a viable function, there shall
2315 // exist for each argument an implicit conversion sequence
2316 // (13.3.3.1) that converts that argument to the corresponding
2317 // parameter of F.
2318 QualType ParamType = Proto->getArgType(ArgIdx);
2319 Candidate.Conversions[ArgIdx + 1]
2320 = TryCopyInitialization(Args[ArgIdx], ParamType,
2321 /*SuppressUserConversions=*/false);
2322 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2323 == ImplicitConversionSequence::BadConversion) {
2324 Candidate.Viable = false;
2325 break;
2326 }
2327 } else {
2328 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2329 // argument for which there is no corresponding parameter is
2330 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2331 Candidate.Conversions[ArgIdx + 1].ConversionKind
2332 = ImplicitConversionSequence::EllipsisConversion;
2333 }
2334 }
2335}
2336
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002337// FIXME: This will eventually be removed, once we've migrated all of
2338// the operator overloading logic over to the scheme used by binary
2339// operators, which works for template instantiation.
2340void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor48a87322009-02-04 16:44:47 +00002341 SourceLocation OpLoc,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002342 Expr **Args, unsigned NumArgs,
Douglas Gregor48a87322009-02-04 16:44:47 +00002343 OverloadCandidateSet& CandidateSet,
2344 SourceRange OpRange) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002345
2346 FunctionSet Functions;
2347
2348 QualType T1 = Args[0]->getType();
2349 QualType T2;
2350 if (NumArgs > 1)
2351 T2 = Args[1]->getType();
2352
2353 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2354 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
2355 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2356 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2357 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2358 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2359}
2360
2361/// \brief Add overload candidates for overloaded operators that are
2362/// member functions.
2363///
2364/// Add the overloaded operator candidates that are member functions
2365/// for the operator Op that was used in an operator expression such
2366/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2367/// CandidateSet will store the added overload candidates. (C++
2368/// [over.match.oper]).
2369void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2370 SourceLocation OpLoc,
2371 Expr **Args, unsigned NumArgs,
2372 OverloadCandidateSet& CandidateSet,
2373 SourceRange OpRange) {
Douglas Gregor5ed15042008-11-18 23:14:02 +00002374 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2375
2376 // C++ [over.match.oper]p3:
2377 // For a unary operator @ with an operand of a type whose
2378 // cv-unqualified version is T1, and for a binary operator @ with
2379 // a left operand of a type whose cv-unqualified version is T1 and
2380 // a right operand of a type whose cv-unqualified version is T2,
2381 // three sets of candidate functions, designated member
2382 // candidates, non-member candidates and built-in candidates, are
2383 // constructed as follows:
2384 QualType T1 = Args[0]->getType();
2385 QualType T2;
2386 if (NumArgs > 1)
2387 T2 = Args[1]->getType();
2388
2389 // -- If T1 is a class type, the set of member candidates is the
2390 // result of the qualified lookup of T1::operator@
2391 // (13.3.1.1.1); otherwise, the set of member candidates is
2392 // empty.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002393 // FIXME: Lookup in base classes, too!
Douglas Gregor5ed15042008-11-18 23:14:02 +00002394 if (const RecordType *T1Rec = T1->getAsRecordType()) {
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002395 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroffab63fd62009-01-08 17:28:14 +00002396 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002397 Oper != OperEnd; ++Oper)
2398 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2399 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002400 /*SuppressUserConversions=*/false);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002401 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002402}
2403
Douglas Gregor70d26122008-11-12 17:17:38 +00002404/// AddBuiltinCandidate - Add a candidate for a built-in
2405/// operator. ResultTy and ParamTys are the result and parameter types
2406/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorab141112009-01-13 00:52:54 +00002407/// arguments being passed to the candidate. IsAssignmentOperator
2408/// should be true when this built-in candidate is an assignment
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002409/// operator. NumContextualBoolArguments is the number of arguments
2410/// (at the beginning of the argument list) that will be contextually
2411/// converted to bool.
Douglas Gregor70d26122008-11-12 17:17:38 +00002412void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2413 Expr **Args, unsigned NumArgs,
Douglas Gregorab141112009-01-13 00:52:54 +00002414 OverloadCandidateSet& CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002415 bool IsAssignmentOperator,
2416 unsigned NumContextualBoolArguments) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002417 // Add this candidate
2418 CandidateSet.push_back(OverloadCandidate());
2419 OverloadCandidate& Candidate = CandidateSet.back();
2420 Candidate.Function = 0;
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00002421 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002422 Candidate.IgnoreObjectArgument = false;
Douglas Gregor70d26122008-11-12 17:17:38 +00002423 Candidate.BuiltinTypes.ResultTy = ResultTy;
2424 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2425 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2426
2427 // Determine the implicit conversion sequences for each of the
2428 // arguments.
2429 Candidate.Viable = true;
2430 Candidate.Conversions.resize(NumArgs);
2431 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorab141112009-01-13 00:52:54 +00002432 // C++ [over.match.oper]p4:
2433 // For the built-in assignment operators, conversions of the
2434 // left operand are restricted as follows:
2435 // -- no temporaries are introduced to hold the left operand, and
2436 // -- no user-defined conversions are applied to the left
2437 // operand to achieve a type match with the left-most
2438 // parameter of a built-in candidate.
2439 //
2440 // We block these conversions by turning off user-defined
2441 // conversions, since that is the only way that initialization of
2442 // a reference to a non-class type can occur from something that
2443 // is not of the same type.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002444 if (ArgIdx < NumContextualBoolArguments) {
2445 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2446 "Contextual conversion to bool requires bool type");
2447 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2448 } else {
2449 Candidate.Conversions[ArgIdx]
2450 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2451 ArgIdx == 0 && IsAssignmentOperator);
2452 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002453 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002454 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002455 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002456 break;
2457 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002458 }
2459}
2460
2461/// BuiltinCandidateTypeSet - A set of types that will be used for the
2462/// candidate operator functions for built-in operators (C++
2463/// [over.built]). The types are separated into pointer types and
2464/// enumeration types.
2465class BuiltinCandidateTypeSet {
2466 /// TypeSet - A set of types.
Douglas Gregor3d4492e2008-11-13 20:12:29 +00002467 typedef llvm::SmallPtrSet<void*, 8> TypeSet;
Douglas Gregor70d26122008-11-12 17:17:38 +00002468
2469 /// PointerTypes - The set of pointer types that will be used in the
2470 /// built-in candidates.
2471 TypeSet PointerTypes;
2472
2473 /// EnumerationTypes - The set of enumeration types that will be
2474 /// used in the built-in candidates.
2475 TypeSet EnumerationTypes;
2476
2477 /// Context - The AST context in which we will build the type sets.
2478 ASTContext &Context;
2479
2480 bool AddWithMoreQualifiedTypeVariants(QualType Ty);
2481
2482public:
2483 /// iterator - Iterates through the types that are part of the set.
Douglas Gregor3d4492e2008-11-13 20:12:29 +00002484 class iterator {
2485 TypeSet::iterator Base;
2486
2487 public:
2488 typedef QualType value_type;
2489 typedef QualType reference;
2490 typedef QualType pointer;
2491 typedef std::ptrdiff_t difference_type;
2492 typedef std::input_iterator_tag iterator_category;
2493
2494 iterator(TypeSet::iterator B) : Base(B) { }
2495
2496 iterator& operator++() {
2497 ++Base;
2498 return *this;
2499 }
2500
2501 iterator operator++(int) {
2502 iterator tmp(*this);
2503 ++(*this);
2504 return tmp;
2505 }
2506
2507 reference operator*() const {
2508 return QualType::getFromOpaquePtr(*Base);
2509 }
2510
2511 pointer operator->() const {
2512 return **this;
2513 }
2514
2515 friend bool operator==(iterator LHS, iterator RHS) {
2516 return LHS.Base == RHS.Base;
2517 }
2518
2519 friend bool operator!=(iterator LHS, iterator RHS) {
2520 return LHS.Base != RHS.Base;
2521 }
2522 };
Douglas Gregor70d26122008-11-12 17:17:38 +00002523
2524 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2525
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002526 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2527 bool AllowExplicitConversions);
Douglas Gregor70d26122008-11-12 17:17:38 +00002528
2529 /// pointer_begin - First pointer type found;
2530 iterator pointer_begin() { return PointerTypes.begin(); }
2531
2532 /// pointer_end - Last pointer type found;
2533 iterator pointer_end() { return PointerTypes.end(); }
2534
2535 /// enumeration_begin - First enumeration type found;
2536 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2537
2538 /// enumeration_end - Last enumeration type found;
2539 iterator enumeration_end() { return EnumerationTypes.end(); }
2540};
2541
2542/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2543/// the set of pointer types along with any more-qualified variants of
2544/// that type. For example, if @p Ty is "int const *", this routine
2545/// will add "int const *", "int const volatile *", "int const
2546/// restrict *", and "int const volatile restrict *" to the set of
2547/// pointer types. Returns true if the add of @p Ty itself succeeded,
2548/// false otherwise.
2549bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) {
2550 // Insert this type.
Douglas Gregor3d4492e2008-11-13 20:12:29 +00002551 if (!PointerTypes.insert(Ty.getAsOpaquePtr()))
Douglas Gregor70d26122008-11-12 17:17:38 +00002552 return false;
2553
2554 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2555 QualType PointeeTy = PointerTy->getPointeeType();
2556 // FIXME: Optimize this so that we don't keep trying to add the same types.
2557
2558 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
2559 // with all pointer conversions that don't cast away constness?
2560 if (!PointeeTy.isConstQualified())
2561 AddWithMoreQualifiedTypeVariants
2562 (Context.getPointerType(PointeeTy.withConst()));
2563 if (!PointeeTy.isVolatileQualified())
2564 AddWithMoreQualifiedTypeVariants
2565 (Context.getPointerType(PointeeTy.withVolatile()));
2566 if (!PointeeTy.isRestrictQualified())
2567 AddWithMoreQualifiedTypeVariants
2568 (Context.getPointerType(PointeeTy.withRestrict()));
2569 }
2570
2571 return true;
2572}
2573
2574/// AddTypesConvertedFrom - Add each of the types to which the type @p
2575/// Ty can be implicit converted to the given set of @p Types. We're
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002576/// primarily interested in pointer types and enumeration types.
2577/// AllowUserConversions is true if we should look at the conversion
2578/// functions of a class type, and AllowExplicitConversions if we
2579/// should also include the explicit conversion functions of a class
2580/// type.
2581void
2582BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2583 bool AllowUserConversions,
2584 bool AllowExplicitConversions) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002585 // Only deal with canonical types.
2586 Ty = Context.getCanonicalType(Ty);
2587
2588 // Look through reference types; they aren't part of the type of an
2589 // expression for the purposes of conversions.
2590 if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2591 Ty = RefTy->getPointeeType();
2592
2593 // We don't care about qualifiers on the type.
2594 Ty = Ty.getUnqualifiedType();
2595
2596 if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2597 QualType PointeeTy = PointerTy->getPointeeType();
2598
2599 // Insert our type, and its more-qualified variants, into the set
2600 // of types.
2601 if (!AddWithMoreQualifiedTypeVariants(Ty))
2602 return;
2603
2604 // Add 'cv void*' to our set of types.
2605 if (!Ty->isVoidType()) {
2606 QualType QualVoid
2607 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2608 AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2609 }
2610
2611 // If this is a pointer to a class type, add pointers to its bases
2612 // (with the same level of cv-qualification as the original
2613 // derived class, of course).
2614 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2615 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2616 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2617 Base != ClassDecl->bases_end(); ++Base) {
2618 QualType BaseTy = Context.getCanonicalType(Base->getType());
2619 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2620
2621 // Add the pointer type, recursively, so that we get all of
2622 // the indirect base classes, too.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002623 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002624 }
2625 }
2626 } else if (Ty->isEnumeralType()) {
Douglas Gregor3d4492e2008-11-13 20:12:29 +00002627 EnumerationTypes.insert(Ty.getAsOpaquePtr());
Douglas Gregor70d26122008-11-12 17:17:38 +00002628 } else if (AllowUserConversions) {
2629 if (const RecordType *TyRec = Ty->getAsRecordType()) {
2630 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2631 // FIXME: Visit conversion functions in the base classes, too.
2632 OverloadedFunctionDecl *Conversions
2633 = ClassDecl->getConversionFunctions();
2634 for (OverloadedFunctionDecl::function_iterator Func
2635 = Conversions->function_begin();
2636 Func != Conversions->function_end(); ++Func) {
2637 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002638 if (AllowExplicitConversions || !Conv->isExplicit())
2639 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002640 }
2641 }
2642 }
2643}
2644
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002645/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2646/// operator overloads to the candidate set (C++ [over.built]), based
2647/// on the operator @p Op and the arguments given. For example, if the
2648/// operator is a binary '+', this routine might add "int
2649/// operator+(int, int)" to cover integer addition.
Douglas Gregor70d26122008-11-12 17:17:38 +00002650void
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002651Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2652 Expr **Args, unsigned NumArgs,
2653 OverloadCandidateSet& CandidateSet) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002654 // The set of "promoted arithmetic types", which are the arithmetic
2655 // types are that preserved by promotion (C++ [over.built]p2). Note
2656 // that the first few of these types are the promoted integral
2657 // types; these types need to be first.
2658 // FIXME: What about complex?
2659 const unsigned FirstIntegralType = 0;
2660 const unsigned LastIntegralType = 13;
2661 const unsigned FirstPromotedIntegralType = 7,
2662 LastPromotedIntegralType = 13;
2663 const unsigned FirstPromotedArithmeticType = 7,
2664 LastPromotedArithmeticType = 16;
2665 const unsigned NumArithmeticTypes = 16;
2666 QualType ArithmeticTypes[NumArithmeticTypes] = {
2667 Context.BoolTy, Context.CharTy, Context.WCharTy,
2668 Context.SignedCharTy, Context.ShortTy,
2669 Context.UnsignedCharTy, Context.UnsignedShortTy,
2670 Context.IntTy, Context.LongTy, Context.LongLongTy,
2671 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2672 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2673 };
2674
2675 // Find all of the types that the arguments can convert to, but only
2676 // if the operator we're looking at has built-in operator candidates
2677 // that make use of these types.
2678 BuiltinCandidateTypeSet CandidateTypes(Context);
2679 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2680 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002681 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregor70d26122008-11-12 17:17:38 +00002682 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002683 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
2684 (Op == OO_Star && NumArgs == 1)) {
2685 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002686 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2687 true,
2688 (Op == OO_Exclaim ||
2689 Op == OO_AmpAmp ||
2690 Op == OO_PipePipe));
Douglas Gregor70d26122008-11-12 17:17:38 +00002691 }
2692
2693 bool isComparison = false;
2694 switch (Op) {
2695 case OO_None:
2696 case NUM_OVERLOADED_OPERATORS:
2697 assert(false && "Expected an overloaded operator");
2698 break;
2699
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002700 case OO_Star: // '*' is either unary or binary
2701 if (NumArgs == 1)
2702 goto UnaryStar;
2703 else
2704 goto BinaryStar;
2705 break;
2706
2707 case OO_Plus: // '+' is either unary or binary
2708 if (NumArgs == 1)
2709 goto UnaryPlus;
2710 else
2711 goto BinaryPlus;
2712 break;
2713
2714 case OO_Minus: // '-' is either unary or binary
2715 if (NumArgs == 1)
2716 goto UnaryMinus;
2717 else
2718 goto BinaryMinus;
2719 break;
2720
2721 case OO_Amp: // '&' is either unary or binary
2722 if (NumArgs == 1)
2723 goto UnaryAmp;
2724 else
2725 goto BinaryAmp;
2726
2727 case OO_PlusPlus:
2728 case OO_MinusMinus:
2729 // C++ [over.built]p3:
2730 //
2731 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2732 // is either volatile or empty, there exist candidate operator
2733 // functions of the form
2734 //
2735 // VQ T& operator++(VQ T&);
2736 // T operator++(VQ T&, int);
2737 //
2738 // C++ [over.built]p4:
2739 //
2740 // For every pair (T, VQ), where T is an arithmetic type other
2741 // than bool, and VQ is either volatile or empty, there exist
2742 // candidate operator functions of the form
2743 //
2744 // VQ T& operator--(VQ T&);
2745 // T operator--(VQ T&, int);
2746 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2747 Arith < NumArithmeticTypes; ++Arith) {
2748 QualType ArithTy = ArithmeticTypes[Arith];
2749 QualType ParamTypes[2]
Sebastian Redlce6fff02009-03-16 23:22:08 +00002750 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002751
2752 // Non-volatile version.
2753 if (NumArgs == 1)
2754 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2755 else
2756 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2757
2758 // Volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00002759 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002760 if (NumArgs == 1)
2761 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2762 else
2763 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2764 }
2765
2766 // C++ [over.built]p5:
2767 //
2768 // For every pair (T, VQ), where T is a cv-qualified or
2769 // cv-unqualified object type, and VQ is either volatile or
2770 // empty, there exist candidate operator functions of the form
2771 //
2772 // T*VQ& operator++(T*VQ&);
2773 // T*VQ& operator--(T*VQ&);
2774 // T* operator++(T*VQ&, int);
2775 // T* operator--(T*VQ&, int);
2776 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2777 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2778 // Skip pointer types that aren't pointers to object types.
Douglas Gregor24a90a52008-11-26 23:31:11 +00002779 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002780 continue;
2781
2782 QualType ParamTypes[2] = {
Sebastian Redlce6fff02009-03-16 23:22:08 +00002783 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002784 };
2785
2786 // Without volatile
2787 if (NumArgs == 1)
2788 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2789 else
2790 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2791
2792 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2793 // With volatile
Sebastian Redlce6fff02009-03-16 23:22:08 +00002794 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002795 if (NumArgs == 1)
2796 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2797 else
2798 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2799 }
2800 }
2801 break;
2802
2803 UnaryStar:
2804 // C++ [over.built]p6:
2805 // For every cv-qualified or cv-unqualified object type T, there
2806 // exist candidate operator functions of the form
2807 //
2808 // T& operator*(T*);
2809 //
2810 // C++ [over.built]p7:
2811 // For every function type T, there exist candidate operator
2812 // functions of the form
2813 // T& operator*(T*);
2814 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2815 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2816 QualType ParamTy = *Ptr;
2817 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00002818 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002819 &ParamTy, Args, 1, CandidateSet);
2820 }
2821 break;
2822
2823 UnaryPlus:
2824 // C++ [over.built]p8:
2825 // For every type T, there exist candidate operator functions of
2826 // the form
2827 //
2828 // T* operator+(T*);
2829 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2830 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2831 QualType ParamTy = *Ptr;
2832 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2833 }
2834
2835 // Fall through
2836
2837 UnaryMinus:
2838 // C++ [over.built]p9:
2839 // For every promoted arithmetic type T, there exist candidate
2840 // operator functions of the form
2841 //
2842 // T operator+(T);
2843 // T operator-(T);
2844 for (unsigned Arith = FirstPromotedArithmeticType;
2845 Arith < LastPromotedArithmeticType; ++Arith) {
2846 QualType ArithTy = ArithmeticTypes[Arith];
2847 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2848 }
2849 break;
2850
2851 case OO_Tilde:
2852 // C++ [over.built]p10:
2853 // For every promoted integral type T, there exist candidate
2854 // operator functions of the form
2855 //
2856 // T operator~(T);
2857 for (unsigned Int = FirstPromotedIntegralType;
2858 Int < LastPromotedIntegralType; ++Int) {
2859 QualType IntTy = ArithmeticTypes[Int];
2860 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2861 }
2862 break;
2863
Douglas Gregor70d26122008-11-12 17:17:38 +00002864 case OO_New:
2865 case OO_Delete:
2866 case OO_Array_New:
2867 case OO_Array_Delete:
Douglas Gregor70d26122008-11-12 17:17:38 +00002868 case OO_Call:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002869 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregor70d26122008-11-12 17:17:38 +00002870 break;
2871
2872 case OO_Comma:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002873 UnaryAmp:
2874 case OO_Arrow:
Douglas Gregor70d26122008-11-12 17:17:38 +00002875 // C++ [over.match.oper]p3:
2876 // -- For the operator ',', the unary operator '&', or the
2877 // operator '->', the built-in candidates set is empty.
Douglas Gregor70d26122008-11-12 17:17:38 +00002878 break;
2879
2880 case OO_Less:
2881 case OO_Greater:
2882 case OO_LessEqual:
2883 case OO_GreaterEqual:
2884 case OO_EqualEqual:
2885 case OO_ExclaimEqual:
2886 // C++ [over.built]p15:
2887 //
2888 // For every pointer or enumeration type T, there exist
2889 // candidate operator functions of the form
2890 //
2891 // bool operator<(T, T);
2892 // bool operator>(T, T);
2893 // bool operator<=(T, T);
2894 // bool operator>=(T, T);
2895 // bool operator==(T, T);
2896 // bool operator!=(T, T);
2897 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2898 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2899 QualType ParamTypes[2] = { *Ptr, *Ptr };
2900 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2901 }
2902 for (BuiltinCandidateTypeSet::iterator Enum
2903 = CandidateTypes.enumeration_begin();
2904 Enum != CandidateTypes.enumeration_end(); ++Enum) {
2905 QualType ParamTypes[2] = { *Enum, *Enum };
2906 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2907 }
2908
2909 // Fall through.
2910 isComparison = true;
2911
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002912 BinaryPlus:
2913 BinaryMinus:
Douglas Gregor70d26122008-11-12 17:17:38 +00002914 if (!isComparison) {
2915 // We didn't fall through, so we must have OO_Plus or OO_Minus.
2916
2917 // C++ [over.built]p13:
2918 //
2919 // For every cv-qualified or cv-unqualified object type T
2920 // there exist candidate operator functions of the form
2921 //
2922 // T* operator+(T*, ptrdiff_t);
2923 // T& operator[](T*, ptrdiff_t); [BELOW]
2924 // T* operator-(T*, ptrdiff_t);
2925 // T* operator+(ptrdiff_t, T*);
2926 // T& operator[](ptrdiff_t, T*); [BELOW]
2927 //
2928 // C++ [over.built]p14:
2929 //
2930 // For every T, where T is a pointer to object type, there
2931 // exist candidate operator functions of the form
2932 //
2933 // ptrdiff_t operator-(T, T);
2934 for (BuiltinCandidateTypeSet::iterator Ptr
2935 = CandidateTypes.pointer_begin();
2936 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2937 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2938
2939 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
2940 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2941
2942 if (Op == OO_Plus) {
2943 // T* operator+(ptrdiff_t, T*);
2944 ParamTypes[0] = ParamTypes[1];
2945 ParamTypes[1] = *Ptr;
2946 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2947 } else {
2948 // ptrdiff_t operator-(T, T);
2949 ParamTypes[1] = *Ptr;
2950 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
2951 Args, 2, CandidateSet);
2952 }
2953 }
2954 }
2955 // Fall through
2956
Douglas Gregor70d26122008-11-12 17:17:38 +00002957 case OO_Slash:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002958 BinaryStar:
Douglas Gregor70d26122008-11-12 17:17:38 +00002959 // C++ [over.built]p12:
2960 //
2961 // For every pair of promoted arithmetic types L and R, there
2962 // exist candidate operator functions of the form
2963 //
2964 // LR operator*(L, R);
2965 // LR operator/(L, R);
2966 // LR operator+(L, R);
2967 // LR operator-(L, R);
2968 // bool operator<(L, R);
2969 // bool operator>(L, R);
2970 // bool operator<=(L, R);
2971 // bool operator>=(L, R);
2972 // bool operator==(L, R);
2973 // bool operator!=(L, R);
2974 //
2975 // where LR is the result of the usual arithmetic conversions
2976 // between types L and R.
2977 for (unsigned Left = FirstPromotedArithmeticType;
2978 Left < LastPromotedArithmeticType; ++Left) {
2979 for (unsigned Right = FirstPromotedArithmeticType;
2980 Right < LastPromotedArithmeticType; ++Right) {
2981 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2982 QualType Result
2983 = isComparison? Context.BoolTy
2984 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2985 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2986 }
2987 }
2988 break;
2989
2990 case OO_Percent:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002991 BinaryAmp:
Douglas Gregor70d26122008-11-12 17:17:38 +00002992 case OO_Caret:
2993 case OO_Pipe:
2994 case OO_LessLess:
2995 case OO_GreaterGreater:
2996 // C++ [over.built]p17:
2997 //
2998 // For every pair of promoted integral types L and R, there
2999 // exist candidate operator functions of the form
3000 //
3001 // LR operator%(L, R);
3002 // LR operator&(L, R);
3003 // LR operator^(L, R);
3004 // LR operator|(L, R);
3005 // L operator<<(L, R);
3006 // L operator>>(L, R);
3007 //
3008 // where LR is the result of the usual arithmetic conversions
3009 // between types L and R.
3010 for (unsigned Left = FirstPromotedIntegralType;
3011 Left < LastPromotedIntegralType; ++Left) {
3012 for (unsigned Right = FirstPromotedIntegralType;
3013 Right < LastPromotedIntegralType; ++Right) {
3014 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3015 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3016 ? LandR[0]
3017 : UsualArithmeticConversionsType(LandR[0], LandR[1]);
3018 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3019 }
3020 }
3021 break;
3022
3023 case OO_Equal:
3024 // C++ [over.built]p20:
3025 //
3026 // For every pair (T, VQ), where T is an enumeration or
3027 // (FIXME:) pointer to member type and VQ is either volatile or
3028 // empty, there exist candidate operator functions of the form
3029 //
3030 // VQ T& operator=(VQ T&, T);
3031 for (BuiltinCandidateTypeSet::iterator Enum
3032 = CandidateTypes.enumeration_begin();
3033 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3034 QualType ParamTypes[2];
3035
3036 // T& operator=(T&, T)
Sebastian Redlce6fff02009-03-16 23:22:08 +00003037 ParamTypes[0] = Context.getLValueReferenceType(*Enum);
Douglas Gregor70d26122008-11-12 17:17:38 +00003038 ParamTypes[1] = *Enum;
Douglas Gregorab141112009-01-13 00:52:54 +00003039 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003040 /*IsAssignmentOperator=*/false);
Douglas Gregor70d26122008-11-12 17:17:38 +00003041
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003042 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
3043 // volatile T& operator=(volatile T&, T)
Sebastian Redlce6fff02009-03-16 23:22:08 +00003044 ParamTypes[0] = Context.getLValueReferenceType((*Enum).withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003045 ParamTypes[1] = *Enum;
Douglas Gregorab141112009-01-13 00:52:54 +00003046 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003047 /*IsAssignmentOperator=*/false);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003048 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003049 }
3050 // Fall through.
3051
3052 case OO_PlusEqual:
3053 case OO_MinusEqual:
3054 // C++ [over.built]p19:
3055 //
3056 // For every pair (T, VQ), where T is any type and VQ is either
3057 // volatile or empty, there exist candidate operator functions
3058 // of the form
3059 //
3060 // T*VQ& operator=(T*VQ&, T*);
3061 //
3062 // C++ [over.built]p21:
3063 //
3064 // For every pair (T, VQ), where T is a cv-qualified or
3065 // cv-unqualified object type and VQ is either volatile or
3066 // empty, there exist candidate operator functions of the form
3067 //
3068 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3069 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3070 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3071 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3072 QualType ParamTypes[2];
3073 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3074
3075 // non-volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003076 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorab141112009-01-13 00:52:54 +00003077 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3078 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003079
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003080 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3081 // volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003082 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregorab141112009-01-13 00:52:54 +00003083 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3084 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003085 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003086 }
3087 // Fall through.
3088
3089 case OO_StarEqual:
3090 case OO_SlashEqual:
3091 // C++ [over.built]p18:
3092 //
3093 // For every triple (L, VQ, R), where L is an arithmetic type,
3094 // VQ is either volatile or empty, and R is a promoted
3095 // arithmetic type, there exist candidate operator functions of
3096 // the form
3097 //
3098 // VQ L& operator=(VQ L&, R);
3099 // VQ L& operator*=(VQ L&, R);
3100 // VQ L& operator/=(VQ L&, R);
3101 // VQ L& operator+=(VQ L&, R);
3102 // VQ L& operator-=(VQ L&, R);
3103 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3104 for (unsigned Right = FirstPromotedArithmeticType;
3105 Right < LastPromotedArithmeticType; ++Right) {
3106 QualType ParamTypes[2];
3107 ParamTypes[1] = ArithmeticTypes[Right];
3108
3109 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003110 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorab141112009-01-13 00:52:54 +00003111 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3112 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003113
3114 // Add this built-in operator as a candidate (VQ is 'volatile').
3115 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003116 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregorab141112009-01-13 00:52:54 +00003117 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3118 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003119 }
3120 }
3121 break;
3122
3123 case OO_PercentEqual:
3124 case OO_LessLessEqual:
3125 case OO_GreaterGreaterEqual:
3126 case OO_AmpEqual:
3127 case OO_CaretEqual:
3128 case OO_PipeEqual:
3129 // C++ [over.built]p22:
3130 //
3131 // For every triple (L, VQ, R), where L is an integral type, VQ
3132 // is either volatile or empty, and R is a promoted integral
3133 // type, there exist candidate operator functions of the form
3134 //
3135 // VQ L& operator%=(VQ L&, R);
3136 // VQ L& operator<<=(VQ L&, R);
3137 // VQ L& operator>>=(VQ L&, R);
3138 // VQ L& operator&=(VQ L&, R);
3139 // VQ L& operator^=(VQ L&, R);
3140 // VQ L& operator|=(VQ L&, R);
3141 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3142 for (unsigned Right = FirstPromotedIntegralType;
3143 Right < LastPromotedIntegralType; ++Right) {
3144 QualType ParamTypes[2];
3145 ParamTypes[1] = ArithmeticTypes[Right];
3146
3147 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003148 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003149 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3150
3151 // Add this built-in operator as a candidate (VQ is 'volatile').
3152 ParamTypes[0] = ArithmeticTypes[Left];
3153 ParamTypes[0].addVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003154 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003155 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3156 }
3157 }
3158 break;
3159
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003160 case OO_Exclaim: {
3161 // C++ [over.operator]p23:
3162 //
3163 // There also exist candidate operator functions of the form
3164 //
3165 // bool operator!(bool);
3166 // bool operator&&(bool, bool); [BELOW]
3167 // bool operator||(bool, bool); [BELOW]
3168 QualType ParamTy = Context.BoolTy;
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003169 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3170 /*IsAssignmentOperator=*/false,
3171 /*NumContextualBoolArguments=*/1);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003172 break;
3173 }
3174
Douglas Gregor70d26122008-11-12 17:17:38 +00003175 case OO_AmpAmp:
3176 case OO_PipePipe: {
3177 // C++ [over.operator]p23:
3178 //
3179 // There also exist candidate operator functions of the form
3180 //
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003181 // bool operator!(bool); [ABOVE]
Douglas Gregor70d26122008-11-12 17:17:38 +00003182 // bool operator&&(bool, bool);
3183 // bool operator||(bool, bool);
3184 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003185 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3186 /*IsAssignmentOperator=*/false,
3187 /*NumContextualBoolArguments=*/2);
Douglas Gregor70d26122008-11-12 17:17:38 +00003188 break;
3189 }
3190
3191 case OO_Subscript:
3192 // C++ [over.built]p13:
3193 //
3194 // For every cv-qualified or cv-unqualified object type T there
3195 // exist candidate operator functions of the form
3196 //
3197 // T* operator+(T*, ptrdiff_t); [ABOVE]
3198 // T& operator[](T*, ptrdiff_t);
3199 // T* operator-(T*, ptrdiff_t); [ABOVE]
3200 // T* operator+(ptrdiff_t, T*); [ABOVE]
3201 // T& operator[](ptrdiff_t, T*);
3202 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3203 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3204 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3205 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003206 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregor70d26122008-11-12 17:17:38 +00003207
3208 // T& operator[](T*, ptrdiff_t)
3209 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3210
3211 // T& operator[](ptrdiff_t, T*);
3212 ParamTypes[0] = ParamTypes[1];
3213 ParamTypes[1] = *Ptr;
3214 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3215 }
3216 break;
3217
3218 case OO_ArrowStar:
3219 // FIXME: No support for pointer-to-members yet.
3220 break;
3221 }
3222}
3223
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003224/// \brief Add function candidates found via argument-dependent lookup
3225/// to the set of overloading candidates.
3226///
3227/// This routine performs argument-dependent name lookup based on the
3228/// given function name (which may also be an operator name) and adds
3229/// all of the overload candidates found by ADL to the overload
3230/// candidate set (C++ [basic.lookup.argdep]).
3231void
3232Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3233 Expr **Args, unsigned NumArgs,
3234 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003235 FunctionSet Functions;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003236
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003237 // Record all of the function candidates that we've already
3238 // added to the overload set, so that we don't add those same
3239 // candidates a second time.
3240 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3241 CandEnd = CandidateSet.end();
3242 Cand != CandEnd; ++Cand)
3243 if (Cand->Function)
3244 Functions.insert(Cand->Function);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003245
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003246 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003247
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003248 // Erase all of the candidates we already knew about.
3249 // FIXME: This is suboptimal. Is there a better way?
3250 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3251 CandEnd = CandidateSet.end();
3252 Cand != CandEnd; ++Cand)
3253 if (Cand->Function)
3254 Functions.erase(Cand->Function);
3255
3256 // For each of the ADL candidates we found, add it to the overload
3257 // set.
3258 for (FunctionSet::iterator Func = Functions.begin(),
3259 FuncEnd = Functions.end();
3260 Func != FuncEnd; ++Func)
3261 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003262}
3263
Douglas Gregord2baafd2008-10-21 16:13:35 +00003264/// isBetterOverloadCandidate - Determines whether the first overload
3265/// candidate is a better candidate than the second (C++ 13.3.3p1).
3266bool
3267Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3268 const OverloadCandidate& Cand2)
3269{
3270 // Define viable functions to be better candidates than non-viable
3271 // functions.
3272 if (!Cand2.Viable)
3273 return Cand1.Viable;
3274 else if (!Cand1.Viable)
3275 return false;
3276
Douglas Gregor3257fb52008-12-22 05:46:06 +00003277 // C++ [over.match.best]p1:
3278 //
3279 // -- if F is a static member function, ICS1(F) is defined such
3280 // that ICS1(F) is neither better nor worse than ICS1(G) for
3281 // any function G, and, symmetrically, ICS1(G) is neither
3282 // better nor worse than ICS1(F).
3283 unsigned StartArg = 0;
3284 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3285 StartArg = 1;
Douglas Gregord2baafd2008-10-21 16:13:35 +00003286
3287 // (C++ 13.3.3p1): a viable function F1 is defined to be a better
3288 // function than another viable function F2 if for all arguments i,
3289 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
3290 // then...
3291 unsigned NumArgs = Cand1.Conversions.size();
3292 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3293 bool HasBetterConversion = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00003294 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00003295 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3296 Cand2.Conversions[ArgIdx])) {
3297 case ImplicitConversionSequence::Better:
3298 // Cand1 has a better conversion sequence.
3299 HasBetterConversion = true;
3300 break;
3301
3302 case ImplicitConversionSequence::Worse:
3303 // Cand1 can't be better than Cand2.
3304 return false;
3305
3306 case ImplicitConversionSequence::Indistinguishable:
3307 // Do nothing.
3308 break;
3309 }
3310 }
3311
3312 if (HasBetterConversion)
3313 return true;
3314
Douglas Gregor70d26122008-11-12 17:17:38 +00003315 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
3316 // implemented, but they require template support.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003317
Douglas Gregor60714f92008-11-07 22:36:19 +00003318 // C++ [over.match.best]p1b4:
3319 //
3320 // -- the context is an initialization by user-defined conversion
3321 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3322 // from the return type of F1 to the destination type (i.e.,
3323 // the type of the entity being initialized) is a better
3324 // conversion sequence than the standard conversion sequence
3325 // from the return type of F2 to the destination type.
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003326 if (Cand1.Function && Cand2.Function &&
3327 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregor60714f92008-11-07 22:36:19 +00003328 isa<CXXConversionDecl>(Cand2.Function)) {
3329 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3330 Cand2.FinalConversion)) {
3331 case ImplicitConversionSequence::Better:
3332 // Cand1 has a better conversion sequence.
3333 return true;
3334
3335 case ImplicitConversionSequence::Worse:
3336 // Cand1 can't be better than Cand2.
3337 return false;
3338
3339 case ImplicitConversionSequence::Indistinguishable:
3340 // Do nothing
3341 break;
3342 }
3343 }
3344
Douglas Gregord2baafd2008-10-21 16:13:35 +00003345 return false;
3346}
3347
3348/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
3349/// within an overload candidate set. If overloading is successful,
3350/// the result will be OR_Success and Best will be set to point to the
3351/// best viable function within the candidate set. Otherwise, one of
3352/// several kinds of errors will be returned; see
3353/// Sema::OverloadingResult.
3354Sema::OverloadingResult
3355Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
3356 OverloadCandidateSet::iterator& Best)
3357{
3358 // Find the best viable function.
3359 Best = CandidateSet.end();
3360 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3361 Cand != CandidateSet.end(); ++Cand) {
3362 if (Cand->Viable) {
3363 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3364 Best = Cand;
3365 }
3366 }
3367
3368 // If we didn't find any viable functions, abort.
3369 if (Best == CandidateSet.end())
3370 return OR_No_Viable_Function;
3371
3372 // Make sure that this function is better than every other viable
3373 // function. If not, we have an ambiguity.
3374 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3375 Cand != CandidateSet.end(); ++Cand) {
3376 if (Cand->Viable &&
3377 Cand != Best &&
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003378 !isBetterOverloadCandidate(*Best, *Cand)) {
3379 Best = CandidateSet.end();
Douglas Gregord2baafd2008-10-21 16:13:35 +00003380 return OR_Ambiguous;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003381 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003382 }
3383
3384 // Best is the best viable function.
Douglas Gregoraa57e862009-02-18 21:56:37 +00003385 if (Best->Function &&
3386 (Best->Function->isDeleted() ||
3387 Best->Function->getAttr<UnavailableAttr>()))
3388 return OR_Deleted;
3389
3390 // If Best refers to a function that is either deleted (C++0x) or
3391 // unavailable (Clang extension) report an error.
3392
Douglas Gregord2baafd2008-10-21 16:13:35 +00003393 return OR_Success;
3394}
3395
3396/// PrintOverloadCandidates - When overload resolution fails, prints
3397/// diagnostic messages containing the candidates in the candidate
3398/// set. If OnlyViable is true, only viable candidates will be printed.
3399void
3400Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3401 bool OnlyViable)
3402{
3403 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3404 LastCand = CandidateSet.end();
3405 for (; Cand != LastCand; ++Cand) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003406 if (Cand->Viable || !OnlyViable) {
3407 if (Cand->Function) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003408 if (Cand->Function->isDeleted() ||
3409 Cand->Function->getAttr<UnavailableAttr>()) {
3410 // Deleted or "unavailable" function.
3411 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3412 << Cand->Function->isDeleted();
3413 } else {
3414 // Normal function
3415 // FIXME: Give a better reason!
3416 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3417 }
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003418 } else if (Cand->IsSurrogate) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003419 // Desugar the type of the surrogate down to a function type,
3420 // retaining as many typedefs as possible while still showing
3421 // the function type (and, therefore, its parameter types).
3422 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003423 bool isLValueReference = false;
3424 bool isRValueReference = false;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003425 bool isPointer = false;
Sebastian Redlce6fff02009-03-16 23:22:08 +00003426 if (const LValueReferenceType *FnTypeRef =
3427 FnType->getAsLValueReferenceType()) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003428 FnType = FnTypeRef->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003429 isLValueReference = true;
3430 } else if (const RValueReferenceType *FnTypeRef =
3431 FnType->getAsRValueReferenceType()) {
3432 FnType = FnTypeRef->getPointeeType();
3433 isRValueReference = true;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003434 }
3435 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
3436 FnType = FnTypePtr->getPointeeType();
3437 isPointer = true;
3438 }
3439 // Desugar down to a function type.
3440 FnType = QualType(FnType->getAsFunctionType(), 0);
3441 // Reconstruct the pointer/reference as appropriate.
3442 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redlce6fff02009-03-16 23:22:08 +00003443 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3444 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003445
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003446 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003447 << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003448 } else {
3449 // FIXME: We need to get the identifier in here
3450 // FIXME: Do we want the error message to point at the
3451 // operator? (built-ins won't have a location)
3452 QualType FnType
3453 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3454 Cand->BuiltinTypes.ParamTypes,
3455 Cand->Conversions.size(),
3456 false, 0);
3457
Chris Lattner4bfd2232008-11-24 06:25:27 +00003458 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003459 }
3460 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003461 }
3462}
3463
Douglas Gregor45014fd2008-11-10 20:40:00 +00003464/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3465/// an overloaded function (C++ [over.over]), where @p From is an
3466/// expression with overloaded function type and @p ToType is the type
3467/// we're trying to resolve to. For example:
3468///
3469/// @code
3470/// int f(double);
3471/// int f(int);
3472///
3473/// int (*pfd)(double) = f; // selects f(double)
3474/// @endcode
3475///
3476/// This routine returns the resulting FunctionDecl if it could be
3477/// resolved, and NULL otherwise. When @p Complain is true, this
3478/// routine will emit diagnostics if there is an error.
3479FunctionDecl *
Sebastian Redl7434fc32009-02-04 21:23:32 +00003480Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor45014fd2008-11-10 20:40:00 +00003481 bool Complain) {
3482 QualType FunctionType = ToType;
Sebastian Redl7434fc32009-02-04 21:23:32 +00003483 bool IsMember = false;
Daniel Dunbarf6c06ce2009-02-26 19:13:44 +00003484 if (const PointerType *ToTypePtr = ToType->getAsPointerType())
Douglas Gregor45014fd2008-11-10 20:40:00 +00003485 FunctionType = ToTypePtr->getPointeeType();
Daniel Dunbarf6c06ce2009-02-26 19:13:44 +00003486 else if (const ReferenceType *ToTypeRef = ToType->getAsReferenceType())
3487 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl7434fc32009-02-04 21:23:32 +00003488 else if (const MemberPointerType *MemTypePtr =
3489 ToType->getAsMemberPointerType()) {
3490 FunctionType = MemTypePtr->getPointeeType();
3491 IsMember = true;
3492 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003493
3494 // We only look at pointers or references to functions.
3495 if (!FunctionType->isFunctionType())
3496 return 0;
3497
3498 // Find the actual overloaded function declaration.
3499 OverloadedFunctionDecl *Ovl = 0;
3500
3501 // C++ [over.over]p1:
3502 // [...] [Note: any redundant set of parentheses surrounding the
3503 // overloaded function name is ignored (5.1). ]
3504 Expr *OvlExpr = From->IgnoreParens();
3505
3506 // C++ [over.over]p1:
3507 // [...] The overloaded function name can be preceded by the &
3508 // operator.
3509 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3510 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3511 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3512 }
3513
3514 // Try to dig out the overloaded function.
3515 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
3516 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
3517
3518 // If there's no overloaded function declaration, we're done.
3519 if (!Ovl)
3520 return 0;
3521
3522 // Look through all of the overloaded functions, searching for one
3523 // whose type matches exactly.
3524 // FIXME: When templates or using declarations come along, we'll actually
3525 // have to deal with duplicates, partial ordering, etc. For now, we
3526 // can just do a simple search.
3527 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
3528 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
3529 Fun != Ovl->function_end(); ++Fun) {
3530 // C++ [over.over]p3:
3531 // Non-member functions and static member functions match
Sebastian Redl3a75abf2009-02-05 12:33:33 +00003532 // targets of type "pointer-to-function" or "reference-to-function."
3533 // Nonstatic member functions match targets of
Sebastian Redl7434fc32009-02-04 21:23:32 +00003534 // type "pointer-to-member-function."
3535 // Note that according to DR 247, the containing class does not matter.
3536 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3537 // Skip non-static functions when converting to pointer, and static
3538 // when converting to member pointer.
3539 if (Method->isStatic() == IsMember)
Douglas Gregor45014fd2008-11-10 20:40:00 +00003540 continue;
Sebastian Redl7434fc32009-02-04 21:23:32 +00003541 } else if (IsMember)
3542 continue;
Douglas Gregor45014fd2008-11-10 20:40:00 +00003543
3544 if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
3545 return *Fun;
3546 }
3547
3548 return 0;
3549}
3550
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003551/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003552/// (which eventually refers to the declaration Func) and the call
3553/// arguments Args/NumArgs, attempt to resolve the function call down
3554/// to a specific function. If overload resolution succeeds, returns
3555/// the function declaration produced by overload
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003556/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003557/// arguments and Fn, and returns NULL.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003558FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003559 DeclarationName UnqualifiedName,
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003560 SourceLocation LParenLoc,
3561 Expr **Args, unsigned NumArgs,
3562 SourceLocation *CommaLocs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003563 SourceLocation RParenLoc,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003564 bool &ArgumentDependentLookup) {
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003565 OverloadCandidateSet CandidateSet;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003566
3567 // Add the functions denoted by Callee to the set of candidate
3568 // functions. While we're doing so, track whether argument-dependent
3569 // lookup still applies, per:
3570 //
3571 // C++0x [basic.lookup.argdep]p3:
3572 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3573 // and let Y be the lookup set produced by argument dependent
3574 // lookup (defined as follows). If X contains
3575 //
3576 // -- a declaration of a class member, or
3577 //
3578 // -- a block-scope function declaration that is not a
3579 // using-declaration, or
3580 //
3581 // -- a declaration that is neither a function or a function
3582 // template
3583 //
3584 // then Y is empty.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003585 if (OverloadedFunctionDecl *Ovl
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003586 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
3587 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3588 FuncEnd = Ovl->function_end();
3589 Func != FuncEnd; ++Func) {
3590 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet);
3591
3592 if ((*Func)->getDeclContext()->isRecord() ||
3593 (*Func)->getDeclContext()->isFunctionOrMethod())
3594 ArgumentDependentLookup = false;
3595 }
3596 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
3597 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
3598
3599 if (Func->getDeclContext()->isRecord() ||
3600 Func->getDeclContext()->isFunctionOrMethod())
3601 ArgumentDependentLookup = false;
3602 }
3603
3604 if (Callee)
3605 UnqualifiedName = Callee->getDeclName();
3606
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003607 if (ArgumentDependentLookup)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003608 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003609 CandidateSet);
3610
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003611 OverloadCandidateSet::iterator Best;
3612 switch (BestViableFunction(CandidateSet, Best)) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00003613 case OR_Success:
3614 return Best->Function;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003615
3616 case OR_No_Viable_Function:
Chris Lattner4a526112009-02-17 07:29:20 +00003617 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003618 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +00003619 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003620 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3621 break;
3622
3623 case OR_Ambiguous:
3624 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00003625 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003626 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3627 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00003628
3629 case OR_Deleted:
3630 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
3631 << Best->Function->isDeleted()
3632 << UnqualifiedName
3633 << Fn->getSourceRange();
3634 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3635 break;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00003636 }
3637
3638 // Overload resolution failed. Destroy all of the subexpressions and
3639 // return NULL.
3640 Fn->Destroy(Context);
3641 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3642 Args[Arg]->Destroy(Context);
3643 return 0;
3644}
3645
Douglas Gregorc78182d2009-03-13 23:49:33 +00003646/// \brief Create a unary operation that may resolve to an overloaded
3647/// operator.
3648///
3649/// \param OpLoc The location of the operator itself (e.g., '*').
3650///
3651/// \param OpcIn The UnaryOperator::Opcode that describes this
3652/// operator.
3653///
3654/// \param Functions The set of non-member functions that will be
3655/// considered by overload resolution. The caller needs to build this
3656/// set based on the context using, e.g.,
3657/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
3658/// set should not contain any member functions; those will be added
3659/// by CreateOverloadedUnaryOp().
3660///
3661/// \param input The input argument.
3662Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
3663 unsigned OpcIn,
3664 FunctionSet &Functions,
3665 ExprArg input) {
3666 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
3667 Expr *Input = (Expr *)input.get();
3668
3669 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
3670 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
3671 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3672
3673 Expr *Args[2] = { Input, 0 };
3674 unsigned NumArgs = 1;
3675
3676 // For post-increment and post-decrement, add the implicit '0' as
3677 // the second argument, so that we know this is a post-increment or
3678 // post-decrement.
3679 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
3680 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
3681 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
3682 SourceLocation());
3683 NumArgs = 2;
3684 }
3685
3686 if (Input->isTypeDependent()) {
3687 OverloadedFunctionDecl *Overloads
3688 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
3689 for (FunctionSet::iterator Func = Functions.begin(),
3690 FuncEnd = Functions.end();
3691 Func != FuncEnd; ++Func)
3692 Overloads->addOverload(*Func);
3693
3694 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
3695 OpLoc, false, false);
3696
3697 input.release();
3698 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
3699 &Args[0], NumArgs,
3700 Context.DependentTy,
3701 OpLoc));
3702 }
3703
3704 // Build an empty overload set.
3705 OverloadCandidateSet CandidateSet;
3706
3707 // Add the candidates from the given function set.
3708 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
3709
3710 // Add operator candidates that are member functions.
3711 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
3712
3713 // Add builtin operator candidates.
3714 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
3715
3716 // Perform overload resolution.
3717 OverloadCandidateSet::iterator Best;
3718 switch (BestViableFunction(CandidateSet, Best)) {
3719 case OR_Success: {
3720 // We found a built-in operator or an overloaded operator.
3721 FunctionDecl *FnDecl = Best->Function;
3722
3723 if (FnDecl) {
3724 // We matched an overloaded operator. Build a call to that
3725 // operator.
3726
3727 // Convert the arguments.
3728 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3729 if (PerformObjectArgumentInitialization(Input, Method))
3730 return ExprError();
3731 } else {
3732 // Convert the arguments.
3733 if (PerformCopyInitialization(Input,
3734 FnDecl->getParamDecl(0)->getType(),
3735 "passing"))
3736 return ExprError();
3737 }
3738
3739 // Determine the result type
3740 QualType ResultTy
3741 = FnDecl->getType()->getAsFunctionType()->getResultType();
3742 ResultTy = ResultTy.getNonReferenceType();
3743
3744 // Build the actual expression node.
3745 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3746 SourceLocation());
3747 UsualUnaryConversions(FnExpr);
3748
3749 input.release();
3750 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
3751 &Input, 1, ResultTy,
3752 OpLoc));
3753 } else {
3754 // We matched a built-in operator. Convert the arguments, then
3755 // break out so that we will build the appropriate built-in
3756 // operator node.
3757 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3758 Best->Conversions[0], "passing"))
3759 return ExprError();
3760
3761 break;
3762 }
3763 }
3764
3765 case OR_No_Viable_Function:
3766 // No viable function; fall through to handling this as a
3767 // built-in operator, which will produce an error message for us.
3768 break;
3769
3770 case OR_Ambiguous:
3771 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3772 << UnaryOperator::getOpcodeStr(Opc)
3773 << Input->getSourceRange();
3774 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3775 return ExprError();
3776
3777 case OR_Deleted:
3778 Diag(OpLoc, diag::err_ovl_deleted_oper)
3779 << Best->Function->isDeleted()
3780 << UnaryOperator::getOpcodeStr(Opc)
3781 << Input->getSourceRange();
3782 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3783 return ExprError();
3784 }
3785
3786 // Either we found no viable overloaded operator or we matched a
3787 // built-in operator. In either case, fall through to trying to
3788 // build a built-in operation.
3789 input.release();
3790 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
3791}
3792
Douglas Gregor00fe3f62009-03-13 18:40:31 +00003793/// \brief Create a binary operation that may resolve to an overloaded
3794/// operator.
3795///
3796/// \param OpLoc The location of the operator itself (e.g., '+').
3797///
3798/// \param OpcIn The BinaryOperator::Opcode that describes this
3799/// operator.
3800///
3801/// \param Functions The set of non-member functions that will be
3802/// considered by overload resolution. The caller needs to build this
3803/// set based on the context using, e.g.,
3804/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
3805/// set should not contain any member functions; those will be added
3806/// by CreateOverloadedBinOp().
3807///
3808/// \param LHS Left-hand argument.
3809/// \param RHS Right-hand argument.
3810Sema::OwningExprResult
3811Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
3812 unsigned OpcIn,
3813 FunctionSet &Functions,
3814 Expr *LHS, Expr *RHS) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00003815 Expr *Args[2] = { LHS, RHS };
3816
3817 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
3818 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
3819 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3820
3821 // If either side is type-dependent, create an appropriate dependent
3822 // expression.
3823 if (LHS->isTypeDependent() || RHS->isTypeDependent()) {
3824 // .* cannot be overloaded.
3825 if (Opc == BinaryOperator::PtrMemD)
3826 return Owned(new (Context) BinaryOperator(LHS, RHS, Opc,
3827 Context.DependentTy, OpLoc));
3828
3829 OverloadedFunctionDecl *Overloads
3830 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
3831 for (FunctionSet::iterator Func = Functions.begin(),
3832 FuncEnd = Functions.end();
3833 Func != FuncEnd; ++Func)
3834 Overloads->addOverload(*Func);
3835
3836 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
3837 OpLoc, false, false);
3838
3839 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
3840 Args, 2,
3841 Context.DependentTy,
3842 OpLoc));
3843 }
3844
3845 // If this is the .* operator, which is not overloadable, just
3846 // create a built-in binary operator.
3847 if (Opc == BinaryOperator::PtrMemD)
3848 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
3849
3850 // If this is one of the assignment operators, we only perform
3851 // overload resolution if the left-hand side is a class or
3852 // enumeration type (C++ [expr.ass]p3).
3853 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3854 !LHS->getType()->isOverloadableType())
3855 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
3856
Douglas Gregorc78182d2009-03-13 23:49:33 +00003857 // Build an empty overload set.
3858 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00003859
3860 // Add the candidates from the given function set.
3861 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
3862
3863 // Add operator candidates that are member functions.
3864 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
3865
3866 // Add builtin operator candidates.
3867 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
3868
3869 // Perform overload resolution.
3870 OverloadCandidateSet::iterator Best;
3871 switch (BestViableFunction(CandidateSet, Best)) {
3872 case OR_Success: {
3873 // We found a built-in operator or an overloaded operator.
3874 FunctionDecl *FnDecl = Best->Function;
3875
3876 if (FnDecl) {
3877 // We matched an overloaded operator. Build a call to that
3878 // operator.
3879
3880 // Convert the arguments.
3881 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3882 if (PerformObjectArgumentInitialization(LHS, Method) ||
3883 PerformCopyInitialization(RHS, FnDecl->getParamDecl(0)->getType(),
3884 "passing"))
3885 return ExprError();
3886 } else {
3887 // Convert the arguments.
3888 if (PerformCopyInitialization(LHS, FnDecl->getParamDecl(0)->getType(),
3889 "passing") ||
3890 PerformCopyInitialization(RHS, FnDecl->getParamDecl(1)->getType(),
3891 "passing"))
3892 return ExprError();
3893 }
3894
3895 // Determine the result type
3896 QualType ResultTy
3897 = FnDecl->getType()->getAsFunctionType()->getResultType();
3898 ResultTy = ResultTy.getNonReferenceType();
3899
3900 // Build the actual expression node.
3901 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3902 SourceLocation());
3903 UsualUnaryConversions(FnExpr);
3904
3905 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
3906 Args, 2, ResultTy,
3907 OpLoc));
3908 } else {
3909 // We matched a built-in operator. Convert the arguments, then
3910 // break out so that we will build the appropriate built-in
3911 // operator node.
3912 if (PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
3913 Best->Conversions[0], "passing") ||
3914 PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
3915 Best->Conversions[1], "passing"))
3916 return ExprError();
3917
3918 break;
3919 }
3920 }
3921
3922 case OR_No_Viable_Function:
3923 // No viable function; fall through to handling this as a
3924 // built-in operator, which will produce an error message for us.
3925 break;
3926
3927 case OR_Ambiguous:
3928 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3929 << BinaryOperator::getOpcodeStr(Opc)
3930 << LHS->getSourceRange() << RHS->getSourceRange();
3931 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3932 return ExprError();
3933
3934 case OR_Deleted:
3935 Diag(OpLoc, diag::err_ovl_deleted_oper)
3936 << Best->Function->isDeleted()
3937 << BinaryOperator::getOpcodeStr(Opc)
3938 << LHS->getSourceRange() << RHS->getSourceRange();
3939 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3940 return ExprError();
3941 }
3942
3943 // Either we found no viable overloaded operator or we matched a
3944 // built-in operator. In either case, try to build a built-in
3945 // operation.
3946 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
3947}
3948
Douglas Gregor3257fb52008-12-22 05:46:06 +00003949/// BuildCallToMemberFunction - Build a call to a member
3950/// function. MemExpr is the expression that refers to the member
3951/// function (and includes the object parameter), Args/NumArgs are the
3952/// arguments to the function call (not including the object
3953/// parameter). The caller needs to validate that the member
3954/// expression refers to a member function or an overloaded member
3955/// function.
3956Sema::ExprResult
3957Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
3958 SourceLocation LParenLoc, Expr **Args,
3959 unsigned NumArgs, SourceLocation *CommaLocs,
3960 SourceLocation RParenLoc) {
3961 // Dig out the member expression. This holds both the object
3962 // argument and the member function we're referring to.
3963 MemberExpr *MemExpr = 0;
3964 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
3965 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
3966 else
3967 MemExpr = dyn_cast<MemberExpr>(MemExprE);
3968 assert(MemExpr && "Building member call without member expression");
3969
3970 // Extract the object argument.
3971 Expr *ObjectArg = MemExpr->getBase();
3972 if (MemExpr->isArrow())
Ted Kremenek0c97e042009-02-07 01:47:29 +00003973 ObjectArg = new (Context) UnaryOperator(ObjectArg, UnaryOperator::Deref,
3974 ObjectArg->getType()->getAsPointerType()->getPointeeType(),
Douglas Gregor8d103492009-02-19 00:52:42 +00003975 ObjectArg->getLocStart());
Douglas Gregor3257fb52008-12-22 05:46:06 +00003976 CXXMethodDecl *Method = 0;
3977 if (OverloadedFunctionDecl *Ovl
3978 = dyn_cast<OverloadedFunctionDecl>(MemExpr->getMemberDecl())) {
3979 // Add overload candidates
3980 OverloadCandidateSet CandidateSet;
3981 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
3982 FuncEnd = Ovl->function_end();
3983 Func != FuncEnd; ++Func) {
3984 assert(isa<CXXMethodDecl>(*Func) && "Function is not a method");
3985 Method = cast<CXXMethodDecl>(*Func);
3986 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
3987 /*SuppressUserConversions=*/false);
3988 }
3989
3990 OverloadCandidateSet::iterator Best;
3991 switch (BestViableFunction(CandidateSet, Best)) {
3992 case OR_Success:
3993 Method = cast<CXXMethodDecl>(Best->Function);
3994 break;
3995
3996 case OR_No_Viable_Function:
3997 Diag(MemExpr->getSourceRange().getBegin(),
3998 diag::err_ovl_no_viable_member_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +00003999 << Ovl->getDeclName() << MemExprE->getSourceRange();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004000 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4001 // FIXME: Leaking incoming expressions!
4002 return true;
4003
4004 case OR_Ambiguous:
4005 Diag(MemExpr->getSourceRange().getBegin(),
4006 diag::err_ovl_ambiguous_member_call)
4007 << Ovl->getDeclName() << MemExprE->getSourceRange();
4008 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4009 // FIXME: Leaking incoming expressions!
4010 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004011
4012 case OR_Deleted:
4013 Diag(MemExpr->getSourceRange().getBegin(),
4014 diag::err_ovl_deleted_member_call)
4015 << Best->Function->isDeleted()
4016 << Ovl->getDeclName() << MemExprE->getSourceRange();
4017 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4018 // FIXME: Leaking incoming expressions!
4019 return true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00004020 }
4021
4022 FixOverloadedFunctionReference(MemExpr, Method);
4023 } else {
4024 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4025 }
4026
4027 assert(Method && "Member call to something that isn't a method?");
Ted Kremenek0c97e042009-02-07 01:47:29 +00004028 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek362abcd2009-02-09 20:51:47 +00004029 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
4030 NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00004031 Method->getResultType().getNonReferenceType(),
4032 RParenLoc));
4033
4034 // Convert the object argument (for a non-static member function call).
4035 if (!Method->isStatic() &&
4036 PerformObjectArgumentInitialization(ObjectArg, Method))
4037 return true;
4038 MemExpr->setBase(ObjectArg);
4039
4040 // Convert the rest of the arguments
Douglas Gregor4fa58902009-02-26 23:50:07 +00004041 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004042 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
4043 RParenLoc))
4044 return true;
4045
Sebastian Redl8b769972009-01-19 00:08:26 +00004046 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004047}
4048
Douglas Gregor10f3c502008-11-19 21:05:33 +00004049/// BuildCallToObjectOfClassType - Build a call to an object of class
4050/// type (C++ [over.call.object]), which can end up invoking an
4051/// overloaded function call operator (@c operator()) or performing a
4052/// user-defined conversion on the object argument.
Douglas Gregor3257fb52008-12-22 05:46:06 +00004053Sema::ExprResult
Douglas Gregora133e262008-12-06 00:22:45 +00004054Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
4055 SourceLocation LParenLoc,
Douglas Gregor10f3c502008-11-19 21:05:33 +00004056 Expr **Args, unsigned NumArgs,
4057 SourceLocation *CommaLocs,
4058 SourceLocation RParenLoc) {
4059 assert(Object->getType()->isRecordType() && "Requires object type argument");
4060 const RecordType *Record = Object->getType()->getAsRecordType();
4061
4062 // C++ [over.call.object]p1:
4063 // If the primary-expression E in the function call syntax
4064 // evaluates to a class object of type “cv T”, then the set of
4065 // candidate functions includes at least the function call
4066 // operators of T. The function call operators of T are obtained by
4067 // ordinary lookup of the name operator() in the context of
4068 // (E).operator().
4069 OverloadCandidateSet CandidateSet;
Douglas Gregor8acb7272008-12-11 16:49:14 +00004070 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004071 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroffab63fd62009-01-08 17:28:14 +00004072 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004073 Oper != OperEnd; ++Oper)
4074 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
4075 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004076
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004077 // C++ [over.call.object]p2:
4078 // In addition, for each conversion function declared in T of the
4079 // form
4080 //
4081 // operator conversion-type-id () cv-qualifier;
4082 //
4083 // where cv-qualifier is the same cv-qualification as, or a
4084 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregor261afa72008-11-20 13:33:37 +00004085 // denotes the type "pointer to function of (P1,...,Pn) returning
4086 // R", or the type "reference to pointer to function of
4087 // (P1,...,Pn) returning R", or the type "reference to function
4088 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004089 // is also considered as a candidate function. Similarly,
4090 // surrogate call functions are added to the set of candidate
4091 // functions for each conversion function declared in an
4092 // accessible base class provided the function is not hidden
4093 // within T by another intervening declaration.
4094 //
4095 // FIXME: Look in base classes for more conversion operators!
4096 OverloadedFunctionDecl *Conversions
4097 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00004098 for (OverloadedFunctionDecl::function_iterator
4099 Func = Conversions->function_begin(),
4100 FuncEnd = Conversions->function_end();
4101 Func != FuncEnd; ++Func) {
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004102 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
4103
4104 // Strip the reference type (if any) and then the pointer type (if
4105 // any) to get down to what might be a function type.
4106 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4107 if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
4108 ConvType = ConvPtrType->getPointeeType();
4109
Douglas Gregor4fa58902009-02-26 23:50:07 +00004110 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004111 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4112 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004113
4114 // Perform overload resolution.
4115 OverloadCandidateSet::iterator Best;
4116 switch (BestViableFunction(CandidateSet, Best)) {
4117 case OR_Success:
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004118 // Overload resolution succeeded; we'll build the appropriate call
4119 // below.
Douglas Gregor10f3c502008-11-19 21:05:33 +00004120 break;
4121
4122 case OR_No_Viable_Function:
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004123 Diag(Object->getSourceRange().getBegin(),
4124 diag::err_ovl_no_viable_object_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004125 << Object->getType() << Object->getSourceRange();
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004126 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004127 break;
4128
4129 case OR_Ambiguous:
4130 Diag(Object->getSourceRange().getBegin(),
4131 diag::err_ovl_ambiguous_object_call)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004132 << Object->getType() << Object->getSourceRange();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004133 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4134 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004135
4136 case OR_Deleted:
4137 Diag(Object->getSourceRange().getBegin(),
4138 diag::err_ovl_deleted_object_call)
4139 << Best->Function->isDeleted()
4140 << Object->getType() << Object->getSourceRange();
4141 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4142 break;
Douglas Gregor10f3c502008-11-19 21:05:33 +00004143 }
4144
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004145 if (Best == CandidateSet.end()) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004146 // We had an error; delete all of the subexpressions and return
4147 // the error.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004148 Object->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004149 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004150 Args[ArgIdx]->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004151 return true;
4152 }
4153
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004154 if (Best->Function == 0) {
4155 // Since there is no function declaration, this is one of the
4156 // surrogate candidates. Dig out the conversion function.
4157 CXXConversionDecl *Conv
4158 = cast<CXXConversionDecl>(
4159 Best->Conversions[0].UserDefined.ConversionFunction);
4160
4161 // We selected one of the surrogate functions that converts the
4162 // object parameter to a function pointer. Perform the conversion
4163 // on the object argument, then let ActOnCallExpr finish the job.
4164 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl8b769972009-01-19 00:08:26 +00004165 ImpCastExprToType(Object,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004166 Conv->getConversionType().getNonReferenceType(),
Sebastian Redlce6fff02009-03-16 23:22:08 +00004167 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00004168 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4169 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4170 CommaLocs, RParenLoc).release();
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004171 }
4172
4173 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4174 // that calls this method, using Object for the implicit object
4175 // parameter and passing along the remaining arguments.
4176 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor4fa58902009-02-26 23:50:07 +00004177 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004178
4179 unsigned NumArgsInProto = Proto->getNumArgs();
4180 unsigned NumArgsToCheck = NumArgs;
4181
4182 // Build the full argument list for the method call (the
4183 // implicit object parameter is placed at the beginning of the
4184 // list).
4185 Expr **MethodArgs;
4186 if (NumArgs < NumArgsInProto) {
4187 NumArgsToCheck = NumArgsInProto;
4188 MethodArgs = new Expr*[NumArgsInProto + 1];
4189 } else {
4190 MethodArgs = new Expr*[NumArgs + 1];
4191 }
4192 MethodArgs[0] = Object;
4193 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4194 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
4195
Ted Kremenek0c97e042009-02-07 01:47:29 +00004196 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
4197 SourceLocation());
Douglas Gregor10f3c502008-11-19 21:05:33 +00004198 UsualUnaryConversions(NewFn);
4199
4200 // Once we've built TheCall, all of the expressions are properly
4201 // owned.
4202 QualType ResultTy = Method->getResultType().getNonReferenceType();
Ted Kremenek0c97e042009-02-07 01:47:29 +00004203 ExprOwningPtr<CXXOperatorCallExpr>
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004204 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
4205 MethodArgs, NumArgs + 1,
Ted Kremenek0c97e042009-02-07 01:47:29 +00004206 ResultTy, RParenLoc));
Douglas Gregor10f3c502008-11-19 21:05:33 +00004207 delete [] MethodArgs;
4208
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004209 // We may have default arguments. If so, we need to allocate more
4210 // slots in the call for them.
4211 if (NumArgs < NumArgsInProto)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004212 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004213 else if (NumArgs > NumArgsInProto)
4214 NumArgsToCheck = NumArgsInProto;
4215
Douglas Gregor10f3c502008-11-19 21:05:33 +00004216 // Initialize the implicit object parameter.
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004217 if (PerformObjectArgumentInitialization(Object, Method))
Douglas Gregor10f3c502008-11-19 21:05:33 +00004218 return true;
4219 TheCall->setArg(0, Object);
4220
4221 // Check the argument types.
4222 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004223 Expr *Arg;
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004224 if (i < NumArgs) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004225 Arg = Args[i];
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004226
4227 // Pass the argument.
4228 QualType ProtoArgType = Proto->getArgType(i);
4229 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
4230 return true;
4231 } else {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004232 Arg = new (Context) CXXDefaultArgExpr(Method->getParamDecl(i));
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004233 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004234
4235 TheCall->setArg(i + 1, Arg);
4236 }
4237
4238 // If this is a variadic call, handle args passed through "...".
4239 if (Proto->isVariadic()) {
4240 // Promote the arguments (C99 6.5.2.2p7).
4241 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4242 Expr *Arg = Args[i];
Anders Carlssonfde627e2009-01-13 05:48:52 +00004243
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00004244 DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004245 TheCall->setArg(i + 1, Arg);
4246 }
4247 }
4248
Sebastian Redl8b769972009-01-19 00:08:26 +00004249 return CheckFunctionCall(Method, TheCall.take()).release();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004250}
4251
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004252/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
4253/// (if one exists), where @c Base is an expression of class type and
4254/// @c Member is the name of the member we're trying to find.
4255Action::ExprResult
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004256Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004257 SourceLocation MemberLoc,
4258 IdentifierInfo &Member) {
4259 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
4260
4261 // C++ [over.ref]p1:
4262 //
4263 // [...] An expression x->m is interpreted as (x.operator->())->m
4264 // for a class object x of type T if T::operator->() exists and if
4265 // the operator is selected as the best match function by the
4266 // overload resolution mechanism (13.3).
4267 // FIXME: look in base classes.
4268 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4269 OverloadCandidateSet CandidateSet;
4270 const RecordType *BaseRecord = Base->getType()->getAsRecordType();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004271
4272 DeclContext::lookup_const_iterator Oper, OperEnd;
Steve Naroffab63fd62009-01-08 17:28:14 +00004273 for (llvm::tie(Oper, OperEnd) = BaseRecord->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004274 Oper != OperEnd; ++Oper)
4275 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004276 /*SuppressUserConversions=*/false);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004277
Ted Kremenek0c97e042009-02-07 01:47:29 +00004278 ExprOwningPtr<Expr> BasePtr(this, Base);
Douglas Gregor9c690e92008-11-21 03:04:22 +00004279
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004280 // Perform overload resolution.
4281 OverloadCandidateSet::iterator Best;
4282 switch (BestViableFunction(CandidateSet, Best)) {
4283 case OR_Success:
4284 // Overload resolution succeeded; we'll build the call below.
4285 break;
4286
4287 case OR_No_Viable_Function:
4288 if (CandidateSet.empty())
4289 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004290 << BasePtr->getType() << BasePtr->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004291 else
4292 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Chris Lattner4a526112009-02-17 07:29:20 +00004293 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004294 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004295 return true;
4296
4297 case OR_Ambiguous:
4298 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004299 << "operator->" << BasePtr->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004300 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004301 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004302
4303 case OR_Deleted:
4304 Diag(OpLoc, diag::err_ovl_deleted_oper)
4305 << Best->Function->isDeleted()
4306 << "operator->" << BasePtr->getSourceRange();
4307 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4308 return true;
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004309 }
4310
4311 // Convert the object parameter.
4312 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9c690e92008-11-21 03:04:22 +00004313 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004314 return true;
Douglas Gregor9c690e92008-11-21 03:04:22 +00004315
4316 // No concerns about early exits now.
4317 BasePtr.take();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004318
4319 // Build the operator call.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004320 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4321 SourceLocation());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004322 UsualUnaryConversions(FnExpr);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004323 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004324 Method->getResultType().getNonReferenceType(),
4325 OpLoc);
Sebastian Redl8b769972009-01-19 00:08:26 +00004326 return ActOnMemberReferenceExpr(S, ExprArg(*this, Base), OpLoc, tok::arrow,
4327 MemberLoc, Member).release();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004328}
4329
Douglas Gregor45014fd2008-11-10 20:40:00 +00004330/// FixOverloadedFunctionReference - E is an expression that refers to
4331/// a C++ overloaded function (possibly with some parentheses and
4332/// perhaps a '&' around it). We have resolved the overloaded function
4333/// to the function declaration Fn, so patch up the expression E to
4334/// refer (possibly indirectly) to Fn.
4335void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4336 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4337 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4338 E->setType(PE->getSubExpr()->getType());
4339 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
4340 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
4341 "Can only take the address of an overloaded function");
Douglas Gregor3f411962009-02-11 01:18:59 +00004342 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4343 if (Method->isStatic()) {
4344 // Do nothing: static member functions aren't any different
4345 // from non-member functions.
4346 }
4347 else if (QualifiedDeclRefExpr *DRE
4348 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4349 // We have taken the address of a pointer to member
4350 // function. Perform the computation here so that we get the
4351 // appropriate pointer to member type.
4352 DRE->setDecl(Fn);
4353 DRE->setType(Fn->getType());
4354 QualType ClassType
4355 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
4356 E->setType(Context.getMemberPointerType(Fn->getType(),
4357 ClassType.getTypePtr()));
4358 return;
4359 }
4360 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00004361 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregor2eedd992009-02-11 00:19:33 +00004362 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregor45014fd2008-11-10 20:40:00 +00004363 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
4364 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
4365 "Expected overloaded function");
4366 DR->setDecl(Fn);
4367 E->setType(Fn->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004368 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4369 MemExpr->setMemberDecl(Fn);
4370 E->setType(Fn->getType());
Douglas Gregor45014fd2008-11-10 20:40:00 +00004371 } else {
4372 assert(false && "Invalid reference to overloaded function");
4373 }
4374}
4375
Douglas Gregord2baafd2008-10-21 16:13:35 +00004376} // end namespace clang