blob: dffaf41feb1162f942d580d86921e73311c491b9 [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"
Anders Carlssona21e7872009-08-26 23:45:07 +000022#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor3d4492e2008-11-13 20:12:29 +000023#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregorddfd9d52008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000025#include "llvm/Support/Compiler.h"
26#include <algorithm>
Edwin Török0fbc71c2009-08-24 13:25:12 +000027#include <cstdio>
Douglas Gregord2baafd2008-10-21 16:13:35 +000028
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
33ImplicitConversionCategory
34GetConversionCategory(ImplicitConversionKind Kind) {
35 static const ImplicitConversionCategory
36 Category[(int)ICK_Num_Conversion_Kinds] = {
37 ICC_Identity,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
41 ICC_Qualification_Adjustment,
42 ICC_Promotion,
43 ICC_Promotion,
Douglas Gregore819caf2009-02-12 00:15:05 +000044 ICC_Promotion,
45 ICC_Conversion,
46 ICC_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000047 ICC_Conversion,
48 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
Douglas Gregor2aecd1f2008-10-29 02:00:59 +000052 ICC_Conversion,
Douglas Gregorfcb19192009-02-11 23:02:49 +000053 ICC_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000054 ICC_Conversion
55 };
56 return Category[(int)Kind];
57}
58
59/// GetConversionRank - Retrieve the implicit conversion rank
60/// corresponding to the given implicit conversion kind.
61ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
62 static const ImplicitConversionRank
63 Rank[(int)ICK_Num_Conversion_Kinds] = {
64 ICR_Exact_Match,
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Promotion,
70 ICR_Promotion,
Douglas Gregore819caf2009-02-12 00:15:05 +000071 ICR_Promotion,
72 ICR_Conversion,
73 ICR_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000074 ICR_Conversion,
75 ICR_Conversion,
76 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
Douglas Gregor2aecd1f2008-10-29 02:00:59 +000079 ICR_Conversion,
Douglas Gregorfcb19192009-02-11 23:02:49 +000080 ICR_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000081 ICR_Conversion
82 };
83 return Rank[(int)Kind];
84}
85
86/// GetImplicitConversionName - Return the name of this kind of
87/// implicit conversion.
88const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
89 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
90 "No conversion",
91 "Lvalue-to-rvalue",
92 "Array-to-pointer",
93 "Function-to-pointer",
94 "Qualification",
95 "Integral promotion",
96 "Floating point promotion",
Douglas Gregore819caf2009-02-12 00:15:05 +000097 "Complex promotion",
Douglas Gregord2baafd2008-10-21 16:13:35 +000098 "Integral conversion",
99 "Floating conversion",
Douglas Gregore819caf2009-02-12 00:15:05 +0000100 "Complex conversion",
Douglas Gregord2baafd2008-10-21 16:13:35 +0000101 "Floating-integral conversion",
Douglas Gregore819caf2009-02-12 00:15:05 +0000102 "Complex-real conversion",
Douglas Gregord2baafd2008-10-21 16:13:35 +0000103 "Pointer conversion",
104 "Pointer-to-member conversion",
Douglas Gregor2aecd1f2008-10-29 02:00:59 +0000105 "Boolean conversion",
Douglas Gregorfcb19192009-02-11 23:02:49 +0000106 "Compatible-types conversion",
Douglas Gregor2aecd1f2008-10-29 02:00:59 +0000107 "Derived-to-base conversion"
Douglas Gregord2baafd2008-10-21 16:13:35 +0000108 };
109 return Name[Kind];
110}
111
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000112/// StandardConversionSequence - Set the standard conversion
113/// sequence to the identity conversion.
114void StandardConversionSequence::setAsIdentityConversion() {
115 First = ICK_Identity;
116 Second = ICK_Identity;
117 Third = ICK_Identity;
118 Deprecated = false;
119 ReferenceBinding = false;
120 DirectBinding = false;
Sebastian Redl9bc16ad2009-03-29 22:46:24 +0000121 RRefBinding = false;
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000122 CopyConstructor = 0;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000123}
124
Douglas Gregord2baafd2008-10-21 16:13:35 +0000125/// getRank - Retrieve the rank of this standard conversion sequence
126/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
127/// implicit conversions.
128ImplicitConversionRank StandardConversionSequence::getRank() const {
129 ImplicitConversionRank Rank = ICR_Exact_Match;
130 if (GetConversionRank(First) > Rank)
131 Rank = GetConversionRank(First);
132 if (GetConversionRank(Second) > Rank)
133 Rank = GetConversionRank(Second);
134 if (GetConversionRank(Third) > Rank)
135 Rank = GetConversionRank(Third);
136 return Rank;
137}
138
139/// isPointerConversionToBool - Determines whether this conversion is
140/// a conversion of a pointer or pointer-to-member to bool. This is
141/// used as part of the ranking of standard conversion sequences
142/// (C++ 13.3.3.2p4).
143bool StandardConversionSequence::isPointerConversionToBool() const
144{
145 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
146 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
147
148 // Note that FromType has not necessarily been transformed by the
149 // array-to-pointer or function-to-pointer implicit conversions, so
150 // check for their presence as well as checking whether FromType is
151 // a pointer.
152 if (ToType->isBooleanType() &&
Douglas Gregor80402cf2008-12-23 00:53:59 +0000153 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregord2baafd2008-10-21 16:13:35 +0000154 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
155 return true;
156
157 return false;
158}
159
Douglas Gregor14046502008-10-23 00:40:37 +0000160/// isPointerConversionToVoidPointer - Determines whether this
161/// conversion is a conversion of a pointer to a void pointer. This is
162/// used as part of the ranking of standard conversion sequences (C++
163/// 13.3.3.2p4).
164bool
165StandardConversionSequence::
166isPointerConversionToVoidPointer(ASTContext& Context) const
167{
168 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
169 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
170
171 // Note that FromType has not necessarily been transformed by the
172 // array-to-pointer implicit conversion, so check for its presence
173 // and redo the conversion to get a pointer.
174 if (First == ICK_Array_To_Pointer)
175 FromType = Context.getArrayDecayedType(FromType);
176
177 if (Second == ICK_Pointer_Conversion)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000178 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor14046502008-10-23 00:40:37 +0000179 return ToPtrType->getPointeeType()->isVoidType();
180
181 return false;
182}
183
Douglas Gregord2baafd2008-10-21 16:13:35 +0000184/// DebugPrint - Print this standard conversion sequence to standard
185/// error. Useful for debugging overloading issues.
186void StandardConversionSequence::DebugPrint() const {
187 bool PrintedSomething = false;
188 if (First != ICK_Identity) {
189 fprintf(stderr, "%s", GetImplicitConversionName(First));
190 PrintedSomething = true;
191 }
192
193 if (Second != ICK_Identity) {
194 if (PrintedSomething) {
195 fprintf(stderr, " -> ");
196 }
197 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000198
199 if (CopyConstructor) {
200 fprintf(stderr, " (by copy constructor)");
201 } else if (DirectBinding) {
202 fprintf(stderr, " (direct reference binding)");
203 } else if (ReferenceBinding) {
204 fprintf(stderr, " (reference binding)");
205 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000206 PrintedSomething = true;
207 }
208
209 if (Third != ICK_Identity) {
210 if (PrintedSomething) {
211 fprintf(stderr, " -> ");
212 }
213 fprintf(stderr, "%s", GetImplicitConversionName(Third));
214 PrintedSomething = true;
215 }
216
217 if (!PrintedSomething) {
218 fprintf(stderr, "No conversions required");
219 }
220}
221
222/// DebugPrint - Print this user-defined conversion sequence to standard
223/// error. Useful for debugging overloading issues.
224void UserDefinedConversionSequence::DebugPrint() const {
225 if (Before.First || Before.Second || Before.Third) {
226 Before.DebugPrint();
227 fprintf(stderr, " -> ");
228 }
Chris Lattner271d4c22008-11-24 05:29:24 +0000229 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregord2baafd2008-10-21 16:13:35 +0000230 if (After.First || After.Second || After.Third) {
231 fprintf(stderr, " -> ");
232 After.DebugPrint();
233 }
234}
235
236/// DebugPrint - Print this implicit conversion sequence to standard
237/// error. Useful for debugging overloading issues.
238void ImplicitConversionSequence::DebugPrint() const {
239 switch (ConversionKind) {
240 case StandardConversion:
241 fprintf(stderr, "Standard conversion: ");
242 Standard.DebugPrint();
243 break;
244 case UserDefinedConversion:
245 fprintf(stderr, "User-defined conversion: ");
246 UserDefined.DebugPrint();
247 break;
248 case EllipsisConversion:
249 fprintf(stderr, "Ellipsis conversion");
250 break;
251 case BadConversion:
252 fprintf(stderr, "Bad conversion");
253 break;
254 }
255
256 fprintf(stderr, "\n");
257}
258
259// IsOverload - Determine whether the given New declaration is an
260// overload of the Old declaration. This routine returns false if New
261// and Old cannot be overloaded, e.g., if they are functions with the
262// same signature (C++ 1.3.10) or if the Old declaration isn't a
263// function (or overload set). When it does return false and Old is an
264// OverloadedFunctionDecl, MatchedDecl will be set to point to the
265// FunctionDecl that New cannot be overloaded with.
266//
267// Example: Given the following input:
268//
269// void f(int, float); // #1
270// void f(int, int); // #2
271// int f(int, int); // #3
272//
273// When we process #1, there is no previous declaration of "f",
274// so IsOverload will not be used.
275//
276// When we process #2, Old is a FunctionDecl for #1. By comparing the
277// parameter types, we see that #1 and #2 are overloaded (since they
278// have different signatures), so this routine returns false;
279// MatchedDecl is unchanged.
280//
281// When we process #3, Old is an OverloadedFunctionDecl containing #1
282// and #2. We compare the signatures of #3 to #1 (they're overloaded,
283// so we do nothing) and then #3 to #2. Since the signatures of #3 and
284// #2 are identical (return types of functions are not part of the
285// signature), IsOverload returns false and MatchedDecl will be set to
286// point to the FunctionDecl for #2.
287bool
288Sema::IsOverload(FunctionDecl *New, Decl* OldD,
289 OverloadedFunctionDecl::function_iterator& MatchedDecl)
290{
291 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
292 // Is this new function an overload of every function in the
293 // overload set?
294 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
295 FuncEnd = Ovl->function_end();
296 for (; Func != FuncEnd; ++Func) {
297 if (!IsOverload(New, *Func, MatchedDecl)) {
298 MatchedDecl = Func;
299 return false;
300 }
301 }
302
303 // This function overloads every function in the overload set.
304 return true;
Douglas Gregorb60eb752009-06-25 22:08:12 +0000305 } else if (FunctionTemplateDecl *Old = dyn_cast<FunctionTemplateDecl>(OldD))
306 return IsOverload(New, Old->getTemplatedDecl(), MatchedDecl);
307 else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000308 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
309 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
310
311 // C++ [temp.fct]p2:
312 // A function template can be overloaded with other function templates
313 // and with normal (non-template) functions.
314 if ((OldTemplate == 0) != (NewTemplate == 0))
315 return true;
316
Douglas Gregord2baafd2008-10-21 16:13:35 +0000317 // Is the function New an overload of the function Old?
318 QualType OldQType = Context.getCanonicalType(Old->getType());
319 QualType NewQType = Context.getCanonicalType(New->getType());
320
321 // Compare the signatures (C++ 1.3.10) of the two functions to
322 // determine whether they are overloads. If we find any mismatch
323 // in the signature, they are overloads.
324
325 // If either of these functions is a K&R-style function (no
326 // prototype), then we consider them to have matching signatures.
Douglas Gregor4fa58902009-02-26 23:50:07 +0000327 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
328 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
Douglas Gregord2baafd2008-10-21 16:13:35 +0000329 return false;
330
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000331 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
332 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000333
334 // The signature of a function includes the types of its
335 // parameters (C++ 1.3.10), which includes the presence or absence
336 // of the ellipsis; see C++ DR 357).
337 if (OldQType != NewQType &&
338 (OldType->getNumArgs() != NewType->getNumArgs() ||
339 OldType->isVariadic() != NewType->isVariadic() ||
340 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
341 NewType->arg_type_begin())))
342 return true;
343
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000344 // C++ [temp.over.link]p4:
345 // The signature of a function template consists of its function
346 // signature, its return type and its template parameter list. The names
347 // of the template parameters are significant only for establishing the
348 // relationship between the template parameters and the rest of the
349 // signature.
350 //
351 // We check the return type and template parameter lists for function
352 // templates first; the remaining checks follow.
353 if (NewTemplate &&
354 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
355 OldTemplate->getTemplateParameters(),
356 false, false, SourceLocation()) ||
357 OldType->getResultType() != NewType->getResultType()))
358 return true;
359
Douglas Gregord2baafd2008-10-21 16:13:35 +0000360 // If the function is a class member, its signature includes the
361 // cv-qualifiers (if any) on the function itself.
362 //
363 // As part of this, also check whether one of the member functions
364 // is static, in which case they are not overloads (C++
365 // 13.1p2). While not part of the definition of the signature,
366 // this check is important to determine whether these functions
367 // can be overloaded.
368 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
369 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
370 if (OldMethod && NewMethod &&
371 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregora7b56a32008-11-21 15:36:28 +0000372 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregord2baafd2008-10-21 16:13:35 +0000373 return true;
374
375 // The signatures match; this is not an overload.
376 return false;
377 } else {
378 // (C++ 13p1):
379 // Only function declarations can be overloaded; object and type
380 // declarations cannot be overloaded.
381 return false;
382 }
383}
384
Douglas Gregor81c29152008-10-29 00:13:59 +0000385/// TryImplicitConversion - Attempt to perform an implicit conversion
386/// from the given expression (Expr) to the given type (ToType). This
387/// function returns an implicit conversion sequence that can be used
388/// to perform the initialization. Given
Douglas Gregord2baafd2008-10-21 16:13:35 +0000389///
390/// void f(float f);
391/// void g(int i) { f(i); }
392///
393/// this routine would produce an implicit conversion sequence to
394/// describe the initialization of f from i, which will be a standard
395/// conversion sequence containing an lvalue-to-rvalue conversion (C++
396/// 4.1) followed by a floating-integral conversion (C++ 4.9).
397//
398/// Note that this routine only determines how the conversion can be
399/// performed; it does not actually perform the conversion. As such,
400/// it will not produce any diagnostics if no conversion is available,
401/// but will instead return an implicit conversion sequence of kind
402/// "BadConversion".
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000403///
404/// If @p SuppressUserConversions, then user-defined conversions are
405/// not permitted.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000406/// If @p AllowExplicit, then explicit user-defined conversions are
407/// permitted.
Sebastian Redla55834a2009-04-12 17:16:29 +0000408/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
409/// no matter its actual lvalueness.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000410ImplicitConversionSequence
Anders Carlssonfcc53032009-08-27 17:14:02 +0000411Sema::TryImplicitConversion(Expr* From, QualType ToType,
412 bool SuppressUserConversions,
Anders Carlsson8e4c1692009-08-28 15:33:32 +0000413 bool AllowExplicit, bool ForceRValue,
414 bool InOverloadResolution)
Anders Carlssonfcc53032009-08-27 17:14:02 +0000415{
Douglas Gregord2baafd2008-10-21 16:13:35 +0000416 ImplicitConversionSequence ICS;
Anders Carlsson8e4c1692009-08-28 15:33:32 +0000417 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000418 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000419 else if (getLangOptions().CPlusPlus &&
420 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Sebastian Redla55834a2009-04-12 17:16:29 +0000421 !SuppressUserConversions, AllowExplicit,
422 ForceRValue)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000423 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregore640ab62008-11-03 17:51:48 +0000424 // C++ [over.ics.user]p4:
425 // A conversion of an expression of class type to the same class
426 // type is given Exact Match rank, and a conversion of an
427 // expression of class type to a base class of that type is
428 // given Conversion rank, in spite of the fact that a copy
429 // constructor (i.e., a user-defined conversion function) is
430 // called for those cases.
431 if (CXXConstructorDecl *Constructor
432 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Douglas Gregord9176392009-02-02 22:11:10 +0000433 QualType FromCanon
434 = Context.getCanonicalType(From->getType().getUnqualifiedType());
435 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
436 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000437 // Turn this into a "standard" conversion sequence, so that it
438 // gets ranked with standard conversion sequences.
Douglas Gregore640ab62008-11-03 17:51:48 +0000439 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
440 ICS.Standard.setAsIdentityConversion();
441 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
442 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000443 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregord9176392009-02-02 22:11:10 +0000444 if (ToCanon != FromCanon)
Douglas Gregore640ab62008-11-03 17:51:48 +0000445 ICS.Standard.Second = ICK_Derived_To_Base;
446 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000447 }
Douglas Gregorb206cc42009-01-30 23:27:23 +0000448
449 // C++ [over.best.ics]p4:
450 // However, when considering the argument of a user-defined
451 // conversion function that is a candidate by 13.3.1.3 when
452 // invoked for the copying of the temporary in the second step
453 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
454 // 13.3.1.6 in all cases, only standard conversion sequences and
455 // ellipsis conversion sequences are allowed.
456 if (SuppressUserConversions &&
457 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
458 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregore640ab62008-11-03 17:51:48 +0000459 } else
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000460 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000461
462 return ICS;
463}
464
465/// IsStandardConversion - Determines whether there is a standard
466/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
467/// expression From to the type ToType. Standard conversion sequences
468/// only consider non-class types; for conversions that involve class
469/// types, use TryImplicitConversion. If a conversion exists, SCS will
470/// contain the standard conversion sequence required to perform this
471/// conversion and this routine will return true. Otherwise, this
472/// routine will return false and the value of SCS is unspecified.
473bool
474Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson8e4c1692009-08-28 15:33:32 +0000475 bool InOverloadResolution,
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000476 StandardConversionSequence &SCS)
477{
Douglas Gregord2baafd2008-10-21 16:13:35 +0000478 QualType FromType = From->getType();
479
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000480 // Standard conversions (C++ [conv])
Douglas Gregor70d26122008-11-12 17:17:38 +0000481 SCS.setAsIdentityConversion();
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000482 SCS.Deprecated = false;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000483 SCS.IncompatibleObjC = false;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000484 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000485 SCS.CopyConstructor = 0;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000486
Douglas Gregorfcb19192009-02-11 23:02:49 +0000487 // There are no standard conversions for class types in C++, so
488 // abort early. When overloading in C, however, we do permit
489 if (FromType->isRecordType() || ToType->isRecordType()) {
490 if (getLangOptions().CPlusPlus)
491 return false;
492
493 // When we're overloading in C, we allow, as standard conversions,
494 }
495
Douglas Gregord2baafd2008-10-21 16:13:35 +0000496 // The first conversion can be an lvalue-to-rvalue conversion,
497 // array-to-pointer conversion, or function-to-pointer conversion
498 // (C++ 4p1).
499
500 // Lvalue-to-rvalue conversion (C++ 4.1):
501 // An lvalue (3.10) of a non-function, non-array type T can be
502 // converted to an rvalue.
503 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
504 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor45014fd2008-11-10 20:40:00 +0000505 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000506 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000507 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000508
509 // If T is a non-class type, the type of the rvalue is the
510 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorfcb19192009-02-11 23:02:49 +0000511 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
512 // just strip the qualifiers because they don't matter.
513
514 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000515 FromType = FromType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000516 } else if (FromType->isArrayType()) {
517 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000518 SCS.First = ICK_Array_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000519
520 // An lvalue or rvalue of type "array of N T" or "array of unknown
521 // bound of T" can be converted to an rvalue of type "pointer to
522 // T" (C++ 4.2p1).
523 FromType = Context.getArrayDecayedType(FromType);
524
525 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
526 // This conversion is deprecated. (C++ D.4).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000527 SCS.Deprecated = true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000528
529 // For the purpose of ranking in overload resolution
530 // (13.3.3.1.1), this conversion is considered an
531 // array-to-pointer conversion followed by a qualification
532 // conversion (4.4). (C++ 4.2p2)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000533 SCS.Second = ICK_Identity;
534 SCS.Third = ICK_Qualification;
535 SCS.ToTypePtr = ToType.getAsOpaquePtr();
536 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000537 }
Mike Stump90fc78e2009-08-04 21:02:39 +0000538 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
539 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000540 SCS.First = ICK_Function_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000541
542 // An lvalue of function type T can be converted to an rvalue of
543 // type "pointer to T." The result is a pointer to the
544 // function. (C++ 4.3p1).
545 FromType = Context.getPointerType(FromType);
Mike Stump90fc78e2009-08-04 21:02:39 +0000546 } else if (FunctionDecl *Fn
Douglas Gregor45014fd2008-11-10 20:40:00 +0000547 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump90fc78e2009-08-04 21:02:39 +0000548 // Address of overloaded function (C++ [over.over]).
Douglas Gregor45014fd2008-11-10 20:40:00 +0000549 SCS.First = ICK_Function_To_Pointer;
550
551 // We were able to resolve the address of the overloaded function,
552 // so we can convert to the type of that function.
553 FromType = Fn->getType();
Sebastian Redlce6fff02009-03-16 23:22:08 +0000554 if (ToType->isLValueReferenceType())
555 FromType = Context.getLValueReferenceType(FromType);
556 else if (ToType->isRValueReferenceType())
557 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl7434fc32009-02-04 21:23:32 +0000558 else if (ToType->isMemberPointerType()) {
559 // Resolve address only succeeds if both sides are member pointers,
560 // but it doesn't have to be the same class. See DR 247.
561 // Note that this means that the type of &Derived::fn can be
562 // Ret (Base::*)(Args) if the fn overload actually found is from the
563 // base class, even if it was brought into the derived class via a
564 // using declaration. The standard isn't clear on this issue at all.
565 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
566 FromType = Context.getMemberPointerType(FromType,
567 Context.getTypeDeclType(M->getParent()).getTypePtr());
568 } else
Douglas Gregor45014fd2008-11-10 20:40:00 +0000569 FromType = Context.getPointerType(FromType);
Mike Stump90fc78e2009-08-04 21:02:39 +0000570 } else {
571 // We don't require any conversions for the first step.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000572 SCS.First = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000573 }
574
575 // The second conversion can be an integral promotion, floating
576 // point promotion, integral conversion, floating point conversion,
577 // floating-integral conversion, pointer conversion,
578 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorfcb19192009-02-11 23:02:49 +0000579 // For overloading in C, this can also be a "compatible-type"
580 // conversion.
Douglas Gregor6fd35572008-12-19 17:40:08 +0000581 bool IncompatibleObjC = false;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000582 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000583 // The unqualified versions of the types are the same: there's no
584 // conversion to do.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000585 SCS.Second = ICK_Identity;
Mike Stump90fc78e2009-08-04 21:02:39 +0000586 } else if (IsIntegralPromotion(From, FromType, ToType)) {
587 // Integral promotion (C++ 4.5).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000588 SCS.Second = ICK_Integral_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000589 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000590 } else if (IsFloatingPointPromotion(FromType, ToType)) {
591 // Floating point promotion (C++ 4.6).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000592 SCS.Second = ICK_Floating_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000593 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000594 } else if (IsComplexPromotion(FromType, ToType)) {
595 // Complex promotion (Clang extension)
Douglas Gregore819caf2009-02-12 00:15:05 +0000596 SCS.Second = ICK_Complex_Promotion;
597 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000598 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000599 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump90fc78e2009-08-04 21:02:39 +0000600 // Integral conversions (C++ 4.7).
601 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000602 SCS.Second = ICK_Integral_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000603 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000604 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
605 // Floating point conversions (C++ 4.8).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000606 SCS.Second = ICK_Floating_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000607 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000608 } else if (FromType->isComplexType() && ToType->isComplexType()) {
609 // Complex conversions (C99 6.3.1.6)
Douglas Gregore819caf2009-02-12 00:15:05 +0000610 SCS.Second = ICK_Complex_Conversion;
611 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000612 } else if ((FromType->isFloatingType() &&
613 ToType->isIntegralType() && (!ToType->isBooleanType() &&
614 !ToType->isEnumeralType())) ||
615 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
616 ToType->isFloatingType())) {
617 // Floating-integral conversions (C++ 4.9).
618 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000619 SCS.Second = ICK_Floating_Integral;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000620 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000621 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
622 (ToType->isComplexType() && FromType->isArithmeticType())) {
623 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregore819caf2009-02-12 00:15:05 +0000624 SCS.Second = ICK_Complex_Real;
625 FromType = ToType.getUnqualifiedType();
Anders Carlsson8e4c1692009-08-28 15:33:32 +0000626 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
627 FromType, IncompatibleObjC)) {
Mike Stump90fc78e2009-08-04 21:02:39 +0000628 // Pointer conversions (C++ 4.10).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000629 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000630 SCS.IncompatibleObjC = IncompatibleObjC;
Mike Stump90fc78e2009-08-04 21:02:39 +0000631 } else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
632 // Pointer to member conversions (4.11).
Sebastian Redlba387562009-01-25 19:43:20 +0000633 SCS.Second = ICK_Pointer_Member;
Mike Stump90fc78e2009-08-04 21:02:39 +0000634 } else if (ToType->isBooleanType() &&
635 (FromType->isArithmeticType() ||
636 FromType->isEnumeralType() ||
637 FromType->isPointerType() ||
638 FromType->isBlockPointerType() ||
639 FromType->isMemberPointerType() ||
640 FromType->isNullPtrType())) {
641 // Boolean conversions (C++ 4.12).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000642 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000643 FromType = Context.BoolTy;
Mike Stump90fc78e2009-08-04 21:02:39 +0000644 } else if (!getLangOptions().CPlusPlus &&
645 Context.typesAreCompatible(ToType, FromType)) {
646 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorfcb19192009-02-11 23:02:49 +0000647 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000648 } else {
649 // No second conversion required.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000650 SCS.Second = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000651 }
652
Douglas Gregor81c29152008-10-29 00:13:59 +0000653 QualType CanonFrom;
654 QualType CanonTo;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000655 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor6573cfd2008-10-21 23:43:52 +0000656 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000657 SCS.Third = ICK_Qualification;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000658 FromType = ToType;
Douglas Gregor81c29152008-10-29 00:13:59 +0000659 CanonFrom = Context.getCanonicalType(FromType);
660 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000661 } else {
662 // No conversion required
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000663 SCS.Third = ICK_Identity;
664
665 // C++ [over.best.ics]p6:
666 // [...] Any difference in top-level cv-qualification is
667 // subsumed by the initialization itself and does not constitute
668 // a conversion. [...]
Douglas Gregor81c29152008-10-29 00:13:59 +0000669 CanonFrom = Context.getCanonicalType(FromType);
670 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000671 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor81c29152008-10-29 00:13:59 +0000672 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
673 FromType = ToType;
674 CanonFrom = CanonTo;
675 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000676 }
677
678 // If we have not converted the argument type to the parameter type,
679 // this is a bad conversion sequence.
Douglas Gregor81c29152008-10-29 00:13:59 +0000680 if (CanonFrom != CanonTo)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000681 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000682
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000683 SCS.ToTypePtr = FromType.getAsOpaquePtr();
684 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000685}
686
687/// IsIntegralPromotion - Determines whether the conversion from the
688/// expression From (whose potentially-adjusted type is FromType) to
689/// ToType is an integral promotion (C++ 4.5). If so, returns true and
690/// sets PromotedType to the promoted type.
691bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
692{
693 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redl12aee862008-11-04 15:59:10 +0000694 // All integers are built-in.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000695 if (!To) {
696 return false;
697 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000698
699 // An rvalue of type char, signed char, unsigned char, short int, or
700 // unsigned short int can be converted to an rvalue of type int if
701 // int can represent all the values of the source type; otherwise,
702 // the source rvalue can be converted to an rvalue of type unsigned
703 // int (C++ 4.5p1).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000704 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000705 if (// We can promote any signed, promotable integer type to an int
706 (FromType->isSignedIntegerType() ||
707 // We can promote any unsigned integer type whose size is
708 // less than int to an int.
709 (!FromType->isSignedIntegerType() &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000710 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000711 return To->getKind() == BuiltinType::Int;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000712 }
713
Douglas Gregord2baafd2008-10-21 16:13:35 +0000714 return To->getKind() == BuiltinType::UInt;
715 }
716
717 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
718 // can be converted to an rvalue of the first of the following types
719 // that can represent all the values of its underlying type: int,
720 // unsigned int, long, or unsigned long (C++ 4.5p2).
721 if ((FromType->isEnumeralType() || FromType->isWideCharType())
722 && ToType->isIntegerType()) {
723 // Determine whether the type we're converting from is signed or
724 // unsigned.
725 bool FromIsSigned;
726 uint64_t FromSize = Context.getTypeSize(FromType);
727 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
728 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
729 FromIsSigned = UnderlyingType->isSignedIntegerType();
730 } else {
731 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
732 FromIsSigned = true;
733 }
734
735 // The types we'll try to promote to, in the appropriate
736 // order. Try each of these types.
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000737 QualType PromoteTypes[6] = {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000738 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000739 Context.LongTy, Context.UnsignedLongTy ,
740 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregord2baafd2008-10-21 16:13:35 +0000741 };
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000742 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000743 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
744 if (FromSize < ToSize ||
745 (FromSize == ToSize &&
746 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
747 // We found the type that we can promote to. If this is the
748 // type we wanted, we have a promotion. Otherwise, no
749 // promotion.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000750 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregord2baafd2008-10-21 16:13:35 +0000751 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
752 }
753 }
754 }
755
756 // An rvalue for an integral bit-field (9.6) can be converted to an
757 // rvalue of type int if int can represent all the values of the
758 // bit-field; otherwise, it can be converted to unsigned int if
759 // unsigned int can represent all the values of the bit-field. If
760 // the bit-field is larger yet, no integral promotion applies to
761 // it. If the bit-field has an enumerated type, it is treated as any
762 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stumpe127ae32009-05-16 07:39:55 +0000763 // FIXME: We should delay checking of bit-fields until we actually perform the
764 // conversion.
Douglas Gregor531434b2009-05-02 02:18:30 +0000765 using llvm::APSInt;
766 if (From)
767 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor82d44772008-12-20 23:49:58 +0000768 APSInt BitWidth;
Douglas Gregor531434b2009-05-02 02:18:30 +0000769 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
770 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
771 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
772 ToSize = Context.getTypeSize(ToType);
Douglas Gregor82d44772008-12-20 23:49:58 +0000773
774 // Are we promoting to an int from a bitfield that fits in an int?
775 if (BitWidth < ToSize ||
776 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
777 return To->getKind() == BuiltinType::Int;
778 }
779
780 // Are we promoting to an unsigned int from an unsigned bitfield
781 // that fits into an unsigned int?
782 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
783 return To->getKind() == BuiltinType::UInt;
784 }
785
786 return false;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000787 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000788 }
Douglas Gregor531434b2009-05-02 02:18:30 +0000789
Douglas Gregord2baafd2008-10-21 16:13:35 +0000790 // An rvalue of type bool can be converted to an rvalue of type int,
791 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000792 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000793 return true;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000794 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000795
796 return false;
797}
798
799/// IsFloatingPointPromotion - Determines whether the conversion from
800/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
801/// returns true and sets PromotedType to the promoted type.
802bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
803{
804 /// An rvalue of type float can be converted to an rvalue of type
805 /// double. (C++ 4.6p1).
806 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
Douglas Gregore819caf2009-02-12 00:15:05 +0000807 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000808 if (FromBuiltin->getKind() == BuiltinType::Float &&
809 ToBuiltin->getKind() == BuiltinType::Double)
810 return true;
811
Douglas Gregore819caf2009-02-12 00:15:05 +0000812 // C99 6.3.1.5p1:
813 // When a float is promoted to double or long double, or a
814 // double is promoted to long double [...].
815 if (!getLangOptions().CPlusPlus &&
816 (FromBuiltin->getKind() == BuiltinType::Float ||
817 FromBuiltin->getKind() == BuiltinType::Double) &&
818 (ToBuiltin->getKind() == BuiltinType::LongDouble))
819 return true;
820 }
821
Douglas Gregord2baafd2008-10-21 16:13:35 +0000822 return false;
823}
824
Douglas Gregore819caf2009-02-12 00:15:05 +0000825/// \brief Determine if a conversion is a complex promotion.
826///
827/// A complex promotion is defined as a complex -> complex conversion
828/// where the conversion between the underlying real types is a
Douglas Gregor4ff48512009-02-12 00:26:06 +0000829/// floating-point or integral promotion.
Douglas Gregore819caf2009-02-12 00:15:05 +0000830bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
831 const ComplexType *FromComplex = FromType->getAsComplexType();
832 if (!FromComplex)
833 return false;
834
835 const ComplexType *ToComplex = ToType->getAsComplexType();
836 if (!ToComplex)
837 return false;
838
839 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor4ff48512009-02-12 00:26:06 +0000840 ToComplex->getElementType()) ||
841 IsIntegralPromotion(0, FromComplex->getElementType(),
842 ToComplex->getElementType());
Douglas Gregore819caf2009-02-12 00:15:05 +0000843}
844
Douglas Gregor24a90a52008-11-26 23:31:11 +0000845/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
846/// the pointer type FromPtr to a pointer to type ToPointee, with the
847/// same type qualifiers as FromPtr has on its pointee type. ToType,
848/// if non-empty, will be a pointer to ToType that may or may not have
849/// the right set of qualifiers on its pointee.
850static QualType
851BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
852 QualType ToPointee, QualType ToType,
853 ASTContext &Context) {
854 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
855 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
856 unsigned Quals = CanonFromPointee.getCVRQualifiers();
857
858 // Exact qualifier match -> return the pointer type we're converting to.
859 if (CanonToPointee.getCVRQualifiers() == Quals) {
860 // ToType is exactly what we need. Return it.
861 if (ToType.getTypePtr())
862 return ToType;
863
864 // Build a pointer to ToPointee. It has the right qualifiers
865 // already.
866 return Context.getPointerType(ToPointee);
867 }
868
869 // Just build a canonical type that has the right qualifiers.
870 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
871}
872
Douglas Gregord2baafd2008-10-21 16:13:35 +0000873/// IsPointerConversion - Determines whether the conversion of the
874/// expression From, which has the (possibly adjusted) type FromType,
875/// can be converted to the type ToType via a pointer conversion (C++
876/// 4.10). If so, returns true and places the converted type (that
877/// might differ from ToType in its cv-qualifiers at some level) into
878/// ConvertedType.
Douglas Gregor9036ef72008-11-27 00:15:41 +0000879///
Douglas Gregor3f5a00c2008-11-27 01:19:21 +0000880/// This routine also supports conversions to and from block pointers
881/// and conversions with Objective-C's 'id', 'id<protocols...>', and
882/// pointers to interfaces. FIXME: Once we've determined the
883/// appropriate overloading rules for Objective-C, we may want to
884/// split the Objective-C checks into a different routine; however,
885/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor6fd35572008-12-19 17:40:08 +0000886/// conversions, so for now they live here. IncompatibleObjC will be
887/// set if the conversion is an allowed Objective-C conversion that
888/// should result in a warning.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000889bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson8e4c1692009-08-28 15:33:32 +0000890 bool InOverloadResolution,
Douglas Gregor6fd35572008-12-19 17:40:08 +0000891 QualType& ConvertedType,
892 bool &IncompatibleObjC)
Douglas Gregord2baafd2008-10-21 16:13:35 +0000893{
Douglas Gregor6fd35572008-12-19 17:40:08 +0000894 IncompatibleObjC = false;
Douglas Gregor932778b2008-12-19 19:13:09 +0000895 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
896 return true;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000897
Douglas Gregorf1d75712008-12-22 20:51:52 +0000898 // Conversion from a null pointer constant to any Objective-C pointer type.
Steve Naroffad75bd22009-07-16 15:41:00 +0000899 if (ToType->isObjCObjectPointerType() &&
Douglas Gregorf1d75712008-12-22 20:51:52 +0000900 From->isNullPointerConstant(Context)) {
901 ConvertedType = ToType;
902 return true;
903 }
904
Douglas Gregor9036ef72008-11-27 00:15:41 +0000905 // Blocks: Block pointers can be converted to void*.
906 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000907 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor9036ef72008-11-27 00:15:41 +0000908 ConvertedType = ToType;
909 return true;
910 }
911 // Blocks: A null pointer constant can be converted to a block
912 // pointer type.
913 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
914 ConvertedType = ToType;
915 return true;
916 }
917
Sebastian Redl5d0ead72009-05-10 18:38:11 +0000918 // If the left-hand-side is nullptr_t, the right side can be a null
919 // pointer constant.
920 if (ToType->isNullPtrType() && From->isNullPointerConstant(Context)) {
921 ConvertedType = ToType;
922 return true;
923 }
924
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000925 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregord2baafd2008-10-21 16:13:35 +0000926 if (!ToTypePtr)
927 return false;
928
929 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
930 if (From->isNullPointerConstant(Context)) {
931 ConvertedType = ToType;
932 return true;
933 }
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000934
Douglas Gregor24a90a52008-11-26 23:31:11 +0000935 // Beyond this point, both types need to be pointers.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000936 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor24a90a52008-11-26 23:31:11 +0000937 if (!FromTypePtr)
938 return false;
939
940 QualType FromPointeeType = FromTypePtr->getPointeeType();
941 QualType ToPointeeType = ToTypePtr->getPointeeType();
942
Douglas Gregord2baafd2008-10-21 16:13:35 +0000943 // An rvalue of type "pointer to cv T," where T is an object type,
944 // can be converted to an rvalue of type "pointer to cv void" (C++
945 // 4.10p2).
Douglas Gregor26ea1222009-03-24 20:32:41 +0000946 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000947 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
948 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000949 ToType, Context);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000950 return true;
951 }
952
Douglas Gregorfcb19192009-02-11 23:02:49 +0000953 // When we're overloading in C, we allow a special kind of pointer
954 // conversion for compatible-but-not-identical pointee types.
955 if (!getLangOptions().CPlusPlus &&
956 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
957 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
958 ToPointeeType,
959 ToType, Context);
960 return true;
961 }
962
Douglas Gregor14046502008-10-23 00:40:37 +0000963 // C++ [conv.ptr]p3:
964 //
965 // An rvalue of type "pointer to cv D," where D is a class type,
966 // can be converted to an rvalue of type "pointer to cv B," where
967 // B is a base class (clause 10) of D. If B is an inaccessible
968 // (clause 11) or ambiguous (10.2) base class of D, a program that
969 // necessitates this conversion is ill-formed. The result of the
970 // conversion is a pointer to the base class sub-object of the
971 // derived class object. The null pointer value is converted to
972 // the null pointer value of the destination type.
973 //
Douglas Gregorbb461502008-10-24 04:54:22 +0000974 // Note that we do not check for ambiguity or inaccessibility
975 // here. That is handled by CheckPointerConversion.
Douglas Gregorfcb19192009-02-11 23:02:49 +0000976 if (getLangOptions().CPlusPlus &&
977 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor24a90a52008-11-26 23:31:11 +0000978 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000979 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
980 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000981 ToType, Context);
982 return true;
983 }
Douglas Gregor14046502008-10-23 00:40:37 +0000984
Douglas Gregor932778b2008-12-19 19:13:09 +0000985 return false;
986}
987
988/// isObjCPointerConversion - Determines whether this is an
989/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
990/// with the same arguments and return values.
991bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
992 QualType& ConvertedType,
993 bool &IncompatibleObjC) {
994 if (!getLangOptions().ObjC1)
995 return false;
996
Steve Naroff329ec222009-07-10 23:34:53 +0000997 // First, we handle all conversions on ObjC object pointer types.
998 const ObjCObjectPointerType* ToObjCPtr = ToType->getAsObjCObjectPointerType();
999 const ObjCObjectPointerType *FromObjCPtr =
1000 FromType->getAsObjCObjectPointerType();
Douglas Gregor932778b2008-12-19 19:13:09 +00001001
Steve Naroff329ec222009-07-10 23:34:53 +00001002 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff7bffd372009-07-15 18:40:39 +00001003 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff329ec222009-07-10 23:34:53 +00001004 // pointer to any interface (in both directions).
Steve Naroff7bffd372009-07-15 18:40:39 +00001005 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00001006 ConvertedType = ToType;
1007 return true;
1008 }
1009 // Conversions with Objective-C's id<...>.
1010 if ((FromObjCPtr->isObjCQualifiedIdType() ||
1011 ToObjCPtr->isObjCQualifiedIdType()) &&
Steve Naroff99eb86b2009-07-23 01:01:38 +00001012 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
1013 /*compare=*/false)) {
Steve Naroff329ec222009-07-10 23:34:53 +00001014 ConvertedType = ToType;
1015 return true;
1016 }
1017 // Objective C++: We're able to convert from a pointer to an
1018 // interface to a pointer to a different interface.
1019 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1020 ConvertedType = ToType;
1021 return true;
1022 }
1023
1024 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1025 // Okay: this is some kind of implicit downcast of Objective-C
1026 // interfaces, which is permitted. However, we're going to
1027 // complain about it.
1028 IncompatibleObjC = true;
1029 ConvertedType = FromType;
1030 return true;
1031 }
1032 }
1033 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor80402cf2008-12-23 00:53:59 +00001034 QualType ToPointeeType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001035 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff329ec222009-07-10 23:34:53 +00001036 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001037 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor80402cf2008-12-23 00:53:59 +00001038 ToPointeeType = ToBlockPtr->getPointeeType();
1039 else
Douglas Gregor932778b2008-12-19 19:13:09 +00001040 return false;
1041
Douglas Gregor80402cf2008-12-23 00:53:59 +00001042 QualType FromPointeeType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001043 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff329ec222009-07-10 23:34:53 +00001044 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001045 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor80402cf2008-12-23 00:53:59 +00001046 FromPointeeType = FromBlockPtr->getPointeeType();
1047 else
Douglas Gregor932778b2008-12-19 19:13:09 +00001048 return false;
1049
Douglas Gregor932778b2008-12-19 19:13:09 +00001050 // If we have pointers to pointers, recursively check whether this
1051 // is an Objective-C conversion.
1052 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1053 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1054 IncompatibleObjC)) {
1055 // We always complain about this conversion.
1056 IncompatibleObjC = true;
1057 ConvertedType = ToType;
1058 return true;
1059 }
Douglas Gregor80402cf2008-12-23 00:53:59 +00001060 // If we have pointers to functions or blocks, check whether the only
Douglas Gregor932778b2008-12-19 19:13:09 +00001061 // differences in the argument and result types are in Objective-C
1062 // pointer conversions. If so, we permit the conversion (but
1063 // complain about it).
Douglas Gregor4fa58902009-02-26 23:50:07 +00001064 const FunctionProtoType *FromFunctionType
1065 = FromPointeeType->getAsFunctionProtoType();
1066 const FunctionProtoType *ToFunctionType
1067 = ToPointeeType->getAsFunctionProtoType();
Douglas Gregor932778b2008-12-19 19:13:09 +00001068 if (FromFunctionType && ToFunctionType) {
1069 // If the function types are exactly the same, this isn't an
1070 // Objective-C pointer conversion.
1071 if (Context.getCanonicalType(FromPointeeType)
1072 == Context.getCanonicalType(ToPointeeType))
1073 return false;
1074
1075 // Perform the quick checks that will tell us whether these
1076 // function types are obviously different.
1077 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1078 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1079 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1080 return false;
1081
1082 bool HasObjCConversion = false;
1083 if (Context.getCanonicalType(FromFunctionType->getResultType())
1084 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1085 // Okay, the types match exactly. Nothing to do.
1086 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1087 ToFunctionType->getResultType(),
1088 ConvertedType, IncompatibleObjC)) {
1089 // Okay, we have an Objective-C pointer conversion.
1090 HasObjCConversion = true;
1091 } else {
1092 // Function types are too different. Abort.
1093 return false;
1094 }
1095
1096 // Check argument types.
1097 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1098 ArgIdx != NumArgs; ++ArgIdx) {
1099 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1100 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1101 if (Context.getCanonicalType(FromArgType)
1102 == Context.getCanonicalType(ToArgType)) {
1103 // Okay, the types match exactly. Nothing to do.
1104 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1105 ConvertedType, IncompatibleObjC)) {
1106 // Okay, we have an Objective-C pointer conversion.
1107 HasObjCConversion = true;
1108 } else {
1109 // Argument types are too different. Abort.
1110 return false;
1111 }
1112 }
1113
1114 if (HasObjCConversion) {
1115 // We had an Objective-C conversion. Allow this pointer
1116 // conversion, but complain about it.
1117 ConvertedType = ToType;
1118 IncompatibleObjC = true;
1119 return true;
1120 }
1121 }
1122
Sebastian Redlba387562009-01-25 19:43:20 +00001123 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001124}
1125
Douglas Gregorbb461502008-10-24 04:54:22 +00001126/// CheckPointerConversion - Check the pointer conversion from the
1127/// expression From to the type ToType. This routine checks for
Sebastian Redl0e35d042009-07-25 15:41:38 +00001128/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregorbb461502008-10-24 04:54:22 +00001129/// conversions for which IsPointerConversion has already returned
1130/// true. It returns true and produces a diagnostic if there was an
1131/// error, or returns false otherwise.
1132bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1133 QualType FromType = From->getType();
1134
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001135 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1136 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregorbb461502008-10-24 04:54:22 +00001137 QualType FromPointeeType = FromPtrType->getPointeeType(),
1138 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregord0c653a2008-12-18 23:43:31 +00001139
Douglas Gregorbb461502008-10-24 04:54:22 +00001140 if (FromPointeeType->isRecordType() &&
1141 ToPointeeType->isRecordType()) {
1142 // We must have a derived-to-base conversion. Check an
1143 // ambiguous or inaccessible conversion.
Douglas Gregor651d1cc2008-10-24 16:17:19 +00001144 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1145 From->getExprLoc(),
1146 From->getSourceRange());
Douglas Gregorbb461502008-10-24 04:54:22 +00001147 }
1148 }
Steve Naroff329ec222009-07-10 23:34:53 +00001149 if (const ObjCObjectPointerType *FromPtrType =
1150 FromType->getAsObjCObjectPointerType())
1151 if (const ObjCObjectPointerType *ToPtrType =
1152 ToType->getAsObjCObjectPointerType()) {
1153 // Objective-C++ conversions are always okay.
1154 // FIXME: We should have a different class of conversions for the
1155 // Objective-C++ implicit conversions.
Steve Naroff7bffd372009-07-15 18:40:39 +00001156 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff329ec222009-07-10 23:34:53 +00001157 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +00001158
Steve Naroff329ec222009-07-10 23:34:53 +00001159 }
Douglas Gregorbb461502008-10-24 04:54:22 +00001160 return false;
1161}
1162
Sebastian Redlba387562009-01-25 19:43:20 +00001163/// IsMemberPointerConversion - Determines whether the conversion of the
1164/// expression From, which has the (possibly adjusted) type FromType, can be
1165/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1166/// If so, returns true and places the converted type (that might differ from
1167/// ToType in its cv-qualifiers at some level) into ConvertedType.
1168bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1169 QualType ToType, QualType &ConvertedType)
1170{
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001171 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redlba387562009-01-25 19:43:20 +00001172 if (!ToTypePtr)
1173 return false;
1174
1175 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1176 if (From->isNullPointerConstant(Context)) {
1177 ConvertedType = ToType;
1178 return true;
1179 }
1180
1181 // Otherwise, both types have to be member pointers.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001182 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redlba387562009-01-25 19:43:20 +00001183 if (!FromTypePtr)
1184 return false;
1185
1186 // A pointer to member of B can be converted to a pointer to member of D,
1187 // where D is derived from B (C++ 4.11p2).
1188 QualType FromClass(FromTypePtr->getClass(), 0);
1189 QualType ToClass(ToTypePtr->getClass(), 0);
1190 // FIXME: What happens when these are dependent? Is this function even called?
1191
1192 if (IsDerivedFrom(ToClass, FromClass)) {
1193 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1194 ToClass.getTypePtr());
1195 return true;
1196 }
1197
1198 return false;
1199}
1200
1201/// CheckMemberPointerConversion - Check the member pointer conversion from the
1202/// expression From to the type ToType. This routine checks for ambiguous or
1203/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1204/// for which IsMemberPointerConversion has already returned true. It returns
1205/// true and produces a diagnostic if there was an error, or returns false
1206/// otherwise.
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001207bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
1208 CastExpr::CastKind &Kind) {
Sebastian Redlba387562009-01-25 19:43:20 +00001209 QualType FromType = From->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001210 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001211 if (!FromPtrType) {
1212 // This must be a null pointer to member pointer conversion
1213 assert(From->isNullPointerConstant(Context) &&
1214 "Expr must be null pointer constant!");
1215 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001216 return false;
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001217 }
Sebastian Redlba387562009-01-25 19:43:20 +00001218
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001219 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001220 assert(ToPtrType && "No member pointer cast has a target type "
1221 "that is not a member pointer.");
Sebastian Redlba387562009-01-25 19:43:20 +00001222
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001223 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1224 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redlba387562009-01-25 19:43:20 +00001225
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001226 // FIXME: What about dependent types?
1227 assert(FromClass->isRecordType() && "Pointer into non-class.");
1228 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redlba387562009-01-25 19:43:20 +00001229
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001230 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1231 /*DetectVirtual=*/true);
1232 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1233 assert(DerivationOkay &&
1234 "Should not have been called if derivation isn't OK.");
1235 (void)DerivationOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001236
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001237 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1238 getUnqualifiedType())) {
1239 // Derivation is ambiguous. Redo the check to find the exact paths.
1240 Paths.clear();
1241 Paths.setRecordingPaths(true);
1242 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1243 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1244 (void)StillOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001245
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001246 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1247 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1248 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1249 return true;
Sebastian Redlba387562009-01-25 19:43:20 +00001250 }
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001251
Douglas Gregor2e047592009-02-28 01:32:25 +00001252 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001253 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1254 << FromClass << ToClass << QualType(VBase, 0)
1255 << From->getSourceRange();
1256 return true;
1257 }
1258
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001259 // Must be a base to derived member conversion.
1260 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redlba387562009-01-25 19:43:20 +00001261 return false;
1262}
1263
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001264/// IsQualificationConversion - Determines whether the conversion from
1265/// an rvalue of type FromType to ToType is a qualification conversion
1266/// (C++ 4.4).
1267bool
1268Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1269{
1270 FromType = Context.getCanonicalType(FromType);
1271 ToType = Context.getCanonicalType(ToType);
1272
1273 // If FromType and ToType are the same type, this is not a
1274 // qualification conversion.
1275 if (FromType == ToType)
1276 return false;
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001277
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001278 // (C++ 4.4p4):
1279 // A conversion can add cv-qualifiers at levels other than the first
1280 // in multi-level pointers, subject to the following rules: [...]
1281 bool PreviousToQualsIncludeConst = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001282 bool UnwrappedAnyPointer = false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001283 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001284 // Within each iteration of the loop, we check the qualifiers to
1285 // determine if this still looks like a qualification
1286 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001287 // pointers or pointers-to-members and do it all again
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001288 // until there are no more pointers or pointers-to-members left to
1289 // unwrap.
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001290 UnwrappedAnyPointer = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001291
1292 // -- for every j > 0, if const is in cv 1,j then const is in cv
1293 // 2,j, and similarly for volatile.
Douglas Gregore5db4f72008-10-22 00:38:21 +00001294 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001295 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001296
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001297 // -- if the cv 1,j and cv 2,j are different, then const is in
1298 // every cv for 0 < k < j.
1299 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001300 && !PreviousToQualsIncludeConst)
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001301 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001302
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001303 // Keep track of whether all prior cv-qualifiers in the "to" type
1304 // include const.
1305 PreviousToQualsIncludeConst
1306 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001307 }
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001308
1309 // We are left with FromType and ToType being the pointee types
1310 // after unwrapping the original FromType and ToType the same number
1311 // of types. If we unwrapped any pointers, and if FromType and
1312 // ToType have the same unqualified type (since we checked
1313 // qualifiers above), then this is a qualification conversion.
1314 return UnwrappedAnyPointer &&
1315 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1316}
1317
Douglas Gregor8c860df2009-08-21 23:19:43 +00001318/// \brief Given a function template or function, extract the function template
1319/// declaration (if any) and the underlying function declaration.
1320template<typename T>
1321static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1322 FunctionTemplateDecl *&FunctionTemplate) {
1323 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1324 if (FunctionTemplate)
1325 Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1326 else
1327 Function = cast<T>(Orig);
1328}
1329
1330
Douglas Gregorb206cc42009-01-30 23:27:23 +00001331/// Determines whether there is a user-defined conversion sequence
1332/// (C++ [over.ics.user]) that converts expression From to the type
1333/// ToType. If such a conversion exists, User will contain the
1334/// user-defined conversion sequence that performs such a conversion
1335/// and this routine will return true. Otherwise, this routine returns
1336/// false and User is unspecified.
1337///
1338/// \param AllowConversionFunctions true if the conversion should
1339/// consider conversion functions at all. If false, only constructors
1340/// will be considered.
1341///
1342/// \param AllowExplicit true if the conversion should consider C++0x
1343/// "explicit" conversion functions as well as non-explicit conversion
1344/// functions (C++0x [class.conv.fct]p2).
Sebastian Redla55834a2009-04-12 17:16:29 +00001345///
1346/// \param ForceRValue true if the expression should be treated as an rvalue
1347/// for overload resolution.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001348bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001349 UserDefinedConversionSequence& User,
Douglas Gregorb206cc42009-01-30 23:27:23 +00001350 bool AllowConversionFunctions,
Sebastian Redla55834a2009-04-12 17:16:29 +00001351 bool AllowExplicit, bool ForceRValue)
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001352{
1353 OverloadCandidateSet CandidateSet;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001354 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001355 if (CXXRecordDecl *ToRecordDecl
1356 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1357 // C++ [over.match.ctor]p1:
1358 // When objects of class type are direct-initialized (8.5), or
1359 // copy-initialized from an expression of the same or a
1360 // derived class type (8.5), overload resolution selects the
1361 // constructor. [...] For copy-initialization, the candidate
1362 // functions are all the converting constructors (12.3.1) of
1363 // that class. The argument list is the expression-list within
1364 // the parentheses of the initializer.
1365 DeclarationName ConstructorName
1366 = Context.DeclarationNames.getCXXConstructorName(
1367 Context.getCanonicalType(ToType).getUnqualifiedType());
1368 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001369 for (llvm::tie(Con, ConEnd)
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001370 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor2e047592009-02-28 01:32:25 +00001371 Con != ConEnd; ++Con) {
Douglas Gregor050cabf2009-08-21 18:42:58 +00001372 // Find the constructor (which may be a template).
1373 CXXConstructorDecl *Constructor = 0;
1374 FunctionTemplateDecl *ConstructorTmpl
1375 = dyn_cast<FunctionTemplateDecl>(*Con);
1376 if (ConstructorTmpl)
1377 Constructor
1378 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1379 else
1380 Constructor = cast<CXXConstructorDecl>(*Con);
1381
Fariborz Jahanian625fb9d2009-08-06 17:22:51 +00001382 if (!Constructor->isInvalidDecl() &&
Douglas Gregor050cabf2009-08-21 18:42:58 +00001383 Constructor->isConvertingConstructor()) {
1384 if (ConstructorTmpl)
1385 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
1386 1, CandidateSet,
1387 /*SuppressUserConversions=*/true,
1388 ForceRValue);
1389 else
1390 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1391 /*SuppressUserConversions=*/true, ForceRValue);
1392 }
Douglas Gregor2e047592009-02-28 01:32:25 +00001393 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001394 }
1395 }
1396
Douglas Gregorb206cc42009-01-30 23:27:23 +00001397 if (!AllowConversionFunctions) {
1398 // Don't allow any conversion functions to enter the overload set.
Anders Carlssona21e7872009-08-26 23:45:07 +00001399 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1400 PDiag(0)
1401 << From->getSourceRange())) {
Douglas Gregorb35c7992009-08-24 15:23:48 +00001402 // No conversion functions from incomplete types.
Douglas Gregor2e047592009-02-28 01:32:25 +00001403 } else if (const RecordType *FromRecordType
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001404 = From->getType()->getAs<RecordType>()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001405 if (CXXRecordDecl *FromRecordDecl
1406 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1407 // Add all of the conversion functions as candidates.
1408 // FIXME: Look for conversions in base classes!
1409 OverloadedFunctionDecl *Conversions
1410 = FromRecordDecl->getConversionFunctions();
1411 for (OverloadedFunctionDecl::function_iterator Func
1412 = Conversions->function_begin();
1413 Func != Conversions->function_end(); ++Func) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00001414 CXXConversionDecl *Conv;
1415 FunctionTemplateDecl *ConvTemplate;
1416 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1417 if (ConvTemplate)
1418 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1419 else
1420 Conv = dyn_cast<CXXConversionDecl>(*Func);
1421
1422 if (AllowExplicit || !Conv->isExplicit()) {
1423 if (ConvTemplate)
1424 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1425 CandidateSet);
1426 else
1427 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1428 }
Douglas Gregor2e047592009-02-28 01:32:25 +00001429 }
Douglas Gregor60714f92008-11-07 22:36:19 +00001430 }
1431 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001432
1433 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001434 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001435 case OR_Success:
1436 // Record the standard conversion we used and the conversion function.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001437 if (CXXConstructorDecl *Constructor
1438 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1439 // C++ [over.ics.user]p1:
1440 // If the user-defined conversion is specified by a
1441 // constructor (12.3.1), the initial standard conversion
1442 // sequence converts the source type to the type required by
1443 // the argument of the constructor.
1444 //
1445 // FIXME: What about ellipsis conversions?
1446 QualType ThisType = Constructor->getThisType(Context);
1447 User.Before = Best->Conversions[0].Standard;
1448 User.ConversionFunction = Constructor;
1449 User.After.setAsIdentityConversion();
1450 User.After.FromTypePtr
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001451 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001452 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1453 return true;
Douglas Gregor60714f92008-11-07 22:36:19 +00001454 } else if (CXXConversionDecl *Conversion
1455 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1456 // C++ [over.ics.user]p1:
1457 //
1458 // [...] If the user-defined conversion is specified by a
1459 // conversion function (12.3.2), the initial standard
1460 // conversion sequence converts the source type to the
1461 // implicit object parameter of the conversion function.
1462 User.Before = Best->Conversions[0].Standard;
1463 User.ConversionFunction = Conversion;
1464
1465 // C++ [over.ics.user]p2:
1466 // The second standard conversion sequence converts the
1467 // result of the user-defined conversion to the target type
1468 // for the sequence. Since an implicit conversion sequence
1469 // is an initialization, the special rules for
1470 // initialization by user-defined conversion apply when
1471 // selecting the best user-defined conversion for a
1472 // user-defined conversion sequence (see 13.3.3 and
1473 // 13.3.3.1).
1474 User.After = Best->FinalConversion;
1475 return true;
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001476 } else {
Douglas Gregor60714f92008-11-07 22:36:19 +00001477 assert(false && "Not a constructor or conversion function?");
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001478 return false;
1479 }
1480
1481 case OR_No_Viable_Function:
Douglas Gregoraa57e862009-02-18 21:56:37 +00001482 case OR_Deleted:
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001483 // No conversion here! We're done.
1484 return false;
1485
1486 case OR_Ambiguous:
1487 // FIXME: See C++ [over.best.ics]p10 for the handling of
1488 // ambiguous conversion sequences.
1489 return false;
1490 }
1491
1492 return false;
1493}
1494
Douglas Gregord2baafd2008-10-21 16:13:35 +00001495/// CompareImplicitConversionSequences - Compare two implicit
1496/// conversion sequences to determine whether one is better than the
1497/// other or if they are indistinguishable (C++ 13.3.3.2).
1498ImplicitConversionSequence::CompareKind
1499Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1500 const ImplicitConversionSequence& ICS2)
1501{
1502 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1503 // conversion sequences (as defined in 13.3.3.1)
1504 // -- a standard conversion sequence (13.3.3.1.1) is a better
1505 // conversion sequence than a user-defined conversion sequence or
1506 // an ellipsis conversion sequence, and
1507 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1508 // conversion sequence than an ellipsis conversion sequence
1509 // (13.3.3.1.3).
1510 //
1511 if (ICS1.ConversionKind < ICS2.ConversionKind)
1512 return ImplicitConversionSequence::Better;
1513 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1514 return ImplicitConversionSequence::Worse;
1515
1516 // Two implicit conversion sequences of the same form are
1517 // indistinguishable conversion sequences unless one of the
1518 // following rules apply: (C++ 13.3.3.2p3):
1519 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1520 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1521 else if (ICS1.ConversionKind ==
1522 ImplicitConversionSequence::UserDefinedConversion) {
1523 // User-defined conversion sequence U1 is a better conversion
1524 // sequence than another user-defined conversion sequence U2 if
1525 // they contain the same user-defined conversion function or
1526 // constructor and if the second standard conversion sequence of
1527 // U1 is better than the second standard conversion sequence of
1528 // U2 (C++ 13.3.3.2p3).
1529 if (ICS1.UserDefined.ConversionFunction ==
1530 ICS2.UserDefined.ConversionFunction)
1531 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1532 ICS2.UserDefined.After);
1533 }
1534
1535 return ImplicitConversionSequence::Indistinguishable;
1536}
1537
1538/// CompareStandardConversionSequences - Compare two standard
1539/// conversion sequences to determine whether one is better than the
1540/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1541ImplicitConversionSequence::CompareKind
1542Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1543 const StandardConversionSequence& SCS2)
1544{
1545 // Standard conversion sequence S1 is a better conversion sequence
1546 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1547
1548 // -- S1 is a proper subsequence of S2 (comparing the conversion
1549 // sequences in the canonical form defined by 13.3.3.1.1,
1550 // excluding any Lvalue Transformation; the identity conversion
1551 // sequence is considered to be a subsequence of any
1552 // non-identity conversion sequence) or, if not that,
1553 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1554 // Neither is a proper subsequence of the other. Do nothing.
1555 ;
1556 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1557 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1558 (SCS1.Second == ICK_Identity &&
1559 SCS1.Third == ICK_Identity))
1560 // SCS1 is a proper subsequence of SCS2.
1561 return ImplicitConversionSequence::Better;
1562 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1563 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1564 (SCS2.Second == ICK_Identity &&
1565 SCS2.Third == ICK_Identity))
1566 // SCS2 is a proper subsequence of SCS1.
1567 return ImplicitConversionSequence::Worse;
1568
1569 // -- the rank of S1 is better than the rank of S2 (by the rules
1570 // defined below), or, if not that,
1571 ImplicitConversionRank Rank1 = SCS1.getRank();
1572 ImplicitConversionRank Rank2 = SCS2.getRank();
1573 if (Rank1 < Rank2)
1574 return ImplicitConversionSequence::Better;
1575 else if (Rank2 < Rank1)
1576 return ImplicitConversionSequence::Worse;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001577
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001578 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1579 // are indistinguishable unless one of the following rules
1580 // applies:
1581
1582 // A conversion that is not a conversion of a pointer, or
1583 // pointer to member, to bool is better than another conversion
1584 // that is such a conversion.
1585 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1586 return SCS2.isPointerConversionToBool()
1587 ? ImplicitConversionSequence::Better
1588 : ImplicitConversionSequence::Worse;
1589
Douglas Gregor14046502008-10-23 00:40:37 +00001590 // C++ [over.ics.rank]p4b2:
1591 //
1592 // If class B is derived directly or indirectly from class A,
Douglas Gregor0e343382008-10-29 14:50:44 +00001593 // conversion of B* to A* is better than conversion of B* to
1594 // void*, and conversion of A* to void* is better than conversion
1595 // of B* to void*.
Douglas Gregor14046502008-10-23 00:40:37 +00001596 bool SCS1ConvertsToVoid
1597 = SCS1.isPointerConversionToVoidPointer(Context);
1598 bool SCS2ConvertsToVoid
1599 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregor0e343382008-10-29 14:50:44 +00001600 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1601 // Exactly one of the conversion sequences is a conversion to
1602 // a void pointer; it's the worse conversion.
Douglas Gregor14046502008-10-23 00:40:37 +00001603 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1604 : ImplicitConversionSequence::Worse;
Douglas Gregor0e343382008-10-29 14:50:44 +00001605 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1606 // Neither conversion sequence converts to a void pointer; compare
1607 // their derived-to-base conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001608 if (ImplicitConversionSequence::CompareKind DerivedCK
1609 = CompareDerivedToBaseConversions(SCS1, SCS2))
1610 return DerivedCK;
Douglas Gregor0e343382008-10-29 14:50:44 +00001611 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1612 // Both conversion sequences are conversions to void
1613 // pointers. Compare the source types to determine if there's an
1614 // inheritance relationship in their sources.
1615 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1616 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1617
1618 // Adjust the types we're converting from via the array-to-pointer
1619 // conversion, if we need to.
1620 if (SCS1.First == ICK_Array_To_Pointer)
1621 FromType1 = Context.getArrayDecayedType(FromType1);
1622 if (SCS2.First == ICK_Array_To_Pointer)
1623 FromType2 = Context.getArrayDecayedType(FromType2);
1624
1625 QualType FromPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001626 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor0e343382008-10-29 14:50:44 +00001627 QualType FromPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001628 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor0e343382008-10-29 14:50:44 +00001629
1630 if (IsDerivedFrom(FromPointee2, FromPointee1))
1631 return ImplicitConversionSequence::Better;
1632 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1633 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001634
1635 // Objective-C++: If one interface is more specific than the
1636 // other, it is the better one.
1637 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1638 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1639 if (FromIface1 && FromIface1) {
1640 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1641 return ImplicitConversionSequence::Better;
1642 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1643 return ImplicitConversionSequence::Worse;
1644 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001645 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001646
1647 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1648 // bullet 3).
Douglas Gregor14046502008-10-23 00:40:37 +00001649 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001650 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor14046502008-10-23 00:40:37 +00001651 return QualCK;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001652
Douglas Gregor0e343382008-10-29 14:50:44 +00001653 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001654 // C++0x [over.ics.rank]p3b4:
1655 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1656 // implicit object parameter of a non-static member function declared
1657 // without a ref-qualifier, and S1 binds an rvalue reference to an
1658 // rvalue and S2 binds an lvalue reference.
Sebastian Redldfc30332009-03-29 15:27:50 +00001659 // FIXME: We don't know if we're dealing with the implicit object parameter,
1660 // or if the member function in this case has a ref qualifier.
1661 // (Of course, we don't have ref qualifiers yet.)
1662 if (SCS1.RRefBinding != SCS2.RRefBinding)
1663 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1664 : ImplicitConversionSequence::Worse;
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001665
1666 // C++ [over.ics.rank]p3b4:
1667 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1668 // which the references refer are the same type except for
1669 // top-level cv-qualifiers, and the type to which the reference
1670 // initialized by S2 refers is more cv-qualified than the type
1671 // to which the reference initialized by S1 refers.
Sebastian Redldfc30332009-03-29 15:27:50 +00001672 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1673 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregor0e343382008-10-29 14:50:44 +00001674 T1 = Context.getCanonicalType(T1);
1675 T2 = Context.getCanonicalType(T2);
1676 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1677 if (T2.isMoreQualifiedThan(T1))
1678 return ImplicitConversionSequence::Better;
1679 else if (T1.isMoreQualifiedThan(T2))
1680 return ImplicitConversionSequence::Worse;
1681 }
1682 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001683
1684 return ImplicitConversionSequence::Indistinguishable;
1685}
1686
1687/// CompareQualificationConversions - Compares two standard conversion
1688/// sequences to determine whether they can be ranked based on their
1689/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1690ImplicitConversionSequence::CompareKind
1691Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1692 const StandardConversionSequence& SCS2)
1693{
Douglas Gregor4459bbe2008-10-22 15:04:37 +00001694 // C++ 13.3.3.2p3:
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001695 // -- S1 and S2 differ only in their qualification conversion and
1696 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1697 // cv-qualification signature of type T1 is a proper subset of
1698 // the cv-qualification signature of type T2, and S1 is not the
1699 // deprecated string literal array-to-pointer conversion (4.2).
1700 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1701 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1702 return ImplicitConversionSequence::Indistinguishable;
1703
1704 // FIXME: the example in the standard doesn't use a qualification
1705 // conversion (!)
1706 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1707 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1708 T1 = Context.getCanonicalType(T1);
1709 T2 = Context.getCanonicalType(T2);
1710
1711 // If the types are the same, we won't learn anything by unwrapped
1712 // them.
1713 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1714 return ImplicitConversionSequence::Indistinguishable;
1715
1716 ImplicitConversionSequence::CompareKind Result
1717 = ImplicitConversionSequence::Indistinguishable;
1718 while (UnwrapSimilarPointerTypes(T1, T2)) {
1719 // Within each iteration of the loop, we check the qualifiers to
1720 // determine if this still looks like a qualification
1721 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001722 // pointers or pointers-to-members and do it all again
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001723 // until there are no more pointers or pointers-to-members left
1724 // to unwrap. This essentially mimics what
1725 // IsQualificationConversion does, but here we're checking for a
1726 // strict subset of qualifiers.
1727 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1728 // The qualifiers are the same, so this doesn't tell us anything
1729 // about how the sequences rank.
1730 ;
1731 else if (T2.isMoreQualifiedThan(T1)) {
1732 // T1 has fewer qualifiers, so it could be the better sequence.
1733 if (Result == ImplicitConversionSequence::Worse)
1734 // Neither has qualifiers that are a subset of the other's
1735 // qualifiers.
1736 return ImplicitConversionSequence::Indistinguishable;
1737
1738 Result = ImplicitConversionSequence::Better;
1739 } else if (T1.isMoreQualifiedThan(T2)) {
1740 // T2 has fewer qualifiers, so it could be the better sequence.
1741 if (Result == ImplicitConversionSequence::Better)
1742 // Neither has qualifiers that are a subset of the other's
1743 // qualifiers.
1744 return ImplicitConversionSequence::Indistinguishable;
1745
1746 Result = ImplicitConversionSequence::Worse;
1747 } else {
1748 // Qualifiers are disjoint.
1749 return ImplicitConversionSequence::Indistinguishable;
1750 }
1751
1752 // If the types after this point are equivalent, we're done.
1753 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1754 break;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001755 }
1756
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001757 // Check that the winning standard conversion sequence isn't using
1758 // the deprecated string literal array to pointer conversion.
1759 switch (Result) {
1760 case ImplicitConversionSequence::Better:
1761 if (SCS1.Deprecated)
1762 Result = ImplicitConversionSequence::Indistinguishable;
1763 break;
1764
1765 case ImplicitConversionSequence::Indistinguishable:
1766 break;
1767
1768 case ImplicitConversionSequence::Worse:
1769 if (SCS2.Deprecated)
1770 Result = ImplicitConversionSequence::Indistinguishable;
1771 break;
1772 }
1773
1774 return Result;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001775}
1776
Douglas Gregor14046502008-10-23 00:40:37 +00001777/// CompareDerivedToBaseConversions - Compares two standard conversion
1778/// sequences to determine whether they can be ranked based on their
Douglas Gregor24a90a52008-11-26 23:31:11 +00001779/// various kinds of derived-to-base conversions (C++
1780/// [over.ics.rank]p4b3). As part of these checks, we also look at
1781/// conversions between Objective-C interface types.
Douglas Gregor14046502008-10-23 00:40:37 +00001782ImplicitConversionSequence::CompareKind
1783Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1784 const StandardConversionSequence& SCS2) {
1785 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1786 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1787 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1788 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1789
1790 // Adjust the types we're converting from via the array-to-pointer
1791 // conversion, if we need to.
1792 if (SCS1.First == ICK_Array_To_Pointer)
1793 FromType1 = Context.getArrayDecayedType(FromType1);
1794 if (SCS2.First == ICK_Array_To_Pointer)
1795 FromType2 = Context.getArrayDecayedType(FromType2);
1796
1797 // Canonicalize all of the types.
1798 FromType1 = Context.getCanonicalType(FromType1);
1799 ToType1 = Context.getCanonicalType(ToType1);
1800 FromType2 = Context.getCanonicalType(FromType2);
1801 ToType2 = Context.getCanonicalType(ToType2);
1802
Douglas Gregor0e343382008-10-29 14:50:44 +00001803 // C++ [over.ics.rank]p4b3:
Douglas Gregor14046502008-10-23 00:40:37 +00001804 //
1805 // If class B is derived directly or indirectly from class A and
1806 // class C is derived directly or indirectly from B,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001807 //
1808 // For Objective-C, we let A, B, and C also be Objective-C
1809 // interfaces.
Douglas Gregor0e343382008-10-29 14:50:44 +00001810
1811 // Compare based on pointer conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001812 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor3f5a00c2008-11-27 01:19:21 +00001813 SCS2.Second == ICK_Pointer_Conversion &&
1814 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1815 FromType1->isPointerType() && FromType2->isPointerType() &&
1816 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregor14046502008-10-23 00:40:37 +00001817 QualType FromPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001818 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001819 QualType ToPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001820 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001821 QualType FromPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001822 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001823 QualType ToPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001824 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor24a90a52008-11-26 23:31:11 +00001825
1826 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1827 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1828 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1829 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1830
Douglas Gregor0e343382008-10-29 14:50:44 +00001831 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor14046502008-10-23 00:40:37 +00001832 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1833 if (IsDerivedFrom(ToPointee1, ToPointee2))
1834 return ImplicitConversionSequence::Better;
1835 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1836 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001837
1838 if (ToIface1 && ToIface2) {
1839 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1840 return ImplicitConversionSequence::Better;
1841 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1842 return ImplicitConversionSequence::Worse;
1843 }
Douglas Gregor14046502008-10-23 00:40:37 +00001844 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001845
1846 // -- conversion of B* to A* is better than conversion of C* to A*,
1847 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1848 if (IsDerivedFrom(FromPointee2, FromPointee1))
1849 return ImplicitConversionSequence::Better;
1850 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1851 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001852
1853 if (FromIface1 && FromIface2) {
1854 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1855 return ImplicitConversionSequence::Better;
1856 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1857 return ImplicitConversionSequence::Worse;
1858 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001859 }
Douglas Gregor14046502008-10-23 00:40:37 +00001860 }
1861
Douglas Gregor0e343382008-10-29 14:50:44 +00001862 // Compare based on reference bindings.
1863 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1864 SCS1.Second == ICK_Derived_To_Base) {
1865 // -- binding of an expression of type C to a reference of type
1866 // B& is better than binding an expression of type C to a
1867 // reference of type A&,
1868 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1869 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1870 if (IsDerivedFrom(ToType1, ToType2))
1871 return ImplicitConversionSequence::Better;
1872 else if (IsDerivedFrom(ToType2, ToType1))
1873 return ImplicitConversionSequence::Worse;
1874 }
1875
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001876 // -- binding of an expression of type B to a reference of type
1877 // A& is better than binding an expression of type C to a
1878 // reference of type A&,
Douglas Gregor0e343382008-10-29 14:50:44 +00001879 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1880 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1881 if (IsDerivedFrom(FromType2, FromType1))
1882 return ImplicitConversionSequence::Better;
1883 else if (IsDerivedFrom(FromType1, FromType2))
1884 return ImplicitConversionSequence::Worse;
1885 }
1886 }
1887
1888
1889 // FIXME: conversion of A::* to B::* is better than conversion of
1890 // A::* to C::*,
1891
1892 // FIXME: conversion of B::* to C::* is better than conversion of
1893 // A::* to C::*, and
1894
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001895 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1896 SCS1.Second == ICK_Derived_To_Base) {
1897 // -- conversion of C to B is better than conversion of C to A,
1898 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1899 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1900 if (IsDerivedFrom(ToType1, ToType2))
1901 return ImplicitConversionSequence::Better;
1902 else if (IsDerivedFrom(ToType2, ToType1))
1903 return ImplicitConversionSequence::Worse;
1904 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001905
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001906 // -- conversion of B to A is better than conversion of C to A.
1907 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1908 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1909 if (IsDerivedFrom(FromType2, FromType1))
1910 return ImplicitConversionSequence::Better;
1911 else if (IsDerivedFrom(FromType1, FromType2))
1912 return ImplicitConversionSequence::Worse;
1913 }
1914 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001915
Douglas Gregor14046502008-10-23 00:40:37 +00001916 return ImplicitConversionSequence::Indistinguishable;
1917}
1918
Douglas Gregor81c29152008-10-29 00:13:59 +00001919/// TryCopyInitialization - Try to copy-initialize a value of type
1920/// ToType from the expression From. Return the implicit conversion
1921/// sequence required to pass this argument, which may be a bad
1922/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001923/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redla55834a2009-04-12 17:16:29 +00001924/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1925/// then we treat @p From as an rvalue, even if it is an lvalue.
Douglas Gregor81c29152008-10-29 00:13:59 +00001926ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001927Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlssone0f3ee62009-08-27 17:37:39 +00001928 bool SuppressUserConversions, bool ForceRValue,
1929 bool InOverloadResolution) {
Douglas Gregorfcb19192009-02-11 23:02:49 +00001930 if (ToType->isReferenceType()) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001931 ImplicitConversionSequence ICS;
Anders Carlsson8f809f92009-08-27 17:30:43 +00001932 CheckReferenceInit(From, ToType,
1933 SuppressUserConversions,
1934 /*AllowExplicit=*/false,
1935 ForceRValue,
1936 &ICS);
Douglas Gregor81c29152008-10-29 00:13:59 +00001937 return ICS;
1938 } else {
Anders Carlsson6ed4a612009-08-27 17:24:15 +00001939 return TryImplicitConversion(From, ToType,
1940 SuppressUserConversions,
1941 /*AllowExplicit=*/false,
Anders Carlsson8e4c1692009-08-28 15:33:32 +00001942 ForceRValue,
1943 InOverloadResolution);
Douglas Gregor81c29152008-10-29 00:13:59 +00001944 }
1945}
1946
Sebastian Redla55834a2009-04-12 17:16:29 +00001947/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1948/// the expression @p From. Returns true (and emits a diagnostic) if there was
1949/// an error, returns false if the initialization succeeded. Elidable should
1950/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1951/// differently in C++0x for this case.
Douglas Gregor81c29152008-10-29 00:13:59 +00001952bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +00001953 const char* Flavor, bool Elidable) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001954 if (!getLangOptions().CPlusPlus) {
1955 // In C, argument passing is the same as performing an assignment.
1956 QualType FromType = From->getType();
Douglas Gregor144b06c2009-04-29 22:16:16 +00001957
Douglas Gregor81c29152008-10-29 00:13:59 +00001958 AssignConvertType ConvTy =
1959 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor144b06c2009-04-29 22:16:16 +00001960 if (ConvTy != Compatible &&
1961 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1962 ConvTy = Compatible;
1963
Douglas Gregor81c29152008-10-29 00:13:59 +00001964 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1965 FromType, From, Flavor);
Douglas Gregor81c29152008-10-29 00:13:59 +00001966 }
Sebastian Redla55834a2009-04-12 17:16:29 +00001967
Chris Lattner271d4c22008-11-24 05:29:24 +00001968 if (ToType->isReferenceType())
Anders Carlsson8f809f92009-08-27 17:30:43 +00001969 return CheckReferenceInit(From, ToType,
1970 /*SuppressUserConversions=*/false,
1971 /*AllowExplicit=*/false,
1972 /*ForceRValue=*/false);
Chris Lattner271d4c22008-11-24 05:29:24 +00001973
Sebastian Redla55834a2009-04-12 17:16:29 +00001974 if (!PerformImplicitConversion(From, ToType, Flavor,
1975 /*AllowExplicit=*/false, Elidable))
Chris Lattner271d4c22008-11-24 05:29:24 +00001976 return false;
Sebastian Redla55834a2009-04-12 17:16:29 +00001977
Chris Lattner271d4c22008-11-24 05:29:24 +00001978 return Diag(From->getSourceRange().getBegin(),
1979 diag::err_typecheck_convert_incompatible)
1980 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001981}
1982
Douglas Gregor5ed15042008-11-18 23:14:02 +00001983/// TryObjectArgumentInitialization - Try to initialize the object
1984/// parameter of the given member function (@c Method) from the
1985/// expression @p From.
1986ImplicitConversionSequence
1987Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1988 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1989 unsigned MethodQuals = Method->getTypeQualifiers();
1990 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1991
1992 // Set up the conversion sequence as a "bad" conversion, to allow us
1993 // to exit early.
1994 ImplicitConversionSequence ICS;
1995 ICS.Standard.setAsIdentityConversion();
1996 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1997
1998 // We need to have an object of class type.
1999 QualType FromType = From->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002000 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002001 FromType = PT->getPointeeType();
2002
2003 assert(FromType->isRecordType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00002004
2005 // The implicit object parmeter is has the type "reference to cv X",
2006 // where X is the class of which the function is a member
2007 // (C++ [over.match.funcs]p4). However, when finding an implicit
2008 // conversion sequence for the argument, we are not allowed to
2009 // create temporaries or perform user-defined conversions
2010 // (C++ [over.match.funcs]p5). We perform a simplified version of
2011 // reference binding here, that allows class rvalues to bind to
2012 // non-constant references.
2013
2014 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2015 // with the implicit object parameter (C++ [over.match.funcs]p5).
2016 QualType FromTypeCanon = Context.getCanonicalType(FromType);
2017 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
2018 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
2019 return ICS;
2020
2021 // Check that we have either the same type or a derived type. It
2022 // affects the conversion rank.
2023 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2024 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2025 ICS.Standard.Second = ICK_Identity;
2026 else if (IsDerivedFrom(FromType, ClassType))
2027 ICS.Standard.Second = ICK_Derived_To_Base;
2028 else
2029 return ICS;
2030
2031 // Success. Mark this as a reference binding.
2032 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2033 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2034 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2035 ICS.Standard.ReferenceBinding = true;
2036 ICS.Standard.DirectBinding = true;
Sebastian Redl9bc16ad2009-03-29 22:46:24 +00002037 ICS.Standard.RRefBinding = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002038 return ICS;
2039}
2040
2041/// PerformObjectArgumentInitialization - Perform initialization of
2042/// the implicit object parameter for the given Method with the given
2043/// expression.
2044bool
2045Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002046 QualType FromRecordType, DestType;
2047 QualType ImplicitParamRecordType =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002048 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002049
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002050 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002051 FromRecordType = PT->getPointeeType();
2052 DestType = Method->getThisType(Context);
2053 } else {
2054 FromRecordType = From->getType();
2055 DestType = ImplicitParamRecordType;
2056 }
2057
Douglas Gregor5ed15042008-11-18 23:14:02 +00002058 ImplicitConversionSequence ICS
2059 = TryObjectArgumentInitialization(From, Method);
2060 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2061 return Diag(From->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002062 diag::err_implicit_object_parameter_init)
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002063 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
2064
Douglas Gregor5ed15042008-11-18 23:14:02 +00002065 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002066 CheckDerivedToBaseConversion(FromRecordType,
2067 ImplicitParamRecordType,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002068 From->getSourceRange().getBegin(),
2069 From->getSourceRange()))
2070 return true;
2071
Anders Carlssone25b6cd2009-08-07 18:45:49 +00002072 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
2073 /*isLvalue=*/true);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002074 return false;
2075}
2076
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002077/// TryContextuallyConvertToBool - Attempt to contextually convert the
2078/// expression From to bool (C++0x [conv]p3).
2079ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Anders Carlsson6ed4a612009-08-27 17:24:15 +00002080 return TryImplicitConversion(From, Context.BoolTy,
2081 // FIXME: Are these flags correct?
2082 /*SuppressUserConversions=*/false,
2083 /*AllowExplicit=*/true,
Anders Carlsson8e4c1692009-08-28 15:33:32 +00002084 /*ForceRValue=*/false,
2085 /*InOverloadResolution=*/false);
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002086}
2087
2088/// PerformContextuallyConvertToBool - Perform a contextual conversion
2089/// of the expression From to bool (C++0x [conv]p3).
2090bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2091 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2092 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2093 return false;
2094
2095 return Diag(From->getSourceRange().getBegin(),
2096 diag::err_typecheck_bool_condition)
2097 << From->getType() << From->getSourceRange();
2098}
2099
Douglas Gregord2baafd2008-10-21 16:13:35 +00002100/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002101/// candidate functions, using the given function call arguments. If
2102/// @p SuppressUserConversions, then don't allow user-defined
2103/// conversions via constructors or conversion operators.
Sebastian Redla55834a2009-04-12 17:16:29 +00002104/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2105/// hacky way to implement the overloading rules for elidable copy
2106/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregord2baafd2008-10-21 16:13:35 +00002107void
2108Sema::AddOverloadCandidate(FunctionDecl *Function,
2109 Expr **Args, unsigned NumArgs,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002110 OverloadCandidateSet& CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00002111 bool SuppressUserConversions,
2112 bool ForceRValue)
Douglas Gregord2baafd2008-10-21 16:13:35 +00002113{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002114 const FunctionProtoType* Proto
2115 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
Douglas Gregord2baafd2008-10-21 16:13:35 +00002116 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregor60714f92008-11-07 22:36:19 +00002117 assert(!isa<CXXConversionDecl>(Function) &&
2118 "Use AddConversionCandidate for conversion functions");
Douglas Gregorb60eb752009-06-25 22:08:12 +00002119 assert(!Function->getDescribedFunctionTemplate() &&
2120 "Use AddTemplateOverloadCandidate for function templates");
2121
Douglas Gregor3257fb52008-12-22 05:46:06 +00002122 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00002123 if (!isa<CXXConstructorDecl>(Method)) {
2124 // If we get here, it's because we're calling a member function
2125 // that is named without a member access expression (e.g.,
2126 // "this->f") that was either written explicitly or created
2127 // implicitly. This can happen with a qualified call to a member
2128 // function, e.g., X::f(). We use a NULL object as the implied
2129 // object argument (C++ [over.call.func]p3).
2130 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2131 SuppressUserConversions, ForceRValue);
2132 return;
2133 }
2134 // We treat a constructor like a non-member function, since its object
2135 // argument doesn't participate in overload resolution.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002136 }
2137
2138
Douglas Gregord2baafd2008-10-21 16:13:35 +00002139 // Add this candidate
2140 CandidateSet.push_back(OverloadCandidate());
2141 OverloadCandidate& Candidate = CandidateSet.back();
2142 Candidate.Function = Function;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002143 Candidate.Viable = true;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002144 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002145 Candidate.IgnoreObjectArgument = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00002146
2147 unsigned NumArgsInProto = Proto->getNumArgs();
2148
2149 // (C++ 13.3.2p2): A candidate function having fewer than m
2150 // parameters is viable only if it has an ellipsis in its parameter
2151 // list (8.3.5).
2152 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2153 Candidate.Viable = false;
2154 return;
2155 }
2156
2157 // (C++ 13.3.2p2): A candidate function having more than m parameters
2158 // is viable only if the (m+1)st parameter has a default argument
2159 // (8.3.6). For the purposes of overload resolution, the
2160 // parameter list is truncated on the right, so that there are
2161 // exactly m parameters.
2162 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2163 if (NumArgs < MinRequiredArgs) {
2164 // Not enough arguments.
2165 Candidate.Viable = false;
2166 return;
2167 }
2168
2169 // Determine the implicit conversion sequences for each of the
2170 // arguments.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002171 Candidate.Conversions.resize(NumArgs);
2172 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2173 if (ArgIdx < NumArgsInProto) {
2174 // (C++ 13.3.2p3): for F to be a viable function, there shall
2175 // exist for each argument an implicit conversion sequence
2176 // (13.3.3.1) that converts that argument to the corresponding
2177 // parameter of F.
2178 QualType ParamType = Proto->getArgType(ArgIdx);
2179 Candidate.Conversions[ArgIdx]
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002180 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlssone0f3ee62009-08-27 17:37:39 +00002181 SuppressUserConversions, ForceRValue,
2182 /*InOverloadResolution=*/true);
Douglas Gregord2baafd2008-10-21 16:13:35 +00002183 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002184 == ImplicitConversionSequence::BadConversion) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00002185 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002186 break;
2187 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002188 } else {
2189 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2190 // argument for which there is no corresponding parameter is
2191 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2192 Candidate.Conversions[ArgIdx].ConversionKind
2193 = ImplicitConversionSequence::EllipsisConversion;
2194 }
2195 }
2196}
2197
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002198/// \brief Add all of the function declarations in the given function set to
2199/// the overload canddiate set.
2200void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2201 Expr **Args, unsigned NumArgs,
2202 OverloadCandidateSet& CandidateSet,
2203 bool SuppressUserConversions) {
2204 for (FunctionSet::const_iterator F = Functions.begin(),
2205 FEnd = Functions.end();
Douglas Gregor993a0602009-06-27 21:05:07 +00002206 F != FEnd; ++F) {
2207 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F))
2208 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2209 SuppressUserConversions);
2210 else
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002211 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*F),
2212 /*FIXME: explicit args */false, 0, 0,
2213 Args, NumArgs, CandidateSet,
Douglas Gregor993a0602009-06-27 21:05:07 +00002214 SuppressUserConversions);
2215 }
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002216}
2217
Douglas Gregor5ed15042008-11-18 23:14:02 +00002218/// AddMethodCandidate - Adds the given C++ member function to the set
2219/// of candidate functions, using the given function call arguments
2220/// and the object argument (@c Object). For example, in a call
2221/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2222/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2223/// allow user-defined conversions via constructors or conversion
Sebastian Redla55834a2009-04-12 17:16:29 +00002224/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2225/// a slightly hacky way to implement the overloading rules for elidable copy
2226/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor5ed15042008-11-18 23:14:02 +00002227void
2228Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2229 Expr **Args, unsigned NumArgs,
2230 OverloadCandidateSet& CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00002231 bool SuppressUserConversions, bool ForceRValue)
Douglas Gregor5ed15042008-11-18 23:14:02 +00002232{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002233 const FunctionProtoType* Proto
2234 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00002235 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redlbd261962009-04-16 17:51:27 +00002236 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor5ed15042008-11-18 23:14:02 +00002237 "Use AddConversionCandidate for conversion functions");
Sebastian Redlbd261962009-04-16 17:51:27 +00002238 assert(!isa<CXXConstructorDecl>(Method) &&
2239 "Use AddOverloadCandidate for constructors");
Douglas Gregor5ed15042008-11-18 23:14:02 +00002240
2241 // Add this candidate
2242 CandidateSet.push_back(OverloadCandidate());
2243 OverloadCandidate& Candidate = CandidateSet.back();
2244 Candidate.Function = Method;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002245 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002246 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002247
2248 unsigned NumArgsInProto = Proto->getNumArgs();
2249
2250 // (C++ 13.3.2p2): A candidate function having fewer than m
2251 // parameters is viable only if it has an ellipsis in its parameter
2252 // list (8.3.5).
2253 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2254 Candidate.Viable = false;
2255 return;
2256 }
2257
2258 // (C++ 13.3.2p2): A candidate function having more than m parameters
2259 // is viable only if the (m+1)st parameter has a default argument
2260 // (8.3.6). For the purposes of overload resolution, the
2261 // parameter list is truncated on the right, so that there are
2262 // exactly m parameters.
2263 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2264 if (NumArgs < MinRequiredArgs) {
2265 // Not enough arguments.
2266 Candidate.Viable = false;
2267 return;
2268 }
2269
2270 Candidate.Viable = true;
2271 Candidate.Conversions.resize(NumArgs + 1);
2272
Douglas Gregor3257fb52008-12-22 05:46:06 +00002273 if (Method->isStatic() || !Object)
2274 // The implicit object argument is ignored.
2275 Candidate.IgnoreObjectArgument = true;
2276 else {
2277 // Determine the implicit conversion sequence for the object
2278 // parameter.
2279 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2280 if (Candidate.Conversions[0].ConversionKind
2281 == ImplicitConversionSequence::BadConversion) {
2282 Candidate.Viable = false;
2283 return;
2284 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002285 }
2286
2287 // Determine the implicit conversion sequences for each of the
2288 // arguments.
2289 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2290 if (ArgIdx < NumArgsInProto) {
2291 // (C++ 13.3.2p3): for F to be a viable function, there shall
2292 // exist for each argument an implicit conversion sequence
2293 // (13.3.3.1) that converts that argument to the corresponding
2294 // parameter of F.
2295 QualType ParamType = Proto->getArgType(ArgIdx);
2296 Candidate.Conversions[ArgIdx + 1]
2297 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlssone0f3ee62009-08-27 17:37:39 +00002298 SuppressUserConversions, ForceRValue,
Anders Carlsson8e4c1692009-08-28 15:33:32 +00002299 /*InOverloadResolution=*/true);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002300 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2301 == ImplicitConversionSequence::BadConversion) {
2302 Candidate.Viable = false;
2303 break;
2304 }
2305 } else {
2306 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2307 // argument for which there is no corresponding parameter is
2308 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2309 Candidate.Conversions[ArgIdx + 1].ConversionKind
2310 = ImplicitConversionSequence::EllipsisConversion;
2311 }
2312 }
2313}
2314
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002315/// \brief Add a C++ member function template as a candidate to the candidate
2316/// set, using template argument deduction to produce an appropriate member
2317/// function template specialization.
2318void
2319Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2320 bool HasExplicitTemplateArgs,
2321 const TemplateArgument *ExplicitTemplateArgs,
2322 unsigned NumExplicitTemplateArgs,
2323 Expr *Object, Expr **Args, unsigned NumArgs,
2324 OverloadCandidateSet& CandidateSet,
2325 bool SuppressUserConversions,
2326 bool ForceRValue) {
2327 // C++ [over.match.funcs]p7:
2328 // In each case where a candidate is a function template, candidate
2329 // function template specializations are generated using template argument
2330 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
2331 // candidate functions in the usual way.113) A given name can refer to one
2332 // or more function templates and also to a set of overloaded non-template
2333 // functions. In such a case, the candidate functions generated from each
2334 // function template are combined with the set of non-template candidate
2335 // functions.
2336 TemplateDeductionInfo Info(Context);
2337 FunctionDecl *Specialization = 0;
2338 if (TemplateDeductionResult Result
2339 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2340 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2341 Args, NumArgs, Specialization, Info)) {
2342 // FIXME: Record what happened with template argument deduction, so
2343 // that we can give the user a beautiful diagnostic.
2344 (void)Result;
2345 return;
2346 }
2347
2348 // Add the function template specialization produced by template argument
2349 // deduction as a candidate.
2350 assert(Specialization && "Missing member function template specialization?");
2351 assert(isa<CXXMethodDecl>(Specialization) &&
2352 "Specialization is not a member function?");
2353 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
2354 CandidateSet, SuppressUserConversions, ForceRValue);
2355}
2356
Douglas Gregor8c860df2009-08-21 23:19:43 +00002357/// \brief Add a C++ function template specialization as a candidate
2358/// in the candidate set, using template argument deduction to produce
2359/// an appropriate function template specialization.
Douglas Gregorb60eb752009-06-25 22:08:12 +00002360void
2361Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002362 bool HasExplicitTemplateArgs,
2363 const TemplateArgument *ExplicitTemplateArgs,
2364 unsigned NumExplicitTemplateArgs,
Douglas Gregorb60eb752009-06-25 22:08:12 +00002365 Expr **Args, unsigned NumArgs,
2366 OverloadCandidateSet& CandidateSet,
2367 bool SuppressUserConversions,
2368 bool ForceRValue) {
2369 // C++ [over.match.funcs]p7:
2370 // In each case where a candidate is a function template, candidate
2371 // function template specializations are generated using template argument
2372 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
2373 // candidate functions in the usual way.113) A given name can refer to one
2374 // or more function templates and also to a set of overloaded non-template
2375 // functions. In such a case, the candidate functions generated from each
2376 // function template are combined with the set of non-template candidate
2377 // functions.
2378 TemplateDeductionInfo Info(Context);
2379 FunctionDecl *Specialization = 0;
2380 if (TemplateDeductionResult Result
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002381 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2382 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2383 Args, NumArgs, Specialization, Info)) {
Douglas Gregorb60eb752009-06-25 22:08:12 +00002384 // FIXME: Record what happened with template argument deduction, so
2385 // that we can give the user a beautiful diagnostic.
2386 (void)Result;
2387 return;
2388 }
2389
2390 // Add the function template specialization produced by template argument
2391 // deduction as a candidate.
2392 assert(Specialization && "Missing function template specialization?");
2393 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2394 SuppressUserConversions, ForceRValue);
2395}
2396
Douglas Gregor60714f92008-11-07 22:36:19 +00002397/// AddConversionCandidate - Add a C++ conversion function as a
2398/// candidate in the candidate set (C++ [over.match.conv],
2399/// C++ [over.match.copy]). From is the expression we're converting from,
2400/// and ToType is the type that we're eventually trying to convert to
2401/// (which may or may not be the same type as the type that the
2402/// conversion function produces).
2403void
2404Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2405 Expr *From, QualType ToType,
2406 OverloadCandidateSet& CandidateSet) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00002407 assert(!Conversion->getDescribedFunctionTemplate() &&
2408 "Conversion function templates use AddTemplateConversionCandidate");
2409
Douglas Gregor60714f92008-11-07 22:36:19 +00002410 // Add this candidate
2411 CandidateSet.push_back(OverloadCandidate());
2412 OverloadCandidate& Candidate = CandidateSet.back();
2413 Candidate.Function = Conversion;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002414 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002415 Candidate.IgnoreObjectArgument = false;
Douglas Gregor60714f92008-11-07 22:36:19 +00002416 Candidate.FinalConversion.setAsIdentityConversion();
2417 Candidate.FinalConversion.FromTypePtr
2418 = Conversion->getConversionType().getAsOpaquePtr();
2419 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2420
Douglas Gregor5ed15042008-11-18 23:14:02 +00002421 // Determine the implicit conversion sequence for the implicit
2422 // object parameter.
Douglas Gregor60714f92008-11-07 22:36:19 +00002423 Candidate.Viable = true;
2424 Candidate.Conversions.resize(1);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002425 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregor60714f92008-11-07 22:36:19 +00002426
Douglas Gregor60714f92008-11-07 22:36:19 +00002427 if (Candidate.Conversions[0].ConversionKind
2428 == ImplicitConversionSequence::BadConversion) {
2429 Candidate.Viable = false;
2430 return;
2431 }
2432
2433 // To determine what the conversion from the result of calling the
2434 // conversion function to the type we're eventually trying to
2435 // convert to (ToType), we need to synthesize a call to the
2436 // conversion function and attempt copy initialization from it. This
2437 // makes sure that we get the right semantics with respect to
2438 // lvalues/rvalues and the type. Fortunately, we can allocate this
2439 // call on the stack and we don't need its arguments to be
2440 // well-formed.
2441 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2442 SourceLocation());
2443 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002444 CastExpr::CK_Unknown,
Douglas Gregor70d26122008-11-12 17:17:38 +00002445 &ConversionRef, false);
Ted Kremenek362abcd2009-02-09 20:51:47 +00002446
2447 // Note that it is safe to allocate CallExpr on the stack here because
2448 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2449 // allocator).
2450 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregor60714f92008-11-07 22:36:19 +00002451 Conversion->getConversionType().getNonReferenceType(),
2452 SourceLocation());
Anders Carlsson06386552009-08-27 17:18:13 +00002453 ImplicitConversionSequence ICS =
2454 TryCopyInitialization(&Call, ToType,
2455 /*SuppressUserConversions=*/true,
Anders Carlssone0f3ee62009-08-27 17:37:39 +00002456 /*ForceRValue=*/false,
2457 /*InOverloadResolution=*/false);
Anders Carlsson06386552009-08-27 17:18:13 +00002458
Douglas Gregor60714f92008-11-07 22:36:19 +00002459 switch (ICS.ConversionKind) {
2460 case ImplicitConversionSequence::StandardConversion:
2461 Candidate.FinalConversion = ICS.Standard;
2462 break;
2463
2464 case ImplicitConversionSequence::BadConversion:
2465 Candidate.Viable = false;
2466 break;
2467
2468 default:
2469 assert(false &&
2470 "Can only end up with a standard conversion sequence or failure");
2471 }
2472}
2473
Douglas Gregor8c860df2009-08-21 23:19:43 +00002474/// \brief Adds a conversion function template specialization
2475/// candidate to the overload set, using template argument deduction
2476/// to deduce the template arguments of the conversion function
2477/// template from the type that we are converting to (C++
2478/// [temp.deduct.conv]).
2479void
2480Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2481 Expr *From, QualType ToType,
2482 OverloadCandidateSet &CandidateSet) {
2483 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2484 "Only conversion function templates permitted here");
2485
2486 TemplateDeductionInfo Info(Context);
2487 CXXConversionDecl *Specialization = 0;
2488 if (TemplateDeductionResult Result
2489 = DeduceTemplateArguments(FunctionTemplate, ToType,
2490 Specialization, Info)) {
2491 // FIXME: Record what happened with template argument deduction, so
2492 // that we can give the user a beautiful diagnostic.
2493 (void)Result;
2494 return;
2495 }
2496
2497 // Add the conversion function template specialization produced by
2498 // template argument deduction as a candidate.
2499 assert(Specialization && "Missing function template specialization?");
2500 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2501}
2502
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002503/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2504/// converts the given @c Object to a function pointer via the
2505/// conversion function @c Conversion, and then attempts to call it
2506/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2507/// the type of function that we'll eventually be calling.
2508void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002509 const FunctionProtoType *Proto,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002510 Expr *Object, Expr **Args, unsigned NumArgs,
2511 OverloadCandidateSet& CandidateSet) {
2512 CandidateSet.push_back(OverloadCandidate());
2513 OverloadCandidate& Candidate = CandidateSet.back();
2514 Candidate.Function = 0;
2515 Candidate.Surrogate = Conversion;
2516 Candidate.Viable = true;
2517 Candidate.IsSurrogate = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002518 Candidate.IgnoreObjectArgument = false;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002519 Candidate.Conversions.resize(NumArgs + 1);
2520
2521 // Determine the implicit conversion sequence for the implicit
2522 // object parameter.
2523 ImplicitConversionSequence ObjectInit
2524 = TryObjectArgumentInitialization(Object, Conversion);
2525 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2526 Candidate.Viable = false;
2527 return;
2528 }
2529
2530 // The first conversion is actually a user-defined conversion whose
2531 // first conversion is ObjectInit's standard conversion (which is
2532 // effectively a reference binding). Record it as such.
2533 Candidate.Conversions[0].ConversionKind
2534 = ImplicitConversionSequence::UserDefinedConversion;
2535 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2536 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2537 Candidate.Conversions[0].UserDefined.After
2538 = Candidate.Conversions[0].UserDefined.Before;
2539 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2540
2541 // Find the
2542 unsigned NumArgsInProto = Proto->getNumArgs();
2543
2544 // (C++ 13.3.2p2): A candidate function having fewer than m
2545 // parameters is viable only if it has an ellipsis in its parameter
2546 // list (8.3.5).
2547 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2548 Candidate.Viable = false;
2549 return;
2550 }
2551
2552 // Function types don't have any default arguments, so just check if
2553 // we have enough arguments.
2554 if (NumArgs < NumArgsInProto) {
2555 // Not enough arguments.
2556 Candidate.Viable = false;
2557 return;
2558 }
2559
2560 // Determine the implicit conversion sequences for each of the
2561 // arguments.
2562 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2563 if (ArgIdx < NumArgsInProto) {
2564 // (C++ 13.3.2p3): for F to be a viable function, there shall
2565 // exist for each argument an implicit conversion sequence
2566 // (13.3.3.1) that converts that argument to the corresponding
2567 // parameter of F.
2568 QualType ParamType = Proto->getArgType(ArgIdx);
2569 Candidate.Conversions[ArgIdx + 1]
2570 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson06386552009-08-27 17:18:13 +00002571 /*SuppressUserConversions=*/false,
Anders Carlssone0f3ee62009-08-27 17:37:39 +00002572 /*ForceRValue=*/false,
2573 /*InOverloadResolution=*/false);
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002574 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2575 == ImplicitConversionSequence::BadConversion) {
2576 Candidate.Viable = false;
2577 break;
2578 }
2579 } else {
2580 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2581 // argument for which there is no corresponding parameter is
2582 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2583 Candidate.Conversions[ArgIdx + 1].ConversionKind
2584 = ImplicitConversionSequence::EllipsisConversion;
2585 }
2586 }
2587}
2588
Mike Stumpe127ae32009-05-16 07:39:55 +00002589// FIXME: This will eventually be removed, once we've migrated all of the
2590// operator overloading logic over to the scheme used by binary operators, which
2591// works for template instantiation.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002592void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor48a87322009-02-04 16:44:47 +00002593 SourceLocation OpLoc,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002594 Expr **Args, unsigned NumArgs,
Douglas Gregor48a87322009-02-04 16:44:47 +00002595 OverloadCandidateSet& CandidateSet,
2596 SourceRange OpRange) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002597
2598 FunctionSet Functions;
2599
2600 QualType T1 = Args[0]->getType();
2601 QualType T2;
2602 if (NumArgs > 1)
2603 T2 = Args[1]->getType();
2604
2605 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregorde72f3e2009-05-19 00:01:19 +00002606 if (S)
2607 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002608 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2609 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2610 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2611 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2612}
2613
2614/// \brief Add overload candidates for overloaded operators that are
2615/// member functions.
2616///
2617/// Add the overloaded operator candidates that are member functions
2618/// for the operator Op that was used in an operator expression such
2619/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2620/// CandidateSet will store the added overload candidates. (C++
2621/// [over.match.oper]).
2622void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2623 SourceLocation OpLoc,
2624 Expr **Args, unsigned NumArgs,
2625 OverloadCandidateSet& CandidateSet,
2626 SourceRange OpRange) {
Douglas Gregor5ed15042008-11-18 23:14:02 +00002627 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2628
2629 // C++ [over.match.oper]p3:
2630 // For a unary operator @ with an operand of a type whose
2631 // cv-unqualified version is T1, and for a binary operator @ with
2632 // a left operand of a type whose cv-unqualified version is T1 and
2633 // a right operand of a type whose cv-unqualified version is T2,
2634 // three sets of candidate functions, designated member
2635 // candidates, non-member candidates and built-in candidates, are
2636 // constructed as follows:
2637 QualType T1 = Args[0]->getType();
2638 QualType T2;
2639 if (NumArgs > 1)
2640 T2 = Args[1]->getType();
2641
2642 // -- If T1 is a class type, the set of member candidates is the
2643 // result of the qualified lookup of T1::operator@
2644 // (13.3.1.1.1); otherwise, the set of member candidates is
2645 // empty.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002646 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor2993edd2009-08-27 23:35:55 +00002647 // Complete the type if it can be completed. Otherwise, we're done.
2648 if (RequireCompleteType(OpLoc, T1, PartialDiagnostic(0)))
2649 return;
2650
2651 LookupResult Operators = LookupQualifiedName(T1Rec->getDecl(), OpName,
2652 LookupOrdinaryName, false);
2653 for (LookupResult::iterator Oper = Operators.begin(),
2654 OperEnd = Operators.end();
2655 Oper != OperEnd;
2656 ++Oper)
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002657 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2658 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002659 /*SuppressUserConversions=*/false);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002660 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002661}
2662
Douglas Gregor70d26122008-11-12 17:17:38 +00002663/// AddBuiltinCandidate - Add a candidate for a built-in
2664/// operator. ResultTy and ParamTys are the result and parameter types
2665/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorab141112009-01-13 00:52:54 +00002666/// arguments being passed to the candidate. IsAssignmentOperator
2667/// should be true when this built-in candidate is an assignment
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002668/// operator. NumContextualBoolArguments is the number of arguments
2669/// (at the beginning of the argument list) that will be contextually
2670/// converted to bool.
Douglas Gregor70d26122008-11-12 17:17:38 +00002671void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2672 Expr **Args, unsigned NumArgs,
Douglas Gregorab141112009-01-13 00:52:54 +00002673 OverloadCandidateSet& CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002674 bool IsAssignmentOperator,
2675 unsigned NumContextualBoolArguments) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002676 // Add this candidate
2677 CandidateSet.push_back(OverloadCandidate());
2678 OverloadCandidate& Candidate = CandidateSet.back();
2679 Candidate.Function = 0;
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00002680 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002681 Candidate.IgnoreObjectArgument = false;
Douglas Gregor70d26122008-11-12 17:17:38 +00002682 Candidate.BuiltinTypes.ResultTy = ResultTy;
2683 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2684 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2685
2686 // Determine the implicit conversion sequences for each of the
2687 // arguments.
2688 Candidate.Viable = true;
2689 Candidate.Conversions.resize(NumArgs);
2690 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorab141112009-01-13 00:52:54 +00002691 // C++ [over.match.oper]p4:
2692 // For the built-in assignment operators, conversions of the
2693 // left operand are restricted as follows:
2694 // -- no temporaries are introduced to hold the left operand, and
2695 // -- no user-defined conversions are applied to the left
2696 // operand to achieve a type match with the left-most
2697 // parameter of a built-in candidate.
2698 //
2699 // We block these conversions by turning off user-defined
2700 // conversions, since that is the only way that initialization of
2701 // a reference to a non-class type can occur from something that
2702 // is not of the same type.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002703 if (ArgIdx < NumContextualBoolArguments) {
2704 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2705 "Contextual conversion to bool requires bool type");
2706 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2707 } else {
2708 Candidate.Conversions[ArgIdx]
2709 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson06386552009-08-27 17:18:13 +00002710 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlssone0f3ee62009-08-27 17:37:39 +00002711 /*ForceRValue=*/false,
2712 /*InOverloadResolution=*/false);
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002713 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002714 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002715 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002716 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002717 break;
2718 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002719 }
2720}
2721
2722/// BuiltinCandidateTypeSet - A set of types that will be used for the
2723/// candidate operator functions for built-in operators (C++
2724/// [over.built]). The types are separated into pointer types and
2725/// enumeration types.
2726class BuiltinCandidateTypeSet {
2727 /// TypeSet - A set of types.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002728 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregor70d26122008-11-12 17:17:38 +00002729
2730 /// PointerTypes - The set of pointer types that will be used in the
2731 /// built-in candidates.
2732 TypeSet PointerTypes;
2733
Sebastian Redl674d1b72009-04-19 21:53:20 +00002734 /// MemberPointerTypes - The set of member pointer types that will be
2735 /// used in the built-in candidates.
2736 TypeSet MemberPointerTypes;
2737
Douglas Gregor70d26122008-11-12 17:17:38 +00002738 /// EnumerationTypes - The set of enumeration types that will be
2739 /// used in the built-in candidates.
2740 TypeSet EnumerationTypes;
2741
Douglas Gregorb35c7992009-08-24 15:23:48 +00002742 /// Sema - The semantic analysis instance where we are building the
2743 /// candidate type set.
2744 Sema &SemaRef;
2745
Douglas Gregor70d26122008-11-12 17:17:38 +00002746 /// Context - The AST context in which we will build the type sets.
2747 ASTContext &Context;
2748
Sebastian Redl674d1b72009-04-19 21:53:20 +00002749 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2750 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002751
2752public:
2753 /// iterator - Iterates through the types that are part of the set.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002754 typedef TypeSet::iterator iterator;
Douglas Gregor70d26122008-11-12 17:17:38 +00002755
Douglas Gregorb35c7992009-08-24 15:23:48 +00002756 BuiltinCandidateTypeSet(Sema &SemaRef)
2757 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregor70d26122008-11-12 17:17:38 +00002758
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002759 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2760 bool AllowExplicitConversions);
Douglas Gregor70d26122008-11-12 17:17:38 +00002761
2762 /// pointer_begin - First pointer type found;
2763 iterator pointer_begin() { return PointerTypes.begin(); }
2764
Sebastian Redl674d1b72009-04-19 21:53:20 +00002765 /// pointer_end - Past the last pointer type found;
Douglas Gregor70d26122008-11-12 17:17:38 +00002766 iterator pointer_end() { return PointerTypes.end(); }
2767
Sebastian Redl674d1b72009-04-19 21:53:20 +00002768 /// member_pointer_begin - First member pointer type found;
2769 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2770
2771 /// member_pointer_end - Past the last member pointer type found;
2772 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2773
Douglas Gregor70d26122008-11-12 17:17:38 +00002774 /// enumeration_begin - First enumeration type found;
2775 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2776
Sebastian Redl674d1b72009-04-19 21:53:20 +00002777 /// enumeration_end - Past the last enumeration type found;
Douglas Gregor70d26122008-11-12 17:17:38 +00002778 iterator enumeration_end() { return EnumerationTypes.end(); }
2779};
2780
Sebastian Redl674d1b72009-04-19 21:53:20 +00002781/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregor70d26122008-11-12 17:17:38 +00002782/// the set of pointer types along with any more-qualified variants of
2783/// that type. For example, if @p Ty is "int const *", this routine
2784/// will add "int const *", "int const volatile *", "int const
2785/// restrict *", and "int const volatile restrict *" to the set of
2786/// pointer types. Returns true if the add of @p Ty itself succeeded,
2787/// false otherwise.
Sebastian Redl674d1b72009-04-19 21:53:20 +00002788bool
2789BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002790 // Insert this type.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002791 if (!PointerTypes.insert(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002792 return false;
2793
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002794 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002795 QualType PointeeTy = PointerTy->getPointeeType();
2796 // FIXME: Optimize this so that we don't keep trying to add the same types.
2797
Mike Stumpe127ae32009-05-16 07:39:55 +00002798 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal with all
2799 // pointer conversions that don't cast away constness?
Douglas Gregor70d26122008-11-12 17:17:38 +00002800 if (!PointeeTy.isConstQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002801 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002802 (Context.getPointerType(PointeeTy.withConst()));
2803 if (!PointeeTy.isVolatileQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002804 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002805 (Context.getPointerType(PointeeTy.withVolatile()));
2806 if (!PointeeTy.isRestrictQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002807 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002808 (Context.getPointerType(PointeeTy.withRestrict()));
2809 }
2810
2811 return true;
2812}
2813
Sebastian Redl674d1b72009-04-19 21:53:20 +00002814/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2815/// to the set of pointer types along with any more-qualified variants of
2816/// that type. For example, if @p Ty is "int const *", this routine
2817/// will add "int const *", "int const volatile *", "int const
2818/// restrict *", and "int const volatile restrict *" to the set of
2819/// pointer types. Returns true if the add of @p Ty itself succeeded,
2820/// false otherwise.
2821bool
2822BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2823 QualType Ty) {
2824 // Insert this type.
2825 if (!MemberPointerTypes.insert(Ty))
2826 return false;
2827
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002828 if (const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>()) {
Sebastian Redl674d1b72009-04-19 21:53:20 +00002829 QualType PointeeTy = PointerTy->getPointeeType();
2830 const Type *ClassTy = PointerTy->getClass();
2831 // FIXME: Optimize this so that we don't keep trying to add the same types.
2832
2833 if (!PointeeTy.isConstQualified())
2834 AddMemberPointerWithMoreQualifiedTypeVariants
2835 (Context.getMemberPointerType(PointeeTy.withConst(), ClassTy));
2836 if (!PointeeTy.isVolatileQualified())
2837 AddMemberPointerWithMoreQualifiedTypeVariants
2838 (Context.getMemberPointerType(PointeeTy.withVolatile(), ClassTy));
2839 if (!PointeeTy.isRestrictQualified())
2840 AddMemberPointerWithMoreQualifiedTypeVariants
2841 (Context.getMemberPointerType(PointeeTy.withRestrict(), ClassTy));
2842 }
2843
2844 return true;
2845}
2846
Douglas Gregor70d26122008-11-12 17:17:38 +00002847/// AddTypesConvertedFrom - Add each of the types to which the type @p
2848/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl674d1b72009-04-19 21:53:20 +00002849/// primarily interested in pointer types and enumeration types. We also
2850/// take member pointer types, for the conditional operator.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002851/// AllowUserConversions is true if we should look at the conversion
2852/// functions of a class type, and AllowExplicitConversions if we
2853/// should also include the explicit conversion functions of a class
2854/// type.
2855void
2856BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2857 bool AllowUserConversions,
2858 bool AllowExplicitConversions) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002859 // Only deal with canonical types.
2860 Ty = Context.getCanonicalType(Ty);
2861
2862 // Look through reference types; they aren't part of the type of an
2863 // expression for the purposes of conversions.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002864 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregor70d26122008-11-12 17:17:38 +00002865 Ty = RefTy->getPointeeType();
2866
2867 // We don't care about qualifiers on the type.
2868 Ty = Ty.getUnqualifiedType();
2869
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002870 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002871 QualType PointeeTy = PointerTy->getPointeeType();
2872
2873 // Insert our type, and its more-qualified variants, into the set
2874 // of types.
Sebastian Redl674d1b72009-04-19 21:53:20 +00002875 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002876 return;
2877
2878 // Add 'cv void*' to our set of types.
2879 if (!Ty->isVoidType()) {
2880 QualType QualVoid
2881 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
Sebastian Redl674d1b72009-04-19 21:53:20 +00002882 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregor70d26122008-11-12 17:17:38 +00002883 }
2884
2885 // If this is a pointer to a class type, add pointers to its bases
2886 // (with the same level of cv-qualification as the original
2887 // derived class, of course).
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002888 if (const RecordType *PointeeRec = PointeeTy->getAs<RecordType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002889 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2890 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2891 Base != ClassDecl->bases_end(); ++Base) {
2892 QualType BaseTy = Context.getCanonicalType(Base->getType());
2893 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2894
2895 // Add the pointer type, recursively, so that we get all of
2896 // the indirect base classes, too.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002897 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002898 }
2899 }
Sebastian Redl674d1b72009-04-19 21:53:20 +00002900 } else if (Ty->isMemberPointerType()) {
2901 // Member pointers are far easier, since the pointee can't be converted.
2902 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2903 return;
Douglas Gregor70d26122008-11-12 17:17:38 +00002904 } else if (Ty->isEnumeralType()) {
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002905 EnumerationTypes.insert(Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002906 } else if (AllowUserConversions) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002907 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorb35c7992009-08-24 15:23:48 +00002908 if (SemaRef.RequireCompleteType(SourceLocation(), Ty, 0)) {
2909 // No conversion functions in incomplete types.
2910 return;
2911 }
2912
Douglas Gregor70d26122008-11-12 17:17:38 +00002913 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2914 // FIXME: Visit conversion functions in the base classes, too.
2915 OverloadedFunctionDecl *Conversions
2916 = ClassDecl->getConversionFunctions();
2917 for (OverloadedFunctionDecl::function_iterator Func
2918 = Conversions->function_begin();
2919 Func != Conversions->function_end(); ++Func) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00002920 CXXConversionDecl *Conv;
2921 FunctionTemplateDecl *ConvTemplate;
2922 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
2923
2924 // Skip conversion function templates; they don't tell us anything
2925 // about which builtin types we can convert to.
2926 if (ConvTemplate)
2927 continue;
2928
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002929 if (AllowExplicitConversions || !Conv->isExplicit())
2930 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002931 }
2932 }
2933 }
2934}
2935
Douglas Gregor9a375942009-08-24 13:43:27 +00002936/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
2937/// the volatile- and non-volatile-qualified assignment operators for the
2938/// given type to the candidate set.
2939static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
2940 QualType T,
2941 Expr **Args,
2942 unsigned NumArgs,
2943 OverloadCandidateSet &CandidateSet) {
2944 QualType ParamTypes[2];
2945
2946 // T& operator=(T&, T)
2947 ParamTypes[0] = S.Context.getLValueReferenceType(T);
2948 ParamTypes[1] = T;
2949 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2950 /*IsAssignmentOperator=*/true);
2951
2952 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
2953 // volatile T& operator=(volatile T&, T)
2954 ParamTypes[0] = S.Context.getLValueReferenceType(T.withVolatile());
2955 ParamTypes[1] = T;
2956 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2957 /*IsAssignmentOperator=*/true);
2958 }
2959}
2960
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002961/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2962/// operator overloads to the candidate set (C++ [over.built]), based
2963/// on the operator @p Op and the arguments given. For example, if the
2964/// operator is a binary '+', this routine might add "int
2965/// operator+(int, int)" to cover integer addition.
Douglas Gregor70d26122008-11-12 17:17:38 +00002966void
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002967Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2968 Expr **Args, unsigned NumArgs,
2969 OverloadCandidateSet& CandidateSet) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002970 // The set of "promoted arithmetic types", which are the arithmetic
2971 // types are that preserved by promotion (C++ [over.built]p2). Note
2972 // that the first few of these types are the promoted integral
2973 // types; these types need to be first.
2974 // FIXME: What about complex?
2975 const unsigned FirstIntegralType = 0;
2976 const unsigned LastIntegralType = 13;
2977 const unsigned FirstPromotedIntegralType = 7,
2978 LastPromotedIntegralType = 13;
2979 const unsigned FirstPromotedArithmeticType = 7,
2980 LastPromotedArithmeticType = 16;
2981 const unsigned NumArithmeticTypes = 16;
2982 QualType ArithmeticTypes[NumArithmeticTypes] = {
Alisdair Meredith2bcacb62009-07-14 06:30:34 +00002983 Context.BoolTy, Context.CharTy, Context.WCharTy,
Douglas Gregor9a375942009-08-24 13:43:27 +00002984// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregor70d26122008-11-12 17:17:38 +00002985 Context.SignedCharTy, Context.ShortTy,
2986 Context.UnsignedCharTy, Context.UnsignedShortTy,
2987 Context.IntTy, Context.LongTy, Context.LongLongTy,
2988 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2989 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2990 };
2991
2992 // Find all of the types that the arguments can convert to, but only
2993 // if the operator we're looking at has built-in operator candidates
2994 // that make use of these types.
Douglas Gregorb35c7992009-08-24 15:23:48 +00002995 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregor70d26122008-11-12 17:17:38 +00002996 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2997 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002998 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregor70d26122008-11-12 17:17:38 +00002999 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003000 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redlbd261962009-04-16 17:51:27 +00003001 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003002 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003003 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
3004 true,
3005 (Op == OO_Exclaim ||
3006 Op == OO_AmpAmp ||
3007 Op == OO_PipePipe));
Douglas Gregor70d26122008-11-12 17:17:38 +00003008 }
3009
3010 bool isComparison = false;
3011 switch (Op) {
3012 case OO_None:
3013 case NUM_OVERLOADED_OPERATORS:
3014 assert(false && "Expected an overloaded operator");
3015 break;
3016
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003017 case OO_Star: // '*' is either unary or binary
3018 if (NumArgs == 1)
3019 goto UnaryStar;
3020 else
3021 goto BinaryStar;
3022 break;
3023
3024 case OO_Plus: // '+' is either unary or binary
3025 if (NumArgs == 1)
3026 goto UnaryPlus;
3027 else
3028 goto BinaryPlus;
3029 break;
3030
3031 case OO_Minus: // '-' is either unary or binary
3032 if (NumArgs == 1)
3033 goto UnaryMinus;
3034 else
3035 goto BinaryMinus;
3036 break;
3037
3038 case OO_Amp: // '&' is either unary or binary
3039 if (NumArgs == 1)
3040 goto UnaryAmp;
3041 else
3042 goto BinaryAmp;
3043
3044 case OO_PlusPlus:
3045 case OO_MinusMinus:
3046 // C++ [over.built]p3:
3047 //
3048 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3049 // is either volatile or empty, there exist candidate operator
3050 // functions of the form
3051 //
3052 // VQ T& operator++(VQ T&);
3053 // T operator++(VQ T&, int);
3054 //
3055 // C++ [over.built]p4:
3056 //
3057 // For every pair (T, VQ), where T is an arithmetic type other
3058 // than bool, and VQ is either volatile or empty, there exist
3059 // candidate operator functions of the form
3060 //
3061 // VQ T& operator--(VQ T&);
3062 // T operator--(VQ T&, int);
3063 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
3064 Arith < NumArithmeticTypes; ++Arith) {
3065 QualType ArithTy = ArithmeticTypes[Arith];
3066 QualType ParamTypes[2]
Sebastian Redlce6fff02009-03-16 23:22:08 +00003067 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003068
3069 // Non-volatile version.
3070 if (NumArgs == 1)
3071 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3072 else
3073 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3074
3075 // Volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003076 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003077 if (NumArgs == 1)
3078 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3079 else
3080 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3081 }
3082
3083 // C++ [over.built]p5:
3084 //
3085 // For every pair (T, VQ), where T is a cv-qualified or
3086 // cv-unqualified object type, and VQ is either volatile or
3087 // empty, there exist candidate operator functions of the form
3088 //
3089 // T*VQ& operator++(T*VQ&);
3090 // T*VQ& operator--(T*VQ&);
3091 // T* operator++(T*VQ&, int);
3092 // T* operator--(T*VQ&, int);
3093 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3094 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3095 // Skip pointer types that aren't pointers to object types.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003096 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003097 continue;
3098
3099 QualType ParamTypes[2] = {
Sebastian Redlce6fff02009-03-16 23:22:08 +00003100 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003101 };
3102
3103 // Without volatile
3104 if (NumArgs == 1)
3105 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3106 else
3107 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3108
3109 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3110 // With volatile
Sebastian Redlce6fff02009-03-16 23:22:08 +00003111 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003112 if (NumArgs == 1)
3113 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3114 else
3115 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3116 }
3117 }
3118 break;
3119
3120 UnaryStar:
3121 // C++ [over.built]p6:
3122 // For every cv-qualified or cv-unqualified object type T, there
3123 // exist candidate operator functions of the form
3124 //
3125 // T& operator*(T*);
3126 //
3127 // C++ [over.built]p7:
3128 // For every function type T, there exist candidate operator
3129 // functions of the form
3130 // T& operator*(T*);
3131 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3132 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3133 QualType ParamTy = *Ptr;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003134 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003135 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003136 &ParamTy, Args, 1, CandidateSet);
3137 }
3138 break;
3139
3140 UnaryPlus:
3141 // C++ [over.built]p8:
3142 // For every type T, there exist candidate operator functions of
3143 // the form
3144 //
3145 // T* operator+(T*);
3146 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3147 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3148 QualType ParamTy = *Ptr;
3149 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3150 }
3151
3152 // Fall through
3153
3154 UnaryMinus:
3155 // C++ [over.built]p9:
3156 // For every promoted arithmetic type T, there exist candidate
3157 // operator functions of the form
3158 //
3159 // T operator+(T);
3160 // T operator-(T);
3161 for (unsigned Arith = FirstPromotedArithmeticType;
3162 Arith < LastPromotedArithmeticType; ++Arith) {
3163 QualType ArithTy = ArithmeticTypes[Arith];
3164 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3165 }
3166 break;
3167
3168 case OO_Tilde:
3169 // C++ [over.built]p10:
3170 // For every promoted integral type T, there exist candidate
3171 // operator functions of the form
3172 //
3173 // T operator~(T);
3174 for (unsigned Int = FirstPromotedIntegralType;
3175 Int < LastPromotedIntegralType; ++Int) {
3176 QualType IntTy = ArithmeticTypes[Int];
3177 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3178 }
3179 break;
3180
Douglas Gregor70d26122008-11-12 17:17:38 +00003181 case OO_New:
3182 case OO_Delete:
3183 case OO_Array_New:
3184 case OO_Array_Delete:
Douglas Gregor70d26122008-11-12 17:17:38 +00003185 case OO_Call:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003186 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregor70d26122008-11-12 17:17:38 +00003187 break;
3188
3189 case OO_Comma:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003190 UnaryAmp:
3191 case OO_Arrow:
Douglas Gregor70d26122008-11-12 17:17:38 +00003192 // C++ [over.match.oper]p3:
3193 // -- For the operator ',', the unary operator '&', or the
3194 // operator '->', the built-in candidates set is empty.
Douglas Gregor70d26122008-11-12 17:17:38 +00003195 break;
3196
Douglas Gregor9a375942009-08-24 13:43:27 +00003197 case OO_EqualEqual:
3198 case OO_ExclaimEqual:
3199 // C++ [over.match.oper]p16:
3200 // For every pointer to member type T, there exist candidate operator
3201 // functions of the form
3202 //
3203 // bool operator==(T,T);
3204 // bool operator!=(T,T);
3205 for (BuiltinCandidateTypeSet::iterator
3206 MemPtr = CandidateTypes.member_pointer_begin(),
3207 MemPtrEnd = CandidateTypes.member_pointer_end();
3208 MemPtr != MemPtrEnd;
3209 ++MemPtr) {
3210 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3211 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3212 }
3213
3214 // Fall through
3215
Douglas Gregor70d26122008-11-12 17:17:38 +00003216 case OO_Less:
3217 case OO_Greater:
3218 case OO_LessEqual:
3219 case OO_GreaterEqual:
Douglas Gregor70d26122008-11-12 17:17:38 +00003220 // C++ [over.built]p15:
3221 //
3222 // For every pointer or enumeration type T, there exist
3223 // candidate operator functions of the form
3224 //
3225 // bool operator<(T, T);
3226 // bool operator>(T, T);
3227 // bool operator<=(T, T);
3228 // bool operator>=(T, T);
3229 // bool operator==(T, T);
3230 // bool operator!=(T, T);
3231 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3232 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3233 QualType ParamTypes[2] = { *Ptr, *Ptr };
3234 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3235 }
3236 for (BuiltinCandidateTypeSet::iterator Enum
3237 = CandidateTypes.enumeration_begin();
3238 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3239 QualType ParamTypes[2] = { *Enum, *Enum };
3240 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3241 }
3242
3243 // Fall through.
3244 isComparison = true;
3245
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003246 BinaryPlus:
3247 BinaryMinus:
Douglas Gregor70d26122008-11-12 17:17:38 +00003248 if (!isComparison) {
3249 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3250
3251 // C++ [over.built]p13:
3252 //
3253 // For every cv-qualified or cv-unqualified object type T
3254 // there exist candidate operator functions of the form
3255 //
3256 // T* operator+(T*, ptrdiff_t);
3257 // T& operator[](T*, ptrdiff_t); [BELOW]
3258 // T* operator-(T*, ptrdiff_t);
3259 // T* operator+(ptrdiff_t, T*);
3260 // T& operator[](ptrdiff_t, T*); [BELOW]
3261 //
3262 // C++ [over.built]p14:
3263 //
3264 // For every T, where T is a pointer to object type, there
3265 // exist candidate operator functions of the form
3266 //
3267 // ptrdiff_t operator-(T, T);
3268 for (BuiltinCandidateTypeSet::iterator Ptr
3269 = CandidateTypes.pointer_begin();
3270 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3271 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3272
3273 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3274 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3275
3276 if (Op == OO_Plus) {
3277 // T* operator+(ptrdiff_t, T*);
3278 ParamTypes[0] = ParamTypes[1];
3279 ParamTypes[1] = *Ptr;
3280 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3281 } else {
3282 // ptrdiff_t operator-(T, T);
3283 ParamTypes[1] = *Ptr;
3284 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3285 Args, 2, CandidateSet);
3286 }
3287 }
3288 }
3289 // Fall through
3290
Douglas Gregor70d26122008-11-12 17:17:38 +00003291 case OO_Slash:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003292 BinaryStar:
Sebastian Redlbd261962009-04-16 17:51:27 +00003293 Conditional:
Douglas Gregor70d26122008-11-12 17:17:38 +00003294 // C++ [over.built]p12:
3295 //
3296 // For every pair of promoted arithmetic types L and R, there
3297 // exist candidate operator functions of the form
3298 //
3299 // LR operator*(L, R);
3300 // LR operator/(L, R);
3301 // LR operator+(L, R);
3302 // LR operator-(L, R);
3303 // bool operator<(L, R);
3304 // bool operator>(L, R);
3305 // bool operator<=(L, R);
3306 // bool operator>=(L, R);
3307 // bool operator==(L, R);
3308 // bool operator!=(L, R);
3309 //
3310 // where LR is the result of the usual arithmetic conversions
3311 // between types L and R.
Sebastian Redlbd261962009-04-16 17:51:27 +00003312 //
3313 // C++ [over.built]p24:
3314 //
3315 // For every pair of promoted arithmetic types L and R, there exist
3316 // candidate operator functions of the form
3317 //
3318 // LR operator?(bool, L, R);
3319 //
3320 // where LR is the result of the usual arithmetic conversions
3321 // between types L and R.
3322 // Our candidates ignore the first parameter.
Douglas Gregor70d26122008-11-12 17:17:38 +00003323 for (unsigned Left = FirstPromotedArithmeticType;
3324 Left < LastPromotedArithmeticType; ++Left) {
3325 for (unsigned Right = FirstPromotedArithmeticType;
3326 Right < LastPromotedArithmeticType; ++Right) {
3327 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman6ae7d112009-08-19 07:44:53 +00003328 QualType Result
3329 = isComparison
3330 ? Context.BoolTy
3331 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003332 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3333 }
3334 }
3335 break;
3336
3337 case OO_Percent:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003338 BinaryAmp:
Douglas Gregor70d26122008-11-12 17:17:38 +00003339 case OO_Caret:
3340 case OO_Pipe:
3341 case OO_LessLess:
3342 case OO_GreaterGreater:
3343 // C++ [over.built]p17:
3344 //
3345 // For every pair of promoted integral types L and R, there
3346 // exist candidate operator functions of the form
3347 //
3348 // LR operator%(L, R);
3349 // LR operator&(L, R);
3350 // LR operator^(L, R);
3351 // LR operator|(L, R);
3352 // L operator<<(L, R);
3353 // L operator>>(L, R);
3354 //
3355 // where LR is the result of the usual arithmetic conversions
3356 // between types L and R.
3357 for (unsigned Left = FirstPromotedIntegralType;
3358 Left < LastPromotedIntegralType; ++Left) {
3359 for (unsigned Right = FirstPromotedIntegralType;
3360 Right < LastPromotedIntegralType; ++Right) {
3361 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3362 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3363 ? LandR[0]
Eli Friedman6ae7d112009-08-19 07:44:53 +00003364 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003365 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3366 }
3367 }
3368 break;
3369
3370 case OO_Equal:
3371 // C++ [over.built]p20:
3372 //
3373 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor9a375942009-08-24 13:43:27 +00003374 // pointer to member type and VQ is either volatile or
Douglas Gregor70d26122008-11-12 17:17:38 +00003375 // empty, there exist candidate operator functions of the form
3376 //
3377 // VQ T& operator=(VQ T&, T);
Douglas Gregor9a375942009-08-24 13:43:27 +00003378 for (BuiltinCandidateTypeSet::iterator
3379 Enum = CandidateTypes.enumeration_begin(),
3380 EnumEnd = CandidateTypes.enumeration_end();
3381 Enum != EnumEnd; ++Enum)
3382 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
3383 CandidateSet);
3384 for (BuiltinCandidateTypeSet::iterator
3385 MemPtr = CandidateTypes.member_pointer_begin(),
3386 MemPtrEnd = CandidateTypes.member_pointer_end();
3387 MemPtr != MemPtrEnd; ++MemPtr)
3388 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
3389 CandidateSet);
3390 // Fall through.
Douglas Gregor70d26122008-11-12 17:17:38 +00003391
3392 case OO_PlusEqual:
3393 case OO_MinusEqual:
3394 // C++ [over.built]p19:
3395 //
3396 // For every pair (T, VQ), where T is any type and VQ is either
3397 // volatile or empty, there exist candidate operator functions
3398 // of the form
3399 //
3400 // T*VQ& operator=(T*VQ&, T*);
3401 //
3402 // C++ [over.built]p21:
3403 //
3404 // For every pair (T, VQ), where T is a cv-qualified or
3405 // cv-unqualified object type and VQ is either volatile or
3406 // empty, there exist candidate operator functions of the form
3407 //
3408 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3409 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3410 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3411 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3412 QualType ParamTypes[2];
3413 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3414
3415 // non-volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003416 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorab141112009-01-13 00:52:54 +00003417 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3418 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003419
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003420 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3421 // volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003422 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregorab141112009-01-13 00:52:54 +00003423 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3424 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003425 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003426 }
3427 // Fall through.
3428
3429 case OO_StarEqual:
3430 case OO_SlashEqual:
3431 // C++ [over.built]p18:
3432 //
3433 // For every triple (L, VQ, R), where L is an arithmetic type,
3434 // VQ is either volatile or empty, and R is a promoted
3435 // arithmetic type, there exist candidate operator functions of
3436 // the form
3437 //
3438 // VQ L& operator=(VQ L&, R);
3439 // VQ L& operator*=(VQ L&, R);
3440 // VQ L& operator/=(VQ L&, R);
3441 // VQ L& operator+=(VQ L&, R);
3442 // VQ L& operator-=(VQ L&, R);
3443 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3444 for (unsigned Right = FirstPromotedArithmeticType;
3445 Right < LastPromotedArithmeticType; ++Right) {
3446 QualType ParamTypes[2];
3447 ParamTypes[1] = ArithmeticTypes[Right];
3448
3449 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003450 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorab141112009-01-13 00:52:54 +00003451 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3452 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003453
3454 // Add this built-in operator as a candidate (VQ is 'volatile').
3455 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003456 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregorab141112009-01-13 00:52:54 +00003457 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3458 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003459 }
3460 }
3461 break;
3462
3463 case OO_PercentEqual:
3464 case OO_LessLessEqual:
3465 case OO_GreaterGreaterEqual:
3466 case OO_AmpEqual:
3467 case OO_CaretEqual:
3468 case OO_PipeEqual:
3469 // C++ [over.built]p22:
3470 //
3471 // For every triple (L, VQ, R), where L is an integral type, VQ
3472 // is either volatile or empty, and R is a promoted integral
3473 // type, there exist candidate operator functions of the form
3474 //
3475 // VQ L& operator%=(VQ L&, R);
3476 // VQ L& operator<<=(VQ L&, R);
3477 // VQ L& operator>>=(VQ L&, R);
3478 // VQ L& operator&=(VQ L&, R);
3479 // VQ L& operator^=(VQ L&, R);
3480 // VQ L& operator|=(VQ L&, R);
3481 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3482 for (unsigned Right = FirstPromotedIntegralType;
3483 Right < LastPromotedIntegralType; ++Right) {
3484 QualType ParamTypes[2];
3485 ParamTypes[1] = ArithmeticTypes[Right];
3486
3487 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003488 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003489 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3490
3491 // Add this built-in operator as a candidate (VQ is 'volatile').
3492 ParamTypes[0] = ArithmeticTypes[Left];
3493 ParamTypes[0].addVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003494 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003495 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3496 }
3497 }
3498 break;
3499
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003500 case OO_Exclaim: {
3501 // C++ [over.operator]p23:
3502 //
3503 // There also exist candidate operator functions of the form
3504 //
3505 // bool operator!(bool);
3506 // bool operator&&(bool, bool); [BELOW]
3507 // bool operator||(bool, bool); [BELOW]
3508 QualType ParamTy = Context.BoolTy;
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003509 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3510 /*IsAssignmentOperator=*/false,
3511 /*NumContextualBoolArguments=*/1);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003512 break;
3513 }
3514
Douglas Gregor70d26122008-11-12 17:17:38 +00003515 case OO_AmpAmp:
3516 case OO_PipePipe: {
3517 // C++ [over.operator]p23:
3518 //
3519 // There also exist candidate operator functions of the form
3520 //
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003521 // bool operator!(bool); [ABOVE]
Douglas Gregor70d26122008-11-12 17:17:38 +00003522 // bool operator&&(bool, bool);
3523 // bool operator||(bool, bool);
3524 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003525 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3526 /*IsAssignmentOperator=*/false,
3527 /*NumContextualBoolArguments=*/2);
Douglas Gregor70d26122008-11-12 17:17:38 +00003528 break;
3529 }
3530
3531 case OO_Subscript:
3532 // C++ [over.built]p13:
3533 //
3534 // For every cv-qualified or cv-unqualified object type T there
3535 // exist candidate operator functions of the form
3536 //
3537 // T* operator+(T*, ptrdiff_t); [ABOVE]
3538 // T& operator[](T*, ptrdiff_t);
3539 // T* operator-(T*, ptrdiff_t); [ABOVE]
3540 // T* operator+(ptrdiff_t, T*); [ABOVE]
3541 // T& operator[](ptrdiff_t, T*);
3542 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3543 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3544 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003545 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003546 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregor70d26122008-11-12 17:17:38 +00003547
3548 // T& operator[](T*, ptrdiff_t)
3549 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3550
3551 // T& operator[](ptrdiff_t, T*);
3552 ParamTypes[0] = ParamTypes[1];
3553 ParamTypes[1] = *Ptr;
3554 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3555 }
3556 break;
3557
3558 case OO_ArrowStar:
3559 // FIXME: No support for pointer-to-members yet.
3560 break;
Sebastian Redlbd261962009-04-16 17:51:27 +00003561
3562 case OO_Conditional:
3563 // Note that we don't consider the first argument, since it has been
3564 // contextually converted to bool long ago. The candidates below are
3565 // therefore added as binary.
3566 //
3567 // C++ [over.built]p24:
3568 // For every type T, where T is a pointer or pointer-to-member type,
3569 // there exist candidate operator functions of the form
3570 //
3571 // T operator?(bool, T, T);
3572 //
Sebastian Redlbd261962009-04-16 17:51:27 +00003573 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3574 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3575 QualType ParamTypes[2] = { *Ptr, *Ptr };
3576 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3577 }
Sebastian Redl674d1b72009-04-19 21:53:20 +00003578 for (BuiltinCandidateTypeSet::iterator Ptr =
3579 CandidateTypes.member_pointer_begin(),
3580 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3581 QualType ParamTypes[2] = { *Ptr, *Ptr };
3582 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3583 }
Sebastian Redlbd261962009-04-16 17:51:27 +00003584 goto Conditional;
Douglas Gregor70d26122008-11-12 17:17:38 +00003585 }
3586}
3587
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003588/// \brief Add function candidates found via argument-dependent lookup
3589/// to the set of overloading candidates.
3590///
3591/// This routine performs argument-dependent name lookup based on the
3592/// given function name (which may also be an operator name) and adds
3593/// all of the overload candidates found by ADL to the overload
3594/// candidate set (C++ [basic.lookup.argdep]).
3595void
3596Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3597 Expr **Args, unsigned NumArgs,
3598 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003599 FunctionSet Functions;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003600
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003601 // Record all of the function candidates that we've already
3602 // added to the overload set, so that we don't add those same
3603 // candidates a second time.
3604 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3605 CandEnd = CandidateSet.end();
3606 Cand != CandEnd; ++Cand)
Douglas Gregor993a0602009-06-27 21:05:07 +00003607 if (Cand->Function) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003608 Functions.insert(Cand->Function);
Douglas Gregor993a0602009-06-27 21:05:07 +00003609 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3610 Functions.insert(FunTmpl);
3611 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003612
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003613 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003614
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003615 // Erase all of the candidates we already knew about.
3616 // FIXME: This is suboptimal. Is there a better way?
3617 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3618 CandEnd = CandidateSet.end();
3619 Cand != CandEnd; ++Cand)
Douglas Gregor993a0602009-06-27 21:05:07 +00003620 if (Cand->Function) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003621 Functions.erase(Cand->Function);
Douglas Gregor993a0602009-06-27 21:05:07 +00003622 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3623 Functions.erase(FunTmpl);
3624 }
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003625
3626 // For each of the ADL candidates we found, add it to the overload
3627 // set.
3628 for (FunctionSet::iterator Func = Functions.begin(),
3629 FuncEnd = Functions.end();
Douglas Gregor993a0602009-06-27 21:05:07 +00003630 Func != FuncEnd; ++Func) {
3631 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
3632 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet);
3633 else
Douglas Gregorc9a03b72009-06-30 23:57:56 +00003634 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
3635 /*FIXME: explicit args */false, 0, 0,
3636 Args, NumArgs, CandidateSet);
Douglas Gregor993a0602009-06-27 21:05:07 +00003637 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003638}
3639
Douglas Gregord2baafd2008-10-21 16:13:35 +00003640/// isBetterOverloadCandidate - Determines whether the first overload
3641/// candidate is a better candidate than the second (C++ 13.3.3p1).
3642bool
3643Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3644 const OverloadCandidate& Cand2)
3645{
3646 // Define viable functions to be better candidates than non-viable
3647 // functions.
3648 if (!Cand2.Viable)
3649 return Cand1.Viable;
3650 else if (!Cand1.Viable)
3651 return false;
3652
Douglas Gregor3257fb52008-12-22 05:46:06 +00003653 // C++ [over.match.best]p1:
3654 //
3655 // -- if F is a static member function, ICS1(F) is defined such
3656 // that ICS1(F) is neither better nor worse than ICS1(G) for
3657 // any function G, and, symmetrically, ICS1(G) is neither
3658 // better nor worse than ICS1(F).
3659 unsigned StartArg = 0;
3660 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3661 StartArg = 1;
Douglas Gregord2baafd2008-10-21 16:13:35 +00003662
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003663 // C++ [over.match.best]p1:
3664 // A viable function F1 is defined to be a better function than another
3665 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
3666 // conversion sequence than ICSi(F2), and then...
Douglas Gregord2baafd2008-10-21 16:13:35 +00003667 unsigned NumArgs = Cand1.Conversions.size();
3668 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3669 bool HasBetterConversion = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00003670 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00003671 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3672 Cand2.Conversions[ArgIdx])) {
3673 case ImplicitConversionSequence::Better:
3674 // Cand1 has a better conversion sequence.
3675 HasBetterConversion = true;
3676 break;
3677
3678 case ImplicitConversionSequence::Worse:
3679 // Cand1 can't be better than Cand2.
3680 return false;
3681
3682 case ImplicitConversionSequence::Indistinguishable:
3683 // Do nothing.
3684 break;
3685 }
3686 }
3687
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003688 // -- for some argument j, ICSj(F1) is a better conversion sequence than
3689 // ICSj(F2), or, if not that,
Douglas Gregord2baafd2008-10-21 16:13:35 +00003690 if (HasBetterConversion)
3691 return true;
3692
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003693 // - F1 is a non-template function and F2 is a function template
3694 // specialization, or, if not that,
3695 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3696 Cand2.Function && Cand2.Function->getPrimaryTemplate())
3697 return true;
3698
3699 // -- F1 and F2 are function template specializations, and the function
3700 // template for F1 is more specialized than the template for F2
3701 // according to the partial ordering rules described in 14.5.5.2, or,
3702 // if not that,
Douglas Gregorf8e51672009-08-02 23:46:29 +00003703 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
3704 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor8c860df2009-08-21 23:19:43 +00003705 if (FunctionTemplateDecl *BetterTemplate
3706 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
3707 Cand2.Function->getPrimaryTemplate(),
3708 true))
3709 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregord2baafd2008-10-21 16:13:35 +00003710
Douglas Gregor60714f92008-11-07 22:36:19 +00003711 // -- the context is an initialization by user-defined conversion
3712 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3713 // from the return type of F1 to the destination type (i.e.,
3714 // the type of the entity being initialized) is a better
3715 // conversion sequence than the standard conversion sequence
3716 // from the return type of F2 to the destination type.
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003717 if (Cand1.Function && Cand2.Function &&
3718 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregor60714f92008-11-07 22:36:19 +00003719 isa<CXXConversionDecl>(Cand2.Function)) {
3720 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3721 Cand2.FinalConversion)) {
3722 case ImplicitConversionSequence::Better:
3723 // Cand1 has a better conversion sequence.
3724 return true;
3725
3726 case ImplicitConversionSequence::Worse:
3727 // Cand1 can't be better than Cand2.
3728 return false;
3729
3730 case ImplicitConversionSequence::Indistinguishable:
3731 // Do nothing
3732 break;
3733 }
3734 }
3735
Douglas Gregord2baafd2008-10-21 16:13:35 +00003736 return false;
3737}
3738
Douglas Gregor98189262009-06-19 23:52:42 +00003739/// \brief Computes the best viable function (C++ 13.3.3)
3740/// within an overload candidate set.
3741///
3742/// \param CandidateSet the set of candidate functions.
3743///
3744/// \param Loc the location of the function name (or operator symbol) for
3745/// which overload resolution occurs.
3746///
3747/// \param Best f overload resolution was successful or found a deleted
3748/// function, Best points to the candidate function found.
3749///
3750/// \returns The result of overload resolution.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003751Sema::OverloadingResult
3752Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregor98189262009-06-19 23:52:42 +00003753 SourceLocation Loc,
Douglas Gregord2baafd2008-10-21 16:13:35 +00003754 OverloadCandidateSet::iterator& Best)
3755{
3756 // Find the best viable function.
3757 Best = CandidateSet.end();
3758 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3759 Cand != CandidateSet.end(); ++Cand) {
3760 if (Cand->Viable) {
3761 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3762 Best = Cand;
3763 }
3764 }
3765
3766 // If we didn't find any viable functions, abort.
3767 if (Best == CandidateSet.end())
3768 return OR_No_Viable_Function;
3769
3770 // Make sure that this function is better than every other viable
3771 // function. If not, we have an ambiguity.
3772 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3773 Cand != CandidateSet.end(); ++Cand) {
3774 if (Cand->Viable &&
3775 Cand != Best &&
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003776 !isBetterOverloadCandidate(*Best, *Cand)) {
3777 Best = CandidateSet.end();
Douglas Gregord2baafd2008-10-21 16:13:35 +00003778 return OR_Ambiguous;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003779 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003780 }
3781
3782 // Best is the best viable function.
Douglas Gregoraa57e862009-02-18 21:56:37 +00003783 if (Best->Function &&
3784 (Best->Function->isDeleted() ||
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003785 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregoraa57e862009-02-18 21:56:37 +00003786 return OR_Deleted;
3787
Douglas Gregor98189262009-06-19 23:52:42 +00003788 // C++ [basic.def.odr]p2:
3789 // An overloaded function is used if it is selected by overload resolution
3790 // when referred to from a potentially-evaluated expression. [Note: this
3791 // covers calls to named functions (5.2.2), operator overloading
3792 // (clause 13), user-defined conversions (12.3.2), allocation function for
3793 // placement new (5.3.4), as well as non-default initialization (8.5).
3794 if (Best->Function)
3795 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregord2baafd2008-10-21 16:13:35 +00003796 return OR_Success;
3797}
3798
3799/// PrintOverloadCandidates - When overload resolution fails, prints
3800/// diagnostic messages containing the candidates in the candidate
3801/// set. If OnlyViable is true, only viable candidates will be printed.
3802void
3803Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3804 bool OnlyViable)
3805{
3806 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3807 LastCand = CandidateSet.end();
3808 for (; Cand != LastCand; ++Cand) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003809 if (Cand->Viable || !OnlyViable) {
3810 if (Cand->Function) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003811 if (Cand->Function->isDeleted() ||
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003812 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003813 // Deleted or "unavailable" function.
3814 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3815 << Cand->Function->isDeleted();
3816 } else {
3817 // Normal function
3818 // FIXME: Give a better reason!
3819 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3820 }
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003821 } else if (Cand->IsSurrogate) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003822 // Desugar the type of the surrogate down to a function type,
3823 // retaining as many typedefs as possible while still showing
3824 // the function type (and, therefore, its parameter types).
3825 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003826 bool isLValueReference = false;
3827 bool isRValueReference = false;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003828 bool isPointer = false;
Sebastian Redlce6fff02009-03-16 23:22:08 +00003829 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003830 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003831 FnType = FnTypeRef->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003832 isLValueReference = true;
3833 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003834 FnType->getAs<RValueReferenceType>()) {
Sebastian Redlce6fff02009-03-16 23:22:08 +00003835 FnType = FnTypeRef->getPointeeType();
3836 isRValueReference = true;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003837 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003838 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003839 FnType = FnTypePtr->getPointeeType();
3840 isPointer = true;
3841 }
3842 // Desugar down to a function type.
3843 FnType = QualType(FnType->getAsFunctionType(), 0);
3844 // Reconstruct the pointer/reference as appropriate.
3845 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redlce6fff02009-03-16 23:22:08 +00003846 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3847 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003848
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003849 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003850 << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003851 } else {
3852 // FIXME: We need to get the identifier in here
Mike Stumpe127ae32009-05-16 07:39:55 +00003853 // FIXME: Do we want the error message to point at the operator?
3854 // (built-ins won't have a location)
Douglas Gregor70d26122008-11-12 17:17:38 +00003855 QualType FnType
3856 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3857 Cand->BuiltinTypes.ParamTypes,
3858 Cand->Conversions.size(),
3859 false, 0);
3860
Chris Lattner4bfd2232008-11-24 06:25:27 +00003861 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003862 }
3863 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003864 }
3865}
3866
Douglas Gregor45014fd2008-11-10 20:40:00 +00003867/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3868/// an overloaded function (C++ [over.over]), where @p From is an
3869/// expression with overloaded function type and @p ToType is the type
3870/// we're trying to resolve to. For example:
3871///
3872/// @code
3873/// int f(double);
3874/// int f(int);
3875///
3876/// int (*pfd)(double) = f; // selects f(double)
3877/// @endcode
3878///
3879/// This routine returns the resulting FunctionDecl if it could be
3880/// resolved, and NULL otherwise. When @p Complain is true, this
3881/// routine will emit diagnostics if there is an error.
3882FunctionDecl *
Sebastian Redl7434fc32009-02-04 21:23:32 +00003883Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor45014fd2008-11-10 20:40:00 +00003884 bool Complain) {
3885 QualType FunctionType = ToType;
Sebastian Redl7434fc32009-02-04 21:23:32 +00003886 bool IsMember = false;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003887 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor45014fd2008-11-10 20:40:00 +00003888 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003889 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarf6c06ce2009-02-26 19:13:44 +00003890 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl7434fc32009-02-04 21:23:32 +00003891 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003892 ToType->getAs<MemberPointerType>()) {
Sebastian Redl7434fc32009-02-04 21:23:32 +00003893 FunctionType = MemTypePtr->getPointeeType();
3894 IsMember = true;
3895 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003896
3897 // We only look at pointers or references to functions.
Douglas Gregor72bb4992009-07-09 17:16:51 +00003898 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor62f78762009-07-08 20:55:45 +00003899 if (!FunctionType->isFunctionType())
Douglas Gregor45014fd2008-11-10 20:40:00 +00003900 return 0;
3901
3902 // Find the actual overloaded function declaration.
3903 OverloadedFunctionDecl *Ovl = 0;
3904
3905 // C++ [over.over]p1:
3906 // [...] [Note: any redundant set of parentheses surrounding the
3907 // overloaded function name is ignored (5.1). ]
3908 Expr *OvlExpr = From->IgnoreParens();
3909
3910 // C++ [over.over]p1:
3911 // [...] The overloaded function name can be preceded by the &
3912 // operator.
3913 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3914 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3915 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3916 }
3917
3918 // Try to dig out the overloaded function.
Douglas Gregor62f78762009-07-08 20:55:45 +00003919 FunctionTemplateDecl *FunctionTemplate = 0;
3920 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003921 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor62f78762009-07-08 20:55:45 +00003922 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
3923 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003924
Douglas Gregor62f78762009-07-08 20:55:45 +00003925 // If there's no overloaded function declaration or function template,
3926 // we're done.
3927 if (!Ovl && !FunctionTemplate)
Douglas Gregor45014fd2008-11-10 20:40:00 +00003928 return 0;
3929
Douglas Gregor62f78762009-07-08 20:55:45 +00003930 OverloadIterator Fun;
3931 if (Ovl)
3932 Fun = Ovl;
3933 else
3934 Fun = FunctionTemplate;
3935
Douglas Gregor45014fd2008-11-10 20:40:00 +00003936 // Look through all of the overloaded functions, searching for one
3937 // whose type matches exactly.
Douglas Gregora142a052009-07-08 23:33:52 +00003938 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
3939
3940 bool FoundNonTemplateFunction = false;
Douglas Gregor62f78762009-07-08 20:55:45 +00003941 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003942 // C++ [over.over]p3:
3943 // Non-member functions and static member functions match
Sebastian Redl3a75abf2009-02-05 12:33:33 +00003944 // targets of type "pointer-to-function" or "reference-to-function."
3945 // Nonstatic member functions match targets of
Sebastian Redl7434fc32009-02-04 21:23:32 +00003946 // type "pointer-to-member-function."
3947 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor62f78762009-07-08 20:55:45 +00003948
3949 if (FunctionTemplateDecl *FunctionTemplate
3950 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Douglas Gregora142a052009-07-08 23:33:52 +00003951 if (CXXMethodDecl *Method
3952 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
3953 // Skip non-static function templates when converting to pointer, and
3954 // static when converting to member pointer.
3955 if (Method->isStatic() == IsMember)
3956 continue;
3957 } else if (IsMember)
3958 continue;
3959
3960 // C++ [over.over]p2:
3961 // If the name is a function template, template argument deduction is
3962 // done (14.8.2.2), and if the argument deduction succeeds, the
3963 // resulting template argument list is used to generate a single
3964 // function template specialization, which is added to the set of
3965 // overloaded functions considered.
Douglas Gregor62f78762009-07-08 20:55:45 +00003966 FunctionDecl *Specialization = 0;
3967 TemplateDeductionInfo Info(Context);
3968 if (TemplateDeductionResult Result
3969 = DeduceTemplateArguments(FunctionTemplate, /*FIXME*/false,
3970 /*FIXME:*/0, /*FIXME:*/0,
3971 FunctionType, Specialization, Info)) {
3972 // FIXME: make a note of the failed deduction for diagnostics.
3973 (void)Result;
3974 } else {
3975 assert(FunctionType
3976 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregora142a052009-07-08 23:33:52 +00003977 Matches.insert(
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00003978 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor62f78762009-07-08 20:55:45 +00003979 }
3980 }
3981
Sebastian Redl7434fc32009-02-04 21:23:32 +00003982 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3983 // Skip non-static functions when converting to pointer, and static
3984 // when converting to member pointer.
3985 if (Method->isStatic() == IsMember)
Douglas Gregor45014fd2008-11-10 20:40:00 +00003986 continue;
Douglas Gregora142a052009-07-08 23:33:52 +00003987 } else if (IsMember)
Sebastian Redl7434fc32009-02-04 21:23:32 +00003988 continue;
Douglas Gregor45014fd2008-11-10 20:40:00 +00003989
Douglas Gregorb60eb752009-06-25 22:08:12 +00003990 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregora142a052009-07-08 23:33:52 +00003991 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00003992 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregora142a052009-07-08 23:33:52 +00003993 FoundNonTemplateFunction = true;
3994 }
Douglas Gregor62f78762009-07-08 20:55:45 +00003995 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003996 }
3997
Douglas Gregora142a052009-07-08 23:33:52 +00003998 // If there were 0 or 1 matches, we're done.
3999 if (Matches.empty())
4000 return 0;
4001 else if (Matches.size() == 1)
4002 return *Matches.begin();
4003
4004 // C++ [over.over]p4:
4005 // If more than one function is selected, [...]
4006 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
Douglas Gregor8c860df2009-08-21 23:19:43 +00004007 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregora142a052009-07-08 23:33:52 +00004008 if (FoundNonTemplateFunction) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00004009 // [...] any function template specializations in the set are
4010 // eliminated if the set also contains a non-template function, [...]
4011 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
Douglas Gregora142a052009-07-08 23:33:52 +00004012 if ((*M)->getPrimaryTemplate() == 0)
4013 RemainingMatches.push_back(*M);
4014 } else {
Douglas Gregor8c860df2009-08-21 23:19:43 +00004015 // [...] and any given function template specialization F1 is
4016 // eliminated if the set contains a second function template
4017 // specialization whose function template is more specialized
4018 // than the function template of F1 according to the partial
4019 // ordering rules of 14.5.5.2.
4020
4021 // The algorithm specified above is quadratic. We instead use a
4022 // two-pass algorithm (similar to the one used to identify the
4023 // best viable function in an overload set) that identifies the
4024 // best function template (if it exists).
4025 MatchIter Best = Matches.begin();
4026 MatchIter M = Best, MEnd = Matches.end();
4027 // Find the most specialized function.
4028 for (++M; M != MEnd; ++M)
4029 if (getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4030 (*Best)->getPrimaryTemplate(),
4031 false)
4032 == (*M)->getPrimaryTemplate())
4033 Best = M;
4034
4035 // Determine whether this function template is more specialized
4036 // that all of the others.
4037 bool Ambiguous = false;
4038 for (M = Matches.begin(); M != MEnd; ++M) {
4039 if (M != Best &&
4040 getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4041 (*Best)->getPrimaryTemplate(),
4042 false)
4043 != (*Best)->getPrimaryTemplate()) {
4044 Ambiguous = true;
4045 break;
4046 }
4047 }
4048
4049 // If one function template was more specialized than all of the
4050 // others, return it.
4051 if (!Ambiguous)
4052 return *Best;
4053
4054 // We could not find a most-specialized function template, which
4055 // is equivalent to having a set of function templates with more
4056 // than one such template. So, we place all of the function
4057 // templates into the set of remaining matches and produce a
4058 // diagnostic below. FIXME: we could perform the quadratic
4059 // algorithm here, pruning the result set to limit the number of
4060 // candidates output later.
4061 RemainingMatches.append(Matches.begin(), Matches.end());
Douglas Gregora142a052009-07-08 23:33:52 +00004062 }
4063
4064 // [...] After such eliminations, if any, there shall remain exactly one
4065 // selected function.
4066 if (RemainingMatches.size() == 1)
4067 return RemainingMatches.front();
4068
4069 // FIXME: We should probably return the same thing that BestViableFunction
4070 // returns (even if we issue the diagnostics here).
4071 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4072 << RemainingMatches[0]->getDeclName();
4073 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4074 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregor45014fd2008-11-10 20:40:00 +00004075 return 0;
4076}
4077
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004078/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004079/// (which eventually refers to the declaration Func) and the call
4080/// arguments Args/NumArgs, attempt to resolve the function call down
4081/// to a specific function. If overload resolution succeeds, returns
4082/// the function declaration produced by overload
Douglas Gregorbf4f0582008-11-26 06:01:48 +00004083/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004084/// arguments and Fn, and returns NULL.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004085FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004086 DeclarationName UnqualifiedName,
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004087 bool HasExplicitTemplateArgs,
4088 const TemplateArgument *ExplicitTemplateArgs,
4089 unsigned NumExplicitTemplateArgs,
Douglas Gregorbf4f0582008-11-26 06:01:48 +00004090 SourceLocation LParenLoc,
4091 Expr **Args, unsigned NumArgs,
4092 SourceLocation *CommaLocs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004093 SourceLocation RParenLoc,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004094 bool &ArgumentDependentLookup) {
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004095 OverloadCandidateSet CandidateSet;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004096
4097 // Add the functions denoted by Callee to the set of candidate
4098 // functions. While we're doing so, track whether argument-dependent
4099 // lookup still applies, per:
4100 //
4101 // C++0x [basic.lookup.argdep]p3:
4102 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4103 // and let Y be the lookup set produced by argument dependent
4104 // lookup (defined as follows). If X contains
4105 //
4106 // -- a declaration of a class member, or
4107 //
4108 // -- a block-scope function declaration that is not a
4109 // using-declaration, or
4110 //
4111 // -- a declaration that is neither a function or a function
4112 // template
4113 //
4114 // then Y is empty.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004115 if (OverloadedFunctionDecl *Ovl
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004116 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
4117 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4118 FuncEnd = Ovl->function_end();
4119 Func != FuncEnd; ++Func) {
Douglas Gregorb60eb752009-06-25 22:08:12 +00004120 DeclContext *Ctx = 0;
4121 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Func)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004122 if (HasExplicitTemplateArgs)
4123 continue;
4124
Douglas Gregorb60eb752009-06-25 22:08:12 +00004125 AddOverloadCandidate(FunDecl, Args, NumArgs, CandidateSet);
4126 Ctx = FunDecl->getDeclContext();
4127 } else {
4128 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*Func);
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004129 AddTemplateOverloadCandidate(FunTmpl, HasExplicitTemplateArgs,
4130 ExplicitTemplateArgs,
4131 NumExplicitTemplateArgs,
4132 Args, NumArgs, CandidateSet);
Douglas Gregorb60eb752009-06-25 22:08:12 +00004133 Ctx = FunTmpl->getDeclContext();
4134 }
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004135
Douglas Gregorb60eb752009-06-25 22:08:12 +00004136
4137 if (Ctx->isRecord() || Ctx->isFunctionOrMethod())
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004138 ArgumentDependentLookup = false;
4139 }
4140 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004141 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004142 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
4143
4144 if (Func->getDeclContext()->isRecord() ||
4145 Func->getDeclContext()->isFunctionOrMethod())
4146 ArgumentDependentLookup = false;
Douglas Gregorb60eb752009-06-25 22:08:12 +00004147 } else if (FunctionTemplateDecl *FuncTemplate
4148 = dyn_cast_or_null<FunctionTemplateDecl>(Callee)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004149 AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4150 ExplicitTemplateArgs,
4151 NumExplicitTemplateArgs,
4152 Args, NumArgs, CandidateSet);
Douglas Gregorb60eb752009-06-25 22:08:12 +00004153
4154 if (FuncTemplate->getDeclContext()->isRecord())
4155 ArgumentDependentLookup = false;
4156 }
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004157
4158 if (Callee)
4159 UnqualifiedName = Callee->getDeclName();
4160
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004161 // FIXME: Pass explicit template arguments through for ADL
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004162 if (ArgumentDependentLookup)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004163 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004164 CandidateSet);
4165
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004166 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004167 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00004168 case OR_Success:
4169 return Best->Function;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004170
4171 case OR_No_Viable_Function:
Chris Lattner4a526112009-02-17 07:29:20 +00004172 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004173 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004174 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004175 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4176 break;
4177
4178 case OR_Ambiguous:
4179 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004180 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004181 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4182 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004183
4184 case OR_Deleted:
4185 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4186 << Best->Function->isDeleted()
4187 << UnqualifiedName
4188 << Fn->getSourceRange();
4189 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4190 break;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004191 }
4192
4193 // Overload resolution failed. Destroy all of the subexpressions and
4194 // return NULL.
4195 Fn->Destroy(Context);
4196 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4197 Args[Arg]->Destroy(Context);
4198 return 0;
4199}
4200
Douglas Gregorc78182d2009-03-13 23:49:33 +00004201/// \brief Create a unary operation that may resolve to an overloaded
4202/// operator.
4203///
4204/// \param OpLoc The location of the operator itself (e.g., '*').
4205///
4206/// \param OpcIn The UnaryOperator::Opcode that describes this
4207/// operator.
4208///
4209/// \param Functions The set of non-member functions that will be
4210/// considered by overload resolution. The caller needs to build this
4211/// set based on the context using, e.g.,
4212/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4213/// set should not contain any member functions; those will be added
4214/// by CreateOverloadedUnaryOp().
4215///
4216/// \param input The input argument.
4217Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4218 unsigned OpcIn,
4219 FunctionSet &Functions,
4220 ExprArg input) {
4221 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4222 Expr *Input = (Expr *)input.get();
4223
4224 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4225 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4226 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4227
4228 Expr *Args[2] = { Input, 0 };
4229 unsigned NumArgs = 1;
4230
4231 // For post-increment and post-decrement, add the implicit '0' as
4232 // the second argument, so that we know this is a post-increment or
4233 // post-decrement.
4234 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4235 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
4236 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
4237 SourceLocation());
4238 NumArgs = 2;
4239 }
4240
4241 if (Input->isTypeDependent()) {
4242 OverloadedFunctionDecl *Overloads
4243 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4244 for (FunctionSet::iterator Func = Functions.begin(),
4245 FuncEnd = Functions.end();
4246 Func != FuncEnd; ++Func)
4247 Overloads->addOverload(*Func);
4248
4249 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4250 OpLoc, false, false);
4251
4252 input.release();
4253 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4254 &Args[0], NumArgs,
4255 Context.DependentTy,
4256 OpLoc));
4257 }
4258
4259 // Build an empty overload set.
4260 OverloadCandidateSet CandidateSet;
4261
4262 // Add the candidates from the given function set.
4263 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4264
4265 // Add operator candidates that are member functions.
4266 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4267
4268 // Add builtin operator candidates.
4269 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
4270
4271 // Perform overload resolution.
4272 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004273 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00004274 case OR_Success: {
4275 // We found a built-in operator or an overloaded operator.
4276 FunctionDecl *FnDecl = Best->Function;
4277
4278 if (FnDecl) {
4279 // We matched an overloaded operator. Build a call to that
4280 // operator.
4281
4282 // Convert the arguments.
4283 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4284 if (PerformObjectArgumentInitialization(Input, Method))
4285 return ExprError();
4286 } else {
4287 // Convert the arguments.
4288 if (PerformCopyInitialization(Input,
4289 FnDecl->getParamDecl(0)->getType(),
4290 "passing"))
4291 return ExprError();
4292 }
4293
4294 // Determine the result type
4295 QualType ResultTy
4296 = FnDecl->getType()->getAsFunctionType()->getResultType();
4297 ResultTy = ResultTy.getNonReferenceType();
4298
4299 // Build the actual expression node.
4300 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4301 SourceLocation());
4302 UsualUnaryConversions(FnExpr);
4303
4304 input.release();
Anders Carlsson16497742009-08-16 04:11:06 +00004305
4306 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4307 &Input, 1, ResultTy, OpLoc);
4308 return MaybeBindToTemporary(CE);
Douglas Gregorc78182d2009-03-13 23:49:33 +00004309 } else {
4310 // We matched a built-in operator. Convert the arguments, then
4311 // break out so that we will build the appropriate built-in
4312 // operator node.
4313 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4314 Best->Conversions[0], "passing"))
4315 return ExprError();
4316
4317 break;
4318 }
4319 }
4320
4321 case OR_No_Viable_Function:
4322 // No viable function; fall through to handling this as a
4323 // built-in operator, which will produce an error message for us.
4324 break;
4325
4326 case OR_Ambiguous:
4327 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4328 << UnaryOperator::getOpcodeStr(Opc)
4329 << Input->getSourceRange();
4330 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4331 return ExprError();
4332
4333 case OR_Deleted:
4334 Diag(OpLoc, diag::err_ovl_deleted_oper)
4335 << Best->Function->isDeleted()
4336 << UnaryOperator::getOpcodeStr(Opc)
4337 << Input->getSourceRange();
4338 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4339 return ExprError();
4340 }
4341
4342 // Either we found no viable overloaded operator or we matched a
4343 // built-in operator. In either case, fall through to trying to
4344 // build a built-in operation.
4345 input.release();
4346 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4347}
4348
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004349/// \brief Create a binary operation that may resolve to an overloaded
4350/// operator.
4351///
4352/// \param OpLoc The location of the operator itself (e.g., '+').
4353///
4354/// \param OpcIn The BinaryOperator::Opcode that describes this
4355/// operator.
4356///
4357/// \param Functions The set of non-member functions that will be
4358/// considered by overload resolution. The caller needs to build this
4359/// set based on the context using, e.g.,
4360/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4361/// set should not contain any member functions; those will be added
4362/// by CreateOverloadedBinOp().
4363///
4364/// \param LHS Left-hand argument.
4365/// \param RHS Right-hand argument.
4366Sema::OwningExprResult
4367Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
4368 unsigned OpcIn,
4369 FunctionSet &Functions,
4370 Expr *LHS, Expr *RHS) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004371 Expr *Args[2] = { LHS, RHS };
Douglas Gregor114c6192009-08-26 17:08:25 +00004372 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004373
4374 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4375 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4376 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4377
4378 // If either side is type-dependent, create an appropriate dependent
4379 // expression.
Douglas Gregor114c6192009-08-26 17:08:25 +00004380 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004381 // .* cannot be overloaded.
4382 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregor114c6192009-08-26 17:08:25 +00004383 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004384 Context.DependentTy, OpLoc));
4385
4386 OverloadedFunctionDecl *Overloads
4387 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4388 for (FunctionSet::iterator Func = Functions.begin(),
4389 FuncEnd = Functions.end();
4390 Func != FuncEnd; ++Func)
4391 Overloads->addOverload(*Func);
4392
4393 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4394 OpLoc, false, false);
4395
4396 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4397 Args, 2,
4398 Context.DependentTy,
4399 OpLoc));
4400 }
4401
4402 // If this is the .* operator, which is not overloadable, just
4403 // create a built-in binary operator.
4404 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregor114c6192009-08-26 17:08:25 +00004405 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004406
4407 // If this is one of the assignment operators, we only perform
4408 // overload resolution if the left-hand side is a class or
4409 // enumeration type (C++ [expr.ass]p3).
4410 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
Douglas Gregor114c6192009-08-26 17:08:25 +00004411 !Args[0]->getType()->isOverloadableType())
4412 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004413
Douglas Gregorc78182d2009-03-13 23:49:33 +00004414 // Build an empty overload set.
4415 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004416
4417 // Add the candidates from the given function set.
4418 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4419
4420 // Add operator candidates that are member functions.
4421 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4422
4423 // Add builtin operator candidates.
4424 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4425
4426 // Perform overload resolution.
4427 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004428 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00004429 case OR_Success: {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004430 // We found a built-in operator or an overloaded operator.
4431 FunctionDecl *FnDecl = Best->Function;
4432
4433 if (FnDecl) {
4434 // We matched an overloaded operator. Build a call to that
4435 // operator.
4436
4437 // Convert the arguments.
4438 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregor114c6192009-08-26 17:08:25 +00004439 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4440 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004441 "passing"))
4442 return ExprError();
4443 } else {
4444 // Convert the arguments.
Douglas Gregor114c6192009-08-26 17:08:25 +00004445 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004446 "passing") ||
Douglas Gregor114c6192009-08-26 17:08:25 +00004447 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004448 "passing"))
4449 return ExprError();
4450 }
4451
4452 // Determine the result type
4453 QualType ResultTy
4454 = FnDecl->getType()->getAsFunctionType()->getResultType();
4455 ResultTy = ResultTy.getNonReferenceType();
4456
4457 // Build the actual expression node.
4458 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argiris Kirtzidiscca21b82009-07-14 03:19:38 +00004459 OpLoc);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004460 UsualUnaryConversions(FnExpr);
4461
Anders Carlsson16497742009-08-16 04:11:06 +00004462 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4463 Args, 2, ResultTy, OpLoc);
4464 return MaybeBindToTemporary(CE);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004465 } else {
4466 // We matched a built-in operator. Convert the arguments, then
4467 // break out so that we will build the appropriate built-in
4468 // operator node.
Douglas Gregor114c6192009-08-26 17:08:25 +00004469 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004470 Best->Conversions[0], "passing") ||
Douglas Gregor114c6192009-08-26 17:08:25 +00004471 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004472 Best->Conversions[1], "passing"))
4473 return ExprError();
4474
4475 break;
4476 }
4477 }
4478
4479 case OR_No_Viable_Function:
Sebastian Redl35196b42009-05-21 11:50:50 +00004480 // For class as left operand for assignment or compound assigment operator
4481 // do not fall through to handling in built-in, but report that no overloaded
4482 // assignment operator found
Douglas Gregor114c6192009-08-26 17:08:25 +00004483 if (Args[0]->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl35196b42009-05-21 11:50:50 +00004484 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4485 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor114c6192009-08-26 17:08:25 +00004486 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Sebastian Redl35196b42009-05-21 11:50:50 +00004487 return ExprError();
4488 }
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004489 // No viable function; fall through to handling this as a
4490 // built-in operator, which will produce an error message for us.
4491 break;
4492
4493 case OR_Ambiguous:
4494 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4495 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor114c6192009-08-26 17:08:25 +00004496 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004497 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4498 return ExprError();
4499
4500 case OR_Deleted:
4501 Diag(OpLoc, diag::err_ovl_deleted_oper)
4502 << Best->Function->isDeleted()
4503 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor114c6192009-08-26 17:08:25 +00004504 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004505 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4506 return ExprError();
4507 }
4508
4509 // Either we found no viable overloaded operator or we matched a
4510 // built-in operator. In either case, try to build a built-in
4511 // operation.
Douglas Gregor114c6192009-08-26 17:08:25 +00004512 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004513}
4514
Douglas Gregor3257fb52008-12-22 05:46:06 +00004515/// BuildCallToMemberFunction - Build a call to a member
4516/// function. MemExpr is the expression that refers to the member
4517/// function (and includes the object parameter), Args/NumArgs are the
4518/// arguments to the function call (not including the object
4519/// parameter). The caller needs to validate that the member
4520/// expression refers to a member function or an overloaded member
4521/// function.
4522Sema::ExprResult
4523Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4524 SourceLocation LParenLoc, Expr **Args,
4525 unsigned NumArgs, SourceLocation *CommaLocs,
4526 SourceLocation RParenLoc) {
4527 // Dig out the member expression. This holds both the object
4528 // argument and the member function we're referring to.
4529 MemberExpr *MemExpr = 0;
4530 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4531 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4532 else
4533 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4534 assert(MemExpr && "Building member call without member expression");
4535
4536 // Extract the object argument.
4537 Expr *ObjectArg = MemExpr->getBase();
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00004538
Douglas Gregor3257fb52008-12-22 05:46:06 +00004539 CXXMethodDecl *Method = 0;
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004540 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
4541 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00004542 // Add overload candidates
4543 OverloadCandidateSet CandidateSet;
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004544 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
4545
Douglas Gregor050cabf2009-08-21 18:42:58 +00004546 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
4547 Func != FuncEnd; ++Func) {
4548 if ((Method = dyn_cast<CXXMethodDecl>(*Func)))
4549 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
4550 /*SuppressUserConversions=*/false);
4551 else
4552 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
4553 /*FIXME:*/false, /*FIXME:*/0,
4554 /*FIXME:*/0, ObjectArg, Args, NumArgs,
4555 CandidateSet,
4556 /*SuppressUsedConversions=*/false);
4557 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004558
Douglas Gregor3257fb52008-12-22 05:46:06 +00004559 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004560 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00004561 case OR_Success:
4562 Method = cast<CXXMethodDecl>(Best->Function);
4563 break;
4564
4565 case OR_No_Viable_Function:
4566 Diag(MemExpr->getSourceRange().getBegin(),
4567 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004568 << DeclName << MemExprE->getSourceRange();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004569 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4570 // FIXME: Leaking incoming expressions!
4571 return true;
4572
4573 case OR_Ambiguous:
4574 Diag(MemExpr->getSourceRange().getBegin(),
4575 diag::err_ovl_ambiguous_member_call)
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004576 << DeclName << MemExprE->getSourceRange();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004577 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4578 // FIXME: Leaking incoming expressions!
4579 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004580
4581 case OR_Deleted:
4582 Diag(MemExpr->getSourceRange().getBegin(),
4583 diag::err_ovl_deleted_member_call)
4584 << Best->Function->isDeleted()
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004585 << DeclName << MemExprE->getSourceRange();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004586 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4587 // FIXME: Leaking incoming expressions!
4588 return true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00004589 }
4590
4591 FixOverloadedFunctionReference(MemExpr, Method);
4592 } else {
4593 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4594 }
4595
4596 assert(Method && "Member call to something that isn't a method?");
Ted Kremenek0c97e042009-02-07 01:47:29 +00004597 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek362abcd2009-02-09 20:51:47 +00004598 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
4599 NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00004600 Method->getResultType().getNonReferenceType(),
4601 RParenLoc));
4602
4603 // Convert the object argument (for a non-static member function call).
4604 if (!Method->isStatic() &&
4605 PerformObjectArgumentInitialization(ObjectArg, Method))
4606 return true;
4607 MemExpr->setBase(ObjectArg);
4608
4609 // Convert the rest of the arguments
Douglas Gregor4fa58902009-02-26 23:50:07 +00004610 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004611 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
4612 RParenLoc))
4613 return true;
4614
Anders Carlsson7fb13802009-08-16 01:56:34 +00004615 if (CheckFunctionCall(Method, TheCall.get()))
4616 return true;
Anders Carlssonb8ff3402009-08-16 03:42:12 +00004617
4618 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004619}
4620
Douglas Gregor10f3c502008-11-19 21:05:33 +00004621/// BuildCallToObjectOfClassType - Build a call to an object of class
4622/// type (C++ [over.call.object]), which can end up invoking an
4623/// overloaded function call operator (@c operator()) or performing a
4624/// user-defined conversion on the object argument.
Douglas Gregor3257fb52008-12-22 05:46:06 +00004625Sema::ExprResult
Douglas Gregora133e262008-12-06 00:22:45 +00004626Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
4627 SourceLocation LParenLoc,
Douglas Gregor10f3c502008-11-19 21:05:33 +00004628 Expr **Args, unsigned NumArgs,
4629 SourceLocation *CommaLocs,
4630 SourceLocation RParenLoc) {
4631 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004632 const RecordType *Record = Object->getType()->getAs<RecordType>();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004633
4634 // C++ [over.call.object]p1:
4635 // If the primary-expression E in the function call syntax
Eli Friedmand5a72f02009-08-05 19:21:58 +00004636 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor10f3c502008-11-19 21:05:33 +00004637 // candidate functions includes at least the function call
4638 // operators of T. The function call operators of T are obtained by
4639 // ordinary lookup of the name operator() in the context of
4640 // (E).operator().
4641 OverloadCandidateSet CandidateSet;
Douglas Gregor8acb7272008-12-11 16:49:14 +00004642 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004643 DeclContext::lookup_const_iterator Oper, OperEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00004644 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004645 Oper != OperEnd; ++Oper)
4646 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
4647 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004648
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004649 // C++ [over.call.object]p2:
4650 // In addition, for each conversion function declared in T of the
4651 // form
4652 //
4653 // operator conversion-type-id () cv-qualifier;
4654 //
4655 // where cv-qualifier is the same cv-qualification as, or a
4656 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregor261afa72008-11-20 13:33:37 +00004657 // denotes the type "pointer to function of (P1,...,Pn) returning
4658 // R", or the type "reference to pointer to function of
4659 // (P1,...,Pn) returning R", or the type "reference to function
4660 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004661 // is also considered as a candidate function. Similarly,
4662 // surrogate call functions are added to the set of candidate
4663 // functions for each conversion function declared in an
4664 // accessible base class provided the function is not hidden
4665 // within T by another intervening declaration.
Douglas Gregorb35c7992009-08-24 15:23:48 +00004666
4667 if (!RequireCompleteType(SourceLocation(), Object->getType(), 0)) {
4668 // FIXME: Look in base classes for more conversion operators!
4669 OverloadedFunctionDecl *Conversions
4670 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
4671 for (OverloadedFunctionDecl::function_iterator
4672 Func = Conversions->function_begin(),
4673 FuncEnd = Conversions->function_end();
4674 Func != FuncEnd; ++Func) {
4675 CXXConversionDecl *Conv;
4676 FunctionTemplateDecl *ConvTemplate;
4677 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
Douglas Gregor8c860df2009-08-21 23:19:43 +00004678
Douglas Gregorb35c7992009-08-24 15:23:48 +00004679 // Skip over templated conversion functions; they aren't
4680 // surrogates.
4681 if (ConvTemplate)
4682 continue;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004683
Douglas Gregorb35c7992009-08-24 15:23:48 +00004684 // Strip the reference type (if any) and then the pointer type (if
4685 // any) to get down to what might be a function type.
4686 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4687 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4688 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004689
Douglas Gregorb35c7992009-08-24 15:23:48 +00004690 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
4691 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4692 }
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004693 }
Douglas Gregorb35c7992009-08-24 15:23:48 +00004694
Douglas Gregor10f3c502008-11-19 21:05:33 +00004695 // Perform overload resolution.
4696 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004697 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004698 case OR_Success:
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004699 // Overload resolution succeeded; we'll build the appropriate call
4700 // below.
Douglas Gregor10f3c502008-11-19 21:05:33 +00004701 break;
4702
4703 case OR_No_Viable_Function:
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004704 Diag(Object->getSourceRange().getBegin(),
4705 diag::err_ovl_no_viable_object_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004706 << Object->getType() << Object->getSourceRange();
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004707 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004708 break;
4709
4710 case OR_Ambiguous:
4711 Diag(Object->getSourceRange().getBegin(),
4712 diag::err_ovl_ambiguous_object_call)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004713 << Object->getType() << Object->getSourceRange();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004714 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4715 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004716
4717 case OR_Deleted:
4718 Diag(Object->getSourceRange().getBegin(),
4719 diag::err_ovl_deleted_object_call)
4720 << Best->Function->isDeleted()
4721 << Object->getType() << Object->getSourceRange();
4722 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4723 break;
Douglas Gregor10f3c502008-11-19 21:05:33 +00004724 }
4725
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004726 if (Best == CandidateSet.end()) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004727 // We had an error; delete all of the subexpressions and return
4728 // the error.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004729 Object->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004730 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004731 Args[ArgIdx]->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004732 return true;
4733 }
4734
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004735 if (Best->Function == 0) {
4736 // Since there is no function declaration, this is one of the
4737 // surrogate candidates. Dig out the conversion function.
4738 CXXConversionDecl *Conv
4739 = cast<CXXConversionDecl>(
4740 Best->Conversions[0].UserDefined.ConversionFunction);
4741
4742 // We selected one of the surrogate functions that converts the
4743 // object parameter to a function pointer. Perform the conversion
4744 // on the object argument, then let ActOnCallExpr finish the job.
4745 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl8b769972009-01-19 00:08:26 +00004746 ImpCastExprToType(Object,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004747 Conv->getConversionType().getNonReferenceType(),
Anders Carlsson85186942009-07-31 01:23:52 +00004748 CastExpr::CK_Unknown,
Sebastian Redlce6fff02009-03-16 23:22:08 +00004749 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00004750 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4751 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4752 CommaLocs, RParenLoc).release();
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004753 }
4754
4755 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4756 // that calls this method, using Object for the implicit object
4757 // parameter and passing along the remaining arguments.
4758 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor4fa58902009-02-26 23:50:07 +00004759 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004760
4761 unsigned NumArgsInProto = Proto->getNumArgs();
4762 unsigned NumArgsToCheck = NumArgs;
4763
4764 // Build the full argument list for the method call (the
4765 // implicit object parameter is placed at the beginning of the
4766 // list).
4767 Expr **MethodArgs;
4768 if (NumArgs < NumArgsInProto) {
4769 NumArgsToCheck = NumArgsInProto;
4770 MethodArgs = new Expr*[NumArgsInProto + 1];
4771 } else {
4772 MethodArgs = new Expr*[NumArgs + 1];
4773 }
4774 MethodArgs[0] = Object;
4775 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4776 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
4777
Ted Kremenek0c97e042009-02-07 01:47:29 +00004778 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
4779 SourceLocation());
Douglas Gregor10f3c502008-11-19 21:05:33 +00004780 UsualUnaryConversions(NewFn);
4781
4782 // Once we've built TheCall, all of the expressions are properly
4783 // owned.
4784 QualType ResultTy = Method->getResultType().getNonReferenceType();
Ted Kremenek0c97e042009-02-07 01:47:29 +00004785 ExprOwningPtr<CXXOperatorCallExpr>
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004786 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
4787 MethodArgs, NumArgs + 1,
Ted Kremenek0c97e042009-02-07 01:47:29 +00004788 ResultTy, RParenLoc));
Douglas Gregor10f3c502008-11-19 21:05:33 +00004789 delete [] MethodArgs;
4790
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004791 // We may have default arguments. If so, we need to allocate more
4792 // slots in the call for them.
4793 if (NumArgs < NumArgsInProto)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004794 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004795 else if (NumArgs > NumArgsInProto)
4796 NumArgsToCheck = NumArgsInProto;
4797
Chris Lattner81f00ed2009-04-12 08:11:20 +00004798 bool IsError = false;
4799
Douglas Gregor10f3c502008-11-19 21:05:33 +00004800 // Initialize the implicit object parameter.
Chris Lattner81f00ed2009-04-12 08:11:20 +00004801 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004802 TheCall->setArg(0, Object);
4803
Chris Lattner81f00ed2009-04-12 08:11:20 +00004804
Douglas Gregor10f3c502008-11-19 21:05:33 +00004805 // Check the argument types.
4806 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004807 Expr *Arg;
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004808 if (i < NumArgs) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004809 Arg = Args[i];
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004810
4811 // Pass the argument.
4812 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner81f00ed2009-04-12 08:11:20 +00004813 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004814 } else {
Anders Carlsson3d752db2009-08-14 18:30:22 +00004815 Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004816 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004817
4818 TheCall->setArg(i + 1, Arg);
4819 }
4820
4821 // If this is a variadic call, handle args passed through "...".
4822 if (Proto->isVariadic()) {
4823 // Promote the arguments (C99 6.5.2.2p7).
4824 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4825 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00004826 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004827 TheCall->setArg(i + 1, Arg);
4828 }
4829 }
4830
Chris Lattner81f00ed2009-04-12 08:11:20 +00004831 if (IsError) return true;
4832
Anders Carlsson7fb13802009-08-16 01:56:34 +00004833 if (CheckFunctionCall(Method, TheCall.get()))
4834 return true;
4835
Anders Carlsson422a5fe2009-08-16 03:53:54 +00004836 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004837}
4838
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004839/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
4840/// (if one exists), where @c Base is an expression of class type and
4841/// @c Member is the name of the member we're trying to find.
Douglas Gregorda61ad22009-08-06 03:17:00 +00004842Sema::OwningExprResult
4843Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
4844 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004845 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
4846
4847 // C++ [over.ref]p1:
4848 //
4849 // [...] An expression x->m is interpreted as (x.operator->())->m
4850 // for a class object x of type T if T::operator->() exists and if
4851 // the operator is selected as the best match function by the
4852 // overload resolution mechanism (13.3).
4853 // FIXME: look in base classes.
4854 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4855 OverloadCandidateSet CandidateSet;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004856 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorda61ad22009-08-06 03:17:00 +00004857
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004858 DeclContext::lookup_const_iterator Oper, OperEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004859 for (llvm::tie(Oper, OperEnd)
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00004860 = BaseRecord->getDecl()->lookup(OpName); Oper != OperEnd; ++Oper)
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004861 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004862 /*SuppressUserConversions=*/false);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004863
4864 // Perform overload resolution.
4865 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004866 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004867 case OR_Success:
4868 // Overload resolution succeeded; we'll build the call below.
4869 break;
4870
4871 case OR_No_Viable_Function:
4872 if (CandidateSet.empty())
4873 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004874 << Base->getType() << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004875 else
4876 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004877 << "operator->" << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004878 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004879 return ExprError();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004880
4881 case OR_Ambiguous:
4882 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004883 << "operator->" << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004884 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004885 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004886
4887 case OR_Deleted:
4888 Diag(OpLoc, diag::err_ovl_deleted_oper)
4889 << Best->Function->isDeleted()
Douglas Gregorda61ad22009-08-06 03:17:00 +00004890 << "operator->" << Base->getSourceRange();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004891 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004892 return ExprError();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004893 }
4894
4895 // Convert the object parameter.
4896 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9c690e92008-11-21 03:04:22 +00004897 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregorda61ad22009-08-06 03:17:00 +00004898 return ExprError();
Douglas Gregor9c690e92008-11-21 03:04:22 +00004899
4900 // No concerns about early exits now.
Douglas Gregorda61ad22009-08-06 03:17:00 +00004901 BaseIn.release();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004902
4903 // Build the operator call.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004904 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4905 SourceLocation());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004906 UsualUnaryConversions(FnExpr);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004907 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004908 Method->getResultType().getNonReferenceType(),
4909 OpLoc);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004910 return Owned(Base);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004911}
4912
Douglas Gregor45014fd2008-11-10 20:40:00 +00004913/// FixOverloadedFunctionReference - E is an expression that refers to
4914/// a C++ overloaded function (possibly with some parentheses and
4915/// perhaps a '&' around it). We have resolved the overloaded function
4916/// to the function declaration Fn, so patch up the expression E to
4917/// refer (possibly indirectly) to Fn.
4918void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4919 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4920 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4921 E->setType(PE->getSubExpr()->getType());
4922 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
4923 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
4924 "Can only take the address of an overloaded function");
Douglas Gregor3f411962009-02-11 01:18:59 +00004925 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4926 if (Method->isStatic()) {
4927 // Do nothing: static member functions aren't any different
4928 // from non-member functions.
Mike Stump90fc78e2009-08-04 21:02:39 +00004929 } else if (QualifiedDeclRefExpr *DRE
Douglas Gregor3f411962009-02-11 01:18:59 +00004930 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4931 // We have taken the address of a pointer to member
4932 // function. Perform the computation here so that we get the
4933 // appropriate pointer to member type.
4934 DRE->setDecl(Fn);
4935 DRE->setType(Fn->getType());
4936 QualType ClassType
4937 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
4938 E->setType(Context.getMemberPointerType(Fn->getType(),
4939 ClassType.getTypePtr()));
4940 return;
4941 }
4942 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00004943 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregor2eedd992009-02-11 00:19:33 +00004944 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregor45014fd2008-11-10 20:40:00 +00004945 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor62f78762009-07-08 20:55:45 +00004946 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
4947 isa<FunctionTemplateDecl>(DR->getDecl())) &&
4948 "Expected overloaded function or function template");
Douglas Gregor45014fd2008-11-10 20:40:00 +00004949 DR->setDecl(Fn);
4950 E->setType(Fn->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004951 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4952 MemExpr->setMemberDecl(Fn);
4953 E->setType(Fn->getType());
Douglas Gregor45014fd2008-11-10 20:40:00 +00004954 } else {
4955 assert(false && "Invalid reference to overloaded function");
4956 }
4957}
4958
Douglas Gregord2baafd2008-10-21 16:13:35 +00004959} // end namespace clang