blob: 0a65a36b47bb17e8f80eeb8b553e13c8a8a1fd73 [file] [log] [blame]
Douglas Gregord2baafd2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregorbb461502008-10-24 04:54:22 +000015#include "SemaInherit.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregor70d26122008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
Douglas Gregor10f3c502008-11-19 21:05:33 +000020#include "clang/AST/ExprCXX.h"
Douglas Gregor70d26122008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Douglas Gregor3d4492e2008-11-13 20:12:29 +000022#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregorddfd9d52008-12-23 00:26:44 +000023#include "llvm/ADT/STLExtras.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000024#include "llvm/Support/Compiler.h"
25#include <algorithm>
Edwin Török0fbc71c2009-08-24 13:25:12 +000026#include <cstdio>
Douglas Gregord2baafd2008-10-21 16:13:35 +000027
28namespace clang {
29
30/// GetConversionCategory - Retrieve the implicit conversion
31/// category corresponding to the given implicit conversion kind.
32ImplicitConversionCategory
33GetConversionCategory(ImplicitConversionKind Kind) {
34 static const ImplicitConversionCategory
35 Category[(int)ICK_Num_Conversion_Kinds] = {
36 ICC_Identity,
37 ICC_Lvalue_Transformation,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Qualification_Adjustment,
41 ICC_Promotion,
42 ICC_Promotion,
Douglas Gregore819caf2009-02-12 00:15:05 +000043 ICC_Promotion,
44 ICC_Conversion,
45 ICC_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000046 ICC_Conversion,
47 ICC_Conversion,
48 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
Douglas Gregor2aecd1f2008-10-29 02:00:59 +000051 ICC_Conversion,
Douglas Gregorfcb19192009-02-11 23:02:49 +000052 ICC_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000053 ICC_Conversion
54 };
55 return Category[(int)Kind];
56}
57
58/// GetConversionRank - Retrieve the implicit conversion rank
59/// corresponding to the given implicit conversion kind.
60ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
61 static const ImplicitConversionRank
62 Rank[(int)ICK_Num_Conversion_Kinds] = {
63 ICR_Exact_Match,
64 ICR_Exact_Match,
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Promotion,
69 ICR_Promotion,
Douglas Gregore819caf2009-02-12 00:15:05 +000070 ICR_Promotion,
71 ICR_Conversion,
72 ICR_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000073 ICR_Conversion,
74 ICR_Conversion,
75 ICR_Conversion,
76 ICR_Conversion,
77 ICR_Conversion,
Douglas Gregor2aecd1f2008-10-29 02:00:59 +000078 ICR_Conversion,
Douglas Gregorfcb19192009-02-11 23:02:49 +000079 ICR_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000080 ICR_Conversion
81 };
82 return Rank[(int)Kind];
83}
84
85/// GetImplicitConversionName - Return the name of this kind of
86/// implicit conversion.
87const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
88 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
89 "No conversion",
90 "Lvalue-to-rvalue",
91 "Array-to-pointer",
92 "Function-to-pointer",
93 "Qualification",
94 "Integral promotion",
95 "Floating point promotion",
Douglas Gregore819caf2009-02-12 00:15:05 +000096 "Complex promotion",
Douglas Gregord2baafd2008-10-21 16:13:35 +000097 "Integral conversion",
98 "Floating conversion",
Douglas Gregore819caf2009-02-12 00:15:05 +000099 "Complex conversion",
Douglas Gregord2baafd2008-10-21 16:13:35 +0000100 "Floating-integral conversion",
Douglas Gregore819caf2009-02-12 00:15:05 +0000101 "Complex-real conversion",
Douglas Gregord2baafd2008-10-21 16:13:35 +0000102 "Pointer conversion",
103 "Pointer-to-member conversion",
Douglas Gregor2aecd1f2008-10-29 02:00:59 +0000104 "Boolean conversion",
Douglas Gregorfcb19192009-02-11 23:02:49 +0000105 "Compatible-types conversion",
Douglas Gregor2aecd1f2008-10-29 02:00:59 +0000106 "Derived-to-base conversion"
Douglas Gregord2baafd2008-10-21 16:13:35 +0000107 };
108 return Name[Kind];
109}
110
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000111/// StandardConversionSequence - Set the standard conversion
112/// sequence to the identity conversion.
113void StandardConversionSequence::setAsIdentityConversion() {
114 First = ICK_Identity;
115 Second = ICK_Identity;
116 Third = ICK_Identity;
117 Deprecated = false;
118 ReferenceBinding = false;
119 DirectBinding = false;
Sebastian Redl9bc16ad2009-03-29 22:46:24 +0000120 RRefBinding = false;
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000121 CopyConstructor = 0;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000122}
123
Douglas Gregord2baafd2008-10-21 16:13:35 +0000124/// getRank - Retrieve the rank of this standard conversion sequence
125/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
126/// implicit conversions.
127ImplicitConversionRank StandardConversionSequence::getRank() const {
128 ImplicitConversionRank Rank = ICR_Exact_Match;
129 if (GetConversionRank(First) > Rank)
130 Rank = GetConversionRank(First);
131 if (GetConversionRank(Second) > Rank)
132 Rank = GetConversionRank(Second);
133 if (GetConversionRank(Third) > Rank)
134 Rank = GetConversionRank(Third);
135 return Rank;
136}
137
138/// isPointerConversionToBool - Determines whether this conversion is
139/// a conversion of a pointer or pointer-to-member to bool. This is
140/// used as part of the ranking of standard conversion sequences
141/// (C++ 13.3.3.2p4).
142bool StandardConversionSequence::isPointerConversionToBool() const
143{
144 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
145 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
146
147 // Note that FromType has not necessarily been transformed by the
148 // array-to-pointer or function-to-pointer implicit conversions, so
149 // check for their presence as well as checking whether FromType is
150 // a pointer.
151 if (ToType->isBooleanType() &&
Douglas Gregor80402cf2008-12-23 00:53:59 +0000152 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregord2baafd2008-10-21 16:13:35 +0000153 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
154 return true;
155
156 return false;
157}
158
Douglas Gregor14046502008-10-23 00:40:37 +0000159/// isPointerConversionToVoidPointer - Determines whether this
160/// conversion is a conversion of a pointer to a void pointer. This is
161/// used as part of the ranking of standard conversion sequences (C++
162/// 13.3.3.2p4).
163bool
164StandardConversionSequence::
165isPointerConversionToVoidPointer(ASTContext& Context) const
166{
167 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
168 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
169
170 // Note that FromType has not necessarily been transformed by the
171 // array-to-pointer implicit conversion, so check for its presence
172 // and redo the conversion to get a pointer.
173 if (First == ICK_Array_To_Pointer)
174 FromType = Context.getArrayDecayedType(FromType);
175
176 if (Second == ICK_Pointer_Conversion)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000177 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor14046502008-10-23 00:40:37 +0000178 return ToPtrType->getPointeeType()->isVoidType();
179
180 return false;
181}
182
Douglas Gregord2baafd2008-10-21 16:13:35 +0000183/// DebugPrint - Print this standard conversion sequence to standard
184/// error. Useful for debugging overloading issues.
185void StandardConversionSequence::DebugPrint() const {
186 bool PrintedSomething = false;
187 if (First != ICK_Identity) {
188 fprintf(stderr, "%s", GetImplicitConversionName(First));
189 PrintedSomething = true;
190 }
191
192 if (Second != ICK_Identity) {
193 if (PrintedSomething) {
194 fprintf(stderr, " -> ");
195 }
196 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000197
198 if (CopyConstructor) {
199 fprintf(stderr, " (by copy constructor)");
200 } else if (DirectBinding) {
201 fprintf(stderr, " (direct reference binding)");
202 } else if (ReferenceBinding) {
203 fprintf(stderr, " (reference binding)");
204 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000205 PrintedSomething = true;
206 }
207
208 if (Third != ICK_Identity) {
209 if (PrintedSomething) {
210 fprintf(stderr, " -> ");
211 }
212 fprintf(stderr, "%s", GetImplicitConversionName(Third));
213 PrintedSomething = true;
214 }
215
216 if (!PrintedSomething) {
217 fprintf(stderr, "No conversions required");
218 }
219}
220
221/// DebugPrint - Print this user-defined conversion sequence to standard
222/// error. Useful for debugging overloading issues.
223void UserDefinedConversionSequence::DebugPrint() const {
224 if (Before.First || Before.Second || Before.Third) {
225 Before.DebugPrint();
226 fprintf(stderr, " -> ");
227 }
Chris Lattner271d4c22008-11-24 05:29:24 +0000228 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregord2baafd2008-10-21 16:13:35 +0000229 if (After.First || After.Second || After.Third) {
230 fprintf(stderr, " -> ");
231 After.DebugPrint();
232 }
233}
234
235/// DebugPrint - Print this implicit conversion sequence to standard
236/// error. Useful for debugging overloading issues.
237void ImplicitConversionSequence::DebugPrint() const {
238 switch (ConversionKind) {
239 case StandardConversion:
240 fprintf(stderr, "Standard conversion: ");
241 Standard.DebugPrint();
242 break;
243 case UserDefinedConversion:
244 fprintf(stderr, "User-defined conversion: ");
245 UserDefined.DebugPrint();
246 break;
247 case EllipsisConversion:
248 fprintf(stderr, "Ellipsis conversion");
249 break;
250 case BadConversion:
251 fprintf(stderr, "Bad conversion");
252 break;
253 }
254
255 fprintf(stderr, "\n");
256}
257
258// IsOverload - Determine whether the given New declaration is an
259// overload of the Old declaration. This routine returns false if New
260// and Old cannot be overloaded, e.g., if they are functions with the
261// same signature (C++ 1.3.10) or if the Old declaration isn't a
262// function (or overload set). When it does return false and Old is an
263// OverloadedFunctionDecl, MatchedDecl will be set to point to the
264// FunctionDecl that New cannot be overloaded with.
265//
266// Example: Given the following input:
267//
268// void f(int, float); // #1
269// void f(int, int); // #2
270// int f(int, int); // #3
271//
272// When we process #1, there is no previous declaration of "f",
273// so IsOverload will not be used.
274//
275// When we process #2, Old is a FunctionDecl for #1. By comparing the
276// parameter types, we see that #1 and #2 are overloaded (since they
277// have different signatures), so this routine returns false;
278// MatchedDecl is unchanged.
279//
280// When we process #3, Old is an OverloadedFunctionDecl containing #1
281// and #2. We compare the signatures of #3 to #1 (they're overloaded,
282// so we do nothing) and then #3 to #2. Since the signatures of #3 and
283// #2 are identical (return types of functions are not part of the
284// signature), IsOverload returns false and MatchedDecl will be set to
285// point to the FunctionDecl for #2.
286bool
287Sema::IsOverload(FunctionDecl *New, Decl* OldD,
288 OverloadedFunctionDecl::function_iterator& MatchedDecl)
289{
290 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
291 // Is this new function an overload of every function in the
292 // overload set?
293 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
294 FuncEnd = Ovl->function_end();
295 for (; Func != FuncEnd; ++Func) {
296 if (!IsOverload(New, *Func, MatchedDecl)) {
297 MatchedDecl = Func;
298 return false;
299 }
300 }
301
302 // This function overloads every function in the overload set.
303 return true;
Douglas Gregorb60eb752009-06-25 22:08:12 +0000304 } else if (FunctionTemplateDecl *Old = dyn_cast<FunctionTemplateDecl>(OldD))
305 return IsOverload(New, Old->getTemplatedDecl(), MatchedDecl);
306 else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000307 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
308 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
309
310 // C++ [temp.fct]p2:
311 // A function template can be overloaded with other function templates
312 // and with normal (non-template) functions.
313 if ((OldTemplate == 0) != (NewTemplate == 0))
314 return true;
315
Douglas Gregord2baafd2008-10-21 16:13:35 +0000316 // Is the function New an overload of the function Old?
317 QualType OldQType = Context.getCanonicalType(Old->getType());
318 QualType NewQType = Context.getCanonicalType(New->getType());
319
320 // Compare the signatures (C++ 1.3.10) of the two functions to
321 // determine whether they are overloads. If we find any mismatch
322 // in the signature, they are overloads.
323
324 // If either of these functions is a K&R-style function (no
325 // prototype), then we consider them to have matching signatures.
Douglas Gregor4fa58902009-02-26 23:50:07 +0000326 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
327 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
Douglas Gregord2baafd2008-10-21 16:13:35 +0000328 return false;
329
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000330 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
331 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000332
333 // The signature of a function includes the types of its
334 // parameters (C++ 1.3.10), which includes the presence or absence
335 // of the ellipsis; see C++ DR 357).
336 if (OldQType != NewQType &&
337 (OldType->getNumArgs() != NewType->getNumArgs() ||
338 OldType->isVariadic() != NewType->isVariadic() ||
339 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
340 NewType->arg_type_begin())))
341 return true;
342
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000343 // C++ [temp.over.link]p4:
344 // The signature of a function template consists of its function
345 // signature, its return type and its template parameter list. The names
346 // of the template parameters are significant only for establishing the
347 // relationship between the template parameters and the rest of the
348 // signature.
349 //
350 // We check the return type and template parameter lists for function
351 // templates first; the remaining checks follow.
352 if (NewTemplate &&
353 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
354 OldTemplate->getTemplateParameters(),
355 false, false, SourceLocation()) ||
356 OldType->getResultType() != NewType->getResultType()))
357 return true;
358
Douglas Gregord2baafd2008-10-21 16:13:35 +0000359 // If the function is a class member, its signature includes the
360 // cv-qualifiers (if any) on the function itself.
361 //
362 // As part of this, also check whether one of the member functions
363 // is static, in which case they are not overloads (C++
364 // 13.1p2). While not part of the definition of the signature,
365 // this check is important to determine whether these functions
366 // can be overloaded.
367 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
368 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
369 if (OldMethod && NewMethod &&
370 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregora7b56a32008-11-21 15:36:28 +0000371 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregord2baafd2008-10-21 16:13:35 +0000372 return true;
373
374 // The signatures match; this is not an overload.
375 return false;
376 } else {
377 // (C++ 13p1):
378 // Only function declarations can be overloaded; object and type
379 // declarations cannot be overloaded.
380 return false;
381 }
382}
383
Douglas Gregor81c29152008-10-29 00:13:59 +0000384/// TryImplicitConversion - Attempt to perform an implicit conversion
385/// from the given expression (Expr) to the given type (ToType). This
386/// function returns an implicit conversion sequence that can be used
387/// to perform the initialization. Given
Douglas Gregord2baafd2008-10-21 16:13:35 +0000388///
389/// void f(float f);
390/// void g(int i) { f(i); }
391///
392/// this routine would produce an implicit conversion sequence to
393/// describe the initialization of f from i, which will be a standard
394/// conversion sequence containing an lvalue-to-rvalue conversion (C++
395/// 4.1) followed by a floating-integral conversion (C++ 4.9).
396//
397/// Note that this routine only determines how the conversion can be
398/// performed; it does not actually perform the conversion. As such,
399/// it will not produce any diagnostics if no conversion is available,
400/// but will instead return an implicit conversion sequence of kind
401/// "BadConversion".
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000402///
403/// If @p SuppressUserConversions, then user-defined conversions are
404/// not permitted.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000405/// If @p AllowExplicit, then explicit user-defined conversions are
406/// permitted.
Sebastian Redla55834a2009-04-12 17:16:29 +0000407/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
408/// no matter its actual lvalueness.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000409ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000410Sema::TryImplicitConversion(Expr* From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000411 bool SuppressUserConversions,
Sebastian Redla55834a2009-04-12 17:16:29 +0000412 bool AllowExplicit, bool ForceRValue)
Douglas Gregord2baafd2008-10-21 16:13:35 +0000413{
414 ImplicitConversionSequence ICS;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000415 if (IsStandardConversion(From, ToType, ICS.Standard))
416 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000417 else if (getLangOptions().CPlusPlus &&
418 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Sebastian Redla55834a2009-04-12 17:16:29 +0000419 !SuppressUserConversions, AllowExplicit,
420 ForceRValue)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000421 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregore640ab62008-11-03 17:51:48 +0000422 // C++ [over.ics.user]p4:
423 // A conversion of an expression of class type to the same class
424 // type is given Exact Match rank, and a conversion of an
425 // expression of class type to a base class of that type is
426 // given Conversion rank, in spite of the fact that a copy
427 // constructor (i.e., a user-defined conversion function) is
428 // called for those cases.
429 if (CXXConstructorDecl *Constructor
430 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Douglas Gregord9176392009-02-02 22:11:10 +0000431 QualType FromCanon
432 = Context.getCanonicalType(From->getType().getUnqualifiedType());
433 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
434 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000435 // Turn this into a "standard" conversion sequence, so that it
436 // gets ranked with standard conversion sequences.
Douglas Gregore640ab62008-11-03 17:51:48 +0000437 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
438 ICS.Standard.setAsIdentityConversion();
439 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
440 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000441 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregord9176392009-02-02 22:11:10 +0000442 if (ToCanon != FromCanon)
Douglas Gregore640ab62008-11-03 17:51:48 +0000443 ICS.Standard.Second = ICK_Derived_To_Base;
444 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000445 }
Douglas Gregorb206cc42009-01-30 23:27:23 +0000446
447 // C++ [over.best.ics]p4:
448 // However, when considering the argument of a user-defined
449 // conversion function that is a candidate by 13.3.1.3 when
450 // invoked for the copying of the temporary in the second step
451 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
452 // 13.3.1.6 in all cases, only standard conversion sequences and
453 // ellipsis conversion sequences are allowed.
454 if (SuppressUserConversions &&
455 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
456 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregore640ab62008-11-03 17:51:48 +0000457 } else
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000458 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000459
460 return ICS;
461}
462
463/// IsStandardConversion - Determines whether there is a standard
464/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
465/// expression From to the type ToType. Standard conversion sequences
466/// only consider non-class types; for conversions that involve class
467/// types, use TryImplicitConversion. If a conversion exists, SCS will
468/// contain the standard conversion sequence required to perform this
469/// conversion and this routine will return true. Otherwise, this
470/// routine will return false and the value of SCS is unspecified.
471bool
472Sema::IsStandardConversion(Expr* From, QualType ToType,
473 StandardConversionSequence &SCS)
474{
Douglas Gregord2baafd2008-10-21 16:13:35 +0000475 QualType FromType = From->getType();
476
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000477 // Standard conversions (C++ [conv])
Douglas Gregor70d26122008-11-12 17:17:38 +0000478 SCS.setAsIdentityConversion();
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000479 SCS.Deprecated = false;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000480 SCS.IncompatibleObjC = false;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000481 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000482 SCS.CopyConstructor = 0;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000483
Douglas Gregorfcb19192009-02-11 23:02:49 +0000484 // There are no standard conversions for class types in C++, so
485 // abort early. When overloading in C, however, we do permit
486 if (FromType->isRecordType() || ToType->isRecordType()) {
487 if (getLangOptions().CPlusPlus)
488 return false;
489
490 // When we're overloading in C, we allow, as standard conversions,
491 }
492
Douglas Gregord2baafd2008-10-21 16:13:35 +0000493 // The first conversion can be an lvalue-to-rvalue conversion,
494 // array-to-pointer conversion, or function-to-pointer conversion
495 // (C++ 4p1).
496
497 // Lvalue-to-rvalue conversion (C++ 4.1):
498 // An lvalue (3.10) of a non-function, non-array type T can be
499 // converted to an rvalue.
500 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
501 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor45014fd2008-11-10 20:40:00 +0000502 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000503 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000504 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000505
506 // If T is a non-class type, the type of the rvalue is the
507 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorfcb19192009-02-11 23:02:49 +0000508 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
509 // just strip the qualifiers because they don't matter.
510
511 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000512 FromType = FromType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000513 } else if (FromType->isArrayType()) {
514 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000515 SCS.First = ICK_Array_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000516
517 // An lvalue or rvalue of type "array of N T" or "array of unknown
518 // bound of T" can be converted to an rvalue of type "pointer to
519 // T" (C++ 4.2p1).
520 FromType = Context.getArrayDecayedType(FromType);
521
522 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
523 // This conversion is deprecated. (C++ D.4).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000524 SCS.Deprecated = true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000525
526 // For the purpose of ranking in overload resolution
527 // (13.3.3.1.1), this conversion is considered an
528 // array-to-pointer conversion followed by a qualification
529 // conversion (4.4). (C++ 4.2p2)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000530 SCS.Second = ICK_Identity;
531 SCS.Third = ICK_Qualification;
532 SCS.ToTypePtr = ToType.getAsOpaquePtr();
533 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000534 }
Mike Stump90fc78e2009-08-04 21:02:39 +0000535 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
536 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000537 SCS.First = ICK_Function_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000538
539 // An lvalue of function type T can be converted to an rvalue of
540 // type "pointer to T." The result is a pointer to the
541 // function. (C++ 4.3p1).
542 FromType = Context.getPointerType(FromType);
Mike Stump90fc78e2009-08-04 21:02:39 +0000543 } else if (FunctionDecl *Fn
Douglas Gregor45014fd2008-11-10 20:40:00 +0000544 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump90fc78e2009-08-04 21:02:39 +0000545 // Address of overloaded function (C++ [over.over]).
Douglas Gregor45014fd2008-11-10 20:40:00 +0000546 SCS.First = ICK_Function_To_Pointer;
547
548 // We were able to resolve the address of the overloaded function,
549 // so we can convert to the type of that function.
550 FromType = Fn->getType();
Sebastian Redlce6fff02009-03-16 23:22:08 +0000551 if (ToType->isLValueReferenceType())
552 FromType = Context.getLValueReferenceType(FromType);
553 else if (ToType->isRValueReferenceType())
554 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl7434fc32009-02-04 21:23:32 +0000555 else if (ToType->isMemberPointerType()) {
556 // Resolve address only succeeds if both sides are member pointers,
557 // but it doesn't have to be the same class. See DR 247.
558 // Note that this means that the type of &Derived::fn can be
559 // Ret (Base::*)(Args) if the fn overload actually found is from the
560 // base class, even if it was brought into the derived class via a
561 // using declaration. The standard isn't clear on this issue at all.
562 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
563 FromType = Context.getMemberPointerType(FromType,
564 Context.getTypeDeclType(M->getParent()).getTypePtr());
565 } else
Douglas Gregor45014fd2008-11-10 20:40:00 +0000566 FromType = Context.getPointerType(FromType);
Mike Stump90fc78e2009-08-04 21:02:39 +0000567 } else {
568 // We don't require any conversions for the first step.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000569 SCS.First = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000570 }
571
572 // The second conversion can be an integral promotion, floating
573 // point promotion, integral conversion, floating point conversion,
574 // floating-integral conversion, pointer conversion,
575 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorfcb19192009-02-11 23:02:49 +0000576 // For overloading in C, this can also be a "compatible-type"
577 // conversion.
Douglas Gregor6fd35572008-12-19 17:40:08 +0000578 bool IncompatibleObjC = false;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000579 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000580 // The unqualified versions of the types are the same: there's no
581 // conversion to do.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000582 SCS.Second = ICK_Identity;
Mike Stump90fc78e2009-08-04 21:02:39 +0000583 } else if (IsIntegralPromotion(From, FromType, ToType)) {
584 // Integral promotion (C++ 4.5).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000585 SCS.Second = ICK_Integral_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000586 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000587 } else if (IsFloatingPointPromotion(FromType, ToType)) {
588 // Floating point promotion (C++ 4.6).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000589 SCS.Second = ICK_Floating_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000590 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000591 } else if (IsComplexPromotion(FromType, ToType)) {
592 // Complex promotion (Clang extension)
Douglas Gregore819caf2009-02-12 00:15:05 +0000593 SCS.Second = ICK_Complex_Promotion;
594 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000595 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000596 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump90fc78e2009-08-04 21:02:39 +0000597 // Integral conversions (C++ 4.7).
598 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000599 SCS.Second = ICK_Integral_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000600 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000601 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
602 // Floating point conversions (C++ 4.8).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000603 SCS.Second = ICK_Floating_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000604 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000605 } else if (FromType->isComplexType() && ToType->isComplexType()) {
606 // Complex conversions (C99 6.3.1.6)
Douglas Gregore819caf2009-02-12 00:15:05 +0000607 SCS.Second = ICK_Complex_Conversion;
608 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000609 } else if ((FromType->isFloatingType() &&
610 ToType->isIntegralType() && (!ToType->isBooleanType() &&
611 !ToType->isEnumeralType())) ||
612 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
613 ToType->isFloatingType())) {
614 // Floating-integral conversions (C++ 4.9).
615 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000616 SCS.Second = ICK_Floating_Integral;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000617 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000618 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
619 (ToType->isComplexType() && FromType->isArithmeticType())) {
620 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregore819caf2009-02-12 00:15:05 +0000621 SCS.Second = ICK_Complex_Real;
622 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000623 } else if (IsPointerConversion(From, FromType, ToType, FromType,
624 IncompatibleObjC)) {
625 // Pointer conversions (C++ 4.10).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000626 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000627 SCS.IncompatibleObjC = IncompatibleObjC;
Mike Stump90fc78e2009-08-04 21:02:39 +0000628 } else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
629 // Pointer to member conversions (4.11).
Sebastian Redlba387562009-01-25 19:43:20 +0000630 SCS.Second = ICK_Pointer_Member;
Mike Stump90fc78e2009-08-04 21:02:39 +0000631 } else if (ToType->isBooleanType() &&
632 (FromType->isArithmeticType() ||
633 FromType->isEnumeralType() ||
634 FromType->isPointerType() ||
635 FromType->isBlockPointerType() ||
636 FromType->isMemberPointerType() ||
637 FromType->isNullPtrType())) {
638 // Boolean conversions (C++ 4.12).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000639 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000640 FromType = Context.BoolTy;
Mike Stump90fc78e2009-08-04 21:02:39 +0000641 } else if (!getLangOptions().CPlusPlus &&
642 Context.typesAreCompatible(ToType, FromType)) {
643 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorfcb19192009-02-11 23:02:49 +0000644 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000645 } else {
646 // No second conversion required.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000647 SCS.Second = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000648 }
649
Douglas Gregor81c29152008-10-29 00:13:59 +0000650 QualType CanonFrom;
651 QualType CanonTo;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000652 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor6573cfd2008-10-21 23:43:52 +0000653 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000654 SCS.Third = ICK_Qualification;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000655 FromType = ToType;
Douglas Gregor81c29152008-10-29 00:13:59 +0000656 CanonFrom = Context.getCanonicalType(FromType);
657 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000658 } else {
659 // No conversion required
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000660 SCS.Third = ICK_Identity;
661
662 // C++ [over.best.ics]p6:
663 // [...] Any difference in top-level cv-qualification is
664 // subsumed by the initialization itself and does not constitute
665 // a conversion. [...]
Douglas Gregor81c29152008-10-29 00:13:59 +0000666 CanonFrom = Context.getCanonicalType(FromType);
667 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000668 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor81c29152008-10-29 00:13:59 +0000669 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
670 FromType = ToType;
671 CanonFrom = CanonTo;
672 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000673 }
674
675 // If we have not converted the argument type to the parameter type,
676 // this is a bad conversion sequence.
Douglas Gregor81c29152008-10-29 00:13:59 +0000677 if (CanonFrom != CanonTo)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000678 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000679
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000680 SCS.ToTypePtr = FromType.getAsOpaquePtr();
681 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000682}
683
684/// IsIntegralPromotion - Determines whether the conversion from the
685/// expression From (whose potentially-adjusted type is FromType) to
686/// ToType is an integral promotion (C++ 4.5). If so, returns true and
687/// sets PromotedType to the promoted type.
688bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
689{
690 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redl12aee862008-11-04 15:59:10 +0000691 // All integers are built-in.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000692 if (!To) {
693 return false;
694 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000695
696 // An rvalue of type char, signed char, unsigned char, short int, or
697 // unsigned short int can be converted to an rvalue of type int if
698 // int can represent all the values of the source type; otherwise,
699 // the source rvalue can be converted to an rvalue of type unsigned
700 // int (C++ 4.5p1).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000701 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000702 if (// We can promote any signed, promotable integer type to an int
703 (FromType->isSignedIntegerType() ||
704 // We can promote any unsigned integer type whose size is
705 // less than int to an int.
706 (!FromType->isSignedIntegerType() &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000707 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000708 return To->getKind() == BuiltinType::Int;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000709 }
710
Douglas Gregord2baafd2008-10-21 16:13:35 +0000711 return To->getKind() == BuiltinType::UInt;
712 }
713
714 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
715 // can be converted to an rvalue of the first of the following types
716 // that can represent all the values of its underlying type: int,
717 // unsigned int, long, or unsigned long (C++ 4.5p2).
718 if ((FromType->isEnumeralType() || FromType->isWideCharType())
719 && ToType->isIntegerType()) {
720 // Determine whether the type we're converting from is signed or
721 // unsigned.
722 bool FromIsSigned;
723 uint64_t FromSize = Context.getTypeSize(FromType);
724 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
725 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
726 FromIsSigned = UnderlyingType->isSignedIntegerType();
727 } else {
728 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
729 FromIsSigned = true;
730 }
731
732 // The types we'll try to promote to, in the appropriate
733 // order. Try each of these types.
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000734 QualType PromoteTypes[6] = {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000735 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000736 Context.LongTy, Context.UnsignedLongTy ,
737 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregord2baafd2008-10-21 16:13:35 +0000738 };
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000739 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000740 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
741 if (FromSize < ToSize ||
742 (FromSize == ToSize &&
743 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
744 // We found the type that we can promote to. If this is the
745 // type we wanted, we have a promotion. Otherwise, no
746 // promotion.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000747 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregord2baafd2008-10-21 16:13:35 +0000748 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
749 }
750 }
751 }
752
753 // An rvalue for an integral bit-field (9.6) can be converted to an
754 // rvalue of type int if int can represent all the values of the
755 // bit-field; otherwise, it can be converted to unsigned int if
756 // unsigned int can represent all the values of the bit-field. If
757 // the bit-field is larger yet, no integral promotion applies to
758 // it. If the bit-field has an enumerated type, it is treated as any
759 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stumpe127ae32009-05-16 07:39:55 +0000760 // FIXME: We should delay checking of bit-fields until we actually perform the
761 // conversion.
Douglas Gregor531434b2009-05-02 02:18:30 +0000762 using llvm::APSInt;
763 if (From)
764 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor82d44772008-12-20 23:49:58 +0000765 APSInt BitWidth;
Douglas Gregor531434b2009-05-02 02:18:30 +0000766 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
767 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
768 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
769 ToSize = Context.getTypeSize(ToType);
Douglas Gregor82d44772008-12-20 23:49:58 +0000770
771 // Are we promoting to an int from a bitfield that fits in an int?
772 if (BitWidth < ToSize ||
773 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
774 return To->getKind() == BuiltinType::Int;
775 }
776
777 // Are we promoting to an unsigned int from an unsigned bitfield
778 // that fits into an unsigned int?
779 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
780 return To->getKind() == BuiltinType::UInt;
781 }
782
783 return false;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000784 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000785 }
Douglas Gregor531434b2009-05-02 02:18:30 +0000786
Douglas Gregord2baafd2008-10-21 16:13:35 +0000787 // An rvalue of type bool can be converted to an rvalue of type int,
788 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000789 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000790 return true;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000791 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000792
793 return false;
794}
795
796/// IsFloatingPointPromotion - Determines whether the conversion from
797/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
798/// returns true and sets PromotedType to the promoted type.
799bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
800{
801 /// An rvalue of type float can be converted to an rvalue of type
802 /// double. (C++ 4.6p1).
803 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
Douglas Gregore819caf2009-02-12 00:15:05 +0000804 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000805 if (FromBuiltin->getKind() == BuiltinType::Float &&
806 ToBuiltin->getKind() == BuiltinType::Double)
807 return true;
808
Douglas Gregore819caf2009-02-12 00:15:05 +0000809 // C99 6.3.1.5p1:
810 // When a float is promoted to double or long double, or a
811 // double is promoted to long double [...].
812 if (!getLangOptions().CPlusPlus &&
813 (FromBuiltin->getKind() == BuiltinType::Float ||
814 FromBuiltin->getKind() == BuiltinType::Double) &&
815 (ToBuiltin->getKind() == BuiltinType::LongDouble))
816 return true;
817 }
818
Douglas Gregord2baafd2008-10-21 16:13:35 +0000819 return false;
820}
821
Douglas Gregore819caf2009-02-12 00:15:05 +0000822/// \brief Determine if a conversion is a complex promotion.
823///
824/// A complex promotion is defined as a complex -> complex conversion
825/// where the conversion between the underlying real types is a
Douglas Gregor4ff48512009-02-12 00:26:06 +0000826/// floating-point or integral promotion.
Douglas Gregore819caf2009-02-12 00:15:05 +0000827bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
828 const ComplexType *FromComplex = FromType->getAsComplexType();
829 if (!FromComplex)
830 return false;
831
832 const ComplexType *ToComplex = ToType->getAsComplexType();
833 if (!ToComplex)
834 return false;
835
836 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor4ff48512009-02-12 00:26:06 +0000837 ToComplex->getElementType()) ||
838 IsIntegralPromotion(0, FromComplex->getElementType(),
839 ToComplex->getElementType());
Douglas Gregore819caf2009-02-12 00:15:05 +0000840}
841
Douglas Gregor24a90a52008-11-26 23:31:11 +0000842/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
843/// the pointer type FromPtr to a pointer to type ToPointee, with the
844/// same type qualifiers as FromPtr has on its pointee type. ToType,
845/// if non-empty, will be a pointer to ToType that may or may not have
846/// the right set of qualifiers on its pointee.
847static QualType
848BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
849 QualType ToPointee, QualType ToType,
850 ASTContext &Context) {
851 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
852 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
853 unsigned Quals = CanonFromPointee.getCVRQualifiers();
854
855 // Exact qualifier match -> return the pointer type we're converting to.
856 if (CanonToPointee.getCVRQualifiers() == Quals) {
857 // ToType is exactly what we need. Return it.
858 if (ToType.getTypePtr())
859 return ToType;
860
861 // Build a pointer to ToPointee. It has the right qualifiers
862 // already.
863 return Context.getPointerType(ToPointee);
864 }
865
866 // Just build a canonical type that has the right qualifiers.
867 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
868}
869
Douglas Gregord2baafd2008-10-21 16:13:35 +0000870/// IsPointerConversion - Determines whether the conversion of the
871/// expression From, which has the (possibly adjusted) type FromType,
872/// can be converted to the type ToType via a pointer conversion (C++
873/// 4.10). If so, returns true and places the converted type (that
874/// might differ from ToType in its cv-qualifiers at some level) into
875/// ConvertedType.
Douglas Gregor9036ef72008-11-27 00:15:41 +0000876///
Douglas Gregor3f5a00c2008-11-27 01:19:21 +0000877/// This routine also supports conversions to and from block pointers
878/// and conversions with Objective-C's 'id', 'id<protocols...>', and
879/// pointers to interfaces. FIXME: Once we've determined the
880/// appropriate overloading rules for Objective-C, we may want to
881/// split the Objective-C checks into a different routine; however,
882/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor6fd35572008-12-19 17:40:08 +0000883/// conversions, so for now they live here. IncompatibleObjC will be
884/// set if the conversion is an allowed Objective-C conversion that
885/// should result in a warning.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000886bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Douglas Gregor6fd35572008-12-19 17:40:08 +0000887 QualType& ConvertedType,
888 bool &IncompatibleObjC)
Douglas Gregord2baafd2008-10-21 16:13:35 +0000889{
Douglas Gregor6fd35572008-12-19 17:40:08 +0000890 IncompatibleObjC = false;
Douglas Gregor932778b2008-12-19 19:13:09 +0000891 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
892 return true;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000893
Douglas Gregorf1d75712008-12-22 20:51:52 +0000894 // Conversion from a null pointer constant to any Objective-C pointer type.
Steve Naroffad75bd22009-07-16 15:41:00 +0000895 if (ToType->isObjCObjectPointerType() &&
Douglas Gregorf1d75712008-12-22 20:51:52 +0000896 From->isNullPointerConstant(Context)) {
897 ConvertedType = ToType;
898 return true;
899 }
900
Douglas Gregor9036ef72008-11-27 00:15:41 +0000901 // Blocks: Block pointers can be converted to void*.
902 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000903 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor9036ef72008-11-27 00:15:41 +0000904 ConvertedType = ToType;
905 return true;
906 }
907 // Blocks: A null pointer constant can be converted to a block
908 // pointer type.
909 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) {
910 ConvertedType = ToType;
911 return true;
912 }
913
Sebastian Redl5d0ead72009-05-10 18:38:11 +0000914 // If the left-hand-side is nullptr_t, the right side can be a null
915 // pointer constant.
916 if (ToType->isNullPtrType() && From->isNullPointerConstant(Context)) {
917 ConvertedType = ToType;
918 return true;
919 }
920
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000921 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregord2baafd2008-10-21 16:13:35 +0000922 if (!ToTypePtr)
923 return false;
924
925 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
926 if (From->isNullPointerConstant(Context)) {
927 ConvertedType = ToType;
928 return true;
929 }
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000930
Douglas Gregor24a90a52008-11-26 23:31:11 +0000931 // Beyond this point, both types need to be pointers.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000932 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor24a90a52008-11-26 23:31:11 +0000933 if (!FromTypePtr)
934 return false;
935
936 QualType FromPointeeType = FromTypePtr->getPointeeType();
937 QualType ToPointeeType = ToTypePtr->getPointeeType();
938
Douglas Gregord2baafd2008-10-21 16:13:35 +0000939 // An rvalue of type "pointer to cv T," where T is an object type,
940 // can be converted to an rvalue of type "pointer to cv void" (C++
941 // 4.10p2).
Douglas Gregor26ea1222009-03-24 20:32:41 +0000942 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000943 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
944 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000945 ToType, Context);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000946 return true;
947 }
948
Douglas Gregorfcb19192009-02-11 23:02:49 +0000949 // When we're overloading in C, we allow a special kind of pointer
950 // conversion for compatible-but-not-identical pointee types.
951 if (!getLangOptions().CPlusPlus &&
952 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
953 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
954 ToPointeeType,
955 ToType, Context);
956 return true;
957 }
958
Douglas Gregor14046502008-10-23 00:40:37 +0000959 // C++ [conv.ptr]p3:
960 //
961 // An rvalue of type "pointer to cv D," where D is a class type,
962 // can be converted to an rvalue of type "pointer to cv B," where
963 // B is a base class (clause 10) of D. If B is an inaccessible
964 // (clause 11) or ambiguous (10.2) base class of D, a program that
965 // necessitates this conversion is ill-formed. The result of the
966 // conversion is a pointer to the base class sub-object of the
967 // derived class object. The null pointer value is converted to
968 // the null pointer value of the destination type.
969 //
Douglas Gregorbb461502008-10-24 04:54:22 +0000970 // Note that we do not check for ambiguity or inaccessibility
971 // here. That is handled by CheckPointerConversion.
Douglas Gregorfcb19192009-02-11 23:02:49 +0000972 if (getLangOptions().CPlusPlus &&
973 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor24a90a52008-11-26 23:31:11 +0000974 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000975 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
976 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000977 ToType, Context);
978 return true;
979 }
Douglas Gregor14046502008-10-23 00:40:37 +0000980
Douglas Gregor932778b2008-12-19 19:13:09 +0000981 return false;
982}
983
984/// isObjCPointerConversion - Determines whether this is an
985/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
986/// with the same arguments and return values.
987bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
988 QualType& ConvertedType,
989 bool &IncompatibleObjC) {
990 if (!getLangOptions().ObjC1)
991 return false;
992
Steve Naroff329ec222009-07-10 23:34:53 +0000993 // First, we handle all conversions on ObjC object pointer types.
994 const ObjCObjectPointerType* ToObjCPtr = ToType->getAsObjCObjectPointerType();
995 const ObjCObjectPointerType *FromObjCPtr =
996 FromType->getAsObjCObjectPointerType();
Douglas Gregor932778b2008-12-19 19:13:09 +0000997
Steve Naroff329ec222009-07-10 23:34:53 +0000998 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff7bffd372009-07-15 18:40:39 +0000999 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff329ec222009-07-10 23:34:53 +00001000 // pointer to any interface (in both directions).
Steve Naroff7bffd372009-07-15 18:40:39 +00001001 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00001002 ConvertedType = ToType;
1003 return true;
1004 }
1005 // Conversions with Objective-C's id<...>.
1006 if ((FromObjCPtr->isObjCQualifiedIdType() ||
1007 ToObjCPtr->isObjCQualifiedIdType()) &&
Steve Naroff99eb86b2009-07-23 01:01:38 +00001008 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
1009 /*compare=*/false)) {
Steve Naroff329ec222009-07-10 23:34:53 +00001010 ConvertedType = ToType;
1011 return true;
1012 }
1013 // Objective C++: We're able to convert from a pointer to an
1014 // interface to a pointer to a different interface.
1015 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1016 ConvertedType = ToType;
1017 return true;
1018 }
1019
1020 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1021 // Okay: this is some kind of implicit downcast of Objective-C
1022 // interfaces, which is permitted. However, we're going to
1023 // complain about it.
1024 IncompatibleObjC = true;
1025 ConvertedType = FromType;
1026 return true;
1027 }
1028 }
1029 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor80402cf2008-12-23 00:53:59 +00001030 QualType ToPointeeType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001031 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff329ec222009-07-10 23:34:53 +00001032 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001033 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor80402cf2008-12-23 00:53:59 +00001034 ToPointeeType = ToBlockPtr->getPointeeType();
1035 else
Douglas Gregor932778b2008-12-19 19:13:09 +00001036 return false;
1037
Douglas Gregor80402cf2008-12-23 00:53:59 +00001038 QualType FromPointeeType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001039 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff329ec222009-07-10 23:34:53 +00001040 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001041 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor80402cf2008-12-23 00:53:59 +00001042 FromPointeeType = FromBlockPtr->getPointeeType();
1043 else
Douglas Gregor932778b2008-12-19 19:13:09 +00001044 return false;
1045
Douglas Gregor932778b2008-12-19 19:13:09 +00001046 // If we have pointers to pointers, recursively check whether this
1047 // is an Objective-C conversion.
1048 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1049 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1050 IncompatibleObjC)) {
1051 // We always complain about this conversion.
1052 IncompatibleObjC = true;
1053 ConvertedType = ToType;
1054 return true;
1055 }
Douglas Gregor80402cf2008-12-23 00:53:59 +00001056 // If we have pointers to functions or blocks, check whether the only
Douglas Gregor932778b2008-12-19 19:13:09 +00001057 // differences in the argument and result types are in Objective-C
1058 // pointer conversions. If so, we permit the conversion (but
1059 // complain about it).
Douglas Gregor4fa58902009-02-26 23:50:07 +00001060 const FunctionProtoType *FromFunctionType
1061 = FromPointeeType->getAsFunctionProtoType();
1062 const FunctionProtoType *ToFunctionType
1063 = ToPointeeType->getAsFunctionProtoType();
Douglas Gregor932778b2008-12-19 19:13:09 +00001064 if (FromFunctionType && ToFunctionType) {
1065 // If the function types are exactly the same, this isn't an
1066 // Objective-C pointer conversion.
1067 if (Context.getCanonicalType(FromPointeeType)
1068 == Context.getCanonicalType(ToPointeeType))
1069 return false;
1070
1071 // Perform the quick checks that will tell us whether these
1072 // function types are obviously different.
1073 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1074 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1075 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1076 return false;
1077
1078 bool HasObjCConversion = false;
1079 if (Context.getCanonicalType(FromFunctionType->getResultType())
1080 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1081 // Okay, the types match exactly. Nothing to do.
1082 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1083 ToFunctionType->getResultType(),
1084 ConvertedType, IncompatibleObjC)) {
1085 // Okay, we have an Objective-C pointer conversion.
1086 HasObjCConversion = true;
1087 } else {
1088 // Function types are too different. Abort.
1089 return false;
1090 }
1091
1092 // Check argument types.
1093 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1094 ArgIdx != NumArgs; ++ArgIdx) {
1095 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1096 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1097 if (Context.getCanonicalType(FromArgType)
1098 == Context.getCanonicalType(ToArgType)) {
1099 // Okay, the types match exactly. Nothing to do.
1100 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1101 ConvertedType, IncompatibleObjC)) {
1102 // Okay, we have an Objective-C pointer conversion.
1103 HasObjCConversion = true;
1104 } else {
1105 // Argument types are too different. Abort.
1106 return false;
1107 }
1108 }
1109
1110 if (HasObjCConversion) {
1111 // We had an Objective-C conversion. Allow this pointer
1112 // conversion, but complain about it.
1113 ConvertedType = ToType;
1114 IncompatibleObjC = true;
1115 return true;
1116 }
1117 }
1118
Sebastian Redlba387562009-01-25 19:43:20 +00001119 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001120}
1121
Douglas Gregorbb461502008-10-24 04:54:22 +00001122/// CheckPointerConversion - Check the pointer conversion from the
1123/// expression From to the type ToType. This routine checks for
Sebastian Redl0e35d042009-07-25 15:41:38 +00001124/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregorbb461502008-10-24 04:54:22 +00001125/// conversions for which IsPointerConversion has already returned
1126/// true. It returns true and produces a diagnostic if there was an
1127/// error, or returns false otherwise.
1128bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1129 QualType FromType = From->getType();
1130
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001131 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1132 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregorbb461502008-10-24 04:54:22 +00001133 QualType FromPointeeType = FromPtrType->getPointeeType(),
1134 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregord0c653a2008-12-18 23:43:31 +00001135
Douglas Gregorbb461502008-10-24 04:54:22 +00001136 if (FromPointeeType->isRecordType() &&
1137 ToPointeeType->isRecordType()) {
1138 // We must have a derived-to-base conversion. Check an
1139 // ambiguous or inaccessible conversion.
Douglas Gregor651d1cc2008-10-24 16:17:19 +00001140 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1141 From->getExprLoc(),
1142 From->getSourceRange());
Douglas Gregorbb461502008-10-24 04:54:22 +00001143 }
1144 }
Steve Naroff329ec222009-07-10 23:34:53 +00001145 if (const ObjCObjectPointerType *FromPtrType =
1146 FromType->getAsObjCObjectPointerType())
1147 if (const ObjCObjectPointerType *ToPtrType =
1148 ToType->getAsObjCObjectPointerType()) {
1149 // Objective-C++ conversions are always okay.
1150 // FIXME: We should have a different class of conversions for the
1151 // Objective-C++ implicit conversions.
Steve Naroff7bffd372009-07-15 18:40:39 +00001152 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff329ec222009-07-10 23:34:53 +00001153 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +00001154
Steve Naroff329ec222009-07-10 23:34:53 +00001155 }
Douglas Gregorbb461502008-10-24 04:54:22 +00001156 return false;
1157}
1158
Sebastian Redlba387562009-01-25 19:43:20 +00001159/// IsMemberPointerConversion - Determines whether the conversion of the
1160/// expression From, which has the (possibly adjusted) type FromType, can be
1161/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1162/// If so, returns true and places the converted type (that might differ from
1163/// ToType in its cv-qualifiers at some level) into ConvertedType.
1164bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1165 QualType ToType, QualType &ConvertedType)
1166{
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001167 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redlba387562009-01-25 19:43:20 +00001168 if (!ToTypePtr)
1169 return false;
1170
1171 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1172 if (From->isNullPointerConstant(Context)) {
1173 ConvertedType = ToType;
1174 return true;
1175 }
1176
1177 // Otherwise, both types have to be member pointers.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001178 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redlba387562009-01-25 19:43:20 +00001179 if (!FromTypePtr)
1180 return false;
1181
1182 // A pointer to member of B can be converted to a pointer to member of D,
1183 // where D is derived from B (C++ 4.11p2).
1184 QualType FromClass(FromTypePtr->getClass(), 0);
1185 QualType ToClass(ToTypePtr->getClass(), 0);
1186 // FIXME: What happens when these are dependent? Is this function even called?
1187
1188 if (IsDerivedFrom(ToClass, FromClass)) {
1189 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1190 ToClass.getTypePtr());
1191 return true;
1192 }
1193
1194 return false;
1195}
1196
1197/// CheckMemberPointerConversion - Check the member pointer conversion from the
1198/// expression From to the type ToType. This routine checks for ambiguous or
1199/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1200/// for which IsMemberPointerConversion has already returned true. It returns
1201/// true and produces a diagnostic if there was an error, or returns false
1202/// otherwise.
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001203bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
1204 CastExpr::CastKind &Kind) {
Sebastian Redlba387562009-01-25 19:43:20 +00001205 QualType FromType = From->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001206 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001207 if (!FromPtrType) {
1208 // This must be a null pointer to member pointer conversion
1209 assert(From->isNullPointerConstant(Context) &&
1210 "Expr must be null pointer constant!");
1211 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001212 return false;
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001213 }
Sebastian Redlba387562009-01-25 19:43:20 +00001214
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001215 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001216 assert(ToPtrType && "No member pointer cast has a target type "
1217 "that is not a member pointer.");
Sebastian Redlba387562009-01-25 19:43:20 +00001218
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001219 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1220 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redlba387562009-01-25 19:43:20 +00001221
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001222 // FIXME: What about dependent types?
1223 assert(FromClass->isRecordType() && "Pointer into non-class.");
1224 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redlba387562009-01-25 19:43:20 +00001225
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001226 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1227 /*DetectVirtual=*/true);
1228 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1229 assert(DerivationOkay &&
1230 "Should not have been called if derivation isn't OK.");
1231 (void)DerivationOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001232
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001233 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1234 getUnqualifiedType())) {
1235 // Derivation is ambiguous. Redo the check to find the exact paths.
1236 Paths.clear();
1237 Paths.setRecordingPaths(true);
1238 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1239 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1240 (void)StillOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001241
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001242 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1243 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1244 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1245 return true;
Sebastian Redlba387562009-01-25 19:43:20 +00001246 }
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001247
Douglas Gregor2e047592009-02-28 01:32:25 +00001248 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001249 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1250 << FromClass << ToClass << QualType(VBase, 0)
1251 << From->getSourceRange();
1252 return true;
1253 }
1254
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001255 // Must be a base to derived member conversion.
1256 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redlba387562009-01-25 19:43:20 +00001257 return false;
1258}
1259
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001260/// IsQualificationConversion - Determines whether the conversion from
1261/// an rvalue of type FromType to ToType is a qualification conversion
1262/// (C++ 4.4).
1263bool
1264Sema::IsQualificationConversion(QualType FromType, QualType ToType)
1265{
1266 FromType = Context.getCanonicalType(FromType);
1267 ToType = Context.getCanonicalType(ToType);
1268
1269 // If FromType and ToType are the same type, this is not a
1270 // qualification conversion.
1271 if (FromType == ToType)
1272 return false;
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001273
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001274 // (C++ 4.4p4):
1275 // A conversion can add cv-qualifiers at levels other than the first
1276 // in multi-level pointers, subject to the following rules: [...]
1277 bool PreviousToQualsIncludeConst = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001278 bool UnwrappedAnyPointer = false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001279 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001280 // Within each iteration of the loop, we check the qualifiers to
1281 // determine if this still looks like a qualification
1282 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001283 // pointers or pointers-to-members and do it all again
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001284 // until there are no more pointers or pointers-to-members left to
1285 // unwrap.
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001286 UnwrappedAnyPointer = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001287
1288 // -- for every j > 0, if const is in cv 1,j then const is in cv
1289 // 2,j, and similarly for volatile.
Douglas Gregore5db4f72008-10-22 00:38:21 +00001290 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001291 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001292
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001293 // -- if the cv 1,j and cv 2,j are different, then const is in
1294 // every cv for 0 < k < j.
1295 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001296 && !PreviousToQualsIncludeConst)
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001297 return false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001298
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001299 // Keep track of whether all prior cv-qualifiers in the "to" type
1300 // include const.
1301 PreviousToQualsIncludeConst
1302 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001303 }
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001304
1305 // We are left with FromType and ToType being the pointee types
1306 // after unwrapping the original FromType and ToType the same number
1307 // of types. If we unwrapped any pointers, and if FromType and
1308 // ToType have the same unqualified type (since we checked
1309 // qualifiers above), then this is a qualification conversion.
1310 return UnwrappedAnyPointer &&
1311 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1312}
1313
Douglas Gregor8c860df2009-08-21 23:19:43 +00001314/// \brief Given a function template or function, extract the function template
1315/// declaration (if any) and the underlying function declaration.
1316template<typename T>
1317static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1318 FunctionTemplateDecl *&FunctionTemplate) {
1319 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1320 if (FunctionTemplate)
1321 Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1322 else
1323 Function = cast<T>(Orig);
1324}
1325
1326
Douglas Gregorb206cc42009-01-30 23:27:23 +00001327/// Determines whether there is a user-defined conversion sequence
1328/// (C++ [over.ics.user]) that converts expression From to the type
1329/// ToType. If such a conversion exists, User will contain the
1330/// user-defined conversion sequence that performs such a conversion
1331/// and this routine will return true. Otherwise, this routine returns
1332/// false and User is unspecified.
1333///
1334/// \param AllowConversionFunctions true if the conversion should
1335/// consider conversion functions at all. If false, only constructors
1336/// will be considered.
1337///
1338/// \param AllowExplicit true if the conversion should consider C++0x
1339/// "explicit" conversion functions as well as non-explicit conversion
1340/// functions (C++0x [class.conv.fct]p2).
Sebastian Redla55834a2009-04-12 17:16:29 +00001341///
1342/// \param ForceRValue true if the expression should be treated as an rvalue
1343/// for overload resolution.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001344bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001345 UserDefinedConversionSequence& User,
Douglas Gregorb206cc42009-01-30 23:27:23 +00001346 bool AllowConversionFunctions,
Sebastian Redla55834a2009-04-12 17:16:29 +00001347 bool AllowExplicit, bool ForceRValue)
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001348{
1349 OverloadCandidateSet CandidateSet;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001350 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001351 if (CXXRecordDecl *ToRecordDecl
1352 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1353 // C++ [over.match.ctor]p1:
1354 // When objects of class type are direct-initialized (8.5), or
1355 // copy-initialized from an expression of the same or a
1356 // derived class type (8.5), overload resolution selects the
1357 // constructor. [...] For copy-initialization, the candidate
1358 // functions are all the converting constructors (12.3.1) of
1359 // that class. The argument list is the expression-list within
1360 // the parentheses of the initializer.
1361 DeclarationName ConstructorName
1362 = Context.DeclarationNames.getCXXConstructorName(
1363 Context.getCanonicalType(ToType).getUnqualifiedType());
1364 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001365 for (llvm::tie(Con, ConEnd)
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001366 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor2e047592009-02-28 01:32:25 +00001367 Con != ConEnd; ++Con) {
Douglas Gregor050cabf2009-08-21 18:42:58 +00001368 // Find the constructor (which may be a template).
1369 CXXConstructorDecl *Constructor = 0;
1370 FunctionTemplateDecl *ConstructorTmpl
1371 = dyn_cast<FunctionTemplateDecl>(*Con);
1372 if (ConstructorTmpl)
1373 Constructor
1374 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1375 else
1376 Constructor = cast<CXXConstructorDecl>(*Con);
1377
Fariborz Jahanian625fb9d2009-08-06 17:22:51 +00001378 if (!Constructor->isInvalidDecl() &&
Douglas Gregor050cabf2009-08-21 18:42:58 +00001379 Constructor->isConvertingConstructor()) {
1380 if (ConstructorTmpl)
1381 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
1382 1, CandidateSet,
1383 /*SuppressUserConversions=*/true,
1384 ForceRValue);
1385 else
1386 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1387 /*SuppressUserConversions=*/true, ForceRValue);
1388 }
Douglas Gregor2e047592009-02-28 01:32:25 +00001389 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001390 }
1391 }
1392
Douglas Gregorb206cc42009-01-30 23:27:23 +00001393 if (!AllowConversionFunctions) {
1394 // Don't allow any conversion functions to enter the overload set.
Douglas Gregor2e047592009-02-28 01:32:25 +00001395 } else if (const RecordType *FromRecordType
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001396 = From->getType()->getAs<RecordType>()) {
Douglas Gregor2e047592009-02-28 01:32:25 +00001397 if (CXXRecordDecl *FromRecordDecl
1398 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1399 // Add all of the conversion functions as candidates.
1400 // FIXME: Look for conversions in base classes!
1401 OverloadedFunctionDecl *Conversions
1402 = FromRecordDecl->getConversionFunctions();
1403 for (OverloadedFunctionDecl::function_iterator Func
1404 = Conversions->function_begin();
1405 Func != Conversions->function_end(); ++Func) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00001406 CXXConversionDecl *Conv;
1407 FunctionTemplateDecl *ConvTemplate;
1408 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1409 if (ConvTemplate)
1410 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1411 else
1412 Conv = dyn_cast<CXXConversionDecl>(*Func);
1413
1414 if (AllowExplicit || !Conv->isExplicit()) {
1415 if (ConvTemplate)
1416 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1417 CandidateSet);
1418 else
1419 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1420 }
Douglas Gregor2e047592009-02-28 01:32:25 +00001421 }
Douglas Gregor60714f92008-11-07 22:36:19 +00001422 }
1423 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001424
1425 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001426 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001427 case OR_Success:
1428 // Record the standard conversion we used and the conversion function.
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001429 if (CXXConstructorDecl *Constructor
1430 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1431 // C++ [over.ics.user]p1:
1432 // If the user-defined conversion is specified by a
1433 // constructor (12.3.1), the initial standard conversion
1434 // sequence converts the source type to the type required by
1435 // the argument of the constructor.
1436 //
1437 // FIXME: What about ellipsis conversions?
1438 QualType ThisType = Constructor->getThisType(Context);
1439 User.Before = Best->Conversions[0].Standard;
1440 User.ConversionFunction = Constructor;
1441 User.After.setAsIdentityConversion();
1442 User.After.FromTypePtr
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001443 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001444 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1445 return true;
Douglas Gregor60714f92008-11-07 22:36:19 +00001446 } else if (CXXConversionDecl *Conversion
1447 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1448 // C++ [over.ics.user]p1:
1449 //
1450 // [...] If the user-defined conversion is specified by a
1451 // conversion function (12.3.2), the initial standard
1452 // conversion sequence converts the source type to the
1453 // implicit object parameter of the conversion function.
1454 User.Before = Best->Conversions[0].Standard;
1455 User.ConversionFunction = Conversion;
1456
1457 // C++ [over.ics.user]p2:
1458 // The second standard conversion sequence converts the
1459 // result of the user-defined conversion to the target type
1460 // for the sequence. Since an implicit conversion sequence
1461 // is an initialization, the special rules for
1462 // initialization by user-defined conversion apply when
1463 // selecting the best user-defined conversion for a
1464 // user-defined conversion sequence (see 13.3.3 and
1465 // 13.3.3.1).
1466 User.After = Best->FinalConversion;
1467 return true;
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001468 } else {
Douglas Gregor60714f92008-11-07 22:36:19 +00001469 assert(false && "Not a constructor or conversion function?");
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001470 return false;
1471 }
1472
1473 case OR_No_Viable_Function:
Douglas Gregoraa57e862009-02-18 21:56:37 +00001474 case OR_Deleted:
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001475 // No conversion here! We're done.
1476 return false;
1477
1478 case OR_Ambiguous:
1479 // FIXME: See C++ [over.best.ics]p10 for the handling of
1480 // ambiguous conversion sequences.
1481 return false;
1482 }
1483
1484 return false;
1485}
1486
Douglas Gregord2baafd2008-10-21 16:13:35 +00001487/// CompareImplicitConversionSequences - Compare two implicit
1488/// conversion sequences to determine whether one is better than the
1489/// other or if they are indistinguishable (C++ 13.3.3.2).
1490ImplicitConversionSequence::CompareKind
1491Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1492 const ImplicitConversionSequence& ICS2)
1493{
1494 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1495 // conversion sequences (as defined in 13.3.3.1)
1496 // -- a standard conversion sequence (13.3.3.1.1) is a better
1497 // conversion sequence than a user-defined conversion sequence or
1498 // an ellipsis conversion sequence, and
1499 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1500 // conversion sequence than an ellipsis conversion sequence
1501 // (13.3.3.1.3).
1502 //
1503 if (ICS1.ConversionKind < ICS2.ConversionKind)
1504 return ImplicitConversionSequence::Better;
1505 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1506 return ImplicitConversionSequence::Worse;
1507
1508 // Two implicit conversion sequences of the same form are
1509 // indistinguishable conversion sequences unless one of the
1510 // following rules apply: (C++ 13.3.3.2p3):
1511 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1512 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1513 else if (ICS1.ConversionKind ==
1514 ImplicitConversionSequence::UserDefinedConversion) {
1515 // User-defined conversion sequence U1 is a better conversion
1516 // sequence than another user-defined conversion sequence U2 if
1517 // they contain the same user-defined conversion function or
1518 // constructor and if the second standard conversion sequence of
1519 // U1 is better than the second standard conversion sequence of
1520 // U2 (C++ 13.3.3.2p3).
1521 if (ICS1.UserDefined.ConversionFunction ==
1522 ICS2.UserDefined.ConversionFunction)
1523 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1524 ICS2.UserDefined.After);
1525 }
1526
1527 return ImplicitConversionSequence::Indistinguishable;
1528}
1529
1530/// CompareStandardConversionSequences - Compare two standard
1531/// conversion sequences to determine whether one is better than the
1532/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1533ImplicitConversionSequence::CompareKind
1534Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1535 const StandardConversionSequence& SCS2)
1536{
1537 // Standard conversion sequence S1 is a better conversion sequence
1538 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1539
1540 // -- S1 is a proper subsequence of S2 (comparing the conversion
1541 // sequences in the canonical form defined by 13.3.3.1.1,
1542 // excluding any Lvalue Transformation; the identity conversion
1543 // sequence is considered to be a subsequence of any
1544 // non-identity conversion sequence) or, if not that,
1545 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1546 // Neither is a proper subsequence of the other. Do nothing.
1547 ;
1548 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1549 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1550 (SCS1.Second == ICK_Identity &&
1551 SCS1.Third == ICK_Identity))
1552 // SCS1 is a proper subsequence of SCS2.
1553 return ImplicitConversionSequence::Better;
1554 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1555 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1556 (SCS2.Second == ICK_Identity &&
1557 SCS2.Third == ICK_Identity))
1558 // SCS2 is a proper subsequence of SCS1.
1559 return ImplicitConversionSequence::Worse;
1560
1561 // -- the rank of S1 is better than the rank of S2 (by the rules
1562 // defined below), or, if not that,
1563 ImplicitConversionRank Rank1 = SCS1.getRank();
1564 ImplicitConversionRank Rank2 = SCS2.getRank();
1565 if (Rank1 < Rank2)
1566 return ImplicitConversionSequence::Better;
1567 else if (Rank2 < Rank1)
1568 return ImplicitConversionSequence::Worse;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001569
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001570 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1571 // are indistinguishable unless one of the following rules
1572 // applies:
1573
1574 // A conversion that is not a conversion of a pointer, or
1575 // pointer to member, to bool is better than another conversion
1576 // that is such a conversion.
1577 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1578 return SCS2.isPointerConversionToBool()
1579 ? ImplicitConversionSequence::Better
1580 : ImplicitConversionSequence::Worse;
1581
Douglas Gregor14046502008-10-23 00:40:37 +00001582 // C++ [over.ics.rank]p4b2:
1583 //
1584 // If class B is derived directly or indirectly from class A,
Douglas Gregor0e343382008-10-29 14:50:44 +00001585 // conversion of B* to A* is better than conversion of B* to
1586 // void*, and conversion of A* to void* is better than conversion
1587 // of B* to void*.
Douglas Gregor14046502008-10-23 00:40:37 +00001588 bool SCS1ConvertsToVoid
1589 = SCS1.isPointerConversionToVoidPointer(Context);
1590 bool SCS2ConvertsToVoid
1591 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregor0e343382008-10-29 14:50:44 +00001592 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1593 // Exactly one of the conversion sequences is a conversion to
1594 // a void pointer; it's the worse conversion.
Douglas Gregor14046502008-10-23 00:40:37 +00001595 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1596 : ImplicitConversionSequence::Worse;
Douglas Gregor0e343382008-10-29 14:50:44 +00001597 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1598 // Neither conversion sequence converts to a void pointer; compare
1599 // their derived-to-base conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001600 if (ImplicitConversionSequence::CompareKind DerivedCK
1601 = CompareDerivedToBaseConversions(SCS1, SCS2))
1602 return DerivedCK;
Douglas Gregor0e343382008-10-29 14:50:44 +00001603 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1604 // Both conversion sequences are conversions to void
1605 // pointers. Compare the source types to determine if there's an
1606 // inheritance relationship in their sources.
1607 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1608 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1609
1610 // Adjust the types we're converting from via the array-to-pointer
1611 // conversion, if we need to.
1612 if (SCS1.First == ICK_Array_To_Pointer)
1613 FromType1 = Context.getArrayDecayedType(FromType1);
1614 if (SCS2.First == ICK_Array_To_Pointer)
1615 FromType2 = Context.getArrayDecayedType(FromType2);
1616
1617 QualType FromPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001618 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor0e343382008-10-29 14:50:44 +00001619 QualType FromPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001620 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor0e343382008-10-29 14:50:44 +00001621
1622 if (IsDerivedFrom(FromPointee2, FromPointee1))
1623 return ImplicitConversionSequence::Better;
1624 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1625 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001626
1627 // Objective-C++: If one interface is more specific than the
1628 // other, it is the better one.
1629 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1630 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1631 if (FromIface1 && FromIface1) {
1632 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1633 return ImplicitConversionSequence::Better;
1634 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1635 return ImplicitConversionSequence::Worse;
1636 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001637 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001638
1639 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1640 // bullet 3).
Douglas Gregor14046502008-10-23 00:40:37 +00001641 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001642 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor14046502008-10-23 00:40:37 +00001643 return QualCK;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001644
Douglas Gregor0e343382008-10-29 14:50:44 +00001645 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001646 // C++0x [over.ics.rank]p3b4:
1647 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1648 // implicit object parameter of a non-static member function declared
1649 // without a ref-qualifier, and S1 binds an rvalue reference to an
1650 // rvalue and S2 binds an lvalue reference.
Sebastian Redldfc30332009-03-29 15:27:50 +00001651 // FIXME: We don't know if we're dealing with the implicit object parameter,
1652 // or if the member function in this case has a ref qualifier.
1653 // (Of course, we don't have ref qualifiers yet.)
1654 if (SCS1.RRefBinding != SCS2.RRefBinding)
1655 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1656 : ImplicitConversionSequence::Worse;
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001657
1658 // C++ [over.ics.rank]p3b4:
1659 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1660 // which the references refer are the same type except for
1661 // top-level cv-qualifiers, and the type to which the reference
1662 // initialized by S2 refers is more cv-qualified than the type
1663 // to which the reference initialized by S1 refers.
Sebastian Redldfc30332009-03-29 15:27:50 +00001664 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1665 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregor0e343382008-10-29 14:50:44 +00001666 T1 = Context.getCanonicalType(T1);
1667 T2 = Context.getCanonicalType(T2);
1668 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1669 if (T2.isMoreQualifiedThan(T1))
1670 return ImplicitConversionSequence::Better;
1671 else if (T1.isMoreQualifiedThan(T2))
1672 return ImplicitConversionSequence::Worse;
1673 }
1674 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001675
1676 return ImplicitConversionSequence::Indistinguishable;
1677}
1678
1679/// CompareQualificationConversions - Compares two standard conversion
1680/// sequences to determine whether they can be ranked based on their
1681/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1682ImplicitConversionSequence::CompareKind
1683Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1684 const StandardConversionSequence& SCS2)
1685{
Douglas Gregor4459bbe2008-10-22 15:04:37 +00001686 // C++ 13.3.3.2p3:
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001687 // -- S1 and S2 differ only in their qualification conversion and
1688 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1689 // cv-qualification signature of type T1 is a proper subset of
1690 // the cv-qualification signature of type T2, and S1 is not the
1691 // deprecated string literal array-to-pointer conversion (4.2).
1692 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1693 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1694 return ImplicitConversionSequence::Indistinguishable;
1695
1696 // FIXME: the example in the standard doesn't use a qualification
1697 // conversion (!)
1698 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1699 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1700 T1 = Context.getCanonicalType(T1);
1701 T2 = Context.getCanonicalType(T2);
1702
1703 // If the types are the same, we won't learn anything by unwrapped
1704 // them.
1705 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1706 return ImplicitConversionSequence::Indistinguishable;
1707
1708 ImplicitConversionSequence::CompareKind Result
1709 = ImplicitConversionSequence::Indistinguishable;
1710 while (UnwrapSimilarPointerTypes(T1, T2)) {
1711 // Within each iteration of the loop, we check the qualifiers to
1712 // determine if this still looks like a qualification
1713 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001714 // pointers or pointers-to-members and do it all again
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001715 // until there are no more pointers or pointers-to-members left
1716 // to unwrap. This essentially mimics what
1717 // IsQualificationConversion does, but here we're checking for a
1718 // strict subset of qualifiers.
1719 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1720 // The qualifiers are the same, so this doesn't tell us anything
1721 // about how the sequences rank.
1722 ;
1723 else if (T2.isMoreQualifiedThan(T1)) {
1724 // T1 has fewer qualifiers, so it could be the better sequence.
1725 if (Result == ImplicitConversionSequence::Worse)
1726 // Neither has qualifiers that are a subset of the other's
1727 // qualifiers.
1728 return ImplicitConversionSequence::Indistinguishable;
1729
1730 Result = ImplicitConversionSequence::Better;
1731 } else if (T1.isMoreQualifiedThan(T2)) {
1732 // T2 has fewer qualifiers, so it could be the better sequence.
1733 if (Result == ImplicitConversionSequence::Better)
1734 // Neither has qualifiers that are a subset of the other's
1735 // qualifiers.
1736 return ImplicitConversionSequence::Indistinguishable;
1737
1738 Result = ImplicitConversionSequence::Worse;
1739 } else {
1740 // Qualifiers are disjoint.
1741 return ImplicitConversionSequence::Indistinguishable;
1742 }
1743
1744 // If the types after this point are equivalent, we're done.
1745 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1746 break;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001747 }
1748
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001749 // Check that the winning standard conversion sequence isn't using
1750 // the deprecated string literal array to pointer conversion.
1751 switch (Result) {
1752 case ImplicitConversionSequence::Better:
1753 if (SCS1.Deprecated)
1754 Result = ImplicitConversionSequence::Indistinguishable;
1755 break;
1756
1757 case ImplicitConversionSequence::Indistinguishable:
1758 break;
1759
1760 case ImplicitConversionSequence::Worse:
1761 if (SCS2.Deprecated)
1762 Result = ImplicitConversionSequence::Indistinguishable;
1763 break;
1764 }
1765
1766 return Result;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001767}
1768
Douglas Gregor14046502008-10-23 00:40:37 +00001769/// CompareDerivedToBaseConversions - Compares two standard conversion
1770/// sequences to determine whether they can be ranked based on their
Douglas Gregor24a90a52008-11-26 23:31:11 +00001771/// various kinds of derived-to-base conversions (C++
1772/// [over.ics.rank]p4b3). As part of these checks, we also look at
1773/// conversions between Objective-C interface types.
Douglas Gregor14046502008-10-23 00:40:37 +00001774ImplicitConversionSequence::CompareKind
1775Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1776 const StandardConversionSequence& SCS2) {
1777 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1778 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1779 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1780 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1781
1782 // Adjust the types we're converting from via the array-to-pointer
1783 // conversion, if we need to.
1784 if (SCS1.First == ICK_Array_To_Pointer)
1785 FromType1 = Context.getArrayDecayedType(FromType1);
1786 if (SCS2.First == ICK_Array_To_Pointer)
1787 FromType2 = Context.getArrayDecayedType(FromType2);
1788
1789 // Canonicalize all of the types.
1790 FromType1 = Context.getCanonicalType(FromType1);
1791 ToType1 = Context.getCanonicalType(ToType1);
1792 FromType2 = Context.getCanonicalType(FromType2);
1793 ToType2 = Context.getCanonicalType(ToType2);
1794
Douglas Gregor0e343382008-10-29 14:50:44 +00001795 // C++ [over.ics.rank]p4b3:
Douglas Gregor14046502008-10-23 00:40:37 +00001796 //
1797 // If class B is derived directly or indirectly from class A and
1798 // class C is derived directly or indirectly from B,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001799 //
1800 // For Objective-C, we let A, B, and C also be Objective-C
1801 // interfaces.
Douglas Gregor0e343382008-10-29 14:50:44 +00001802
1803 // Compare based on pointer conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001804 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor3f5a00c2008-11-27 01:19:21 +00001805 SCS2.Second == ICK_Pointer_Conversion &&
1806 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1807 FromType1->isPointerType() && FromType2->isPointerType() &&
1808 ToType1->isPointerType() && ToType2->isPointerType()) {
Douglas Gregor14046502008-10-23 00:40:37 +00001809 QualType FromPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001810 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001811 QualType ToPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001812 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001813 QualType FromPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001814 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001815 QualType ToPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001816 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor24a90a52008-11-26 23:31:11 +00001817
1818 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1819 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1820 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1821 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1822
Douglas Gregor0e343382008-10-29 14:50:44 +00001823 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor14046502008-10-23 00:40:37 +00001824 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1825 if (IsDerivedFrom(ToPointee1, ToPointee2))
1826 return ImplicitConversionSequence::Better;
1827 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1828 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001829
1830 if (ToIface1 && ToIface2) {
1831 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1832 return ImplicitConversionSequence::Better;
1833 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1834 return ImplicitConversionSequence::Worse;
1835 }
Douglas Gregor14046502008-10-23 00:40:37 +00001836 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001837
1838 // -- conversion of B* to A* is better than conversion of C* to A*,
1839 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1840 if (IsDerivedFrom(FromPointee2, FromPointee1))
1841 return ImplicitConversionSequence::Better;
1842 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1843 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001844
1845 if (FromIface1 && FromIface2) {
1846 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1847 return ImplicitConversionSequence::Better;
1848 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1849 return ImplicitConversionSequence::Worse;
1850 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001851 }
Douglas Gregor14046502008-10-23 00:40:37 +00001852 }
1853
Douglas Gregor0e343382008-10-29 14:50:44 +00001854 // Compare based on reference bindings.
1855 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1856 SCS1.Second == ICK_Derived_To_Base) {
1857 // -- binding of an expression of type C to a reference of type
1858 // B& is better than binding an expression of type C to a
1859 // reference of type A&,
1860 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1861 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1862 if (IsDerivedFrom(ToType1, ToType2))
1863 return ImplicitConversionSequence::Better;
1864 else if (IsDerivedFrom(ToType2, ToType1))
1865 return ImplicitConversionSequence::Worse;
1866 }
1867
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001868 // -- binding of an expression of type B to a reference of type
1869 // A& is better than binding an expression of type C to a
1870 // reference of type A&,
Douglas Gregor0e343382008-10-29 14:50:44 +00001871 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1872 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1873 if (IsDerivedFrom(FromType2, FromType1))
1874 return ImplicitConversionSequence::Better;
1875 else if (IsDerivedFrom(FromType1, FromType2))
1876 return ImplicitConversionSequence::Worse;
1877 }
1878 }
1879
1880
1881 // FIXME: conversion of A::* to B::* is better than conversion of
1882 // A::* to C::*,
1883
1884 // FIXME: conversion of B::* to C::* is better than conversion of
1885 // A::* to C::*, and
1886
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001887 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1888 SCS1.Second == ICK_Derived_To_Base) {
1889 // -- conversion of C to B is better than conversion of C to A,
1890 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1891 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1892 if (IsDerivedFrom(ToType1, ToType2))
1893 return ImplicitConversionSequence::Better;
1894 else if (IsDerivedFrom(ToType2, ToType1))
1895 return ImplicitConversionSequence::Worse;
1896 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001897
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001898 // -- conversion of B to A is better than conversion of C to A.
1899 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1900 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1901 if (IsDerivedFrom(FromType2, FromType1))
1902 return ImplicitConversionSequence::Better;
1903 else if (IsDerivedFrom(FromType1, FromType2))
1904 return ImplicitConversionSequence::Worse;
1905 }
1906 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001907
Douglas Gregor14046502008-10-23 00:40:37 +00001908 return ImplicitConversionSequence::Indistinguishable;
1909}
1910
Douglas Gregor81c29152008-10-29 00:13:59 +00001911/// TryCopyInitialization - Try to copy-initialize a value of type
1912/// ToType from the expression From. Return the implicit conversion
1913/// sequence required to pass this argument, which may be a bad
1914/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001915/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redla55834a2009-04-12 17:16:29 +00001916/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1917/// then we treat @p From as an rvalue, even if it is an lvalue.
Douglas Gregor81c29152008-10-29 00:13:59 +00001918ImplicitConversionSequence
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001919Sema::TryCopyInitialization(Expr *From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +00001920 bool SuppressUserConversions, bool ForceRValue) {
Douglas Gregorfcb19192009-02-11 23:02:49 +00001921 if (ToType->isReferenceType()) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001922 ImplicitConversionSequence ICS;
Sebastian Redla55834a2009-04-12 17:16:29 +00001923 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions,
1924 /*AllowExplicit=*/false, ForceRValue);
Douglas Gregor81c29152008-10-29 00:13:59 +00001925 return ICS;
1926 } else {
Sebastian Redla55834a2009-04-12 17:16:29 +00001927 return TryImplicitConversion(From, ToType, SuppressUserConversions,
1928 ForceRValue);
Douglas Gregor81c29152008-10-29 00:13:59 +00001929 }
1930}
1931
Sebastian Redla55834a2009-04-12 17:16:29 +00001932/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1933/// the expression @p From. Returns true (and emits a diagnostic) if there was
1934/// an error, returns false if the initialization succeeded. Elidable should
1935/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1936/// differently in C++0x for this case.
Douglas Gregor81c29152008-10-29 00:13:59 +00001937bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +00001938 const char* Flavor, bool Elidable) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001939 if (!getLangOptions().CPlusPlus) {
1940 // In C, argument passing is the same as performing an assignment.
1941 QualType FromType = From->getType();
Douglas Gregor144b06c2009-04-29 22:16:16 +00001942
Douglas Gregor81c29152008-10-29 00:13:59 +00001943 AssignConvertType ConvTy =
1944 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor144b06c2009-04-29 22:16:16 +00001945 if (ConvTy != Compatible &&
1946 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1947 ConvTy = Compatible;
1948
Douglas Gregor81c29152008-10-29 00:13:59 +00001949 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1950 FromType, From, Flavor);
Douglas Gregor81c29152008-10-29 00:13:59 +00001951 }
Sebastian Redla55834a2009-04-12 17:16:29 +00001952
Chris Lattner271d4c22008-11-24 05:29:24 +00001953 if (ToType->isReferenceType())
1954 return CheckReferenceInit(From, ToType);
1955
Sebastian Redla55834a2009-04-12 17:16:29 +00001956 if (!PerformImplicitConversion(From, ToType, Flavor,
1957 /*AllowExplicit=*/false, Elidable))
Chris Lattner271d4c22008-11-24 05:29:24 +00001958 return false;
Sebastian Redla55834a2009-04-12 17:16:29 +00001959
Chris Lattner271d4c22008-11-24 05:29:24 +00001960 return Diag(From->getSourceRange().getBegin(),
1961 diag::err_typecheck_convert_incompatible)
1962 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001963}
1964
Douglas Gregor5ed15042008-11-18 23:14:02 +00001965/// TryObjectArgumentInitialization - Try to initialize the object
1966/// parameter of the given member function (@c Method) from the
1967/// expression @p From.
1968ImplicitConversionSequence
1969Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1970 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1971 unsigned MethodQuals = Method->getTypeQualifiers();
1972 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1973
1974 // Set up the conversion sequence as a "bad" conversion, to allow us
1975 // to exit early.
1976 ImplicitConversionSequence ICS;
1977 ICS.Standard.setAsIdentityConversion();
1978 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1979
1980 // We need to have an object of class type.
1981 QualType FromType = From->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001982 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00001983 FromType = PT->getPointeeType();
1984
1985 assert(FromType->isRecordType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00001986
1987 // The implicit object parmeter is has the type "reference to cv X",
1988 // where X is the class of which the function is a member
1989 // (C++ [over.match.funcs]p4). However, when finding an implicit
1990 // conversion sequence for the argument, we are not allowed to
1991 // create temporaries or perform user-defined conversions
1992 // (C++ [over.match.funcs]p5). We perform a simplified version of
1993 // reference binding here, that allows class rvalues to bind to
1994 // non-constant references.
1995
1996 // First check the qualifiers. We don't care about lvalue-vs-rvalue
1997 // with the implicit object parameter (C++ [over.match.funcs]p5).
1998 QualType FromTypeCanon = Context.getCanonicalType(FromType);
1999 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
2000 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
2001 return ICS;
2002
2003 // Check that we have either the same type or a derived type. It
2004 // affects the conversion rank.
2005 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2006 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2007 ICS.Standard.Second = ICK_Identity;
2008 else if (IsDerivedFrom(FromType, ClassType))
2009 ICS.Standard.Second = ICK_Derived_To_Base;
2010 else
2011 return ICS;
2012
2013 // Success. Mark this as a reference binding.
2014 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2015 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2016 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2017 ICS.Standard.ReferenceBinding = true;
2018 ICS.Standard.DirectBinding = true;
Sebastian Redl9bc16ad2009-03-29 22:46:24 +00002019 ICS.Standard.RRefBinding = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002020 return ICS;
2021}
2022
2023/// PerformObjectArgumentInitialization - Perform initialization of
2024/// the implicit object parameter for the given Method with the given
2025/// expression.
2026bool
2027Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002028 QualType FromRecordType, DestType;
2029 QualType ImplicitParamRecordType =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002030 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002031
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002032 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002033 FromRecordType = PT->getPointeeType();
2034 DestType = Method->getThisType(Context);
2035 } else {
2036 FromRecordType = From->getType();
2037 DestType = ImplicitParamRecordType;
2038 }
2039
Douglas Gregor5ed15042008-11-18 23:14:02 +00002040 ImplicitConversionSequence ICS
2041 = TryObjectArgumentInitialization(From, Method);
2042 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2043 return Diag(From->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002044 diag::err_implicit_object_parameter_init)
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002045 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
2046
Douglas Gregor5ed15042008-11-18 23:14:02 +00002047 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002048 CheckDerivedToBaseConversion(FromRecordType,
2049 ImplicitParamRecordType,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002050 From->getSourceRange().getBegin(),
2051 From->getSourceRange()))
2052 return true;
2053
Anders Carlssone25b6cd2009-08-07 18:45:49 +00002054 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
2055 /*isLvalue=*/true);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002056 return false;
2057}
2058
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002059/// TryContextuallyConvertToBool - Attempt to contextually convert the
2060/// expression From to bool (C++0x [conv]p3).
2061ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
2062 return TryImplicitConversion(From, Context.BoolTy, false, true);
2063}
2064
2065/// PerformContextuallyConvertToBool - Perform a contextual conversion
2066/// of the expression From to bool (C++0x [conv]p3).
2067bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2068 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2069 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2070 return false;
2071
2072 return Diag(From->getSourceRange().getBegin(),
2073 diag::err_typecheck_bool_condition)
2074 << From->getType() << From->getSourceRange();
2075}
2076
Douglas Gregord2baafd2008-10-21 16:13:35 +00002077/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002078/// candidate functions, using the given function call arguments. If
2079/// @p SuppressUserConversions, then don't allow user-defined
2080/// conversions via constructors or conversion operators.
Sebastian Redla55834a2009-04-12 17:16:29 +00002081/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2082/// hacky way to implement the overloading rules for elidable copy
2083/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregord2baafd2008-10-21 16:13:35 +00002084void
2085Sema::AddOverloadCandidate(FunctionDecl *Function,
2086 Expr **Args, unsigned NumArgs,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002087 OverloadCandidateSet& CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00002088 bool SuppressUserConversions,
2089 bool ForceRValue)
Douglas Gregord2baafd2008-10-21 16:13:35 +00002090{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002091 const FunctionProtoType* Proto
2092 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
Douglas Gregord2baafd2008-10-21 16:13:35 +00002093 assert(Proto && "Functions without a prototype cannot be overloaded");
Douglas Gregor60714f92008-11-07 22:36:19 +00002094 assert(!isa<CXXConversionDecl>(Function) &&
2095 "Use AddConversionCandidate for conversion functions");
Douglas Gregorb60eb752009-06-25 22:08:12 +00002096 assert(!Function->getDescribedFunctionTemplate() &&
2097 "Use AddTemplateOverloadCandidate for function templates");
2098
Douglas Gregor3257fb52008-12-22 05:46:06 +00002099 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00002100 if (!isa<CXXConstructorDecl>(Method)) {
2101 // If we get here, it's because we're calling a member function
2102 // that is named without a member access expression (e.g.,
2103 // "this->f") that was either written explicitly or created
2104 // implicitly. This can happen with a qualified call to a member
2105 // function, e.g., X::f(). We use a NULL object as the implied
2106 // object argument (C++ [over.call.func]p3).
2107 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2108 SuppressUserConversions, ForceRValue);
2109 return;
2110 }
2111 // We treat a constructor like a non-member function, since its object
2112 // argument doesn't participate in overload resolution.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002113 }
2114
2115
Douglas Gregord2baafd2008-10-21 16:13:35 +00002116 // Add this candidate
2117 CandidateSet.push_back(OverloadCandidate());
2118 OverloadCandidate& Candidate = CandidateSet.back();
2119 Candidate.Function = Function;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002120 Candidate.Viable = true;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002121 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002122 Candidate.IgnoreObjectArgument = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00002123
2124 unsigned NumArgsInProto = Proto->getNumArgs();
2125
2126 // (C++ 13.3.2p2): A candidate function having fewer than m
2127 // parameters is viable only if it has an ellipsis in its parameter
2128 // list (8.3.5).
2129 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2130 Candidate.Viable = false;
2131 return;
2132 }
2133
2134 // (C++ 13.3.2p2): A candidate function having more than m parameters
2135 // is viable only if the (m+1)st parameter has a default argument
2136 // (8.3.6). For the purposes of overload resolution, the
2137 // parameter list is truncated on the right, so that there are
2138 // exactly m parameters.
2139 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2140 if (NumArgs < MinRequiredArgs) {
2141 // Not enough arguments.
2142 Candidate.Viable = false;
2143 return;
2144 }
2145
2146 // Determine the implicit conversion sequences for each of the
2147 // arguments.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002148 Candidate.Conversions.resize(NumArgs);
2149 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2150 if (ArgIdx < NumArgsInProto) {
2151 // (C++ 13.3.2p3): for F to be a viable function, there shall
2152 // exist for each argument an implicit conversion sequence
2153 // (13.3.3.1) that converts that argument to the corresponding
2154 // parameter of F.
2155 QualType ParamType = Proto->getArgType(ArgIdx);
2156 Candidate.Conversions[ArgIdx]
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002157 = TryCopyInitialization(Args[ArgIdx], ParamType,
Sebastian Redla55834a2009-04-12 17:16:29 +00002158 SuppressUserConversions, ForceRValue);
Douglas Gregord2baafd2008-10-21 16:13:35 +00002159 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002160 == ImplicitConversionSequence::BadConversion) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00002161 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002162 break;
2163 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002164 } else {
2165 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2166 // argument for which there is no corresponding parameter is
2167 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2168 Candidate.Conversions[ArgIdx].ConversionKind
2169 = ImplicitConversionSequence::EllipsisConversion;
2170 }
2171 }
2172}
2173
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002174/// \brief Add all of the function declarations in the given function set to
2175/// the overload canddiate set.
2176void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2177 Expr **Args, unsigned NumArgs,
2178 OverloadCandidateSet& CandidateSet,
2179 bool SuppressUserConversions) {
2180 for (FunctionSet::const_iterator F = Functions.begin(),
2181 FEnd = Functions.end();
Douglas Gregor993a0602009-06-27 21:05:07 +00002182 F != FEnd; ++F) {
2183 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F))
2184 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2185 SuppressUserConversions);
2186 else
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002187 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*F),
2188 /*FIXME: explicit args */false, 0, 0,
2189 Args, NumArgs, CandidateSet,
Douglas Gregor993a0602009-06-27 21:05:07 +00002190 SuppressUserConversions);
2191 }
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002192}
2193
Douglas Gregor5ed15042008-11-18 23:14:02 +00002194/// AddMethodCandidate - Adds the given C++ member function to the set
2195/// of candidate functions, using the given function call arguments
2196/// and the object argument (@c Object). For example, in a call
2197/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2198/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2199/// allow user-defined conversions via constructors or conversion
Sebastian Redla55834a2009-04-12 17:16:29 +00002200/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2201/// a slightly hacky way to implement the overloading rules for elidable copy
2202/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor5ed15042008-11-18 23:14:02 +00002203void
2204Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2205 Expr **Args, unsigned NumArgs,
2206 OverloadCandidateSet& CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00002207 bool SuppressUserConversions, bool ForceRValue)
Douglas Gregor5ed15042008-11-18 23:14:02 +00002208{
Douglas Gregor4fa58902009-02-26 23:50:07 +00002209 const FunctionProtoType* Proto
2210 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00002211 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redlbd261962009-04-16 17:51:27 +00002212 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor5ed15042008-11-18 23:14:02 +00002213 "Use AddConversionCandidate for conversion functions");
Sebastian Redlbd261962009-04-16 17:51:27 +00002214 assert(!isa<CXXConstructorDecl>(Method) &&
2215 "Use AddOverloadCandidate for constructors");
Douglas Gregor5ed15042008-11-18 23:14:02 +00002216
2217 // Add this candidate
2218 CandidateSet.push_back(OverloadCandidate());
2219 OverloadCandidate& Candidate = CandidateSet.back();
2220 Candidate.Function = Method;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002221 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002222 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002223
2224 unsigned NumArgsInProto = Proto->getNumArgs();
2225
2226 // (C++ 13.3.2p2): A candidate function having fewer than m
2227 // parameters is viable only if it has an ellipsis in its parameter
2228 // list (8.3.5).
2229 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2230 Candidate.Viable = false;
2231 return;
2232 }
2233
2234 // (C++ 13.3.2p2): A candidate function having more than m parameters
2235 // is viable only if the (m+1)st parameter has a default argument
2236 // (8.3.6). For the purposes of overload resolution, the
2237 // parameter list is truncated on the right, so that there are
2238 // exactly m parameters.
2239 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2240 if (NumArgs < MinRequiredArgs) {
2241 // Not enough arguments.
2242 Candidate.Viable = false;
2243 return;
2244 }
2245
2246 Candidate.Viable = true;
2247 Candidate.Conversions.resize(NumArgs + 1);
2248
Douglas Gregor3257fb52008-12-22 05:46:06 +00002249 if (Method->isStatic() || !Object)
2250 // The implicit object argument is ignored.
2251 Candidate.IgnoreObjectArgument = true;
2252 else {
2253 // Determine the implicit conversion sequence for the object
2254 // parameter.
2255 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2256 if (Candidate.Conversions[0].ConversionKind
2257 == ImplicitConversionSequence::BadConversion) {
2258 Candidate.Viable = false;
2259 return;
2260 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002261 }
2262
2263 // Determine the implicit conversion sequences for each of the
2264 // arguments.
2265 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2266 if (ArgIdx < NumArgsInProto) {
2267 // (C++ 13.3.2p3): for F to be a viable function, there shall
2268 // exist for each argument an implicit conversion sequence
2269 // (13.3.3.1) that converts that argument to the corresponding
2270 // parameter of F.
2271 QualType ParamType = Proto->getArgType(ArgIdx);
2272 Candidate.Conversions[ArgIdx + 1]
2273 = TryCopyInitialization(Args[ArgIdx], ParamType,
Sebastian Redla55834a2009-04-12 17:16:29 +00002274 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002275 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2276 == ImplicitConversionSequence::BadConversion) {
2277 Candidate.Viable = false;
2278 break;
2279 }
2280 } else {
2281 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2282 // argument for which there is no corresponding parameter is
2283 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2284 Candidate.Conversions[ArgIdx + 1].ConversionKind
2285 = ImplicitConversionSequence::EllipsisConversion;
2286 }
2287 }
2288}
2289
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002290/// \brief Add a C++ member function template as a candidate to the candidate
2291/// set, using template argument deduction to produce an appropriate member
2292/// function template specialization.
2293void
2294Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2295 bool HasExplicitTemplateArgs,
2296 const TemplateArgument *ExplicitTemplateArgs,
2297 unsigned NumExplicitTemplateArgs,
2298 Expr *Object, Expr **Args, unsigned NumArgs,
2299 OverloadCandidateSet& CandidateSet,
2300 bool SuppressUserConversions,
2301 bool ForceRValue) {
2302 // C++ [over.match.funcs]p7:
2303 // In each case where a candidate is a function template, candidate
2304 // function template specializations are generated using template argument
2305 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
2306 // candidate functions in the usual way.113) A given name can refer to one
2307 // or more function templates and also to a set of overloaded non-template
2308 // functions. In such a case, the candidate functions generated from each
2309 // function template are combined with the set of non-template candidate
2310 // functions.
2311 TemplateDeductionInfo Info(Context);
2312 FunctionDecl *Specialization = 0;
2313 if (TemplateDeductionResult Result
2314 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2315 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2316 Args, NumArgs, Specialization, Info)) {
2317 // FIXME: Record what happened with template argument deduction, so
2318 // that we can give the user a beautiful diagnostic.
2319 (void)Result;
2320 return;
2321 }
2322
2323 // Add the function template specialization produced by template argument
2324 // deduction as a candidate.
2325 assert(Specialization && "Missing member function template specialization?");
2326 assert(isa<CXXMethodDecl>(Specialization) &&
2327 "Specialization is not a member function?");
2328 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
2329 CandidateSet, SuppressUserConversions, ForceRValue);
2330}
2331
Douglas Gregor8c860df2009-08-21 23:19:43 +00002332/// \brief Add a C++ function template specialization as a candidate
2333/// in the candidate set, using template argument deduction to produce
2334/// an appropriate function template specialization.
Douglas Gregorb60eb752009-06-25 22:08:12 +00002335void
2336Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002337 bool HasExplicitTemplateArgs,
2338 const TemplateArgument *ExplicitTemplateArgs,
2339 unsigned NumExplicitTemplateArgs,
Douglas Gregorb60eb752009-06-25 22:08:12 +00002340 Expr **Args, unsigned NumArgs,
2341 OverloadCandidateSet& CandidateSet,
2342 bool SuppressUserConversions,
2343 bool ForceRValue) {
2344 // C++ [over.match.funcs]p7:
2345 // In each case where a candidate is a function template, candidate
2346 // function template specializations are generated using template argument
2347 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
2348 // candidate functions in the usual way.113) A given name can refer to one
2349 // or more function templates and also to a set of overloaded non-template
2350 // functions. In such a case, the candidate functions generated from each
2351 // function template are combined with the set of non-template candidate
2352 // functions.
2353 TemplateDeductionInfo Info(Context);
2354 FunctionDecl *Specialization = 0;
2355 if (TemplateDeductionResult Result
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002356 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2357 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2358 Args, NumArgs, Specialization, Info)) {
Douglas Gregorb60eb752009-06-25 22:08:12 +00002359 // FIXME: Record what happened with template argument deduction, so
2360 // that we can give the user a beautiful diagnostic.
2361 (void)Result;
2362 return;
2363 }
2364
2365 // Add the function template specialization produced by template argument
2366 // deduction as a candidate.
2367 assert(Specialization && "Missing function template specialization?");
2368 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2369 SuppressUserConversions, ForceRValue);
2370}
2371
Douglas Gregor60714f92008-11-07 22:36:19 +00002372/// AddConversionCandidate - Add a C++ conversion function as a
2373/// candidate in the candidate set (C++ [over.match.conv],
2374/// C++ [over.match.copy]). From is the expression we're converting from,
2375/// and ToType is the type that we're eventually trying to convert to
2376/// (which may or may not be the same type as the type that the
2377/// conversion function produces).
2378void
2379Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2380 Expr *From, QualType ToType,
2381 OverloadCandidateSet& CandidateSet) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00002382 assert(!Conversion->getDescribedFunctionTemplate() &&
2383 "Conversion function templates use AddTemplateConversionCandidate");
2384
Douglas Gregor60714f92008-11-07 22:36:19 +00002385 // Add this candidate
2386 CandidateSet.push_back(OverloadCandidate());
2387 OverloadCandidate& Candidate = CandidateSet.back();
2388 Candidate.Function = Conversion;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002389 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002390 Candidate.IgnoreObjectArgument = false;
Douglas Gregor60714f92008-11-07 22:36:19 +00002391 Candidate.FinalConversion.setAsIdentityConversion();
2392 Candidate.FinalConversion.FromTypePtr
2393 = Conversion->getConversionType().getAsOpaquePtr();
2394 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2395
Douglas Gregor5ed15042008-11-18 23:14:02 +00002396 // Determine the implicit conversion sequence for the implicit
2397 // object parameter.
Douglas Gregor60714f92008-11-07 22:36:19 +00002398 Candidate.Viable = true;
2399 Candidate.Conversions.resize(1);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002400 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregor60714f92008-11-07 22:36:19 +00002401
Douglas Gregor60714f92008-11-07 22:36:19 +00002402 if (Candidate.Conversions[0].ConversionKind
2403 == ImplicitConversionSequence::BadConversion) {
2404 Candidate.Viable = false;
2405 return;
2406 }
2407
2408 // To determine what the conversion from the result of calling the
2409 // conversion function to the type we're eventually trying to
2410 // convert to (ToType), we need to synthesize a call to the
2411 // conversion function and attempt copy initialization from it. This
2412 // makes sure that we get the right semantics with respect to
2413 // lvalues/rvalues and the type. Fortunately, we can allocate this
2414 // call on the stack and we don't need its arguments to be
2415 // well-formed.
2416 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2417 SourceLocation());
2418 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002419 CastExpr::CK_Unknown,
Douglas Gregor70d26122008-11-12 17:17:38 +00002420 &ConversionRef, false);
Ted Kremenek362abcd2009-02-09 20:51:47 +00002421
2422 // Note that it is safe to allocate CallExpr on the stack here because
2423 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2424 // allocator).
2425 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregor60714f92008-11-07 22:36:19 +00002426 Conversion->getConversionType().getNonReferenceType(),
2427 SourceLocation());
2428 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
2429 switch (ICS.ConversionKind) {
2430 case ImplicitConversionSequence::StandardConversion:
2431 Candidate.FinalConversion = ICS.Standard;
2432 break;
2433
2434 case ImplicitConversionSequence::BadConversion:
2435 Candidate.Viable = false;
2436 break;
2437
2438 default:
2439 assert(false &&
2440 "Can only end up with a standard conversion sequence or failure");
2441 }
2442}
2443
Douglas Gregor8c860df2009-08-21 23:19:43 +00002444/// \brief Adds a conversion function template specialization
2445/// candidate to the overload set, using template argument deduction
2446/// to deduce the template arguments of the conversion function
2447/// template from the type that we are converting to (C++
2448/// [temp.deduct.conv]).
2449void
2450Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2451 Expr *From, QualType ToType,
2452 OverloadCandidateSet &CandidateSet) {
2453 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2454 "Only conversion function templates permitted here");
2455
2456 TemplateDeductionInfo Info(Context);
2457 CXXConversionDecl *Specialization = 0;
2458 if (TemplateDeductionResult Result
2459 = DeduceTemplateArguments(FunctionTemplate, ToType,
2460 Specialization, Info)) {
2461 // FIXME: Record what happened with template argument deduction, so
2462 // that we can give the user a beautiful diagnostic.
2463 (void)Result;
2464 return;
2465 }
2466
2467 // Add the conversion function template specialization produced by
2468 // template argument deduction as a candidate.
2469 assert(Specialization && "Missing function template specialization?");
2470 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2471}
2472
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002473/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2474/// converts the given @c Object to a function pointer via the
2475/// conversion function @c Conversion, and then attempts to call it
2476/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2477/// the type of function that we'll eventually be calling.
2478void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002479 const FunctionProtoType *Proto,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002480 Expr *Object, Expr **Args, unsigned NumArgs,
2481 OverloadCandidateSet& CandidateSet) {
2482 CandidateSet.push_back(OverloadCandidate());
2483 OverloadCandidate& Candidate = CandidateSet.back();
2484 Candidate.Function = 0;
2485 Candidate.Surrogate = Conversion;
2486 Candidate.Viable = true;
2487 Candidate.IsSurrogate = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002488 Candidate.IgnoreObjectArgument = false;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002489 Candidate.Conversions.resize(NumArgs + 1);
2490
2491 // Determine the implicit conversion sequence for the implicit
2492 // object parameter.
2493 ImplicitConversionSequence ObjectInit
2494 = TryObjectArgumentInitialization(Object, Conversion);
2495 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2496 Candidate.Viable = false;
2497 return;
2498 }
2499
2500 // The first conversion is actually a user-defined conversion whose
2501 // first conversion is ObjectInit's standard conversion (which is
2502 // effectively a reference binding). Record it as such.
2503 Candidate.Conversions[0].ConversionKind
2504 = ImplicitConversionSequence::UserDefinedConversion;
2505 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2506 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2507 Candidate.Conversions[0].UserDefined.After
2508 = Candidate.Conversions[0].UserDefined.Before;
2509 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2510
2511 // Find the
2512 unsigned NumArgsInProto = Proto->getNumArgs();
2513
2514 // (C++ 13.3.2p2): A candidate function having fewer than m
2515 // parameters is viable only if it has an ellipsis in its parameter
2516 // list (8.3.5).
2517 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2518 Candidate.Viable = false;
2519 return;
2520 }
2521
2522 // Function types don't have any default arguments, so just check if
2523 // we have enough arguments.
2524 if (NumArgs < NumArgsInProto) {
2525 // Not enough arguments.
2526 Candidate.Viable = false;
2527 return;
2528 }
2529
2530 // Determine the implicit conversion sequences for each of the
2531 // arguments.
2532 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2533 if (ArgIdx < NumArgsInProto) {
2534 // (C++ 13.3.2p3): for F to be a viable function, there shall
2535 // exist for each argument an implicit conversion sequence
2536 // (13.3.3.1) that converts that argument to the corresponding
2537 // parameter of F.
2538 QualType ParamType = Proto->getArgType(ArgIdx);
2539 Candidate.Conversions[ArgIdx + 1]
2540 = TryCopyInitialization(Args[ArgIdx], ParamType,
2541 /*SuppressUserConversions=*/false);
2542 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2543 == ImplicitConversionSequence::BadConversion) {
2544 Candidate.Viable = false;
2545 break;
2546 }
2547 } else {
2548 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2549 // argument for which there is no corresponding parameter is
2550 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2551 Candidate.Conversions[ArgIdx + 1].ConversionKind
2552 = ImplicitConversionSequence::EllipsisConversion;
2553 }
2554 }
2555}
2556
Mike Stumpe127ae32009-05-16 07:39:55 +00002557// FIXME: This will eventually be removed, once we've migrated all of the
2558// operator overloading logic over to the scheme used by binary operators, which
2559// works for template instantiation.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002560void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor48a87322009-02-04 16:44:47 +00002561 SourceLocation OpLoc,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002562 Expr **Args, unsigned NumArgs,
Douglas Gregor48a87322009-02-04 16:44:47 +00002563 OverloadCandidateSet& CandidateSet,
2564 SourceRange OpRange) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002565
2566 FunctionSet Functions;
2567
2568 QualType T1 = Args[0]->getType();
2569 QualType T2;
2570 if (NumArgs > 1)
2571 T2 = Args[1]->getType();
2572
2573 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregorde72f3e2009-05-19 00:01:19 +00002574 if (S)
2575 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002576 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2577 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2578 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2579 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2580}
2581
2582/// \brief Add overload candidates for overloaded operators that are
2583/// member functions.
2584///
2585/// Add the overloaded operator candidates that are member functions
2586/// for the operator Op that was used in an operator expression such
2587/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2588/// CandidateSet will store the added overload candidates. (C++
2589/// [over.match.oper]).
2590void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2591 SourceLocation OpLoc,
2592 Expr **Args, unsigned NumArgs,
2593 OverloadCandidateSet& CandidateSet,
2594 SourceRange OpRange) {
Douglas Gregor5ed15042008-11-18 23:14:02 +00002595 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2596
2597 // C++ [over.match.oper]p3:
2598 // For a unary operator @ with an operand of a type whose
2599 // cv-unqualified version is T1, and for a binary operator @ with
2600 // a left operand of a type whose cv-unqualified version is T1 and
2601 // a right operand of a type whose cv-unqualified version is T2,
2602 // three sets of candidate functions, designated member
2603 // candidates, non-member candidates and built-in candidates, are
2604 // constructed as follows:
2605 QualType T1 = Args[0]->getType();
2606 QualType T2;
2607 if (NumArgs > 1)
2608 T2 = Args[1]->getType();
2609
2610 // -- If T1 is a class type, the set of member candidates is the
2611 // result of the qualified lookup of T1::operator@
2612 // (13.3.1.1.1); otherwise, the set of member candidates is
2613 // empty.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002614 // FIXME: Lookup in base classes, too!
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002615 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002616 DeclContext::lookup_const_iterator Oper, OperEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002617 for (llvm::tie(Oper, OperEnd) = T1Rec->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002618 Oper != OperEnd; ++Oper)
2619 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2620 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002621 /*SuppressUserConversions=*/false);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002622 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002623}
2624
Douglas Gregor70d26122008-11-12 17:17:38 +00002625/// AddBuiltinCandidate - Add a candidate for a built-in
2626/// operator. ResultTy and ParamTys are the result and parameter types
2627/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorab141112009-01-13 00:52:54 +00002628/// arguments being passed to the candidate. IsAssignmentOperator
2629/// should be true when this built-in candidate is an assignment
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002630/// operator. NumContextualBoolArguments is the number of arguments
2631/// (at the beginning of the argument list) that will be contextually
2632/// converted to bool.
Douglas Gregor70d26122008-11-12 17:17:38 +00002633void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2634 Expr **Args, unsigned NumArgs,
Douglas Gregorab141112009-01-13 00:52:54 +00002635 OverloadCandidateSet& CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002636 bool IsAssignmentOperator,
2637 unsigned NumContextualBoolArguments) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002638 // Add this candidate
2639 CandidateSet.push_back(OverloadCandidate());
2640 OverloadCandidate& Candidate = CandidateSet.back();
2641 Candidate.Function = 0;
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00002642 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002643 Candidate.IgnoreObjectArgument = false;
Douglas Gregor70d26122008-11-12 17:17:38 +00002644 Candidate.BuiltinTypes.ResultTy = ResultTy;
2645 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2646 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2647
2648 // Determine the implicit conversion sequences for each of the
2649 // arguments.
2650 Candidate.Viable = true;
2651 Candidate.Conversions.resize(NumArgs);
2652 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorab141112009-01-13 00:52:54 +00002653 // C++ [over.match.oper]p4:
2654 // For the built-in assignment operators, conversions of the
2655 // left operand are restricted as follows:
2656 // -- no temporaries are introduced to hold the left operand, and
2657 // -- no user-defined conversions are applied to the left
2658 // operand to achieve a type match with the left-most
2659 // parameter of a built-in candidate.
2660 //
2661 // We block these conversions by turning off user-defined
2662 // conversions, since that is the only way that initialization of
2663 // a reference to a non-class type can occur from something that
2664 // is not of the same type.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002665 if (ArgIdx < NumContextualBoolArguments) {
2666 assert(ParamTys[ArgIdx] == Context.BoolTy &&
2667 "Contextual conversion to bool requires bool type");
2668 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2669 } else {
2670 Candidate.Conversions[ArgIdx]
2671 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2672 ArgIdx == 0 && IsAssignmentOperator);
2673 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002674 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002675 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002676 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002677 break;
2678 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002679 }
2680}
2681
2682/// BuiltinCandidateTypeSet - A set of types that will be used for the
2683/// candidate operator functions for built-in operators (C++
2684/// [over.built]). The types are separated into pointer types and
2685/// enumeration types.
2686class BuiltinCandidateTypeSet {
2687 /// TypeSet - A set of types.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002688 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregor70d26122008-11-12 17:17:38 +00002689
2690 /// PointerTypes - The set of pointer types that will be used in the
2691 /// built-in candidates.
2692 TypeSet PointerTypes;
2693
Sebastian Redl674d1b72009-04-19 21:53:20 +00002694 /// MemberPointerTypes - The set of member pointer types that will be
2695 /// used in the built-in candidates.
2696 TypeSet MemberPointerTypes;
2697
Douglas Gregor70d26122008-11-12 17:17:38 +00002698 /// EnumerationTypes - The set of enumeration types that will be
2699 /// used in the built-in candidates.
2700 TypeSet EnumerationTypes;
2701
2702 /// Context - The AST context in which we will build the type sets.
2703 ASTContext &Context;
2704
Sebastian Redl674d1b72009-04-19 21:53:20 +00002705 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2706 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002707
2708public:
2709 /// iterator - Iterates through the types that are part of the set.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002710 typedef TypeSet::iterator iterator;
Douglas Gregor70d26122008-11-12 17:17:38 +00002711
2712 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2713
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002714 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2715 bool AllowExplicitConversions);
Douglas Gregor70d26122008-11-12 17:17:38 +00002716
2717 /// pointer_begin - First pointer type found;
2718 iterator pointer_begin() { return PointerTypes.begin(); }
2719
Sebastian Redl674d1b72009-04-19 21:53:20 +00002720 /// pointer_end - Past the last pointer type found;
Douglas Gregor70d26122008-11-12 17:17:38 +00002721 iterator pointer_end() { return PointerTypes.end(); }
2722
Sebastian Redl674d1b72009-04-19 21:53:20 +00002723 /// member_pointer_begin - First member pointer type found;
2724 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2725
2726 /// member_pointer_end - Past the last member pointer type found;
2727 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2728
Douglas Gregor70d26122008-11-12 17:17:38 +00002729 /// enumeration_begin - First enumeration type found;
2730 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2731
Sebastian Redl674d1b72009-04-19 21:53:20 +00002732 /// enumeration_end - Past the last enumeration type found;
Douglas Gregor70d26122008-11-12 17:17:38 +00002733 iterator enumeration_end() { return EnumerationTypes.end(); }
2734};
2735
Sebastian Redl674d1b72009-04-19 21:53:20 +00002736/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregor70d26122008-11-12 17:17:38 +00002737/// the set of pointer types along with any more-qualified variants of
2738/// that type. For example, if @p Ty is "int const *", this routine
2739/// will add "int const *", "int const volatile *", "int const
2740/// restrict *", and "int const volatile restrict *" to the set of
2741/// pointer types. Returns true if the add of @p Ty itself succeeded,
2742/// false otherwise.
Sebastian Redl674d1b72009-04-19 21:53:20 +00002743bool
2744BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002745 // Insert this type.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002746 if (!PointerTypes.insert(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002747 return false;
2748
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002749 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002750 QualType PointeeTy = PointerTy->getPointeeType();
2751 // FIXME: Optimize this so that we don't keep trying to add the same types.
2752
Mike Stumpe127ae32009-05-16 07:39:55 +00002753 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal with all
2754 // pointer conversions that don't cast away constness?
Douglas Gregor70d26122008-11-12 17:17:38 +00002755 if (!PointeeTy.isConstQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002756 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002757 (Context.getPointerType(PointeeTy.withConst()));
2758 if (!PointeeTy.isVolatileQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002759 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002760 (Context.getPointerType(PointeeTy.withVolatile()));
2761 if (!PointeeTy.isRestrictQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002762 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002763 (Context.getPointerType(PointeeTy.withRestrict()));
2764 }
2765
2766 return true;
2767}
2768
Sebastian Redl674d1b72009-04-19 21:53:20 +00002769/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2770/// to the set of pointer types along with any more-qualified variants of
2771/// that type. For example, if @p Ty is "int const *", this routine
2772/// will add "int const *", "int const volatile *", "int const
2773/// restrict *", and "int const volatile restrict *" to the set of
2774/// pointer types. Returns true if the add of @p Ty itself succeeded,
2775/// false otherwise.
2776bool
2777BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2778 QualType Ty) {
2779 // Insert this type.
2780 if (!MemberPointerTypes.insert(Ty))
2781 return false;
2782
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002783 if (const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>()) {
Sebastian Redl674d1b72009-04-19 21:53:20 +00002784 QualType PointeeTy = PointerTy->getPointeeType();
2785 const Type *ClassTy = PointerTy->getClass();
2786 // FIXME: Optimize this so that we don't keep trying to add the same types.
2787
2788 if (!PointeeTy.isConstQualified())
2789 AddMemberPointerWithMoreQualifiedTypeVariants
2790 (Context.getMemberPointerType(PointeeTy.withConst(), ClassTy));
2791 if (!PointeeTy.isVolatileQualified())
2792 AddMemberPointerWithMoreQualifiedTypeVariants
2793 (Context.getMemberPointerType(PointeeTy.withVolatile(), ClassTy));
2794 if (!PointeeTy.isRestrictQualified())
2795 AddMemberPointerWithMoreQualifiedTypeVariants
2796 (Context.getMemberPointerType(PointeeTy.withRestrict(), ClassTy));
2797 }
2798
2799 return true;
2800}
2801
Douglas Gregor70d26122008-11-12 17:17:38 +00002802/// AddTypesConvertedFrom - Add each of the types to which the type @p
2803/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl674d1b72009-04-19 21:53:20 +00002804/// primarily interested in pointer types and enumeration types. We also
2805/// take member pointer types, for the conditional operator.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002806/// AllowUserConversions is true if we should look at the conversion
2807/// functions of a class type, and AllowExplicitConversions if we
2808/// should also include the explicit conversion functions of a class
2809/// type.
2810void
2811BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2812 bool AllowUserConversions,
2813 bool AllowExplicitConversions) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002814 // Only deal with canonical types.
2815 Ty = Context.getCanonicalType(Ty);
2816
2817 // Look through reference types; they aren't part of the type of an
2818 // expression for the purposes of conversions.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002819 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregor70d26122008-11-12 17:17:38 +00002820 Ty = RefTy->getPointeeType();
2821
2822 // We don't care about qualifiers on the type.
2823 Ty = Ty.getUnqualifiedType();
2824
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002825 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002826 QualType PointeeTy = PointerTy->getPointeeType();
2827
2828 // Insert our type, and its more-qualified variants, into the set
2829 // of types.
Sebastian Redl674d1b72009-04-19 21:53:20 +00002830 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002831 return;
2832
2833 // Add 'cv void*' to our set of types.
2834 if (!Ty->isVoidType()) {
2835 QualType QualVoid
2836 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
Sebastian Redl674d1b72009-04-19 21:53:20 +00002837 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregor70d26122008-11-12 17:17:38 +00002838 }
2839
2840 // If this is a pointer to a class type, add pointers to its bases
2841 // (with the same level of cv-qualification as the original
2842 // derived class, of course).
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002843 if (const RecordType *PointeeRec = PointeeTy->getAs<RecordType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002844 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2845 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2846 Base != ClassDecl->bases_end(); ++Base) {
2847 QualType BaseTy = Context.getCanonicalType(Base->getType());
2848 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2849
2850 // Add the pointer type, recursively, so that we get all of
2851 // the indirect base classes, too.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002852 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002853 }
2854 }
Sebastian Redl674d1b72009-04-19 21:53:20 +00002855 } else if (Ty->isMemberPointerType()) {
2856 // Member pointers are far easier, since the pointee can't be converted.
2857 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2858 return;
Douglas Gregor70d26122008-11-12 17:17:38 +00002859 } else if (Ty->isEnumeralType()) {
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002860 EnumerationTypes.insert(Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002861 } else if (AllowUserConversions) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002862 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002863 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2864 // FIXME: Visit conversion functions in the base classes, too.
2865 OverloadedFunctionDecl *Conversions
2866 = ClassDecl->getConversionFunctions();
2867 for (OverloadedFunctionDecl::function_iterator Func
2868 = Conversions->function_begin();
2869 Func != Conversions->function_end(); ++Func) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00002870 CXXConversionDecl *Conv;
2871 FunctionTemplateDecl *ConvTemplate;
2872 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
2873
2874 // Skip conversion function templates; they don't tell us anything
2875 // about which builtin types we can convert to.
2876 if (ConvTemplate)
2877 continue;
2878
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002879 if (AllowExplicitConversions || !Conv->isExplicit())
2880 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002881 }
2882 }
2883 }
2884}
2885
Douglas Gregor9a375942009-08-24 13:43:27 +00002886/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
2887/// the volatile- and non-volatile-qualified assignment operators for the
2888/// given type to the candidate set.
2889static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
2890 QualType T,
2891 Expr **Args,
2892 unsigned NumArgs,
2893 OverloadCandidateSet &CandidateSet) {
2894 QualType ParamTypes[2];
2895
2896 // T& operator=(T&, T)
2897 ParamTypes[0] = S.Context.getLValueReferenceType(T);
2898 ParamTypes[1] = T;
2899 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2900 /*IsAssignmentOperator=*/true);
2901
2902 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
2903 // volatile T& operator=(volatile T&, T)
2904 ParamTypes[0] = S.Context.getLValueReferenceType(T.withVolatile());
2905 ParamTypes[1] = T;
2906 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2907 /*IsAssignmentOperator=*/true);
2908 }
2909}
2910
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002911/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2912/// operator overloads to the candidate set (C++ [over.built]), based
2913/// on the operator @p Op and the arguments given. For example, if the
2914/// operator is a binary '+', this routine might add "int
2915/// operator+(int, int)" to cover integer addition.
Douglas Gregor70d26122008-11-12 17:17:38 +00002916void
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002917Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2918 Expr **Args, unsigned NumArgs,
2919 OverloadCandidateSet& CandidateSet) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002920 // The set of "promoted arithmetic types", which are the arithmetic
2921 // types are that preserved by promotion (C++ [over.built]p2). Note
2922 // that the first few of these types are the promoted integral
2923 // types; these types need to be first.
2924 // FIXME: What about complex?
2925 const unsigned FirstIntegralType = 0;
2926 const unsigned LastIntegralType = 13;
2927 const unsigned FirstPromotedIntegralType = 7,
2928 LastPromotedIntegralType = 13;
2929 const unsigned FirstPromotedArithmeticType = 7,
2930 LastPromotedArithmeticType = 16;
2931 const unsigned NumArithmeticTypes = 16;
2932 QualType ArithmeticTypes[NumArithmeticTypes] = {
Alisdair Meredith2bcacb62009-07-14 06:30:34 +00002933 Context.BoolTy, Context.CharTy, Context.WCharTy,
Douglas Gregor9a375942009-08-24 13:43:27 +00002934// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregor70d26122008-11-12 17:17:38 +00002935 Context.SignedCharTy, Context.ShortTy,
2936 Context.UnsignedCharTy, Context.UnsignedShortTy,
2937 Context.IntTy, Context.LongTy, Context.LongLongTy,
2938 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2939 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2940 };
2941
2942 // Find all of the types that the arguments can convert to, but only
2943 // if the operator we're looking at has built-in operator candidates
2944 // that make use of these types.
2945 BuiltinCandidateTypeSet CandidateTypes(Context);
2946 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2947 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002948 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregor70d26122008-11-12 17:17:38 +00002949 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002950 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redlbd261962009-04-16 17:51:27 +00002951 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002952 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002953 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
2954 true,
2955 (Op == OO_Exclaim ||
2956 Op == OO_AmpAmp ||
2957 Op == OO_PipePipe));
Douglas Gregor70d26122008-11-12 17:17:38 +00002958 }
2959
2960 bool isComparison = false;
2961 switch (Op) {
2962 case OO_None:
2963 case NUM_OVERLOADED_OPERATORS:
2964 assert(false && "Expected an overloaded operator");
2965 break;
2966
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002967 case OO_Star: // '*' is either unary or binary
2968 if (NumArgs == 1)
2969 goto UnaryStar;
2970 else
2971 goto BinaryStar;
2972 break;
2973
2974 case OO_Plus: // '+' is either unary or binary
2975 if (NumArgs == 1)
2976 goto UnaryPlus;
2977 else
2978 goto BinaryPlus;
2979 break;
2980
2981 case OO_Minus: // '-' is either unary or binary
2982 if (NumArgs == 1)
2983 goto UnaryMinus;
2984 else
2985 goto BinaryMinus;
2986 break;
2987
2988 case OO_Amp: // '&' is either unary or binary
2989 if (NumArgs == 1)
2990 goto UnaryAmp;
2991 else
2992 goto BinaryAmp;
2993
2994 case OO_PlusPlus:
2995 case OO_MinusMinus:
2996 // C++ [over.built]p3:
2997 //
2998 // For every pair (T, VQ), where T is an arithmetic type, and VQ
2999 // is either volatile or empty, there exist candidate operator
3000 // functions of the form
3001 //
3002 // VQ T& operator++(VQ T&);
3003 // T operator++(VQ T&, int);
3004 //
3005 // C++ [over.built]p4:
3006 //
3007 // For every pair (T, VQ), where T is an arithmetic type other
3008 // than bool, and VQ is either volatile or empty, there exist
3009 // candidate operator functions of the form
3010 //
3011 // VQ T& operator--(VQ T&);
3012 // T operator--(VQ T&, int);
3013 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
3014 Arith < NumArithmeticTypes; ++Arith) {
3015 QualType ArithTy = ArithmeticTypes[Arith];
3016 QualType ParamTypes[2]
Sebastian Redlce6fff02009-03-16 23:22:08 +00003017 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003018
3019 // Non-volatile version.
3020 if (NumArgs == 1)
3021 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3022 else
3023 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3024
3025 // Volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003026 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003027 if (NumArgs == 1)
3028 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3029 else
3030 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3031 }
3032
3033 // C++ [over.built]p5:
3034 //
3035 // For every pair (T, VQ), where T is a cv-qualified or
3036 // cv-unqualified object type, and VQ is either volatile or
3037 // empty, there exist candidate operator functions of the form
3038 //
3039 // T*VQ& operator++(T*VQ&);
3040 // T*VQ& operator--(T*VQ&);
3041 // T* operator++(T*VQ&, int);
3042 // T* operator--(T*VQ&, int);
3043 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3044 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3045 // Skip pointer types that aren't pointers to object types.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003046 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003047 continue;
3048
3049 QualType ParamTypes[2] = {
Sebastian Redlce6fff02009-03-16 23:22:08 +00003050 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003051 };
3052
3053 // Without volatile
3054 if (NumArgs == 1)
3055 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3056 else
3057 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3058
3059 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3060 // With volatile
Sebastian Redlce6fff02009-03-16 23:22:08 +00003061 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003062 if (NumArgs == 1)
3063 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3064 else
3065 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3066 }
3067 }
3068 break;
3069
3070 UnaryStar:
3071 // C++ [over.built]p6:
3072 // For every cv-qualified or cv-unqualified object type T, there
3073 // exist candidate operator functions of the form
3074 //
3075 // T& operator*(T*);
3076 //
3077 // C++ [over.built]p7:
3078 // For every function type T, there exist candidate operator
3079 // functions of the form
3080 // T& operator*(T*);
3081 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3082 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3083 QualType ParamTy = *Ptr;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003084 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003085 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003086 &ParamTy, Args, 1, CandidateSet);
3087 }
3088 break;
3089
3090 UnaryPlus:
3091 // C++ [over.built]p8:
3092 // For every type T, there exist candidate operator functions of
3093 // the form
3094 //
3095 // T* operator+(T*);
3096 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3097 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3098 QualType ParamTy = *Ptr;
3099 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3100 }
3101
3102 // Fall through
3103
3104 UnaryMinus:
3105 // C++ [over.built]p9:
3106 // For every promoted arithmetic type T, there exist candidate
3107 // operator functions of the form
3108 //
3109 // T operator+(T);
3110 // T operator-(T);
3111 for (unsigned Arith = FirstPromotedArithmeticType;
3112 Arith < LastPromotedArithmeticType; ++Arith) {
3113 QualType ArithTy = ArithmeticTypes[Arith];
3114 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3115 }
3116 break;
3117
3118 case OO_Tilde:
3119 // C++ [over.built]p10:
3120 // For every promoted integral type T, there exist candidate
3121 // operator functions of the form
3122 //
3123 // T operator~(T);
3124 for (unsigned Int = FirstPromotedIntegralType;
3125 Int < LastPromotedIntegralType; ++Int) {
3126 QualType IntTy = ArithmeticTypes[Int];
3127 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3128 }
3129 break;
3130
Douglas Gregor70d26122008-11-12 17:17:38 +00003131 case OO_New:
3132 case OO_Delete:
3133 case OO_Array_New:
3134 case OO_Array_Delete:
Douglas Gregor70d26122008-11-12 17:17:38 +00003135 case OO_Call:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003136 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregor70d26122008-11-12 17:17:38 +00003137 break;
3138
3139 case OO_Comma:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003140 UnaryAmp:
3141 case OO_Arrow:
Douglas Gregor70d26122008-11-12 17:17:38 +00003142 // C++ [over.match.oper]p3:
3143 // -- For the operator ',', the unary operator '&', or the
3144 // operator '->', the built-in candidates set is empty.
Douglas Gregor70d26122008-11-12 17:17:38 +00003145 break;
3146
Douglas Gregor9a375942009-08-24 13:43:27 +00003147 case OO_EqualEqual:
3148 case OO_ExclaimEqual:
3149 // C++ [over.match.oper]p16:
3150 // For every pointer to member type T, there exist candidate operator
3151 // functions of the form
3152 //
3153 // bool operator==(T,T);
3154 // bool operator!=(T,T);
3155 for (BuiltinCandidateTypeSet::iterator
3156 MemPtr = CandidateTypes.member_pointer_begin(),
3157 MemPtrEnd = CandidateTypes.member_pointer_end();
3158 MemPtr != MemPtrEnd;
3159 ++MemPtr) {
3160 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3161 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3162 }
3163
3164 // Fall through
3165
Douglas Gregor70d26122008-11-12 17:17:38 +00003166 case OO_Less:
3167 case OO_Greater:
3168 case OO_LessEqual:
3169 case OO_GreaterEqual:
Douglas Gregor70d26122008-11-12 17:17:38 +00003170 // C++ [over.built]p15:
3171 //
3172 // For every pointer or enumeration type T, there exist
3173 // candidate operator functions of the form
3174 //
3175 // bool operator<(T, T);
3176 // bool operator>(T, T);
3177 // bool operator<=(T, T);
3178 // bool operator>=(T, T);
3179 // bool operator==(T, T);
3180 // bool operator!=(T, T);
3181 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3182 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3183 QualType ParamTypes[2] = { *Ptr, *Ptr };
3184 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3185 }
3186 for (BuiltinCandidateTypeSet::iterator Enum
3187 = CandidateTypes.enumeration_begin();
3188 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3189 QualType ParamTypes[2] = { *Enum, *Enum };
3190 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3191 }
3192
3193 // Fall through.
3194 isComparison = true;
3195
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003196 BinaryPlus:
3197 BinaryMinus:
Douglas Gregor70d26122008-11-12 17:17:38 +00003198 if (!isComparison) {
3199 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3200
3201 // C++ [over.built]p13:
3202 //
3203 // For every cv-qualified or cv-unqualified object type T
3204 // there exist candidate operator functions of the form
3205 //
3206 // T* operator+(T*, ptrdiff_t);
3207 // T& operator[](T*, ptrdiff_t); [BELOW]
3208 // T* operator-(T*, ptrdiff_t);
3209 // T* operator+(ptrdiff_t, T*);
3210 // T& operator[](ptrdiff_t, T*); [BELOW]
3211 //
3212 // C++ [over.built]p14:
3213 //
3214 // For every T, where T is a pointer to object type, there
3215 // exist candidate operator functions of the form
3216 //
3217 // ptrdiff_t operator-(T, T);
3218 for (BuiltinCandidateTypeSet::iterator Ptr
3219 = CandidateTypes.pointer_begin();
3220 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3221 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3222
3223 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3224 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3225
3226 if (Op == OO_Plus) {
3227 // T* operator+(ptrdiff_t, T*);
3228 ParamTypes[0] = ParamTypes[1];
3229 ParamTypes[1] = *Ptr;
3230 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3231 } else {
3232 // ptrdiff_t operator-(T, T);
3233 ParamTypes[1] = *Ptr;
3234 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3235 Args, 2, CandidateSet);
3236 }
3237 }
3238 }
3239 // Fall through
3240
Douglas Gregor70d26122008-11-12 17:17:38 +00003241 case OO_Slash:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003242 BinaryStar:
Sebastian Redlbd261962009-04-16 17:51:27 +00003243 Conditional:
Douglas Gregor70d26122008-11-12 17:17:38 +00003244 // C++ [over.built]p12:
3245 //
3246 // For every pair of promoted arithmetic types L and R, there
3247 // exist candidate operator functions of the form
3248 //
3249 // LR operator*(L, R);
3250 // LR operator/(L, R);
3251 // LR operator+(L, R);
3252 // LR operator-(L, R);
3253 // bool operator<(L, R);
3254 // bool operator>(L, R);
3255 // bool operator<=(L, R);
3256 // bool operator>=(L, R);
3257 // bool operator==(L, R);
3258 // bool operator!=(L, R);
3259 //
3260 // where LR is the result of the usual arithmetic conversions
3261 // between types L and R.
Sebastian Redlbd261962009-04-16 17:51:27 +00003262 //
3263 // C++ [over.built]p24:
3264 //
3265 // For every pair of promoted arithmetic types L and R, there exist
3266 // candidate operator functions of the form
3267 //
3268 // LR operator?(bool, L, R);
3269 //
3270 // where LR is the result of the usual arithmetic conversions
3271 // between types L and R.
3272 // Our candidates ignore the first parameter.
Douglas Gregor70d26122008-11-12 17:17:38 +00003273 for (unsigned Left = FirstPromotedArithmeticType;
3274 Left < LastPromotedArithmeticType; ++Left) {
3275 for (unsigned Right = FirstPromotedArithmeticType;
3276 Right < LastPromotedArithmeticType; ++Right) {
3277 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman6ae7d112009-08-19 07:44:53 +00003278 QualType Result
3279 = isComparison
3280 ? Context.BoolTy
3281 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003282 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3283 }
3284 }
3285 break;
3286
3287 case OO_Percent:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003288 BinaryAmp:
Douglas Gregor70d26122008-11-12 17:17:38 +00003289 case OO_Caret:
3290 case OO_Pipe:
3291 case OO_LessLess:
3292 case OO_GreaterGreater:
3293 // C++ [over.built]p17:
3294 //
3295 // For every pair of promoted integral types L and R, there
3296 // exist candidate operator functions of the form
3297 //
3298 // LR operator%(L, R);
3299 // LR operator&(L, R);
3300 // LR operator^(L, R);
3301 // LR operator|(L, R);
3302 // L operator<<(L, R);
3303 // L operator>>(L, R);
3304 //
3305 // where LR is the result of the usual arithmetic conversions
3306 // between types L and R.
3307 for (unsigned Left = FirstPromotedIntegralType;
3308 Left < LastPromotedIntegralType; ++Left) {
3309 for (unsigned Right = FirstPromotedIntegralType;
3310 Right < LastPromotedIntegralType; ++Right) {
3311 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3312 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3313 ? LandR[0]
Eli Friedman6ae7d112009-08-19 07:44:53 +00003314 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003315 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3316 }
3317 }
3318 break;
3319
3320 case OO_Equal:
3321 // C++ [over.built]p20:
3322 //
3323 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor9a375942009-08-24 13:43:27 +00003324 // pointer to member type and VQ is either volatile or
Douglas Gregor70d26122008-11-12 17:17:38 +00003325 // empty, there exist candidate operator functions of the form
3326 //
3327 // VQ T& operator=(VQ T&, T);
Douglas Gregor9a375942009-08-24 13:43:27 +00003328 for (BuiltinCandidateTypeSet::iterator
3329 Enum = CandidateTypes.enumeration_begin(),
3330 EnumEnd = CandidateTypes.enumeration_end();
3331 Enum != EnumEnd; ++Enum)
3332 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
3333 CandidateSet);
3334 for (BuiltinCandidateTypeSet::iterator
3335 MemPtr = CandidateTypes.member_pointer_begin(),
3336 MemPtrEnd = CandidateTypes.member_pointer_end();
3337 MemPtr != MemPtrEnd; ++MemPtr)
3338 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
3339 CandidateSet);
3340 // Fall through.
Douglas Gregor70d26122008-11-12 17:17:38 +00003341
3342 case OO_PlusEqual:
3343 case OO_MinusEqual:
3344 // C++ [over.built]p19:
3345 //
3346 // For every pair (T, VQ), where T is any type and VQ is either
3347 // volatile or empty, there exist candidate operator functions
3348 // of the form
3349 //
3350 // T*VQ& operator=(T*VQ&, T*);
3351 //
3352 // C++ [over.built]p21:
3353 //
3354 // For every pair (T, VQ), where T is a cv-qualified or
3355 // cv-unqualified object type and VQ is either volatile or
3356 // empty, there exist candidate operator functions of the form
3357 //
3358 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3359 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3360 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3361 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3362 QualType ParamTypes[2];
3363 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3364
3365 // non-volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003366 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorab141112009-01-13 00:52:54 +00003367 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3368 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003369
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003370 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3371 // volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003372 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregorab141112009-01-13 00:52:54 +00003373 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3374 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003375 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003376 }
3377 // Fall through.
3378
3379 case OO_StarEqual:
3380 case OO_SlashEqual:
3381 // C++ [over.built]p18:
3382 //
3383 // For every triple (L, VQ, R), where L is an arithmetic type,
3384 // VQ is either volatile or empty, and R is a promoted
3385 // arithmetic type, there exist candidate operator functions of
3386 // the form
3387 //
3388 // VQ L& operator=(VQ L&, R);
3389 // VQ L& operator*=(VQ L&, R);
3390 // VQ L& operator/=(VQ L&, R);
3391 // VQ L& operator+=(VQ L&, R);
3392 // VQ L& operator-=(VQ L&, R);
3393 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3394 for (unsigned Right = FirstPromotedArithmeticType;
3395 Right < LastPromotedArithmeticType; ++Right) {
3396 QualType ParamTypes[2];
3397 ParamTypes[1] = ArithmeticTypes[Right];
3398
3399 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003400 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorab141112009-01-13 00:52:54 +00003401 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3402 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003403
3404 // Add this built-in operator as a candidate (VQ is 'volatile').
3405 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003406 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregorab141112009-01-13 00:52:54 +00003407 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3408 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003409 }
3410 }
3411 break;
3412
3413 case OO_PercentEqual:
3414 case OO_LessLessEqual:
3415 case OO_GreaterGreaterEqual:
3416 case OO_AmpEqual:
3417 case OO_CaretEqual:
3418 case OO_PipeEqual:
3419 // C++ [over.built]p22:
3420 //
3421 // For every triple (L, VQ, R), where L is an integral type, VQ
3422 // is either volatile or empty, and R is a promoted integral
3423 // type, there exist candidate operator functions of the form
3424 //
3425 // VQ L& operator%=(VQ L&, R);
3426 // VQ L& operator<<=(VQ L&, R);
3427 // VQ L& operator>>=(VQ L&, R);
3428 // VQ L& operator&=(VQ L&, R);
3429 // VQ L& operator^=(VQ L&, R);
3430 // VQ L& operator|=(VQ L&, R);
3431 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3432 for (unsigned Right = FirstPromotedIntegralType;
3433 Right < LastPromotedIntegralType; ++Right) {
3434 QualType ParamTypes[2];
3435 ParamTypes[1] = ArithmeticTypes[Right];
3436
3437 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003438 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003439 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3440
3441 // Add this built-in operator as a candidate (VQ is 'volatile').
3442 ParamTypes[0] = ArithmeticTypes[Left];
3443 ParamTypes[0].addVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003444 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003445 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3446 }
3447 }
3448 break;
3449
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003450 case OO_Exclaim: {
3451 // C++ [over.operator]p23:
3452 //
3453 // There also exist candidate operator functions of the form
3454 //
3455 // bool operator!(bool);
3456 // bool operator&&(bool, bool); [BELOW]
3457 // bool operator||(bool, bool); [BELOW]
3458 QualType ParamTy = Context.BoolTy;
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003459 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3460 /*IsAssignmentOperator=*/false,
3461 /*NumContextualBoolArguments=*/1);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003462 break;
3463 }
3464
Douglas Gregor70d26122008-11-12 17:17:38 +00003465 case OO_AmpAmp:
3466 case OO_PipePipe: {
3467 // C++ [over.operator]p23:
3468 //
3469 // There also exist candidate operator functions of the form
3470 //
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003471 // bool operator!(bool); [ABOVE]
Douglas Gregor70d26122008-11-12 17:17:38 +00003472 // bool operator&&(bool, bool);
3473 // bool operator||(bool, bool);
3474 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003475 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3476 /*IsAssignmentOperator=*/false,
3477 /*NumContextualBoolArguments=*/2);
Douglas Gregor70d26122008-11-12 17:17:38 +00003478 break;
3479 }
3480
3481 case OO_Subscript:
3482 // C++ [over.built]p13:
3483 //
3484 // For every cv-qualified or cv-unqualified object type T there
3485 // exist candidate operator functions of the form
3486 //
3487 // T* operator+(T*, ptrdiff_t); [ABOVE]
3488 // T& operator[](T*, ptrdiff_t);
3489 // T* operator-(T*, ptrdiff_t); [ABOVE]
3490 // T* operator+(ptrdiff_t, T*); [ABOVE]
3491 // T& operator[](ptrdiff_t, T*);
3492 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3493 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3494 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003495 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003496 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregor70d26122008-11-12 17:17:38 +00003497
3498 // T& operator[](T*, ptrdiff_t)
3499 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3500
3501 // T& operator[](ptrdiff_t, T*);
3502 ParamTypes[0] = ParamTypes[1];
3503 ParamTypes[1] = *Ptr;
3504 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3505 }
3506 break;
3507
3508 case OO_ArrowStar:
3509 // FIXME: No support for pointer-to-members yet.
3510 break;
Sebastian Redlbd261962009-04-16 17:51:27 +00003511
3512 case OO_Conditional:
3513 // Note that we don't consider the first argument, since it has been
3514 // contextually converted to bool long ago. The candidates below are
3515 // therefore added as binary.
3516 //
3517 // C++ [over.built]p24:
3518 // For every type T, where T is a pointer or pointer-to-member type,
3519 // there exist candidate operator functions of the form
3520 //
3521 // T operator?(bool, T, T);
3522 //
Sebastian Redlbd261962009-04-16 17:51:27 +00003523 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3524 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3525 QualType ParamTypes[2] = { *Ptr, *Ptr };
3526 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3527 }
Sebastian Redl674d1b72009-04-19 21:53:20 +00003528 for (BuiltinCandidateTypeSet::iterator Ptr =
3529 CandidateTypes.member_pointer_begin(),
3530 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3531 QualType ParamTypes[2] = { *Ptr, *Ptr };
3532 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3533 }
Sebastian Redlbd261962009-04-16 17:51:27 +00003534 goto Conditional;
Douglas Gregor70d26122008-11-12 17:17:38 +00003535 }
3536}
3537
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003538/// \brief Add function candidates found via argument-dependent lookup
3539/// to the set of overloading candidates.
3540///
3541/// This routine performs argument-dependent name lookup based on the
3542/// given function name (which may also be an operator name) and adds
3543/// all of the overload candidates found by ADL to the overload
3544/// candidate set (C++ [basic.lookup.argdep]).
3545void
3546Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3547 Expr **Args, unsigned NumArgs,
3548 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003549 FunctionSet Functions;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003550
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003551 // Record all of the function candidates that we've already
3552 // added to the overload set, so that we don't add those same
3553 // candidates a second time.
3554 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3555 CandEnd = CandidateSet.end();
3556 Cand != CandEnd; ++Cand)
Douglas Gregor993a0602009-06-27 21:05:07 +00003557 if (Cand->Function) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003558 Functions.insert(Cand->Function);
Douglas Gregor993a0602009-06-27 21:05:07 +00003559 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3560 Functions.insert(FunTmpl);
3561 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003562
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003563 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003564
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003565 // Erase all of the candidates we already knew about.
3566 // FIXME: This is suboptimal. Is there a better way?
3567 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3568 CandEnd = CandidateSet.end();
3569 Cand != CandEnd; ++Cand)
Douglas Gregor993a0602009-06-27 21:05:07 +00003570 if (Cand->Function) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003571 Functions.erase(Cand->Function);
Douglas Gregor993a0602009-06-27 21:05:07 +00003572 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3573 Functions.erase(FunTmpl);
3574 }
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003575
3576 // For each of the ADL candidates we found, add it to the overload
3577 // set.
3578 for (FunctionSet::iterator Func = Functions.begin(),
3579 FuncEnd = Functions.end();
Douglas Gregor993a0602009-06-27 21:05:07 +00003580 Func != FuncEnd; ++Func) {
3581 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
3582 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet);
3583 else
Douglas Gregorc9a03b72009-06-30 23:57:56 +00003584 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
3585 /*FIXME: explicit args */false, 0, 0,
3586 Args, NumArgs, CandidateSet);
Douglas Gregor993a0602009-06-27 21:05:07 +00003587 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003588}
3589
Douglas Gregord2baafd2008-10-21 16:13:35 +00003590/// isBetterOverloadCandidate - Determines whether the first overload
3591/// candidate is a better candidate than the second (C++ 13.3.3p1).
3592bool
3593Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3594 const OverloadCandidate& Cand2)
3595{
3596 // Define viable functions to be better candidates than non-viable
3597 // functions.
3598 if (!Cand2.Viable)
3599 return Cand1.Viable;
3600 else if (!Cand1.Viable)
3601 return false;
3602
Douglas Gregor3257fb52008-12-22 05:46:06 +00003603 // C++ [over.match.best]p1:
3604 //
3605 // -- if F is a static member function, ICS1(F) is defined such
3606 // that ICS1(F) is neither better nor worse than ICS1(G) for
3607 // any function G, and, symmetrically, ICS1(G) is neither
3608 // better nor worse than ICS1(F).
3609 unsigned StartArg = 0;
3610 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3611 StartArg = 1;
Douglas Gregord2baafd2008-10-21 16:13:35 +00003612
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003613 // C++ [over.match.best]p1:
3614 // A viable function F1 is defined to be a better function than another
3615 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
3616 // conversion sequence than ICSi(F2), and then...
Douglas Gregord2baafd2008-10-21 16:13:35 +00003617 unsigned NumArgs = Cand1.Conversions.size();
3618 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3619 bool HasBetterConversion = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00003620 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00003621 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3622 Cand2.Conversions[ArgIdx])) {
3623 case ImplicitConversionSequence::Better:
3624 // Cand1 has a better conversion sequence.
3625 HasBetterConversion = true;
3626 break;
3627
3628 case ImplicitConversionSequence::Worse:
3629 // Cand1 can't be better than Cand2.
3630 return false;
3631
3632 case ImplicitConversionSequence::Indistinguishable:
3633 // Do nothing.
3634 break;
3635 }
3636 }
3637
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003638 // -- for some argument j, ICSj(F1) is a better conversion sequence than
3639 // ICSj(F2), or, if not that,
Douglas Gregord2baafd2008-10-21 16:13:35 +00003640 if (HasBetterConversion)
3641 return true;
3642
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003643 // - F1 is a non-template function and F2 is a function template
3644 // specialization, or, if not that,
3645 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3646 Cand2.Function && Cand2.Function->getPrimaryTemplate())
3647 return true;
3648
3649 // -- F1 and F2 are function template specializations, and the function
3650 // template for F1 is more specialized than the template for F2
3651 // according to the partial ordering rules described in 14.5.5.2, or,
3652 // if not that,
Douglas Gregorf8e51672009-08-02 23:46:29 +00003653 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
3654 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor8c860df2009-08-21 23:19:43 +00003655 if (FunctionTemplateDecl *BetterTemplate
3656 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
3657 Cand2.Function->getPrimaryTemplate(),
3658 true))
3659 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregord2baafd2008-10-21 16:13:35 +00003660
Douglas Gregor60714f92008-11-07 22:36:19 +00003661 // -- the context is an initialization by user-defined conversion
3662 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3663 // from the return type of F1 to the destination type (i.e.,
3664 // the type of the entity being initialized) is a better
3665 // conversion sequence than the standard conversion sequence
3666 // from the return type of F2 to the destination type.
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003667 if (Cand1.Function && Cand2.Function &&
3668 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregor60714f92008-11-07 22:36:19 +00003669 isa<CXXConversionDecl>(Cand2.Function)) {
3670 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3671 Cand2.FinalConversion)) {
3672 case ImplicitConversionSequence::Better:
3673 // Cand1 has a better conversion sequence.
3674 return true;
3675
3676 case ImplicitConversionSequence::Worse:
3677 // Cand1 can't be better than Cand2.
3678 return false;
3679
3680 case ImplicitConversionSequence::Indistinguishable:
3681 // Do nothing
3682 break;
3683 }
3684 }
3685
Douglas Gregord2baafd2008-10-21 16:13:35 +00003686 return false;
3687}
3688
Douglas Gregor98189262009-06-19 23:52:42 +00003689/// \brief Computes the best viable function (C++ 13.3.3)
3690/// within an overload candidate set.
3691///
3692/// \param CandidateSet the set of candidate functions.
3693///
3694/// \param Loc the location of the function name (or operator symbol) for
3695/// which overload resolution occurs.
3696///
3697/// \param Best f overload resolution was successful or found a deleted
3698/// function, Best points to the candidate function found.
3699///
3700/// \returns The result of overload resolution.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003701Sema::OverloadingResult
3702Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregor98189262009-06-19 23:52:42 +00003703 SourceLocation Loc,
Douglas Gregord2baafd2008-10-21 16:13:35 +00003704 OverloadCandidateSet::iterator& Best)
3705{
3706 // Find the best viable function.
3707 Best = CandidateSet.end();
3708 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3709 Cand != CandidateSet.end(); ++Cand) {
3710 if (Cand->Viable) {
3711 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3712 Best = Cand;
3713 }
3714 }
3715
3716 // If we didn't find any viable functions, abort.
3717 if (Best == CandidateSet.end())
3718 return OR_No_Viable_Function;
3719
3720 // Make sure that this function is better than every other viable
3721 // function. If not, we have an ambiguity.
3722 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3723 Cand != CandidateSet.end(); ++Cand) {
3724 if (Cand->Viable &&
3725 Cand != Best &&
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003726 !isBetterOverloadCandidate(*Best, *Cand)) {
3727 Best = CandidateSet.end();
Douglas Gregord2baafd2008-10-21 16:13:35 +00003728 return OR_Ambiguous;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003729 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003730 }
3731
3732 // Best is the best viable function.
Douglas Gregoraa57e862009-02-18 21:56:37 +00003733 if (Best->Function &&
3734 (Best->Function->isDeleted() ||
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003735 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregoraa57e862009-02-18 21:56:37 +00003736 return OR_Deleted;
3737
Douglas Gregor98189262009-06-19 23:52:42 +00003738 // C++ [basic.def.odr]p2:
3739 // An overloaded function is used if it is selected by overload resolution
3740 // when referred to from a potentially-evaluated expression. [Note: this
3741 // covers calls to named functions (5.2.2), operator overloading
3742 // (clause 13), user-defined conversions (12.3.2), allocation function for
3743 // placement new (5.3.4), as well as non-default initialization (8.5).
3744 if (Best->Function)
3745 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregord2baafd2008-10-21 16:13:35 +00003746 return OR_Success;
3747}
3748
3749/// PrintOverloadCandidates - When overload resolution fails, prints
3750/// diagnostic messages containing the candidates in the candidate
3751/// set. If OnlyViable is true, only viable candidates will be printed.
3752void
3753Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3754 bool OnlyViable)
3755{
3756 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3757 LastCand = CandidateSet.end();
3758 for (; Cand != LastCand; ++Cand) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003759 if (Cand->Viable || !OnlyViable) {
3760 if (Cand->Function) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003761 if (Cand->Function->isDeleted() ||
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003762 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003763 // Deleted or "unavailable" function.
3764 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3765 << Cand->Function->isDeleted();
3766 } else {
3767 // Normal function
3768 // FIXME: Give a better reason!
3769 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3770 }
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003771 } else if (Cand->IsSurrogate) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003772 // Desugar the type of the surrogate down to a function type,
3773 // retaining as many typedefs as possible while still showing
3774 // the function type (and, therefore, its parameter types).
3775 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003776 bool isLValueReference = false;
3777 bool isRValueReference = false;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003778 bool isPointer = false;
Sebastian Redlce6fff02009-03-16 23:22:08 +00003779 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003780 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003781 FnType = FnTypeRef->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003782 isLValueReference = true;
3783 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003784 FnType->getAs<RValueReferenceType>()) {
Sebastian Redlce6fff02009-03-16 23:22:08 +00003785 FnType = FnTypeRef->getPointeeType();
3786 isRValueReference = true;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003787 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003788 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003789 FnType = FnTypePtr->getPointeeType();
3790 isPointer = true;
3791 }
3792 // Desugar down to a function type.
3793 FnType = QualType(FnType->getAsFunctionType(), 0);
3794 // Reconstruct the pointer/reference as appropriate.
3795 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redlce6fff02009-03-16 23:22:08 +00003796 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3797 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003798
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003799 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003800 << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003801 } else {
3802 // FIXME: We need to get the identifier in here
Mike Stumpe127ae32009-05-16 07:39:55 +00003803 // FIXME: Do we want the error message to point at the operator?
3804 // (built-ins won't have a location)
Douglas Gregor70d26122008-11-12 17:17:38 +00003805 QualType FnType
3806 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3807 Cand->BuiltinTypes.ParamTypes,
3808 Cand->Conversions.size(),
3809 false, 0);
3810
Chris Lattner4bfd2232008-11-24 06:25:27 +00003811 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003812 }
3813 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003814 }
3815}
3816
Douglas Gregor45014fd2008-11-10 20:40:00 +00003817/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3818/// an overloaded function (C++ [over.over]), where @p From is an
3819/// expression with overloaded function type and @p ToType is the type
3820/// we're trying to resolve to. For example:
3821///
3822/// @code
3823/// int f(double);
3824/// int f(int);
3825///
3826/// int (*pfd)(double) = f; // selects f(double)
3827/// @endcode
3828///
3829/// This routine returns the resulting FunctionDecl if it could be
3830/// resolved, and NULL otherwise. When @p Complain is true, this
3831/// routine will emit diagnostics if there is an error.
3832FunctionDecl *
Sebastian Redl7434fc32009-02-04 21:23:32 +00003833Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor45014fd2008-11-10 20:40:00 +00003834 bool Complain) {
3835 QualType FunctionType = ToType;
Sebastian Redl7434fc32009-02-04 21:23:32 +00003836 bool IsMember = false;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003837 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor45014fd2008-11-10 20:40:00 +00003838 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003839 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarf6c06ce2009-02-26 19:13:44 +00003840 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl7434fc32009-02-04 21:23:32 +00003841 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003842 ToType->getAs<MemberPointerType>()) {
Sebastian Redl7434fc32009-02-04 21:23:32 +00003843 FunctionType = MemTypePtr->getPointeeType();
3844 IsMember = true;
3845 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003846
3847 // We only look at pointers or references to functions.
Douglas Gregor72bb4992009-07-09 17:16:51 +00003848 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor62f78762009-07-08 20:55:45 +00003849 if (!FunctionType->isFunctionType())
Douglas Gregor45014fd2008-11-10 20:40:00 +00003850 return 0;
3851
3852 // Find the actual overloaded function declaration.
3853 OverloadedFunctionDecl *Ovl = 0;
3854
3855 // C++ [over.over]p1:
3856 // [...] [Note: any redundant set of parentheses surrounding the
3857 // overloaded function name is ignored (5.1). ]
3858 Expr *OvlExpr = From->IgnoreParens();
3859
3860 // C++ [over.over]p1:
3861 // [...] The overloaded function name can be preceded by the &
3862 // operator.
3863 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3864 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3865 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3866 }
3867
3868 // Try to dig out the overloaded function.
Douglas Gregor62f78762009-07-08 20:55:45 +00003869 FunctionTemplateDecl *FunctionTemplate = 0;
3870 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003871 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor62f78762009-07-08 20:55:45 +00003872 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
3873 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003874
Douglas Gregor62f78762009-07-08 20:55:45 +00003875 // If there's no overloaded function declaration or function template,
3876 // we're done.
3877 if (!Ovl && !FunctionTemplate)
Douglas Gregor45014fd2008-11-10 20:40:00 +00003878 return 0;
3879
Douglas Gregor62f78762009-07-08 20:55:45 +00003880 OverloadIterator Fun;
3881 if (Ovl)
3882 Fun = Ovl;
3883 else
3884 Fun = FunctionTemplate;
3885
Douglas Gregor45014fd2008-11-10 20:40:00 +00003886 // Look through all of the overloaded functions, searching for one
3887 // whose type matches exactly.
Douglas Gregora142a052009-07-08 23:33:52 +00003888 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
3889
3890 bool FoundNonTemplateFunction = false;
Douglas Gregor62f78762009-07-08 20:55:45 +00003891 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003892 // C++ [over.over]p3:
3893 // Non-member functions and static member functions match
Sebastian Redl3a75abf2009-02-05 12:33:33 +00003894 // targets of type "pointer-to-function" or "reference-to-function."
3895 // Nonstatic member functions match targets of
Sebastian Redl7434fc32009-02-04 21:23:32 +00003896 // type "pointer-to-member-function."
3897 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor62f78762009-07-08 20:55:45 +00003898
3899 if (FunctionTemplateDecl *FunctionTemplate
3900 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Douglas Gregora142a052009-07-08 23:33:52 +00003901 if (CXXMethodDecl *Method
3902 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
3903 // Skip non-static function templates when converting to pointer, and
3904 // static when converting to member pointer.
3905 if (Method->isStatic() == IsMember)
3906 continue;
3907 } else if (IsMember)
3908 continue;
3909
3910 // C++ [over.over]p2:
3911 // If the name is a function template, template argument deduction is
3912 // done (14.8.2.2), and if the argument deduction succeeds, the
3913 // resulting template argument list is used to generate a single
3914 // function template specialization, which is added to the set of
3915 // overloaded functions considered.
Douglas Gregor62f78762009-07-08 20:55:45 +00003916 FunctionDecl *Specialization = 0;
3917 TemplateDeductionInfo Info(Context);
3918 if (TemplateDeductionResult Result
3919 = DeduceTemplateArguments(FunctionTemplate, /*FIXME*/false,
3920 /*FIXME:*/0, /*FIXME:*/0,
3921 FunctionType, Specialization, Info)) {
3922 // FIXME: make a note of the failed deduction for diagnostics.
3923 (void)Result;
3924 } else {
3925 assert(FunctionType
3926 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregora142a052009-07-08 23:33:52 +00003927 Matches.insert(
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00003928 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor62f78762009-07-08 20:55:45 +00003929 }
3930 }
3931
Sebastian Redl7434fc32009-02-04 21:23:32 +00003932 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3933 // Skip non-static functions when converting to pointer, and static
3934 // when converting to member pointer.
3935 if (Method->isStatic() == IsMember)
Douglas Gregor45014fd2008-11-10 20:40:00 +00003936 continue;
Douglas Gregora142a052009-07-08 23:33:52 +00003937 } else if (IsMember)
Sebastian Redl7434fc32009-02-04 21:23:32 +00003938 continue;
Douglas Gregor45014fd2008-11-10 20:40:00 +00003939
Douglas Gregorb60eb752009-06-25 22:08:12 +00003940 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregora142a052009-07-08 23:33:52 +00003941 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00003942 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregora142a052009-07-08 23:33:52 +00003943 FoundNonTemplateFunction = true;
3944 }
Douglas Gregor62f78762009-07-08 20:55:45 +00003945 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003946 }
3947
Douglas Gregora142a052009-07-08 23:33:52 +00003948 // If there were 0 or 1 matches, we're done.
3949 if (Matches.empty())
3950 return 0;
3951 else if (Matches.size() == 1)
3952 return *Matches.begin();
3953
3954 // C++ [over.over]p4:
3955 // If more than one function is selected, [...]
3956 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
Douglas Gregor8c860df2009-08-21 23:19:43 +00003957 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregora142a052009-07-08 23:33:52 +00003958 if (FoundNonTemplateFunction) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00003959 // [...] any function template specializations in the set are
3960 // eliminated if the set also contains a non-template function, [...]
3961 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
Douglas Gregora142a052009-07-08 23:33:52 +00003962 if ((*M)->getPrimaryTemplate() == 0)
3963 RemainingMatches.push_back(*M);
3964 } else {
Douglas Gregor8c860df2009-08-21 23:19:43 +00003965 // [...] and any given function template specialization F1 is
3966 // eliminated if the set contains a second function template
3967 // specialization whose function template is more specialized
3968 // than the function template of F1 according to the partial
3969 // ordering rules of 14.5.5.2.
3970
3971 // The algorithm specified above is quadratic. We instead use a
3972 // two-pass algorithm (similar to the one used to identify the
3973 // best viable function in an overload set) that identifies the
3974 // best function template (if it exists).
3975 MatchIter Best = Matches.begin();
3976 MatchIter M = Best, MEnd = Matches.end();
3977 // Find the most specialized function.
3978 for (++M; M != MEnd; ++M)
3979 if (getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
3980 (*Best)->getPrimaryTemplate(),
3981 false)
3982 == (*M)->getPrimaryTemplate())
3983 Best = M;
3984
3985 // Determine whether this function template is more specialized
3986 // that all of the others.
3987 bool Ambiguous = false;
3988 for (M = Matches.begin(); M != MEnd; ++M) {
3989 if (M != Best &&
3990 getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
3991 (*Best)->getPrimaryTemplate(),
3992 false)
3993 != (*Best)->getPrimaryTemplate()) {
3994 Ambiguous = true;
3995 break;
3996 }
3997 }
3998
3999 // If one function template was more specialized than all of the
4000 // others, return it.
4001 if (!Ambiguous)
4002 return *Best;
4003
4004 // We could not find a most-specialized function template, which
4005 // is equivalent to having a set of function templates with more
4006 // than one such template. So, we place all of the function
4007 // templates into the set of remaining matches and produce a
4008 // diagnostic below. FIXME: we could perform the quadratic
4009 // algorithm here, pruning the result set to limit the number of
4010 // candidates output later.
4011 RemainingMatches.append(Matches.begin(), Matches.end());
Douglas Gregora142a052009-07-08 23:33:52 +00004012 }
4013
4014 // [...] After such eliminations, if any, there shall remain exactly one
4015 // selected function.
4016 if (RemainingMatches.size() == 1)
4017 return RemainingMatches.front();
4018
4019 // FIXME: We should probably return the same thing that BestViableFunction
4020 // returns (even if we issue the diagnostics here).
4021 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4022 << RemainingMatches[0]->getDeclName();
4023 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4024 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregor45014fd2008-11-10 20:40:00 +00004025 return 0;
4026}
4027
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004028/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004029/// (which eventually refers to the declaration Func) and the call
4030/// arguments Args/NumArgs, attempt to resolve the function call down
4031/// to a specific function. If overload resolution succeeds, returns
4032/// the function declaration produced by overload
Douglas Gregorbf4f0582008-11-26 06:01:48 +00004033/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004034/// arguments and Fn, and returns NULL.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004035FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004036 DeclarationName UnqualifiedName,
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004037 bool HasExplicitTemplateArgs,
4038 const TemplateArgument *ExplicitTemplateArgs,
4039 unsigned NumExplicitTemplateArgs,
Douglas Gregorbf4f0582008-11-26 06:01:48 +00004040 SourceLocation LParenLoc,
4041 Expr **Args, unsigned NumArgs,
4042 SourceLocation *CommaLocs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004043 SourceLocation RParenLoc,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004044 bool &ArgumentDependentLookup) {
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004045 OverloadCandidateSet CandidateSet;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004046
4047 // Add the functions denoted by Callee to the set of candidate
4048 // functions. While we're doing so, track whether argument-dependent
4049 // lookup still applies, per:
4050 //
4051 // C++0x [basic.lookup.argdep]p3:
4052 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4053 // and let Y be the lookup set produced by argument dependent
4054 // lookup (defined as follows). If X contains
4055 //
4056 // -- a declaration of a class member, or
4057 //
4058 // -- a block-scope function declaration that is not a
4059 // using-declaration, or
4060 //
4061 // -- a declaration that is neither a function or a function
4062 // template
4063 //
4064 // then Y is empty.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004065 if (OverloadedFunctionDecl *Ovl
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004066 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
4067 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4068 FuncEnd = Ovl->function_end();
4069 Func != FuncEnd; ++Func) {
Douglas Gregorb60eb752009-06-25 22:08:12 +00004070 DeclContext *Ctx = 0;
4071 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Func)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004072 if (HasExplicitTemplateArgs)
4073 continue;
4074
Douglas Gregorb60eb752009-06-25 22:08:12 +00004075 AddOverloadCandidate(FunDecl, Args, NumArgs, CandidateSet);
4076 Ctx = FunDecl->getDeclContext();
4077 } else {
4078 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*Func);
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004079 AddTemplateOverloadCandidate(FunTmpl, HasExplicitTemplateArgs,
4080 ExplicitTemplateArgs,
4081 NumExplicitTemplateArgs,
4082 Args, NumArgs, CandidateSet);
Douglas Gregorb60eb752009-06-25 22:08:12 +00004083 Ctx = FunTmpl->getDeclContext();
4084 }
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004085
Douglas Gregorb60eb752009-06-25 22:08:12 +00004086
4087 if (Ctx->isRecord() || Ctx->isFunctionOrMethod())
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004088 ArgumentDependentLookup = false;
4089 }
4090 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004091 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004092 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
4093
4094 if (Func->getDeclContext()->isRecord() ||
4095 Func->getDeclContext()->isFunctionOrMethod())
4096 ArgumentDependentLookup = false;
Douglas Gregorb60eb752009-06-25 22:08:12 +00004097 } else if (FunctionTemplateDecl *FuncTemplate
4098 = dyn_cast_or_null<FunctionTemplateDecl>(Callee)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004099 AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4100 ExplicitTemplateArgs,
4101 NumExplicitTemplateArgs,
4102 Args, NumArgs, CandidateSet);
Douglas Gregorb60eb752009-06-25 22:08:12 +00004103
4104 if (FuncTemplate->getDeclContext()->isRecord())
4105 ArgumentDependentLookup = false;
4106 }
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004107
4108 if (Callee)
4109 UnqualifiedName = Callee->getDeclName();
4110
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004111 // FIXME: Pass explicit template arguments through for ADL
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004112 if (ArgumentDependentLookup)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004113 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004114 CandidateSet);
4115
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004116 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004117 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00004118 case OR_Success:
4119 return Best->Function;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004120
4121 case OR_No_Viable_Function:
Chris Lattner4a526112009-02-17 07:29:20 +00004122 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004123 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004124 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004125 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4126 break;
4127
4128 case OR_Ambiguous:
4129 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004130 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004131 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4132 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004133
4134 case OR_Deleted:
4135 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4136 << Best->Function->isDeleted()
4137 << UnqualifiedName
4138 << Fn->getSourceRange();
4139 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4140 break;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004141 }
4142
4143 // Overload resolution failed. Destroy all of the subexpressions and
4144 // return NULL.
4145 Fn->Destroy(Context);
4146 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4147 Args[Arg]->Destroy(Context);
4148 return 0;
4149}
4150
Douglas Gregorc78182d2009-03-13 23:49:33 +00004151/// \brief Create a unary operation that may resolve to an overloaded
4152/// operator.
4153///
4154/// \param OpLoc The location of the operator itself (e.g., '*').
4155///
4156/// \param OpcIn The UnaryOperator::Opcode that describes this
4157/// operator.
4158///
4159/// \param Functions The set of non-member functions that will be
4160/// considered by overload resolution. The caller needs to build this
4161/// set based on the context using, e.g.,
4162/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4163/// set should not contain any member functions; those will be added
4164/// by CreateOverloadedUnaryOp().
4165///
4166/// \param input The input argument.
4167Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4168 unsigned OpcIn,
4169 FunctionSet &Functions,
4170 ExprArg input) {
4171 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4172 Expr *Input = (Expr *)input.get();
4173
4174 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4175 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4176 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4177
4178 Expr *Args[2] = { Input, 0 };
4179 unsigned NumArgs = 1;
4180
4181 // For post-increment and post-decrement, add the implicit '0' as
4182 // the second argument, so that we know this is a post-increment or
4183 // post-decrement.
4184 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4185 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
4186 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
4187 SourceLocation());
4188 NumArgs = 2;
4189 }
4190
4191 if (Input->isTypeDependent()) {
4192 OverloadedFunctionDecl *Overloads
4193 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4194 for (FunctionSet::iterator Func = Functions.begin(),
4195 FuncEnd = Functions.end();
4196 Func != FuncEnd; ++Func)
4197 Overloads->addOverload(*Func);
4198
4199 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4200 OpLoc, false, false);
4201
4202 input.release();
4203 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4204 &Args[0], NumArgs,
4205 Context.DependentTy,
4206 OpLoc));
4207 }
4208
4209 // Build an empty overload set.
4210 OverloadCandidateSet CandidateSet;
4211
4212 // Add the candidates from the given function set.
4213 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4214
4215 // Add operator candidates that are member functions.
4216 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4217
4218 // Add builtin operator candidates.
4219 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
4220
4221 // Perform overload resolution.
4222 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004223 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00004224 case OR_Success: {
4225 // We found a built-in operator or an overloaded operator.
4226 FunctionDecl *FnDecl = Best->Function;
4227
4228 if (FnDecl) {
4229 // We matched an overloaded operator. Build a call to that
4230 // operator.
4231
4232 // Convert the arguments.
4233 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4234 if (PerformObjectArgumentInitialization(Input, Method))
4235 return ExprError();
4236 } else {
4237 // Convert the arguments.
4238 if (PerformCopyInitialization(Input,
4239 FnDecl->getParamDecl(0)->getType(),
4240 "passing"))
4241 return ExprError();
4242 }
4243
4244 // Determine the result type
4245 QualType ResultTy
4246 = FnDecl->getType()->getAsFunctionType()->getResultType();
4247 ResultTy = ResultTy.getNonReferenceType();
4248
4249 // Build the actual expression node.
4250 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4251 SourceLocation());
4252 UsualUnaryConversions(FnExpr);
4253
4254 input.release();
Anders Carlsson16497742009-08-16 04:11:06 +00004255
4256 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4257 &Input, 1, ResultTy, OpLoc);
4258 return MaybeBindToTemporary(CE);
Douglas Gregorc78182d2009-03-13 23:49:33 +00004259 } else {
4260 // We matched a built-in operator. Convert the arguments, then
4261 // break out so that we will build the appropriate built-in
4262 // operator node.
4263 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4264 Best->Conversions[0], "passing"))
4265 return ExprError();
4266
4267 break;
4268 }
4269 }
4270
4271 case OR_No_Viable_Function:
4272 // No viable function; fall through to handling this as a
4273 // built-in operator, which will produce an error message for us.
4274 break;
4275
4276 case OR_Ambiguous:
4277 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4278 << UnaryOperator::getOpcodeStr(Opc)
4279 << Input->getSourceRange();
4280 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4281 return ExprError();
4282
4283 case OR_Deleted:
4284 Diag(OpLoc, diag::err_ovl_deleted_oper)
4285 << Best->Function->isDeleted()
4286 << UnaryOperator::getOpcodeStr(Opc)
4287 << Input->getSourceRange();
4288 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4289 return ExprError();
4290 }
4291
4292 // Either we found no viable overloaded operator or we matched a
4293 // built-in operator. In either case, fall through to trying to
4294 // build a built-in operation.
4295 input.release();
4296 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4297}
4298
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004299/// \brief Create a binary operation that may resolve to an overloaded
4300/// operator.
4301///
4302/// \param OpLoc The location of the operator itself (e.g., '+').
4303///
4304/// \param OpcIn The BinaryOperator::Opcode that describes this
4305/// operator.
4306///
4307/// \param Functions The set of non-member functions that will be
4308/// considered by overload resolution. The caller needs to build this
4309/// set based on the context using, e.g.,
4310/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4311/// set should not contain any member functions; those will be added
4312/// by CreateOverloadedBinOp().
4313///
4314/// \param LHS Left-hand argument.
4315/// \param RHS Right-hand argument.
4316Sema::OwningExprResult
4317Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
4318 unsigned OpcIn,
4319 FunctionSet &Functions,
4320 Expr *LHS, Expr *RHS) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004321 Expr *Args[2] = { LHS, RHS };
4322
4323 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4324 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4325 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4326
4327 // If either side is type-dependent, create an appropriate dependent
4328 // expression.
4329 if (LHS->isTypeDependent() || RHS->isTypeDependent()) {
4330 // .* cannot be overloaded.
4331 if (Opc == BinaryOperator::PtrMemD)
4332 return Owned(new (Context) BinaryOperator(LHS, RHS, Opc,
4333 Context.DependentTy, OpLoc));
4334
4335 OverloadedFunctionDecl *Overloads
4336 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4337 for (FunctionSet::iterator Func = Functions.begin(),
4338 FuncEnd = Functions.end();
4339 Func != FuncEnd; ++Func)
4340 Overloads->addOverload(*Func);
4341
4342 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4343 OpLoc, false, false);
4344
4345 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4346 Args, 2,
4347 Context.DependentTy,
4348 OpLoc));
4349 }
4350
4351 // If this is the .* operator, which is not overloadable, just
4352 // create a built-in binary operator.
4353 if (Opc == BinaryOperator::PtrMemD)
4354 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4355
4356 // If this is one of the assignment operators, we only perform
4357 // overload resolution if the left-hand side is a class or
4358 // enumeration type (C++ [expr.ass]p3).
4359 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
4360 !LHS->getType()->isOverloadableType())
4361 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4362
Douglas Gregorc78182d2009-03-13 23:49:33 +00004363 // Build an empty overload set.
4364 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004365
4366 // Add the candidates from the given function set.
4367 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4368
4369 // Add operator candidates that are member functions.
4370 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4371
4372 // Add builtin operator candidates.
4373 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4374
4375 // Perform overload resolution.
4376 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004377 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00004378 case OR_Success: {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004379 // We found a built-in operator or an overloaded operator.
4380 FunctionDecl *FnDecl = Best->Function;
4381
4382 if (FnDecl) {
4383 // We matched an overloaded operator. Build a call to that
4384 // operator.
4385
4386 // Convert the arguments.
4387 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4388 if (PerformObjectArgumentInitialization(LHS, Method) ||
4389 PerformCopyInitialization(RHS, FnDecl->getParamDecl(0)->getType(),
4390 "passing"))
4391 return ExprError();
4392 } else {
4393 // Convert the arguments.
4394 if (PerformCopyInitialization(LHS, FnDecl->getParamDecl(0)->getType(),
4395 "passing") ||
4396 PerformCopyInitialization(RHS, FnDecl->getParamDecl(1)->getType(),
4397 "passing"))
4398 return ExprError();
4399 }
4400
4401 // Determine the result type
4402 QualType ResultTy
4403 = FnDecl->getType()->getAsFunctionType()->getResultType();
4404 ResultTy = ResultTy.getNonReferenceType();
4405
4406 // Build the actual expression node.
4407 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argiris Kirtzidiscca21b82009-07-14 03:19:38 +00004408 OpLoc);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004409 UsualUnaryConversions(FnExpr);
4410
Anders Carlsson16497742009-08-16 04:11:06 +00004411 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4412 Args, 2, ResultTy, OpLoc);
4413 return MaybeBindToTemporary(CE);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004414 } else {
4415 // We matched a built-in operator. Convert the arguments, then
4416 // break out so that we will build the appropriate built-in
4417 // operator node.
4418 if (PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
4419 Best->Conversions[0], "passing") ||
4420 PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
4421 Best->Conversions[1], "passing"))
4422 return ExprError();
4423
4424 break;
4425 }
4426 }
4427
4428 case OR_No_Viable_Function:
Sebastian Redl35196b42009-05-21 11:50:50 +00004429 // For class as left operand for assignment or compound assigment operator
4430 // do not fall through to handling in built-in, but report that no overloaded
4431 // assignment operator found
4432 if (LHS->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
4433 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4434 << BinaryOperator::getOpcodeStr(Opc)
4435 << LHS->getSourceRange() << RHS->getSourceRange();
4436 return ExprError();
4437 }
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004438 // No viable function; fall through to handling this as a
4439 // built-in operator, which will produce an error message for us.
4440 break;
4441
4442 case OR_Ambiguous:
4443 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4444 << BinaryOperator::getOpcodeStr(Opc)
4445 << LHS->getSourceRange() << RHS->getSourceRange();
4446 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4447 return ExprError();
4448
4449 case OR_Deleted:
4450 Diag(OpLoc, diag::err_ovl_deleted_oper)
4451 << Best->Function->isDeleted()
4452 << BinaryOperator::getOpcodeStr(Opc)
4453 << LHS->getSourceRange() << RHS->getSourceRange();
4454 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4455 return ExprError();
4456 }
4457
4458 // Either we found no viable overloaded operator or we matched a
4459 // built-in operator. In either case, try to build a built-in
4460 // operation.
4461 return CreateBuiltinBinOp(OpLoc, Opc, LHS, RHS);
4462}
4463
Douglas Gregor3257fb52008-12-22 05:46:06 +00004464/// BuildCallToMemberFunction - Build a call to a member
4465/// function. MemExpr is the expression that refers to the member
4466/// function (and includes the object parameter), Args/NumArgs are the
4467/// arguments to the function call (not including the object
4468/// parameter). The caller needs to validate that the member
4469/// expression refers to a member function or an overloaded member
4470/// function.
4471Sema::ExprResult
4472Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4473 SourceLocation LParenLoc, Expr **Args,
4474 unsigned NumArgs, SourceLocation *CommaLocs,
4475 SourceLocation RParenLoc) {
4476 // Dig out the member expression. This holds both the object
4477 // argument and the member function we're referring to.
4478 MemberExpr *MemExpr = 0;
4479 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4480 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4481 else
4482 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4483 assert(MemExpr && "Building member call without member expression");
4484
4485 // Extract the object argument.
4486 Expr *ObjectArg = MemExpr->getBase();
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00004487
Douglas Gregor3257fb52008-12-22 05:46:06 +00004488 CXXMethodDecl *Method = 0;
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004489 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
4490 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00004491 // Add overload candidates
4492 OverloadCandidateSet CandidateSet;
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004493 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
4494
Douglas Gregor050cabf2009-08-21 18:42:58 +00004495 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
4496 Func != FuncEnd; ++Func) {
4497 if ((Method = dyn_cast<CXXMethodDecl>(*Func)))
4498 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
4499 /*SuppressUserConversions=*/false);
4500 else
4501 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
4502 /*FIXME:*/false, /*FIXME:*/0,
4503 /*FIXME:*/0, ObjectArg, Args, NumArgs,
4504 CandidateSet,
4505 /*SuppressUsedConversions=*/false);
4506 }
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004507
Douglas Gregor3257fb52008-12-22 05:46:06 +00004508 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004509 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00004510 case OR_Success:
4511 Method = cast<CXXMethodDecl>(Best->Function);
4512 break;
4513
4514 case OR_No_Viable_Function:
4515 Diag(MemExpr->getSourceRange().getBegin(),
4516 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004517 << DeclName << MemExprE->getSourceRange();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004518 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4519 // FIXME: Leaking incoming expressions!
4520 return true;
4521
4522 case OR_Ambiguous:
4523 Diag(MemExpr->getSourceRange().getBegin(),
4524 diag::err_ovl_ambiguous_member_call)
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004525 << DeclName << MemExprE->getSourceRange();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004526 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4527 // FIXME: Leaking incoming expressions!
4528 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004529
4530 case OR_Deleted:
4531 Diag(MemExpr->getSourceRange().getBegin(),
4532 diag::err_ovl_deleted_member_call)
4533 << Best->Function->isDeleted()
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004534 << DeclName << MemExprE->getSourceRange();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004535 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4536 // FIXME: Leaking incoming expressions!
4537 return true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00004538 }
4539
4540 FixOverloadedFunctionReference(MemExpr, Method);
4541 } else {
4542 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4543 }
4544
4545 assert(Method && "Member call to something that isn't a method?");
Ted Kremenek0c97e042009-02-07 01:47:29 +00004546 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek362abcd2009-02-09 20:51:47 +00004547 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
4548 NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00004549 Method->getResultType().getNonReferenceType(),
4550 RParenLoc));
4551
4552 // Convert the object argument (for a non-static member function call).
4553 if (!Method->isStatic() &&
4554 PerformObjectArgumentInitialization(ObjectArg, Method))
4555 return true;
4556 MemExpr->setBase(ObjectArg);
4557
4558 // Convert the rest of the arguments
Douglas Gregor4fa58902009-02-26 23:50:07 +00004559 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004560 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
4561 RParenLoc))
4562 return true;
4563
Anders Carlsson7fb13802009-08-16 01:56:34 +00004564 if (CheckFunctionCall(Method, TheCall.get()))
4565 return true;
Anders Carlssonb8ff3402009-08-16 03:42:12 +00004566
4567 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004568}
4569
Douglas Gregor10f3c502008-11-19 21:05:33 +00004570/// BuildCallToObjectOfClassType - Build a call to an object of class
4571/// type (C++ [over.call.object]), which can end up invoking an
4572/// overloaded function call operator (@c operator()) or performing a
4573/// user-defined conversion on the object argument.
Douglas Gregor3257fb52008-12-22 05:46:06 +00004574Sema::ExprResult
Douglas Gregora133e262008-12-06 00:22:45 +00004575Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
4576 SourceLocation LParenLoc,
Douglas Gregor10f3c502008-11-19 21:05:33 +00004577 Expr **Args, unsigned NumArgs,
4578 SourceLocation *CommaLocs,
4579 SourceLocation RParenLoc) {
4580 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004581 const RecordType *Record = Object->getType()->getAs<RecordType>();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004582
4583 // C++ [over.call.object]p1:
4584 // If the primary-expression E in the function call syntax
Eli Friedmand5a72f02009-08-05 19:21:58 +00004585 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor10f3c502008-11-19 21:05:33 +00004586 // candidate functions includes at least the function call
4587 // operators of T. The function call operators of T are obtained by
4588 // ordinary lookup of the name operator() in the context of
4589 // (E).operator().
4590 OverloadCandidateSet CandidateSet;
Douglas Gregor8acb7272008-12-11 16:49:14 +00004591 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004592 DeclContext::lookup_const_iterator Oper, OperEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00004593 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004594 Oper != OperEnd; ++Oper)
4595 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
4596 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004597
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004598 // C++ [over.call.object]p2:
4599 // In addition, for each conversion function declared in T of the
4600 // form
4601 //
4602 // operator conversion-type-id () cv-qualifier;
4603 //
4604 // where cv-qualifier is the same cv-qualification as, or a
4605 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregor261afa72008-11-20 13:33:37 +00004606 // denotes the type "pointer to function of (P1,...,Pn) returning
4607 // R", or the type "reference to pointer to function of
4608 // (P1,...,Pn) returning R", or the type "reference to function
4609 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004610 // is also considered as a candidate function. Similarly,
4611 // surrogate call functions are added to the set of candidate
4612 // functions for each conversion function declared in an
4613 // accessible base class provided the function is not hidden
4614 // within T by another intervening declaration.
4615 //
4616 // FIXME: Look in base classes for more conversion operators!
4617 OverloadedFunctionDecl *Conversions
4618 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00004619 for (OverloadedFunctionDecl::function_iterator
4620 Func = Conversions->function_begin(),
4621 FuncEnd = Conversions->function_end();
4622 Func != FuncEnd; ++Func) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00004623 CXXConversionDecl *Conv;
4624 FunctionTemplateDecl *ConvTemplate;
4625 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
4626
4627 // Skip over templated conversion functions; they aren't
4628 // surrogates.
4629 if (ConvTemplate)
4630 continue;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004631
4632 // Strip the reference type (if any) and then the pointer type (if
4633 // any) to get down to what might be a function type.
4634 QualType ConvType = Conv->getConversionType().getNonReferenceType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004635 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004636 ConvType = ConvPtrType->getPointeeType();
4637
Douglas Gregor4fa58902009-02-26 23:50:07 +00004638 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004639 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4640 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004641
4642 // Perform overload resolution.
4643 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004644 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004645 case OR_Success:
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004646 // Overload resolution succeeded; we'll build the appropriate call
4647 // below.
Douglas Gregor10f3c502008-11-19 21:05:33 +00004648 break;
4649
4650 case OR_No_Viable_Function:
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004651 Diag(Object->getSourceRange().getBegin(),
4652 diag::err_ovl_no_viable_object_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004653 << Object->getType() << Object->getSourceRange();
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004654 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004655 break;
4656
4657 case OR_Ambiguous:
4658 Diag(Object->getSourceRange().getBegin(),
4659 diag::err_ovl_ambiguous_object_call)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004660 << Object->getType() << Object->getSourceRange();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004661 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4662 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004663
4664 case OR_Deleted:
4665 Diag(Object->getSourceRange().getBegin(),
4666 diag::err_ovl_deleted_object_call)
4667 << Best->Function->isDeleted()
4668 << Object->getType() << Object->getSourceRange();
4669 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4670 break;
Douglas Gregor10f3c502008-11-19 21:05:33 +00004671 }
4672
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004673 if (Best == CandidateSet.end()) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004674 // We had an error; delete all of the subexpressions and return
4675 // the error.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004676 Object->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004677 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004678 Args[ArgIdx]->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004679 return true;
4680 }
4681
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004682 if (Best->Function == 0) {
4683 // Since there is no function declaration, this is one of the
4684 // surrogate candidates. Dig out the conversion function.
4685 CXXConversionDecl *Conv
4686 = cast<CXXConversionDecl>(
4687 Best->Conversions[0].UserDefined.ConversionFunction);
4688
4689 // We selected one of the surrogate functions that converts the
4690 // object parameter to a function pointer. Perform the conversion
4691 // on the object argument, then let ActOnCallExpr finish the job.
4692 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl8b769972009-01-19 00:08:26 +00004693 ImpCastExprToType(Object,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004694 Conv->getConversionType().getNonReferenceType(),
Anders Carlsson85186942009-07-31 01:23:52 +00004695 CastExpr::CK_Unknown,
Sebastian Redlce6fff02009-03-16 23:22:08 +00004696 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00004697 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4698 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4699 CommaLocs, RParenLoc).release();
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004700 }
4701
4702 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4703 // that calls this method, using Object for the implicit object
4704 // parameter and passing along the remaining arguments.
4705 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor4fa58902009-02-26 23:50:07 +00004706 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004707
4708 unsigned NumArgsInProto = Proto->getNumArgs();
4709 unsigned NumArgsToCheck = NumArgs;
4710
4711 // Build the full argument list for the method call (the
4712 // implicit object parameter is placed at the beginning of the
4713 // list).
4714 Expr **MethodArgs;
4715 if (NumArgs < NumArgsInProto) {
4716 NumArgsToCheck = NumArgsInProto;
4717 MethodArgs = new Expr*[NumArgsInProto + 1];
4718 } else {
4719 MethodArgs = new Expr*[NumArgs + 1];
4720 }
4721 MethodArgs[0] = Object;
4722 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4723 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
4724
Ted Kremenek0c97e042009-02-07 01:47:29 +00004725 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
4726 SourceLocation());
Douglas Gregor10f3c502008-11-19 21:05:33 +00004727 UsualUnaryConversions(NewFn);
4728
4729 // Once we've built TheCall, all of the expressions are properly
4730 // owned.
4731 QualType ResultTy = Method->getResultType().getNonReferenceType();
Ted Kremenek0c97e042009-02-07 01:47:29 +00004732 ExprOwningPtr<CXXOperatorCallExpr>
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004733 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
4734 MethodArgs, NumArgs + 1,
Ted Kremenek0c97e042009-02-07 01:47:29 +00004735 ResultTy, RParenLoc));
Douglas Gregor10f3c502008-11-19 21:05:33 +00004736 delete [] MethodArgs;
4737
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004738 // We may have default arguments. If so, we need to allocate more
4739 // slots in the call for them.
4740 if (NumArgs < NumArgsInProto)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004741 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004742 else if (NumArgs > NumArgsInProto)
4743 NumArgsToCheck = NumArgsInProto;
4744
Chris Lattner81f00ed2009-04-12 08:11:20 +00004745 bool IsError = false;
4746
Douglas Gregor10f3c502008-11-19 21:05:33 +00004747 // Initialize the implicit object parameter.
Chris Lattner81f00ed2009-04-12 08:11:20 +00004748 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004749 TheCall->setArg(0, Object);
4750
Chris Lattner81f00ed2009-04-12 08:11:20 +00004751
Douglas Gregor10f3c502008-11-19 21:05:33 +00004752 // Check the argument types.
4753 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004754 Expr *Arg;
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004755 if (i < NumArgs) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004756 Arg = Args[i];
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004757
4758 // Pass the argument.
4759 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner81f00ed2009-04-12 08:11:20 +00004760 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004761 } else {
Anders Carlsson3d752db2009-08-14 18:30:22 +00004762 Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004763 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004764
4765 TheCall->setArg(i + 1, Arg);
4766 }
4767
4768 // If this is a variadic call, handle args passed through "...".
4769 if (Proto->isVariadic()) {
4770 // Promote the arguments (C99 6.5.2.2p7).
4771 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4772 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00004773 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004774 TheCall->setArg(i + 1, Arg);
4775 }
4776 }
4777
Chris Lattner81f00ed2009-04-12 08:11:20 +00004778 if (IsError) return true;
4779
Anders Carlsson7fb13802009-08-16 01:56:34 +00004780 if (CheckFunctionCall(Method, TheCall.get()))
4781 return true;
4782
Anders Carlsson422a5fe2009-08-16 03:53:54 +00004783 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004784}
4785
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004786/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
4787/// (if one exists), where @c Base is an expression of class type and
4788/// @c Member is the name of the member we're trying to find.
Douglas Gregorda61ad22009-08-06 03:17:00 +00004789Sema::OwningExprResult
4790Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
4791 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004792 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
4793
4794 // C++ [over.ref]p1:
4795 //
4796 // [...] An expression x->m is interpreted as (x.operator->())->m
4797 // for a class object x of type T if T::operator->() exists and if
4798 // the operator is selected as the best match function by the
4799 // overload resolution mechanism (13.3).
4800 // FIXME: look in base classes.
4801 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4802 OverloadCandidateSet CandidateSet;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004803 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorda61ad22009-08-06 03:17:00 +00004804
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004805 DeclContext::lookup_const_iterator Oper, OperEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004806 for (llvm::tie(Oper, OperEnd)
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00004807 = BaseRecord->getDecl()->lookup(OpName); Oper != OperEnd; ++Oper)
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004808 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004809 /*SuppressUserConversions=*/false);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004810
4811 // Perform overload resolution.
4812 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004813 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004814 case OR_Success:
4815 // Overload resolution succeeded; we'll build the call below.
4816 break;
4817
4818 case OR_No_Viable_Function:
4819 if (CandidateSet.empty())
4820 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004821 << Base->getType() << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004822 else
4823 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004824 << "operator->" << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004825 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004826 return ExprError();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004827
4828 case OR_Ambiguous:
4829 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004830 << "operator->" << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004831 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004832 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004833
4834 case OR_Deleted:
4835 Diag(OpLoc, diag::err_ovl_deleted_oper)
4836 << Best->Function->isDeleted()
Douglas Gregorda61ad22009-08-06 03:17:00 +00004837 << "operator->" << Base->getSourceRange();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004838 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004839 return ExprError();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004840 }
4841
4842 // Convert the object parameter.
4843 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9c690e92008-11-21 03:04:22 +00004844 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregorda61ad22009-08-06 03:17:00 +00004845 return ExprError();
Douglas Gregor9c690e92008-11-21 03:04:22 +00004846
4847 // No concerns about early exits now.
Douglas Gregorda61ad22009-08-06 03:17:00 +00004848 BaseIn.release();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004849
4850 // Build the operator call.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004851 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4852 SourceLocation());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004853 UsualUnaryConversions(FnExpr);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004854 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004855 Method->getResultType().getNonReferenceType(),
4856 OpLoc);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004857 return Owned(Base);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004858}
4859
Douglas Gregor45014fd2008-11-10 20:40:00 +00004860/// FixOverloadedFunctionReference - E is an expression that refers to
4861/// a C++ overloaded function (possibly with some parentheses and
4862/// perhaps a '&' around it). We have resolved the overloaded function
4863/// to the function declaration Fn, so patch up the expression E to
4864/// refer (possibly indirectly) to Fn.
4865void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4866 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4867 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4868 E->setType(PE->getSubExpr()->getType());
4869 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
4870 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
4871 "Can only take the address of an overloaded function");
Douglas Gregor3f411962009-02-11 01:18:59 +00004872 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4873 if (Method->isStatic()) {
4874 // Do nothing: static member functions aren't any different
4875 // from non-member functions.
Mike Stump90fc78e2009-08-04 21:02:39 +00004876 } else if (QualifiedDeclRefExpr *DRE
Douglas Gregor3f411962009-02-11 01:18:59 +00004877 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4878 // We have taken the address of a pointer to member
4879 // function. Perform the computation here so that we get the
4880 // appropriate pointer to member type.
4881 DRE->setDecl(Fn);
4882 DRE->setType(Fn->getType());
4883 QualType ClassType
4884 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
4885 E->setType(Context.getMemberPointerType(Fn->getType(),
4886 ClassType.getTypePtr()));
4887 return;
4888 }
4889 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00004890 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregor2eedd992009-02-11 00:19:33 +00004891 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregor45014fd2008-11-10 20:40:00 +00004892 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor62f78762009-07-08 20:55:45 +00004893 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
4894 isa<FunctionTemplateDecl>(DR->getDecl())) &&
4895 "Expected overloaded function or function template");
Douglas Gregor45014fd2008-11-10 20:40:00 +00004896 DR->setDecl(Fn);
4897 E->setType(Fn->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004898 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4899 MemExpr->setMemberDecl(Fn);
4900 E->setType(Fn->getType());
Douglas Gregor45014fd2008-11-10 20:40:00 +00004901 } else {
4902 assert(false && "Invalid reference to overloaded function");
4903 }
4904}
4905
Douglas Gregord2baafd2008-10-21 16:13:35 +00004906} // end namespace clang