blob: c5bbd34af8a6fc0867b776850a85684789922103 [file] [log] [blame]
Douglas Gregord2baafd2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregorbb461502008-10-24 04:54:22 +000015#include "SemaInherit.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregor70d26122008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
Douglas Gregor10f3c502008-11-19 21:05:33 +000020#include "clang/AST/ExprCXX.h"
Douglas Gregor70d26122008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Anders Carlssona21e7872009-08-26 23:45:07 +000022#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor3d4492e2008-11-13 20:12:29 +000023#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregorddfd9d52008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000025#include "llvm/Support/Compiler.h"
26#include <algorithm>
Edwin Török0fbc71c2009-08-24 13:25:12 +000027#include <cstdio>
Douglas Gregord2baafd2008-10-21 16:13:35 +000028
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
Mike Stump25cf7602009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregord2baafd2008-10-21 16:13:35 +000034GetConversionCategory(ImplicitConversionKind Kind) {
35 static const ImplicitConversionCategory
36 Category[(int)ICK_Num_Conversion_Kinds] = {
37 ICC_Identity,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
41 ICC_Qualification_Adjustment,
42 ICC_Promotion,
43 ICC_Promotion,
Douglas Gregore819caf2009-02-12 00:15:05 +000044 ICC_Promotion,
45 ICC_Conversion,
46 ICC_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000047 ICC_Conversion,
48 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
Douglas Gregor2aecd1f2008-10-29 02:00:59 +000052 ICC_Conversion,
Douglas Gregorfcb19192009-02-11 23:02:49 +000053 ICC_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000054 ICC_Conversion
55 };
56 return Category[(int)Kind];
57}
58
59/// GetConversionRank - Retrieve the implicit conversion rank
60/// corresponding to the given implicit conversion kind.
61ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
62 static const ImplicitConversionRank
63 Rank[(int)ICK_Num_Conversion_Kinds] = {
64 ICR_Exact_Match,
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Promotion,
70 ICR_Promotion,
Douglas Gregore819caf2009-02-12 00:15:05 +000071 ICR_Promotion,
72 ICR_Conversion,
73 ICR_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000074 ICR_Conversion,
75 ICR_Conversion,
76 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
Douglas Gregor2aecd1f2008-10-29 02:00:59 +000079 ICR_Conversion,
Douglas Gregorfcb19192009-02-11 23:02:49 +000080 ICR_Conversion,
Douglas Gregord2baafd2008-10-21 16:13:35 +000081 ICR_Conversion
82 };
83 return Rank[(int)Kind];
84}
85
86/// GetImplicitConversionName - Return the name of this kind of
87/// implicit conversion.
88const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
89 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
90 "No conversion",
91 "Lvalue-to-rvalue",
92 "Array-to-pointer",
93 "Function-to-pointer",
94 "Qualification",
95 "Integral promotion",
96 "Floating point promotion",
Douglas Gregore819caf2009-02-12 00:15:05 +000097 "Complex promotion",
Douglas Gregord2baafd2008-10-21 16:13:35 +000098 "Integral conversion",
99 "Floating conversion",
Douglas Gregore819caf2009-02-12 00:15:05 +0000100 "Complex conversion",
Douglas Gregord2baafd2008-10-21 16:13:35 +0000101 "Floating-integral conversion",
Douglas Gregore819caf2009-02-12 00:15:05 +0000102 "Complex-real conversion",
Douglas Gregord2baafd2008-10-21 16:13:35 +0000103 "Pointer conversion",
104 "Pointer-to-member conversion",
Douglas Gregor2aecd1f2008-10-29 02:00:59 +0000105 "Boolean conversion",
Douglas Gregorfcb19192009-02-11 23:02:49 +0000106 "Compatible-types conversion",
Douglas Gregor2aecd1f2008-10-29 02:00:59 +0000107 "Derived-to-base conversion"
Douglas Gregord2baafd2008-10-21 16:13:35 +0000108 };
109 return Name[Kind];
110}
111
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000112/// StandardConversionSequence - Set the standard conversion
113/// sequence to the identity conversion.
114void StandardConversionSequence::setAsIdentityConversion() {
115 First = ICK_Identity;
116 Second = ICK_Identity;
117 Third = ICK_Identity;
118 Deprecated = false;
119 ReferenceBinding = false;
120 DirectBinding = false;
Sebastian Redl9bc16ad2009-03-29 22:46:24 +0000121 RRefBinding = false;
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000122 CopyConstructor = 0;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000123}
124
Douglas Gregord2baafd2008-10-21 16:13:35 +0000125/// getRank - Retrieve the rank of this standard conversion sequence
126/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
127/// implicit conversions.
128ImplicitConversionRank StandardConversionSequence::getRank() const {
129 ImplicitConversionRank Rank = ICR_Exact_Match;
130 if (GetConversionRank(First) > Rank)
131 Rank = GetConversionRank(First);
132 if (GetConversionRank(Second) > Rank)
133 Rank = GetConversionRank(Second);
134 if (GetConversionRank(Third) > Rank)
135 Rank = GetConversionRank(Third);
136 return Rank;
137}
138
139/// isPointerConversionToBool - Determines whether this conversion is
140/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump25cf7602009-09-09 15:08:12 +0000141/// used as part of the ranking of standard conversion sequences
Douglas Gregord2baafd2008-10-21 16:13:35 +0000142/// (C++ 13.3.3.2p4).
Mike Stump25cf7602009-09-09 15:08:12 +0000143bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000144 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).
Mike Stump25cf7602009-09-09 15:08:12 +0000163bool
Douglas Gregor14046502008-10-23 00:40:37 +0000164StandardConversionSequence::
Mike Stump25cf7602009-09-09 15:08:12 +0000165isPointerConversionToVoidPointer(ASTContext& Context) const {
Douglas Gregor14046502008-10-23 00:40:37 +0000166 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
167 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
168
169 // Note that FromType has not necessarily been transformed by the
170 // array-to-pointer implicit conversion, so check for its presence
171 // and redo the conversion to get a pointer.
172 if (First == ICK_Array_To_Pointer)
173 FromType = Context.getArrayDecayedType(FromType);
174
175 if (Second == ICK_Pointer_Conversion)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000176 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor14046502008-10-23 00:40:37 +0000177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregord2baafd2008-10-21 16:13:35 +0000182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
185 bool PrintedSomething = false;
186 if (First != ICK_Identity) {
187 fprintf(stderr, "%s", GetImplicitConversionName(First));
188 PrintedSomething = true;
189 }
190
191 if (Second != ICK_Identity) {
192 if (PrintedSomething) {
193 fprintf(stderr, " -> ");
194 }
195 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000196
197 if (CopyConstructor) {
198 fprintf(stderr, " (by copy constructor)");
199 } else if (DirectBinding) {
200 fprintf(stderr, " (direct reference binding)");
201 } else if (ReferenceBinding) {
202 fprintf(stderr, " (reference binding)");
203 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000204 PrintedSomething = true;
205 }
206
207 if (Third != ICK_Identity) {
208 if (PrintedSomething) {
209 fprintf(stderr, " -> ");
210 }
211 fprintf(stderr, "%s", GetImplicitConversionName(Third));
212 PrintedSomething = true;
213 }
214
215 if (!PrintedSomething) {
216 fprintf(stderr, "No conversions required");
217 }
218}
219
220/// DebugPrint - Print this user-defined conversion sequence to standard
221/// error. Useful for debugging overloading issues.
222void UserDefinedConversionSequence::DebugPrint() const {
223 if (Before.First || Before.Second || Before.Third) {
224 Before.DebugPrint();
225 fprintf(stderr, " -> ");
226 }
Chris Lattner271d4c22008-11-24 05:29:24 +0000227 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregord2baafd2008-10-21 16:13:35 +0000228 if (After.First || After.Second || After.Third) {
229 fprintf(stderr, " -> ");
230 After.DebugPrint();
231 }
232}
233
234/// DebugPrint - Print this implicit conversion sequence to standard
235/// error. Useful for debugging overloading issues.
236void ImplicitConversionSequence::DebugPrint() const {
237 switch (ConversionKind) {
238 case StandardConversion:
239 fprintf(stderr, "Standard conversion: ");
240 Standard.DebugPrint();
241 break;
242 case UserDefinedConversion:
243 fprintf(stderr, "User-defined conversion: ");
244 UserDefined.DebugPrint();
245 break;
246 case EllipsisConversion:
247 fprintf(stderr, "Ellipsis conversion");
248 break;
249 case BadConversion:
250 fprintf(stderr, "Bad conversion");
251 break;
252 }
253
254 fprintf(stderr, "\n");
255}
256
257// IsOverload - Determine whether the given New declaration is an
258// overload of the Old declaration. This routine returns false if New
259// and Old cannot be overloaded, e.g., if they are functions with the
260// same signature (C++ 1.3.10) or if the Old declaration isn't a
261// function (or overload set). When it does return false and Old is an
262// OverloadedFunctionDecl, MatchedDecl will be set to point to the
Mike Stump25cf7602009-09-09 15:08:12 +0000263// FunctionDecl that New cannot be overloaded with.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000264//
265// Example: Given the following input:
266//
267// void f(int, float); // #1
268// void f(int, int); // #2
269// int f(int, int); // #3
270//
271// When we process #1, there is no previous declaration of "f",
Mike Stump25cf7602009-09-09 15:08:12 +0000272// so IsOverload will not be used.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000273//
274// When we process #2, Old is a FunctionDecl for #1. By comparing the
275// parameter types, we see that #1 and #2 are overloaded (since they
276// have different signatures), so this routine returns false;
277// MatchedDecl is unchanged.
278//
279// When we process #3, Old is an OverloadedFunctionDecl containing #1
280// and #2. We compare the signatures of #3 to #1 (they're overloaded,
281// so we do nothing) and then #3 to #2. Since the signatures of #3 and
282// #2 are identical (return types of functions are not part of the
283// signature), IsOverload returns false and MatchedDecl will be set to
284// point to the FunctionDecl for #2.
285bool
Mike Stump25cf7602009-09-09 15:08:12 +0000286Sema::IsOverload(FunctionDecl *New, Decl* OldD,
287 OverloadedFunctionDecl::function_iterator& MatchedDecl) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000288 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
289 // Is this new function an overload of every function in the
290 // overload set?
291 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
292 FuncEnd = Ovl->function_end();
293 for (; Func != FuncEnd; ++Func) {
294 if (!IsOverload(New, *Func, MatchedDecl)) {
295 MatchedDecl = Func;
296 return false;
297 }
298 }
299
300 // This function overloads every function in the overload set.
301 return true;
Douglas Gregorb60eb752009-06-25 22:08:12 +0000302 } else if (FunctionTemplateDecl *Old = dyn_cast<FunctionTemplateDecl>(OldD))
303 return IsOverload(New, Old->getTemplatedDecl(), MatchedDecl);
304 else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000305 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
Mike Stump25cf7602009-09-09 15:08:12 +0000306 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
307
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000308 // C++ [temp.fct]p2:
309 // A function template can be overloaded with other function templates
310 // and with normal (non-template) functions.
311 if ((OldTemplate == 0) != (NewTemplate == 0))
312 return true;
313
Douglas Gregord2baafd2008-10-21 16:13:35 +0000314 // Is the function New an overload of the function Old?
315 QualType OldQType = Context.getCanonicalType(Old->getType());
316 QualType NewQType = Context.getCanonicalType(New->getType());
317
318 // Compare the signatures (C++ 1.3.10) of the two functions to
319 // determine whether they are overloads. If we find any mismatch
320 // in the signature, they are overloads.
321
322 // If either of these functions is a K&R-style function (no
323 // prototype), then we consider them to have matching signatures.
Douglas Gregor4fa58902009-02-26 23:50:07 +0000324 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
325 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
Douglas Gregord2baafd2008-10-21 16:13:35 +0000326 return false;
327
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000328 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
329 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000330
331 // The signature of a function includes the types of its
332 // parameters (C++ 1.3.10), which includes the presence or absence
333 // of the ellipsis; see C++ DR 357).
334 if (OldQType != NewQType &&
335 (OldType->getNumArgs() != NewType->getNumArgs() ||
336 OldType->isVariadic() != NewType->isVariadic() ||
337 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
338 NewType->arg_type_begin())))
339 return true;
340
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000341 // C++ [temp.over.link]p4:
Mike Stump25cf7602009-09-09 15:08:12 +0000342 // The signature of a function template consists of its function
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000343 // signature, its return type and its template parameter list. The names
344 // of the template parameters are significant only for establishing the
Mike Stump25cf7602009-09-09 15:08:12 +0000345 // relationship between the template parameters and the rest of the
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000346 // signature.
347 //
348 // We check the return type and template parameter lists for function
349 // templates first; the remaining checks follow.
350 if (NewTemplate &&
Mike Stump25cf7602009-09-09 15:08:12 +0000351 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
352 OldTemplate->getTemplateParameters(),
Douglas Gregorbf6bc302009-06-24 16:50:40 +0000353 false, false, SourceLocation()) ||
354 OldType->getResultType() != NewType->getResultType()))
355 return true;
Mike Stump25cf7602009-09-09 15:08:12 +0000356
Douglas Gregord2baafd2008-10-21 16:13:35 +0000357 // If the function is a class member, its signature includes the
358 // cv-qualifiers (if any) on the function itself.
359 //
360 // As part of this, also check whether one of the member functions
361 // is static, in which case they are not overloads (C++
362 // 13.1p2). While not part of the definition of the signature,
363 // this check is important to determine whether these functions
364 // can be overloaded.
365 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
366 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
Mike Stump25cf7602009-09-09 15:08:12 +0000367 if (OldMethod && NewMethod &&
Douglas Gregord2baafd2008-10-21 16:13:35 +0000368 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregora7b56a32008-11-21 15:36:28 +0000369 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregord2baafd2008-10-21 16:13:35 +0000370 return true;
371
372 // The signatures match; this is not an overload.
373 return false;
374 } else {
375 // (C++ 13p1):
376 // Only function declarations can be overloaded; object and type
377 // declarations cannot be overloaded.
378 return false;
379 }
380}
381
Douglas Gregor81c29152008-10-29 00:13:59 +0000382/// TryImplicitConversion - Attempt to perform an implicit conversion
383/// from the given expression (Expr) to the given type (ToType). This
384/// function returns an implicit conversion sequence that can be used
385/// to perform the initialization. Given
Douglas Gregord2baafd2008-10-21 16:13:35 +0000386///
387/// void f(float f);
388/// void g(int i) { f(i); }
389///
390/// this routine would produce an implicit conversion sequence to
391/// describe the initialization of f from i, which will be a standard
392/// conversion sequence containing an lvalue-to-rvalue conversion (C++
393/// 4.1) followed by a floating-integral conversion (C++ 4.9).
394//
395/// Note that this routine only determines how the conversion can be
396/// performed; it does not actually perform the conversion. As such,
397/// it will not produce any diagnostics if no conversion is available,
398/// but will instead return an implicit conversion sequence of kind
399/// "BadConversion".
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000400///
401/// If @p SuppressUserConversions, then user-defined conversions are
402/// not permitted.
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000403/// If @p AllowExplicit, then explicit user-defined conversions are
404/// permitted.
Sebastian Redla55834a2009-04-12 17:16:29 +0000405/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
406/// no matter its actual lvalueness.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000407ImplicitConversionSequence
Anders Carlssonfcc53032009-08-27 17:14:02 +0000408Sema::TryImplicitConversion(Expr* From, QualType ToType,
409 bool SuppressUserConversions,
Anders Carlsson8e4c1692009-08-28 15:33:32 +0000410 bool AllowExplicit, bool ForceRValue,
Mike Stump25cf7602009-09-09 15:08:12 +0000411 bool InOverloadResolution) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000412 ImplicitConversionSequence ICS;
Anders Carlsson8e4c1692009-08-28 15:33:32 +0000413 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000414 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000415 else if (getLangOptions().CPlusPlus &&
Mike Stump25cf7602009-09-09 15:08:12 +0000416 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Sebastian Redla55834a2009-04-12 17:16:29 +0000417 !SuppressUserConversions, AllowExplicit,
418 ForceRValue)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000419 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregore640ab62008-11-03 17:51:48 +0000420 // C++ [over.ics.user]p4:
421 // A conversion of an expression of class type to the same class
422 // type is given Exact Match rank, and a conversion of an
423 // expression of class type to a base class of that type is
424 // given Conversion rank, in spite of the fact that a copy
425 // constructor (i.e., a user-defined conversion function) is
426 // called for those cases.
Mike Stump25cf7602009-09-09 15:08:12 +0000427 if (CXXConstructorDecl *Constructor
Douglas Gregore640ab62008-11-03 17:51:48 +0000428 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump25cf7602009-09-09 15:08:12 +0000429 QualType FromCanon
Douglas Gregord9176392009-02-02 22:11:10 +0000430 = Context.getCanonicalType(From->getType().getUnqualifiedType());
431 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
432 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000433 // Turn this into a "standard" conversion sequence, so that it
434 // gets ranked with standard conversion sequences.
Douglas Gregore640ab62008-11-03 17:51:48 +0000435 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
436 ICS.Standard.setAsIdentityConversion();
437 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
438 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000439 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregord9176392009-02-02 22:11:10 +0000440 if (ToCanon != FromCanon)
Douglas Gregore640ab62008-11-03 17:51:48 +0000441 ICS.Standard.Second = ICK_Derived_To_Base;
442 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000443 }
Douglas Gregorb206cc42009-01-30 23:27:23 +0000444
445 // C++ [over.best.ics]p4:
446 // However, when considering the argument of a user-defined
447 // conversion function that is a candidate by 13.3.1.3 when
448 // invoked for the copying of the temporary in the second step
449 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
450 // 13.3.1.6 in all cases, only standard conversion sequences and
451 // ellipsis conversion sequences are allowed.
452 if (SuppressUserConversions &&
453 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
454 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregore640ab62008-11-03 17:51:48 +0000455 } else
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000456 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000457
458 return ICS;
459}
460
461/// IsStandardConversion - Determines whether there is a standard
462/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
463/// expression From to the type ToType. Standard conversion sequences
464/// only consider non-class types; for conversions that involve class
465/// types, use TryImplicitConversion. If a conversion exists, SCS will
466/// contain the standard conversion sequence required to perform this
467/// conversion and this routine will return true. Otherwise, this
468/// routine will return false and the value of SCS is unspecified.
Mike Stump25cf7602009-09-09 15:08:12 +0000469bool
470Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson8e4c1692009-08-28 15:33:32 +0000471 bool InOverloadResolution,
Mike Stump25cf7602009-09-09 15:08:12 +0000472 StandardConversionSequence &SCS) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000473 QualType FromType = From->getType();
474
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000475 // Standard conversions (C++ [conv])
Douglas Gregor70d26122008-11-12 17:17:38 +0000476 SCS.setAsIdentityConversion();
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000477 SCS.Deprecated = false;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000478 SCS.IncompatibleObjC = false;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000479 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregora3b34bb2008-11-03 19:09:14 +0000480 SCS.CopyConstructor = 0;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000481
Douglas Gregorfcb19192009-02-11 23:02:49 +0000482 // There are no standard conversions for class types in C++, so
Mike Stump25cf7602009-09-09 15:08:12 +0000483 // abort early. When overloading in C, however, we do permit
Douglas Gregorfcb19192009-02-11 23:02:49 +0000484 if (FromType->isRecordType() || ToType->isRecordType()) {
485 if (getLangOptions().CPlusPlus)
486 return false;
487
Mike Stump25cf7602009-09-09 15:08:12 +0000488 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorfcb19192009-02-11 23:02:49 +0000489 }
490
Douglas Gregord2baafd2008-10-21 16:13:35 +0000491 // The first conversion can be an lvalue-to-rvalue conversion,
492 // array-to-pointer conversion, or function-to-pointer conversion
493 // (C++ 4p1).
494
Mike Stump25cf7602009-09-09 15:08:12 +0000495 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregord2baafd2008-10-21 16:13:35 +0000496 // An lvalue (3.10) of a non-function, non-array type T can be
497 // converted to an rvalue.
498 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump25cf7602009-09-09 15:08:12 +0000499 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor45014fd2008-11-10 20:40:00 +0000500 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor00fe3f62009-03-13 18:40:31 +0000501 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000502 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000503
504 // If T is a non-class type, the type of the rvalue is the
505 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorfcb19192009-02-11 23:02:49 +0000506 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
507 // just strip the qualifiers because they don't matter.
508
509 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000510 FromType = FromType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000511 } else if (FromType->isArrayType()) {
512 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000513 SCS.First = ICK_Array_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000514
515 // An lvalue or rvalue of type "array of N T" or "array of unknown
516 // bound of T" can be converted to an rvalue of type "pointer to
517 // T" (C++ 4.2p1).
518 FromType = Context.getArrayDecayedType(FromType);
519
520 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
521 // This conversion is deprecated. (C++ D.4).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000522 SCS.Deprecated = true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000523
524 // For the purpose of ranking in overload resolution
525 // (13.3.3.1.1), this conversion is considered an
526 // array-to-pointer conversion followed by a qualification
527 // conversion (4.4). (C++ 4.2p2)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000528 SCS.Second = ICK_Identity;
529 SCS.Third = ICK_Qualification;
530 SCS.ToTypePtr = ToType.getAsOpaquePtr();
531 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000532 }
Mike Stump90fc78e2009-08-04 21:02:39 +0000533 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
534 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000535 SCS.First = ICK_Function_To_Pointer;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000536
537 // An lvalue of function type T can be converted to an rvalue of
538 // type "pointer to T." The result is a pointer to the
539 // function. (C++ 4.3p1).
540 FromType = Context.getPointerType(FromType);
Mike Stump25cf7602009-09-09 15:08:12 +0000541 } else if (FunctionDecl *Fn
Douglas Gregor45014fd2008-11-10 20:40:00 +0000542 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump90fc78e2009-08-04 21:02:39 +0000543 // Address of overloaded function (C++ [over.over]).
Douglas Gregor45014fd2008-11-10 20:40:00 +0000544 SCS.First = ICK_Function_To_Pointer;
545
546 // We were able to resolve the address of the overloaded function,
547 // so we can convert to the type of that function.
548 FromType = Fn->getType();
Sebastian Redlce6fff02009-03-16 23:22:08 +0000549 if (ToType->isLValueReferenceType())
550 FromType = Context.getLValueReferenceType(FromType);
551 else if (ToType->isRValueReferenceType())
552 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl7434fc32009-02-04 21:23:32 +0000553 else if (ToType->isMemberPointerType()) {
554 // Resolve address only succeeds if both sides are member pointers,
555 // but it doesn't have to be the same class. See DR 247.
556 // Note that this means that the type of &Derived::fn can be
557 // Ret (Base::*)(Args) if the fn overload actually found is from the
558 // base class, even if it was brought into the derived class via a
559 // using declaration. The standard isn't clear on this issue at all.
560 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
561 FromType = Context.getMemberPointerType(FromType,
562 Context.getTypeDeclType(M->getParent()).getTypePtr());
563 } else
Douglas Gregor45014fd2008-11-10 20:40:00 +0000564 FromType = Context.getPointerType(FromType);
Mike Stump90fc78e2009-08-04 21:02:39 +0000565 } else {
566 // We don't require any conversions for the first step.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000567 SCS.First = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000568 }
569
570 // The second conversion can be an integral promotion, floating
571 // point promotion, integral conversion, floating point conversion,
572 // floating-integral conversion, pointer conversion,
573 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorfcb19192009-02-11 23:02:49 +0000574 // For overloading in C, this can also be a "compatible-type"
575 // conversion.
Douglas Gregor6fd35572008-12-19 17:40:08 +0000576 bool IncompatibleObjC = false;
Douglas Gregorfcb19192009-02-11 23:02:49 +0000577 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000578 // The unqualified versions of the types are the same: there's no
579 // conversion to do.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000580 SCS.Second = ICK_Identity;
Mike Stump90fc78e2009-08-04 21:02:39 +0000581 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump25cf7602009-09-09 15:08:12 +0000582 // Integral promotion (C++ 4.5).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000583 SCS.Second = ICK_Integral_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000584 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000585 } else if (IsFloatingPointPromotion(FromType, ToType)) {
586 // Floating point promotion (C++ 4.6).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000587 SCS.Second = ICK_Floating_Promotion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000588 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000589 } else if (IsComplexPromotion(FromType, ToType)) {
590 // Complex promotion (Clang extension)
Douglas Gregore819caf2009-02-12 00:15:05 +0000591 SCS.Second = ICK_Complex_Promotion;
592 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000593 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000594 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump90fc78e2009-08-04 21:02:39 +0000595 // Integral conversions (C++ 4.7).
596 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000597 SCS.Second = ICK_Integral_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000598 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000599 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
600 // Floating point conversions (C++ 4.8).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000601 SCS.Second = ICK_Floating_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000602 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000603 } else if (FromType->isComplexType() && ToType->isComplexType()) {
604 // Complex conversions (C99 6.3.1.6)
Douglas Gregore819caf2009-02-12 00:15:05 +0000605 SCS.Second = ICK_Complex_Conversion;
606 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000607 } else if ((FromType->isFloatingType() &&
608 ToType->isIntegralType() && (!ToType->isBooleanType() &&
609 !ToType->isEnumeralType())) ||
Mike Stump25cf7602009-09-09 15:08:12 +0000610 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump90fc78e2009-08-04 21:02:39 +0000611 ToType->isFloatingType())) {
612 // Floating-integral conversions (C++ 4.9).
613 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000614 SCS.Second = ICK_Floating_Integral;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000615 FromType = ToType.getUnqualifiedType();
Mike Stump90fc78e2009-08-04 21:02:39 +0000616 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
617 (ToType->isComplexType() && FromType->isArithmeticType())) {
618 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregore819caf2009-02-12 00:15:05 +0000619 SCS.Second = ICK_Complex_Real;
620 FromType = ToType.getUnqualifiedType();
Anders Carlsson8e4c1692009-08-28 15:33:32 +0000621 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
622 FromType, IncompatibleObjC)) {
Mike Stump90fc78e2009-08-04 21:02:39 +0000623 // Pointer conversions (C++ 4.10).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000624 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000625 SCS.IncompatibleObjC = IncompatibleObjC;
Mike Stump90fc78e2009-08-04 21:02:39 +0000626 } else if (IsMemberPointerConversion(From, FromType, ToType, FromType)) {
627 // Pointer to member conversions (4.11).
Sebastian Redlba387562009-01-25 19:43:20 +0000628 SCS.Second = ICK_Pointer_Member;
Mike Stump90fc78e2009-08-04 21:02:39 +0000629 } else if (ToType->isBooleanType() &&
630 (FromType->isArithmeticType() ||
631 FromType->isEnumeralType() ||
632 FromType->isPointerType() ||
633 FromType->isBlockPointerType() ||
634 FromType->isMemberPointerType() ||
635 FromType->isNullPtrType())) {
636 // Boolean conversions (C++ 4.12).
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000637 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000638 FromType = Context.BoolTy;
Mike Stump25cf7602009-09-09 15:08:12 +0000639 } else if (!getLangOptions().CPlusPlus &&
Mike Stump90fc78e2009-08-04 21:02:39 +0000640 Context.typesAreCompatible(ToType, FromType)) {
641 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorfcb19192009-02-11 23:02:49 +0000642 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000643 } else {
644 // No second conversion required.
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000645 SCS.Second = ICK_Identity;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000646 }
647
Douglas Gregor81c29152008-10-29 00:13:59 +0000648 QualType CanonFrom;
649 QualType CanonTo;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000650 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor6573cfd2008-10-21 23:43:52 +0000651 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000652 SCS.Third = ICK_Qualification;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000653 FromType = ToType;
Douglas Gregor81c29152008-10-29 00:13:59 +0000654 CanonFrom = Context.getCanonicalType(FromType);
655 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000656 } else {
657 // No conversion required
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000658 SCS.Third = ICK_Identity;
659
Mike Stump25cf7602009-09-09 15:08:12 +0000660 // C++ [over.best.ics]p6:
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000661 // [...] Any difference in top-level cv-qualification is
662 // subsumed by the initialization itself and does not constitute
663 // a conversion. [...]
Douglas Gregor81c29152008-10-29 00:13:59 +0000664 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump25cf7602009-09-09 15:08:12 +0000665 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000666 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor81c29152008-10-29 00:13:59 +0000667 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
668 FromType = ToType;
669 CanonFrom = CanonTo;
670 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000671 }
672
673 // If we have not converted the argument type to the parameter type,
674 // this is a bad conversion sequence.
Douglas Gregor81c29152008-10-29 00:13:59 +0000675 if (CanonFrom != CanonTo)
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000676 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000677
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000678 SCS.ToTypePtr = FromType.getAsOpaquePtr();
679 return true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000680}
681
682/// IsIntegralPromotion - Determines whether the conversion from the
683/// expression From (whose potentially-adjusted type is FromType) to
684/// ToType is an integral promotion (C++ 4.5). If so, returns true and
685/// sets PromotedType to the promoted type.
Mike Stump25cf7602009-09-09 15:08:12 +0000686bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000687 const BuiltinType *To = ToType->getAsBuiltinType();
Sebastian Redl12aee862008-11-04 15:59:10 +0000688 // All integers are built-in.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000689 if (!To) {
690 return false;
691 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000692
693 // An rvalue of type char, signed char, unsigned char, short int, or
694 // unsigned short int can be converted to an rvalue of type int if
695 // int can represent all the values of the source type; otherwise,
696 // the source rvalue can be converted to an rvalue of type unsigned
697 // int (C++ 4.5p1).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000698 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000699 if (// We can promote any signed, promotable integer type to an int
700 (FromType->isSignedIntegerType() ||
701 // We can promote any unsigned integer type whose size is
702 // less than int to an int.
Mike Stump25cf7602009-09-09 15:08:12 +0000703 (!FromType->isSignedIntegerType() &&
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000704 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000705 return To->getKind() == BuiltinType::Int;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000706 }
707
Douglas Gregord2baafd2008-10-21 16:13:35 +0000708 return To->getKind() == BuiltinType::UInt;
709 }
710
711 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
712 // can be converted to an rvalue of the first of the following types
713 // that can represent all the values of its underlying type: int,
714 // unsigned int, long, or unsigned long (C++ 4.5p2).
715 if ((FromType->isEnumeralType() || FromType->isWideCharType())
716 && ToType->isIntegerType()) {
717 // Determine whether the type we're converting from is signed or
718 // unsigned.
719 bool FromIsSigned;
720 uint64_t FromSize = Context.getTypeSize(FromType);
721 if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
722 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
723 FromIsSigned = UnderlyingType->isSignedIntegerType();
724 } else {
725 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
726 FromIsSigned = true;
727 }
728
729 // The types we'll try to promote to, in the appropriate
730 // order. Try each of these types.
Mike Stump25cf7602009-09-09 15:08:12 +0000731 QualType PromoteTypes[6] = {
732 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000733 Context.LongTy, Context.UnsignedLongTy ,
734 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregord2baafd2008-10-21 16:13:35 +0000735 };
Douglas Gregor6b5e34f2008-12-12 02:00:36 +0000736 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000737 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
738 if (FromSize < ToSize ||
Mike Stump25cf7602009-09-09 15:08:12 +0000739 (FromSize == ToSize &&
Douglas Gregord2baafd2008-10-21 16:13:35 +0000740 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
741 // We found the type that we can promote to. If this is the
742 // type we wanted, we have a promotion. Otherwise, no
743 // promotion.
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000744 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregord2baafd2008-10-21 16:13:35 +0000745 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
746 }
747 }
748 }
749
750 // An rvalue for an integral bit-field (9.6) can be converted to an
751 // rvalue of type int if int can represent all the values of the
752 // bit-field; otherwise, it can be converted to unsigned int if
753 // unsigned int can represent all the values of the bit-field. If
754 // the bit-field is larger yet, no integral promotion applies to
755 // it. If the bit-field has an enumerated type, it is treated as any
756 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stumpe127ae32009-05-16 07:39:55 +0000757 // FIXME: We should delay checking of bit-fields until we actually perform the
758 // conversion.
Douglas Gregor531434b2009-05-02 02:18:30 +0000759 using llvm::APSInt;
760 if (From)
761 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor82d44772008-12-20 23:49:58 +0000762 APSInt BitWidth;
Douglas Gregor531434b2009-05-02 02:18:30 +0000763 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
764 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
765 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
766 ToSize = Context.getTypeSize(ToType);
Mike Stump25cf7602009-09-09 15:08:12 +0000767
Douglas Gregor82d44772008-12-20 23:49:58 +0000768 // Are we promoting to an int from a bitfield that fits in an int?
769 if (BitWidth < ToSize ||
770 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
771 return To->getKind() == BuiltinType::Int;
772 }
Mike Stump25cf7602009-09-09 15:08:12 +0000773
Douglas Gregor82d44772008-12-20 23:49:58 +0000774 // Are we promoting to an unsigned int from an unsigned bitfield
775 // that fits into an unsigned int?
776 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
777 return To->getKind() == BuiltinType::UInt;
778 }
Mike Stump25cf7602009-09-09 15:08:12 +0000779
Douglas Gregor82d44772008-12-20 23:49:58 +0000780 return false;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000781 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000782 }
Mike Stump25cf7602009-09-09 15:08:12 +0000783
Douglas Gregord2baafd2008-10-21 16:13:35 +0000784 // An rvalue of type bool can be converted to an rvalue of type int,
785 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000786 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000787 return true;
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000788 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000789
790 return false;
791}
792
793/// IsFloatingPointPromotion - Determines whether the conversion from
794/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
795/// returns true and sets PromotedType to the promoted type.
Mike Stump25cf7602009-09-09 15:08:12 +0000796bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000797 /// An rvalue of type float can be converted to an rvalue of type
798 /// double. (C++ 4.6p1).
799 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
Douglas Gregore819caf2009-02-12 00:15:05 +0000800 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000801 if (FromBuiltin->getKind() == BuiltinType::Float &&
802 ToBuiltin->getKind() == BuiltinType::Double)
803 return true;
804
Douglas Gregore819caf2009-02-12 00:15:05 +0000805 // C99 6.3.1.5p1:
806 // When a float is promoted to double or long double, or a
807 // double is promoted to long double [...].
808 if (!getLangOptions().CPlusPlus &&
809 (FromBuiltin->getKind() == BuiltinType::Float ||
810 FromBuiltin->getKind() == BuiltinType::Double) &&
811 (ToBuiltin->getKind() == BuiltinType::LongDouble))
812 return true;
813 }
814
Douglas Gregord2baafd2008-10-21 16:13:35 +0000815 return false;
816}
817
Douglas Gregore819caf2009-02-12 00:15:05 +0000818/// \brief Determine if a conversion is a complex promotion.
819///
820/// A complex promotion is defined as a complex -> complex conversion
821/// where the conversion between the underlying real types is a
Douglas Gregor4ff48512009-02-12 00:26:06 +0000822/// floating-point or integral promotion.
Douglas Gregore819caf2009-02-12 00:15:05 +0000823bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
824 const ComplexType *FromComplex = FromType->getAsComplexType();
825 if (!FromComplex)
826 return false;
827
828 const ComplexType *ToComplex = ToType->getAsComplexType();
829 if (!ToComplex)
830 return false;
831
832 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor4ff48512009-02-12 00:26:06 +0000833 ToComplex->getElementType()) ||
834 IsIntegralPromotion(0, FromComplex->getElementType(),
835 ToComplex->getElementType());
Douglas Gregore819caf2009-02-12 00:15:05 +0000836}
837
Douglas Gregor24a90a52008-11-26 23:31:11 +0000838/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
839/// the pointer type FromPtr to a pointer to type ToPointee, with the
840/// same type qualifiers as FromPtr has on its pointee type. ToType,
841/// if non-empty, will be a pointer to ToType that may or may not have
842/// the right set of qualifiers on its pointee.
Mike Stump25cf7602009-09-09 15:08:12 +0000843static QualType
844BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000845 QualType ToPointee, QualType ToType,
846 ASTContext &Context) {
847 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
848 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
849 unsigned Quals = CanonFromPointee.getCVRQualifiers();
Mike Stump25cf7602009-09-09 15:08:12 +0000850
851 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor24a90a52008-11-26 23:31:11 +0000852 if (CanonToPointee.getCVRQualifiers() == Quals) {
853 // ToType is exactly what we need. Return it.
854 if (ToType.getTypePtr())
855 return ToType;
856
857 // Build a pointer to ToPointee. It has the right qualifiers
858 // already.
859 return Context.getPointerType(ToPointee);
860 }
861
862 // Just build a canonical type that has the right qualifiers.
863 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
864}
865
Mike Stump25cf7602009-09-09 15:08:12 +0000866static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson1e901552009-08-28 15:55:56 +0000867 bool InOverloadResolution,
868 ASTContext &Context) {
869 // Handle value-dependent integral null pointer constants correctly.
870 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
871 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
872 Expr->getType()->isIntegralType())
873 return !InOverloadResolution;
874
875 return Expr->isNullPointerConstant(Context);
876}
Mike Stump25cf7602009-09-09 15:08:12 +0000877
Douglas Gregord2baafd2008-10-21 16:13:35 +0000878/// IsPointerConversion - Determines whether the conversion of the
879/// expression From, which has the (possibly adjusted) type FromType,
880/// can be converted to the type ToType via a pointer conversion (C++
881/// 4.10). If so, returns true and places the converted type (that
882/// might differ from ToType in its cv-qualifiers at some level) into
883/// ConvertedType.
Douglas Gregor9036ef72008-11-27 00:15:41 +0000884///
Douglas Gregor3f5a00c2008-11-27 01:19:21 +0000885/// This routine also supports conversions to and from block pointers
886/// and conversions with Objective-C's 'id', 'id<protocols...>', and
887/// pointers to interfaces. FIXME: Once we've determined the
888/// appropriate overloading rules for Objective-C, we may want to
889/// split the Objective-C checks into a different routine; however,
890/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor6fd35572008-12-19 17:40:08 +0000891/// conversions, so for now they live here. IncompatibleObjC will be
892/// set if the conversion is an allowed Objective-C conversion that
893/// should result in a warning.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000894bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson8e4c1692009-08-28 15:33:32 +0000895 bool InOverloadResolution,
Douglas Gregor6fd35572008-12-19 17:40:08 +0000896 QualType& ConvertedType,
Mike Stump25cf7602009-09-09 15:08:12 +0000897 bool &IncompatibleObjC) {
Douglas Gregor6fd35572008-12-19 17:40:08 +0000898 IncompatibleObjC = false;
Douglas Gregor932778b2008-12-19 19:13:09 +0000899 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
900 return true;
Douglas Gregor6fd35572008-12-19 17:40:08 +0000901
Mike Stump25cf7602009-09-09 15:08:12 +0000902 // Conversion from a null pointer constant to any Objective-C pointer type.
903 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson1e901552009-08-28 15:55:56 +0000904 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregorf1d75712008-12-22 20:51:52 +0000905 ConvertedType = ToType;
906 return true;
907 }
908
Douglas Gregor9036ef72008-11-27 00:15:41 +0000909 // Blocks: Block pointers can be converted to void*.
910 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000911 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor9036ef72008-11-27 00:15:41 +0000912 ConvertedType = ToType;
913 return true;
914 }
915 // Blocks: A null pointer constant can be converted to a block
916 // pointer type.
Mike Stump25cf7602009-09-09 15:08:12 +0000917 if (ToType->isBlockPointerType() &&
Anders Carlsson1e901552009-08-28 15:55:56 +0000918 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor9036ef72008-11-27 00:15:41 +0000919 ConvertedType = ToType;
920 return true;
921 }
922
Sebastian Redl5d0ead72009-05-10 18:38:11 +0000923 // If the left-hand-side is nullptr_t, the right side can be a null
924 // pointer constant.
Mike Stump25cf7602009-09-09 15:08:12 +0000925 if (ToType->isNullPtrType() &&
Anders Carlsson1e901552009-08-28 15:55:56 +0000926 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl5d0ead72009-05-10 18:38:11 +0000927 ConvertedType = ToType;
928 return true;
929 }
930
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000931 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregord2baafd2008-10-21 16:13:35 +0000932 if (!ToTypePtr)
933 return false;
934
935 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson1e901552009-08-28 15:55:56 +0000936 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000937 ConvertedType = ToType;
938 return true;
939 }
Sebastian Redl9ac68aa2008-10-31 14:43:28 +0000940
Douglas Gregor24a90a52008-11-26 23:31:11 +0000941 // Beyond this point, both types need to be pointers.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000942 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor24a90a52008-11-26 23:31:11 +0000943 if (!FromTypePtr)
944 return false;
945
946 QualType FromPointeeType = FromTypePtr->getPointeeType();
947 QualType ToPointeeType = ToTypePtr->getPointeeType();
948
Douglas Gregord2baafd2008-10-21 16:13:35 +0000949 // An rvalue of type "pointer to cv T," where T is an object type,
950 // can be converted to an rvalue of type "pointer to cv void" (C++
951 // 4.10p2).
Douglas Gregor26ea1222009-03-24 20:32:41 +0000952 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump25cf7602009-09-09 15:08:12 +0000953 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000954 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000955 ToType, Context);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000956 return true;
957 }
958
Douglas Gregorfcb19192009-02-11 23:02:49 +0000959 // When we're overloading in C, we allow a special kind of pointer
960 // conversion for compatible-but-not-identical pointee types.
Mike Stump25cf7602009-09-09 15:08:12 +0000961 if (!getLangOptions().CPlusPlus &&
Douglas Gregorfcb19192009-02-11 23:02:49 +0000962 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump25cf7602009-09-09 15:08:12 +0000963 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorfcb19192009-02-11 23:02:49 +0000964 ToPointeeType,
Mike Stump25cf7602009-09-09 15:08:12 +0000965 ToType, Context);
Douglas Gregorfcb19192009-02-11 23:02:49 +0000966 return true;
967 }
968
Douglas Gregor14046502008-10-23 00:40:37 +0000969 // C++ [conv.ptr]p3:
Mike Stump25cf7602009-09-09 15:08:12 +0000970 //
Douglas Gregor14046502008-10-23 00:40:37 +0000971 // An rvalue of type "pointer to cv D," where D is a class type,
972 // can be converted to an rvalue of type "pointer to cv B," where
973 // B is a base class (clause 10) of D. If B is an inaccessible
974 // (clause 11) or ambiguous (10.2) base class of D, a program that
975 // necessitates this conversion is ill-formed. The result of the
976 // conversion is a pointer to the base class sub-object of the
977 // derived class object. The null pointer value is converted to
978 // the null pointer value of the destination type.
979 //
Douglas Gregorbb461502008-10-24 04:54:22 +0000980 // Note that we do not check for ambiguity or inaccessibility
981 // here. That is handled by CheckPointerConversion.
Douglas Gregorfcb19192009-02-11 23:02:49 +0000982 if (getLangOptions().CPlusPlus &&
983 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor24a90a52008-11-26 23:31:11 +0000984 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump25cf7602009-09-09 15:08:12 +0000985 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor8bb7ad82008-11-27 00:52:49 +0000986 ToPointeeType,
Douglas Gregor24a90a52008-11-26 23:31:11 +0000987 ToType, Context);
988 return true;
989 }
Douglas Gregor14046502008-10-23 00:40:37 +0000990
Douglas Gregor932778b2008-12-19 19:13:09 +0000991 return false;
992}
993
994/// isObjCPointerConversion - Determines whether this is an
995/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
996/// with the same arguments and return values.
Mike Stump25cf7602009-09-09 15:08:12 +0000997bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregor932778b2008-12-19 19:13:09 +0000998 QualType& ConvertedType,
999 bool &IncompatibleObjC) {
1000 if (!getLangOptions().ObjC1)
1001 return false;
1002
Steve Naroff329ec222009-07-10 23:34:53 +00001003 // First, we handle all conversions on ObjC object pointer types.
1004 const ObjCObjectPointerType* ToObjCPtr = ToType->getAsObjCObjectPointerType();
Mike Stump25cf7602009-09-09 15:08:12 +00001005 const ObjCObjectPointerType *FromObjCPtr =
Steve Naroff329ec222009-07-10 23:34:53 +00001006 FromType->getAsObjCObjectPointerType();
Douglas Gregor932778b2008-12-19 19:13:09 +00001007
Steve Naroff329ec222009-07-10 23:34:53 +00001008 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff7bffd372009-07-15 18:40:39 +00001009 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff329ec222009-07-10 23:34:53 +00001010 // pointer to any interface (in both directions).
Steve Naroff7bffd372009-07-15 18:40:39 +00001011 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00001012 ConvertedType = ToType;
1013 return true;
1014 }
1015 // Conversions with Objective-C's id<...>.
Mike Stump25cf7602009-09-09 15:08:12 +00001016 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff329ec222009-07-10 23:34:53 +00001017 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump25cf7602009-09-09 15:08:12 +00001018 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff99eb86b2009-07-23 01:01:38 +00001019 /*compare=*/false)) {
Steve Naroff329ec222009-07-10 23:34:53 +00001020 ConvertedType = ToType;
1021 return true;
1022 }
1023 // Objective C++: We're able to convert from a pointer to an
1024 // interface to a pointer to a different interface.
1025 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1026 ConvertedType = ToType;
1027 return true;
1028 }
1029
1030 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1031 // Okay: this is some kind of implicit downcast of Objective-C
1032 // interfaces, which is permitted. However, we're going to
1033 // complain about it.
1034 IncompatibleObjC = true;
1035 ConvertedType = FromType;
1036 return true;
1037 }
Mike Stump25cf7602009-09-09 15:08:12 +00001038 }
Steve Naroff329ec222009-07-10 23:34:53 +00001039 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor80402cf2008-12-23 00:53:59 +00001040 QualType ToPointeeType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001041 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff329ec222009-07-10 23:34:53 +00001042 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001043 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor80402cf2008-12-23 00:53:59 +00001044 ToPointeeType = ToBlockPtr->getPointeeType();
1045 else
Douglas Gregor932778b2008-12-19 19:13:09 +00001046 return false;
1047
Douglas Gregor80402cf2008-12-23 00:53:59 +00001048 QualType FromPointeeType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001049 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff329ec222009-07-10 23:34:53 +00001050 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001051 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor80402cf2008-12-23 00:53:59 +00001052 FromPointeeType = FromBlockPtr->getPointeeType();
1053 else
Douglas Gregor932778b2008-12-19 19:13:09 +00001054 return false;
1055
Douglas Gregor932778b2008-12-19 19:13:09 +00001056 // If we have pointers to pointers, recursively check whether this
1057 // is an Objective-C conversion.
1058 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1059 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1060 IncompatibleObjC)) {
1061 // We always complain about this conversion.
1062 IncompatibleObjC = true;
1063 ConvertedType = ToType;
1064 return true;
1065 }
Douglas Gregor80402cf2008-12-23 00:53:59 +00001066 // If we have pointers to functions or blocks, check whether the only
Douglas Gregor932778b2008-12-19 19:13:09 +00001067 // differences in the argument and result types are in Objective-C
1068 // pointer conversions. If so, we permit the conversion (but
1069 // complain about it).
Mike Stump25cf7602009-09-09 15:08:12 +00001070 const FunctionProtoType *FromFunctionType
Douglas Gregor4fa58902009-02-26 23:50:07 +00001071 = FromPointeeType->getAsFunctionProtoType();
1072 const FunctionProtoType *ToFunctionType
1073 = ToPointeeType->getAsFunctionProtoType();
Douglas Gregor932778b2008-12-19 19:13:09 +00001074 if (FromFunctionType && ToFunctionType) {
1075 // If the function types are exactly the same, this isn't an
1076 // Objective-C pointer conversion.
1077 if (Context.getCanonicalType(FromPointeeType)
1078 == Context.getCanonicalType(ToPointeeType))
1079 return false;
1080
1081 // Perform the quick checks that will tell us whether these
1082 // function types are obviously different.
1083 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1084 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1085 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1086 return false;
1087
1088 bool HasObjCConversion = false;
1089 if (Context.getCanonicalType(FromFunctionType->getResultType())
1090 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1091 // Okay, the types match exactly. Nothing to do.
1092 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1093 ToFunctionType->getResultType(),
1094 ConvertedType, IncompatibleObjC)) {
1095 // Okay, we have an Objective-C pointer conversion.
1096 HasObjCConversion = true;
1097 } else {
1098 // Function types are too different. Abort.
1099 return false;
1100 }
Mike Stump25cf7602009-09-09 15:08:12 +00001101
Douglas Gregor932778b2008-12-19 19:13:09 +00001102 // Check argument types.
1103 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1104 ArgIdx != NumArgs; ++ArgIdx) {
1105 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1106 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1107 if (Context.getCanonicalType(FromArgType)
1108 == Context.getCanonicalType(ToArgType)) {
1109 // Okay, the types match exactly. Nothing to do.
1110 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1111 ConvertedType, IncompatibleObjC)) {
1112 // Okay, we have an Objective-C pointer conversion.
1113 HasObjCConversion = true;
1114 } else {
1115 // Argument types are too different. Abort.
1116 return false;
1117 }
1118 }
1119
1120 if (HasObjCConversion) {
1121 // We had an Objective-C conversion. Allow this pointer
1122 // conversion, but complain about it.
1123 ConvertedType = ToType;
1124 IncompatibleObjC = true;
1125 return true;
1126 }
1127 }
1128
Sebastian Redlba387562009-01-25 19:43:20 +00001129 return false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001130}
1131
Douglas Gregorbb461502008-10-24 04:54:22 +00001132/// CheckPointerConversion - Check the pointer conversion from the
1133/// expression From to the type ToType. This routine checks for
Sebastian Redl0e35d042009-07-25 15:41:38 +00001134/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregorbb461502008-10-24 04:54:22 +00001135/// conversions for which IsPointerConversion has already returned
1136/// true. It returns true and produces a diagnostic if there was an
1137/// error, or returns false otherwise.
1138bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
1139 QualType FromType = From->getType();
1140
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001141 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1142 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregorbb461502008-10-24 04:54:22 +00001143 QualType FromPointeeType = FromPtrType->getPointeeType(),
1144 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregord0c653a2008-12-18 23:43:31 +00001145
Douglas Gregorbb461502008-10-24 04:54:22 +00001146 if (FromPointeeType->isRecordType() &&
1147 ToPointeeType->isRecordType()) {
1148 // We must have a derived-to-base conversion. Check an
1149 // ambiguous or inaccessible conversion.
Douglas Gregor651d1cc2008-10-24 16:17:19 +00001150 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1151 From->getExprLoc(),
1152 From->getSourceRange());
Douglas Gregorbb461502008-10-24 04:54:22 +00001153 }
1154 }
Mike Stump25cf7602009-09-09 15:08:12 +00001155 if (const ObjCObjectPointerType *FromPtrType =
Steve Naroff329ec222009-07-10 23:34:53 +00001156 FromType->getAsObjCObjectPointerType())
Mike Stump25cf7602009-09-09 15:08:12 +00001157 if (const ObjCObjectPointerType *ToPtrType =
Steve Naroff329ec222009-07-10 23:34:53 +00001158 ToType->getAsObjCObjectPointerType()) {
1159 // Objective-C++ conversions are always okay.
1160 // FIXME: We should have a different class of conversions for the
1161 // Objective-C++ implicit conversions.
Steve Naroff7bffd372009-07-15 18:40:39 +00001162 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff329ec222009-07-10 23:34:53 +00001163 return false;
Douglas Gregorbb461502008-10-24 04:54:22 +00001164
Steve Naroff329ec222009-07-10 23:34:53 +00001165 }
Douglas Gregorbb461502008-10-24 04:54:22 +00001166 return false;
1167}
1168
Sebastian Redlba387562009-01-25 19:43:20 +00001169/// IsMemberPointerConversion - Determines whether the conversion of the
1170/// expression From, which has the (possibly adjusted) type FromType, can be
1171/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1172/// If so, returns true and places the converted type (that might differ from
1173/// ToType in its cv-qualifiers at some level) into ConvertedType.
1174bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Mike Stump25cf7602009-09-09 15:08:12 +00001175 QualType ToType, QualType &ConvertedType) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001176 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redlba387562009-01-25 19:43:20 +00001177 if (!ToTypePtr)
1178 return false;
1179
1180 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1181 if (From->isNullPointerConstant(Context)) {
1182 ConvertedType = ToType;
1183 return true;
1184 }
1185
1186 // Otherwise, both types have to be member pointers.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001187 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redlba387562009-01-25 19:43:20 +00001188 if (!FromTypePtr)
1189 return false;
1190
1191 // A pointer to member of B can be converted to a pointer to member of D,
1192 // where D is derived from B (C++ 4.11p2).
1193 QualType FromClass(FromTypePtr->getClass(), 0);
1194 QualType ToClass(ToTypePtr->getClass(), 0);
1195 // FIXME: What happens when these are dependent? Is this function even called?
1196
1197 if (IsDerivedFrom(ToClass, FromClass)) {
1198 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1199 ToClass.getTypePtr());
1200 return true;
1201 }
1202
1203 return false;
1204}
1205
1206/// CheckMemberPointerConversion - Check the member pointer conversion from the
1207/// expression From to the type ToType. This routine checks for ambiguous or
1208/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1209/// for which IsMemberPointerConversion has already returned true. It returns
1210/// true and produces a diagnostic if there was an error, or returns false
1211/// otherwise.
Mike Stump25cf7602009-09-09 15:08:12 +00001212bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001213 CastExpr::CastKind &Kind) {
Sebastian Redlba387562009-01-25 19:43:20 +00001214 QualType FromType = From->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001215 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001216 if (!FromPtrType) {
1217 // This must be a null pointer to member pointer conversion
Mike Stump25cf7602009-09-09 15:08:12 +00001218 assert(From->isNullPointerConstant(Context) &&
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001219 "Expr must be null pointer constant!");
1220 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001221 return false;
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001222 }
Sebastian Redlba387562009-01-25 19:43:20 +00001223
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001224 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001225 assert(ToPtrType && "No member pointer cast has a target type "
1226 "that is not a member pointer.");
Sebastian Redlba387562009-01-25 19:43:20 +00001227
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001228 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1229 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redlba387562009-01-25 19:43:20 +00001230
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001231 // FIXME: What about dependent types?
1232 assert(FromClass->isRecordType() && "Pointer into non-class.");
1233 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redlba387562009-01-25 19:43:20 +00001234
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001235 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1236 /*DetectVirtual=*/true);
1237 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1238 assert(DerivationOkay &&
1239 "Should not have been called if derivation isn't OK.");
1240 (void)DerivationOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001241
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001242 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1243 getUnqualifiedType())) {
1244 // Derivation is ambiguous. Redo the check to find the exact paths.
1245 Paths.clear();
1246 Paths.setRecordingPaths(true);
1247 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1248 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1249 (void)StillOkay;
Sebastian Redlba387562009-01-25 19:43:20 +00001250
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001251 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1252 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1253 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1254 return true;
Sebastian Redlba387562009-01-25 19:43:20 +00001255 }
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001256
Douglas Gregor2e047592009-02-28 01:32:25 +00001257 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001258 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1259 << FromClass << ToClass << QualType(VBase, 0)
1260 << From->getSourceRange();
1261 return true;
1262 }
1263
Anders Carlsson512f4ba2009-08-22 23:33:40 +00001264 // Must be a base to derived member conversion.
1265 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redlba387562009-01-25 19:43:20 +00001266 return false;
1267}
1268
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001269/// IsQualificationConversion - Determines whether the conversion from
1270/// an rvalue of type FromType to ToType is a qualification conversion
1271/// (C++ 4.4).
Mike Stump25cf7602009-09-09 15:08:12 +00001272bool
1273Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001274 FromType = Context.getCanonicalType(FromType);
1275 ToType = Context.getCanonicalType(ToType);
1276
1277 // If FromType and ToType are the same type, this is not a
1278 // qualification conversion.
1279 if (FromType == ToType)
1280 return false;
Sebastian Redlf41a58c2009-01-28 18:33:18 +00001281
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001282 // (C++ 4.4p4):
1283 // A conversion can add cv-qualifiers at levels other than the first
1284 // in multi-level pointers, subject to the following rules: [...]
1285 bool PreviousToQualsIncludeConst = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001286 bool UnwrappedAnyPointer = false;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001287 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001288 // Within each iteration of the loop, we check the qualifiers to
1289 // determine if this still looks like a qualification
1290 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001291 // pointers or pointers-to-members and do it all again
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001292 // until there are no more pointers or pointers-to-members left to
1293 // unwrap.
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001294 UnwrappedAnyPointer = true;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001295
1296 // -- for every j > 0, if const is in cv 1,j then const is in cv
1297 // 2,j, and similarly for volatile.
Douglas Gregore5db4f72008-10-22 00:38:21 +00001298 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001299 return false;
Mike Stump25cf7602009-09-09 15:08:12 +00001300
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001301 // -- if the cv 1,j and cv 2,j are different, then const is in
1302 // every cv for 0 < k < j.
1303 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001304 && !PreviousToQualsIncludeConst)
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001305 return false;
Mike Stump25cf7602009-09-09 15:08:12 +00001306
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001307 // Keep track of whether all prior cv-qualifiers in the "to" type
1308 // include const.
Mike Stump25cf7602009-09-09 15:08:12 +00001309 PreviousToQualsIncludeConst
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001310 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001311 }
Douglas Gregor6573cfd2008-10-21 23:43:52 +00001312
1313 // We are left with FromType and ToType being the pointee types
1314 // after unwrapping the original FromType and ToType the same number
1315 // of types. If we unwrapped any pointers, and if FromType and
1316 // ToType have the same unqualified type (since we checked
1317 // qualifiers above), then this is a qualification conversion.
1318 return UnwrappedAnyPointer &&
1319 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1320}
1321
Douglas Gregor8c860df2009-08-21 23:19:43 +00001322/// \brief Given a function template or function, extract the function template
1323/// declaration (if any) and the underlying function declaration.
1324template<typename T>
1325static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1326 FunctionTemplateDecl *&FunctionTemplate) {
1327 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1328 if (FunctionTemplate)
1329 Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1330 else
1331 Function = cast<T>(Orig);
1332}
1333
1334
Douglas Gregorb206cc42009-01-30 23:27:23 +00001335/// Determines whether there is a user-defined conversion sequence
1336/// (C++ [over.ics.user]) that converts expression From to the type
1337/// ToType. If such a conversion exists, User will contain the
1338/// user-defined conversion sequence that performs such a conversion
1339/// and this routine will return true. Otherwise, this routine returns
1340/// false and User is unspecified.
1341///
1342/// \param AllowConversionFunctions true if the conversion should
1343/// consider conversion functions at all. If false, only constructors
1344/// will be considered.
1345///
1346/// \param AllowExplicit true if the conversion should consider C++0x
1347/// "explicit" conversion functions as well as non-explicit conversion
1348/// functions (C++0x [class.conv.fct]p2).
Sebastian Redla55834a2009-04-12 17:16:29 +00001349///
1350/// \param ForceRValue true if the expression should be treated as an rvalue
1351/// for overload resolution.
Mike Stump25cf7602009-09-09 15:08:12 +00001352bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001353 UserDefinedConversionSequence& User,
Douglas Gregorb206cc42009-01-30 23:27:23 +00001354 bool AllowConversionFunctions,
Mike Stump25cf7602009-09-09 15:08:12 +00001355 bool AllowExplicit, bool ForceRValue) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001356 OverloadCandidateSet CandidateSet;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001357 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Mike Stump25cf7602009-09-09 15:08:12 +00001358 if (CXXRecordDecl *ToRecordDecl
Douglas Gregor2e047592009-02-28 01:32:25 +00001359 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1360 // C++ [over.match.ctor]p1:
1361 // When objects of class type are direct-initialized (8.5), or
1362 // copy-initialized from an expression of the same or a
1363 // derived class type (8.5), overload resolution selects the
1364 // constructor. [...] For copy-initialization, the candidate
1365 // functions are all the converting constructors (12.3.1) of
1366 // that class. The argument list is the expression-list within
1367 // the parentheses of the initializer.
Mike Stump25cf7602009-09-09 15:08:12 +00001368 DeclarationName ConstructorName
Douglas Gregor2e047592009-02-28 01:32:25 +00001369 = Context.DeclarationNames.getCXXConstructorName(
1370 Context.getCanonicalType(ToType).getUnqualifiedType());
1371 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump25cf7602009-09-09 15:08:12 +00001372 for (llvm::tie(Con, ConEnd)
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001373 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor2e047592009-02-28 01:32:25 +00001374 Con != ConEnd; ++Con) {
Douglas Gregor050cabf2009-08-21 18:42:58 +00001375 // Find the constructor (which may be a template).
1376 CXXConstructorDecl *Constructor = 0;
1377 FunctionTemplateDecl *ConstructorTmpl
1378 = dyn_cast<FunctionTemplateDecl>(*Con);
1379 if (ConstructorTmpl)
Mike Stump25cf7602009-09-09 15:08:12 +00001380 Constructor
Douglas Gregor050cabf2009-08-21 18:42:58 +00001381 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1382 else
1383 Constructor = cast<CXXConstructorDecl>(*Con);
Mike Stump25cf7602009-09-09 15:08:12 +00001384
Fariborz Jahanian625fb9d2009-08-06 17:22:51 +00001385 if (!Constructor->isInvalidDecl() &&
Anders Carlsson94894572009-08-28 16:57:08 +00001386 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor050cabf2009-08-21 18:42:58 +00001387 if (ConstructorTmpl)
Mike Stump25cf7602009-09-09 15:08:12 +00001388 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
Douglas Gregor050cabf2009-08-21 18:42:58 +00001389 1, CandidateSet,
Mike Stump25cf7602009-09-09 15:08:12 +00001390 /*SuppressUserConversions=*/true,
Douglas Gregor050cabf2009-08-21 18:42:58 +00001391 ForceRValue);
1392 else
1393 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1394 /*SuppressUserConversions=*/true, ForceRValue);
1395 }
Douglas Gregor2e047592009-02-28 01:32:25 +00001396 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001397 }
1398 }
1399
Douglas Gregorb206cc42009-01-30 23:27:23 +00001400 if (!AllowConversionFunctions) {
1401 // Don't allow any conversion functions to enter the overload set.
Mike Stump25cf7602009-09-09 15:08:12 +00001402 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1403 PDiag(0)
Anders Carlssona21e7872009-08-26 23:45:07 +00001404 << From->getSourceRange())) {
Douglas Gregorb35c7992009-08-24 15:23:48 +00001405 // No conversion functions from incomplete types.
Mike Stump25cf7602009-09-09 15:08:12 +00001406 } else if (const RecordType *FromRecordType
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001407 = From->getType()->getAs<RecordType>()) {
Mike Stump25cf7602009-09-09 15:08:12 +00001408 if (CXXRecordDecl *FromRecordDecl
Douglas Gregor2e047592009-02-28 01:32:25 +00001409 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1410 // Add all of the conversion functions as candidates.
1411 // FIXME: Look for conversions in base classes!
Mike Stump25cf7602009-09-09 15:08:12 +00001412 OverloadedFunctionDecl *Conversions
Douglas Gregor2e047592009-02-28 01:32:25 +00001413 = FromRecordDecl->getConversionFunctions();
Mike Stump25cf7602009-09-09 15:08:12 +00001414 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregor2e047592009-02-28 01:32:25 +00001415 = Conversions->function_begin();
1416 Func != Conversions->function_end(); ++Func) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00001417 CXXConversionDecl *Conv;
1418 FunctionTemplateDecl *ConvTemplate;
1419 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1420 if (ConvTemplate)
1421 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Mike Stump25cf7602009-09-09 15:08:12 +00001422 else
Douglas Gregor8c860df2009-08-21 23:19:43 +00001423 Conv = dyn_cast<CXXConversionDecl>(*Func);
1424
1425 if (AllowExplicit || !Conv->isExplicit()) {
1426 if (ConvTemplate)
Mike Stump25cf7602009-09-09 15:08:12 +00001427 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
Douglas Gregor8c860df2009-08-21 23:19:43 +00001428 CandidateSet);
1429 else
1430 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1431 }
Douglas Gregor2e047592009-02-28 01:32:25 +00001432 }
Douglas Gregor60714f92008-11-07 22:36:19 +00001433 }
1434 }
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001435
1436 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001437 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001438 case OR_Success:
1439 // Record the standard conversion we used and the conversion function.
Mike Stump25cf7602009-09-09 15:08:12 +00001440 if (CXXConstructorDecl *Constructor
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001441 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1442 // C++ [over.ics.user]p1:
1443 // If the user-defined conversion is specified by a
1444 // constructor (12.3.1), the initial standard conversion
1445 // sequence converts the source type to the type required by
1446 // the argument of the constructor.
1447 //
1448 // FIXME: What about ellipsis conversions?
1449 QualType ThisType = Constructor->getThisType(Context);
1450 User.Before = Best->Conversions[0].Standard;
1451 User.ConversionFunction = Constructor;
1452 User.After.setAsIdentityConversion();
Mike Stump25cf7602009-09-09 15:08:12 +00001453 User.After.FromTypePtr
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001454 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001455 User.After.ToTypePtr = ToType.getAsOpaquePtr();
1456 return true;
Douglas Gregor60714f92008-11-07 22:36:19 +00001457 } else if (CXXConversionDecl *Conversion
1458 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1459 // C++ [over.ics.user]p1:
1460 //
1461 // [...] If the user-defined conversion is specified by a
1462 // conversion function (12.3.2), the initial standard
1463 // conversion sequence converts the source type to the
1464 // implicit object parameter of the conversion function.
1465 User.Before = Best->Conversions[0].Standard;
1466 User.ConversionFunction = Conversion;
Mike Stump25cf7602009-09-09 15:08:12 +00001467
1468 // C++ [over.ics.user]p2:
Douglas Gregor60714f92008-11-07 22:36:19 +00001469 // The second standard conversion sequence converts the
1470 // result of the user-defined conversion to the target type
1471 // for the sequence. Since an implicit conversion sequence
1472 // is an initialization, the special rules for
1473 // initialization by user-defined conversion apply when
1474 // selecting the best user-defined conversion for a
1475 // user-defined conversion sequence (see 13.3.3 and
1476 // 13.3.3.1).
1477 User.After = Best->FinalConversion;
1478 return true;
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001479 } else {
Douglas Gregor60714f92008-11-07 22:36:19 +00001480 assert(false && "Not a constructor or conversion function?");
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001481 return false;
1482 }
Mike Stump25cf7602009-09-09 15:08:12 +00001483
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001484 case OR_No_Viable_Function:
Douglas Gregoraa57e862009-02-18 21:56:37 +00001485 case OR_Deleted:
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001486 // No conversion here! We're done.
1487 return false;
1488
1489 case OR_Ambiguous:
1490 // FIXME: See C++ [over.best.ics]p10 for the handling of
1491 // ambiguous conversion sequences.
1492 return false;
1493 }
1494
1495 return false;
1496}
1497
Douglas Gregord2baafd2008-10-21 16:13:35 +00001498/// CompareImplicitConversionSequences - Compare two implicit
1499/// conversion sequences to determine whether one is better than the
1500/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump25cf7602009-09-09 15:08:12 +00001501ImplicitConversionSequence::CompareKind
Douglas Gregord2baafd2008-10-21 16:13:35 +00001502Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1503 const ImplicitConversionSequence& ICS2)
1504{
1505 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1506 // conversion sequences (as defined in 13.3.3.1)
1507 // -- a standard conversion sequence (13.3.3.1.1) is a better
1508 // conversion sequence than a user-defined conversion sequence or
1509 // an ellipsis conversion sequence, and
1510 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1511 // conversion sequence than an ellipsis conversion sequence
1512 // (13.3.3.1.3).
Mike Stump25cf7602009-09-09 15:08:12 +00001513 //
Douglas Gregord2baafd2008-10-21 16:13:35 +00001514 if (ICS1.ConversionKind < ICS2.ConversionKind)
1515 return ImplicitConversionSequence::Better;
1516 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1517 return ImplicitConversionSequence::Worse;
1518
1519 // Two implicit conversion sequences of the same form are
1520 // indistinguishable conversion sequences unless one of the
1521 // following rules apply: (C++ 13.3.3.2p3):
1522 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1523 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump25cf7602009-09-09 15:08:12 +00001524 else if (ICS1.ConversionKind ==
Douglas Gregord2baafd2008-10-21 16:13:35 +00001525 ImplicitConversionSequence::UserDefinedConversion) {
1526 // User-defined conversion sequence U1 is a better conversion
1527 // sequence than another user-defined conversion sequence U2 if
1528 // they contain the same user-defined conversion function or
1529 // constructor and if the second standard conversion sequence of
1530 // U1 is better than the second standard conversion sequence of
1531 // U2 (C++ 13.3.3.2p3).
Mike Stump25cf7602009-09-09 15:08:12 +00001532 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregord2baafd2008-10-21 16:13:35 +00001533 ICS2.UserDefined.ConversionFunction)
1534 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1535 ICS2.UserDefined.After);
1536 }
1537
1538 return ImplicitConversionSequence::Indistinguishable;
1539}
1540
1541/// CompareStandardConversionSequences - Compare two standard
1542/// conversion sequences to determine whether one is better than the
1543/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump25cf7602009-09-09 15:08:12 +00001544ImplicitConversionSequence::CompareKind
Douglas Gregord2baafd2008-10-21 16:13:35 +00001545Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1546 const StandardConversionSequence& SCS2)
1547{
1548 // Standard conversion sequence S1 is a better conversion sequence
1549 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1550
1551 // -- S1 is a proper subsequence of S2 (comparing the conversion
1552 // sequences in the canonical form defined by 13.3.3.1.1,
1553 // excluding any Lvalue Transformation; the identity conversion
1554 // sequence is considered to be a subsequence of any
1555 // non-identity conversion sequence) or, if not that,
1556 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1557 // Neither is a proper subsequence of the other. Do nothing.
1558 ;
1559 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1560 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump25cf7602009-09-09 15:08:12 +00001561 (SCS1.Second == ICK_Identity &&
Douglas Gregord2baafd2008-10-21 16:13:35 +00001562 SCS1.Third == ICK_Identity))
1563 // SCS1 is a proper subsequence of SCS2.
1564 return ImplicitConversionSequence::Better;
1565 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1566 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump25cf7602009-09-09 15:08:12 +00001567 (SCS2.Second == ICK_Identity &&
Douglas Gregord2baafd2008-10-21 16:13:35 +00001568 SCS2.Third == ICK_Identity))
1569 // SCS2 is a proper subsequence of SCS1.
1570 return ImplicitConversionSequence::Worse;
1571
1572 // -- the rank of S1 is better than the rank of S2 (by the rules
1573 // defined below), or, if not that,
1574 ImplicitConversionRank Rank1 = SCS1.getRank();
1575 ImplicitConversionRank Rank2 = SCS2.getRank();
1576 if (Rank1 < Rank2)
1577 return ImplicitConversionSequence::Better;
1578 else if (Rank2 < Rank1)
1579 return ImplicitConversionSequence::Worse;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001580
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001581 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1582 // are indistinguishable unless one of the following rules
1583 // applies:
Mike Stump25cf7602009-09-09 15:08:12 +00001584
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001585 // A conversion that is not a conversion of a pointer, or
1586 // pointer to member, to bool is better than another conversion
1587 // that is such a conversion.
1588 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1589 return SCS2.isPointerConversionToBool()
1590 ? ImplicitConversionSequence::Better
1591 : ImplicitConversionSequence::Worse;
1592
Douglas Gregor14046502008-10-23 00:40:37 +00001593 // C++ [over.ics.rank]p4b2:
1594 //
1595 // If class B is derived directly or indirectly from class A,
Douglas Gregor0e343382008-10-29 14:50:44 +00001596 // conversion of B* to A* is better than conversion of B* to
1597 // void*, and conversion of A* to void* is better than conversion
1598 // of B* to void*.
Mike Stump25cf7602009-09-09 15:08:12 +00001599 bool SCS1ConvertsToVoid
Douglas Gregor14046502008-10-23 00:40:37 +00001600 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump25cf7602009-09-09 15:08:12 +00001601 bool SCS2ConvertsToVoid
Douglas Gregor14046502008-10-23 00:40:37 +00001602 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregor0e343382008-10-29 14:50:44 +00001603 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1604 // Exactly one of the conversion sequences is a conversion to
1605 // a void pointer; it's the worse conversion.
Douglas Gregor14046502008-10-23 00:40:37 +00001606 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1607 : ImplicitConversionSequence::Worse;
Douglas Gregor0e343382008-10-29 14:50:44 +00001608 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1609 // Neither conversion sequence converts to a void pointer; compare
1610 // their derived-to-base conversions.
Douglas Gregor14046502008-10-23 00:40:37 +00001611 if (ImplicitConversionSequence::CompareKind DerivedCK
1612 = CompareDerivedToBaseConversions(SCS1, SCS2))
1613 return DerivedCK;
Douglas Gregor0e343382008-10-29 14:50:44 +00001614 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1615 // Both conversion sequences are conversions to void
1616 // pointers. Compare the source types to determine if there's an
1617 // inheritance relationship in their sources.
1618 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1619 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1620
1621 // Adjust the types we're converting from via the array-to-pointer
1622 // conversion, if we need to.
1623 if (SCS1.First == ICK_Array_To_Pointer)
1624 FromType1 = Context.getArrayDecayedType(FromType1);
1625 if (SCS2.First == ICK_Array_To_Pointer)
1626 FromType2 = Context.getArrayDecayedType(FromType2);
1627
Mike Stump25cf7602009-09-09 15:08:12 +00001628 QualType FromPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001629 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor0e343382008-10-29 14:50:44 +00001630 QualType FromPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001631 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor0e343382008-10-29 14:50:44 +00001632
1633 if (IsDerivedFrom(FromPointee2, FromPointee1))
1634 return ImplicitConversionSequence::Better;
1635 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1636 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001637
1638 // Objective-C++: If one interface is more specific than the
1639 // other, it is the better one.
1640 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1641 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1642 if (FromIface1 && FromIface1) {
1643 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1644 return ImplicitConversionSequence::Better;
1645 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1646 return ImplicitConversionSequence::Worse;
1647 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001648 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001649
1650 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1651 // bullet 3).
Mike Stump25cf7602009-09-09 15:08:12 +00001652 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001653 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor14046502008-10-23 00:40:37 +00001654 return QualCK;
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001655
Douglas Gregor0e343382008-10-29 14:50:44 +00001656 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001657 // C++0x [over.ics.rank]p3b4:
1658 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1659 // implicit object parameter of a non-static member function declared
1660 // without a ref-qualifier, and S1 binds an rvalue reference to an
1661 // rvalue and S2 binds an lvalue reference.
Sebastian Redldfc30332009-03-29 15:27:50 +00001662 // FIXME: We don't know if we're dealing with the implicit object parameter,
1663 // or if the member function in this case has a ref qualifier.
1664 // (Of course, we don't have ref qualifiers yet.)
1665 if (SCS1.RRefBinding != SCS2.RRefBinding)
1666 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1667 : ImplicitConversionSequence::Worse;
Sebastian Redl8a8b3512009-03-22 23:49:27 +00001668
1669 // C++ [over.ics.rank]p3b4:
1670 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1671 // which the references refer are the same type except for
1672 // top-level cv-qualifiers, and the type to which the reference
1673 // initialized by S2 refers is more cv-qualified than the type
1674 // to which the reference initialized by S1 refers.
Sebastian Redldfc30332009-03-29 15:27:50 +00001675 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1676 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregor0e343382008-10-29 14:50:44 +00001677 T1 = Context.getCanonicalType(T1);
1678 T2 = Context.getCanonicalType(T2);
1679 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1680 if (T2.isMoreQualifiedThan(T1))
1681 return ImplicitConversionSequence::Better;
1682 else if (T1.isMoreQualifiedThan(T2))
1683 return ImplicitConversionSequence::Worse;
1684 }
1685 }
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001686
1687 return ImplicitConversionSequence::Indistinguishable;
1688}
1689
1690/// CompareQualificationConversions - Compares two standard conversion
1691/// sequences to determine whether they can be ranked based on their
Mike Stump25cf7602009-09-09 15:08:12 +00001692/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1693ImplicitConversionSequence::CompareKind
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001694Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump25cf7602009-09-09 15:08:12 +00001695 const StandardConversionSequence& SCS2) {
Douglas Gregor4459bbe2008-10-22 15:04:37 +00001696 // C++ 13.3.3.2p3:
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001697 // -- S1 and S2 differ only in their qualification conversion and
1698 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1699 // cv-qualification signature of type T1 is a proper subset of
1700 // the cv-qualification signature of type T2, and S1 is not the
1701 // deprecated string literal array-to-pointer conversion (4.2).
1702 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1703 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1704 return ImplicitConversionSequence::Indistinguishable;
1705
1706 // FIXME: the example in the standard doesn't use a qualification
1707 // conversion (!)
1708 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1709 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1710 T1 = Context.getCanonicalType(T1);
1711 T2 = Context.getCanonicalType(T2);
1712
1713 // If the types are the same, we won't learn anything by unwrapped
1714 // them.
1715 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1716 return ImplicitConversionSequence::Indistinguishable;
1717
Mike Stump25cf7602009-09-09 15:08:12 +00001718 ImplicitConversionSequence::CompareKind Result
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001719 = ImplicitConversionSequence::Indistinguishable;
1720 while (UnwrapSimilarPointerTypes(T1, T2)) {
1721 // Within each iteration of the loop, we check the qualifiers to
1722 // determine if this still looks like a qualification
1723 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorabed2172008-10-22 17:49:05 +00001724 // pointers or pointers-to-members and do it all again
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001725 // until there are no more pointers or pointers-to-members left
1726 // to unwrap. This essentially mimics what
1727 // IsQualificationConversion does, but here we're checking for a
1728 // strict subset of qualifiers.
1729 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1730 // The qualifiers are the same, so this doesn't tell us anything
1731 // about how the sequences rank.
1732 ;
1733 else if (T2.isMoreQualifiedThan(T1)) {
1734 // T1 has fewer qualifiers, so it could be the better sequence.
1735 if (Result == ImplicitConversionSequence::Worse)
1736 // Neither has qualifiers that are a subset of the other's
1737 // qualifiers.
1738 return ImplicitConversionSequence::Indistinguishable;
Mike Stump25cf7602009-09-09 15:08:12 +00001739
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001740 Result = ImplicitConversionSequence::Better;
1741 } else if (T1.isMoreQualifiedThan(T2)) {
1742 // T2 has fewer qualifiers, so it could be the better sequence.
1743 if (Result == ImplicitConversionSequence::Better)
1744 // Neither has qualifiers that are a subset of the other's
1745 // qualifiers.
1746 return ImplicitConversionSequence::Indistinguishable;
Mike Stump25cf7602009-09-09 15:08:12 +00001747
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001748 Result = ImplicitConversionSequence::Worse;
1749 } else {
1750 // Qualifiers are disjoint.
1751 return ImplicitConversionSequence::Indistinguishable;
1752 }
1753
1754 // If the types after this point are equivalent, we're done.
1755 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1756 break;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001757 }
1758
Douglas Gregorccc0ccc2008-10-22 14:17:15 +00001759 // Check that the winning standard conversion sequence isn't using
1760 // the deprecated string literal array to pointer conversion.
1761 switch (Result) {
1762 case ImplicitConversionSequence::Better:
1763 if (SCS1.Deprecated)
1764 Result = ImplicitConversionSequence::Indistinguishable;
1765 break;
1766
1767 case ImplicitConversionSequence::Indistinguishable:
1768 break;
1769
1770 case ImplicitConversionSequence::Worse:
1771 if (SCS2.Deprecated)
1772 Result = ImplicitConversionSequence::Indistinguishable;
1773 break;
1774 }
1775
1776 return Result;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001777}
1778
Douglas Gregor14046502008-10-23 00:40:37 +00001779/// CompareDerivedToBaseConversions - Compares two standard conversion
1780/// sequences to determine whether they can be ranked based on their
Douglas Gregor24a90a52008-11-26 23:31:11 +00001781/// various kinds of derived-to-base conversions (C++
1782/// [over.ics.rank]p4b3). As part of these checks, we also look at
1783/// conversions between Objective-C interface types.
Douglas Gregor14046502008-10-23 00:40:37 +00001784ImplicitConversionSequence::CompareKind
1785Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1786 const StandardConversionSequence& SCS2) {
1787 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1788 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1789 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1790 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1791
1792 // Adjust the types we're converting from via the array-to-pointer
1793 // conversion, if we need to.
1794 if (SCS1.First == ICK_Array_To_Pointer)
1795 FromType1 = Context.getArrayDecayedType(FromType1);
1796 if (SCS2.First == ICK_Array_To_Pointer)
1797 FromType2 = Context.getArrayDecayedType(FromType2);
1798
1799 // Canonicalize all of the types.
1800 FromType1 = Context.getCanonicalType(FromType1);
1801 ToType1 = Context.getCanonicalType(ToType1);
1802 FromType2 = Context.getCanonicalType(FromType2);
1803 ToType2 = Context.getCanonicalType(ToType2);
1804
Douglas Gregor0e343382008-10-29 14:50:44 +00001805 // C++ [over.ics.rank]p4b3:
Douglas Gregor14046502008-10-23 00:40:37 +00001806 //
1807 // If class B is derived directly or indirectly from class A and
1808 // class C is derived directly or indirectly from B,
Douglas Gregor24a90a52008-11-26 23:31:11 +00001809 //
1810 // For Objective-C, we let A, B, and C also be Objective-C
1811 // interfaces.
Douglas Gregor0e343382008-10-29 14:50:44 +00001812
1813 // Compare based on pointer conversions.
Mike Stump25cf7602009-09-09 15:08:12 +00001814 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor3f5a00c2008-11-27 01:19:21 +00001815 SCS2.Second == ICK_Pointer_Conversion &&
1816 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1817 FromType1->isPointerType() && FromType2->isPointerType() &&
1818 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump25cf7602009-09-09 15:08:12 +00001819 QualType FromPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001820 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump25cf7602009-09-09 15:08:12 +00001821 QualType ToPointee1
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001822 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001823 QualType FromPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001824 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor14046502008-10-23 00:40:37 +00001825 QualType ToPointee2
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001826 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor24a90a52008-11-26 23:31:11 +00001827
1828 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType();
1829 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType();
1830 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType();
1831 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType();
1832
Douglas Gregor0e343382008-10-29 14:50:44 +00001833 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor14046502008-10-23 00:40:37 +00001834 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1835 if (IsDerivedFrom(ToPointee1, ToPointee2))
1836 return ImplicitConversionSequence::Better;
1837 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1838 return ImplicitConversionSequence::Worse;
Douglas Gregor24a90a52008-11-26 23:31:11 +00001839
1840 if (ToIface1 && ToIface2) {
1841 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1842 return ImplicitConversionSequence::Better;
1843 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1844 return ImplicitConversionSequence::Worse;
1845 }
Douglas Gregor14046502008-10-23 00:40:37 +00001846 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001847
1848 // -- conversion of B* to A* is better than conversion of C* to A*,
1849 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1850 if (IsDerivedFrom(FromPointee2, FromPointee1))
1851 return ImplicitConversionSequence::Better;
1852 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1853 return ImplicitConversionSequence::Worse;
Mike Stump25cf7602009-09-09 15:08:12 +00001854
Douglas Gregor24a90a52008-11-26 23:31:11 +00001855 if (FromIface1 && FromIface2) {
1856 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1857 return ImplicitConversionSequence::Better;
1858 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1859 return ImplicitConversionSequence::Worse;
1860 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001861 }
Douglas Gregor14046502008-10-23 00:40:37 +00001862 }
1863
Douglas Gregor0e343382008-10-29 14:50:44 +00001864 // Compare based on reference bindings.
1865 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1866 SCS1.Second == ICK_Derived_To_Base) {
1867 // -- binding of an expression of type C to a reference of type
1868 // B& is better than binding an expression of type C to a
1869 // reference of type A&,
1870 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1871 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1872 if (IsDerivedFrom(ToType1, ToType2))
1873 return ImplicitConversionSequence::Better;
1874 else if (IsDerivedFrom(ToType2, ToType1))
1875 return ImplicitConversionSequence::Worse;
1876 }
1877
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001878 // -- binding of an expression of type B to a reference of type
1879 // A& is better than binding an expression of type C to a
1880 // reference of type A&,
Douglas Gregor0e343382008-10-29 14:50:44 +00001881 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1882 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1883 if (IsDerivedFrom(FromType2, FromType1))
1884 return ImplicitConversionSequence::Better;
1885 else if (IsDerivedFrom(FromType1, FromType2))
1886 return ImplicitConversionSequence::Worse;
1887 }
1888 }
1889
1890
1891 // FIXME: conversion of A::* to B::* is better than conversion of
1892 // A::* to C::*,
1893
1894 // FIXME: conversion of B::* to C::* is better than conversion of
1895 // A::* to C::*, and
1896
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001897 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1898 SCS1.Second == ICK_Derived_To_Base) {
1899 // -- conversion of C to B is better than conversion of C to A,
1900 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1901 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1902 if (IsDerivedFrom(ToType1, ToType2))
1903 return ImplicitConversionSequence::Better;
1904 else if (IsDerivedFrom(ToType2, ToType1))
1905 return ImplicitConversionSequence::Worse;
1906 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001907
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001908 // -- conversion of B to A is better than conversion of C to A.
1909 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1910 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1911 if (IsDerivedFrom(FromType2, FromType1))
1912 return ImplicitConversionSequence::Better;
1913 else if (IsDerivedFrom(FromType1, FromType2))
1914 return ImplicitConversionSequence::Worse;
1915 }
1916 }
Douglas Gregor0e343382008-10-29 14:50:44 +00001917
Douglas Gregor14046502008-10-23 00:40:37 +00001918 return ImplicitConversionSequence::Indistinguishable;
1919}
1920
Douglas Gregor81c29152008-10-29 00:13:59 +00001921/// TryCopyInitialization - Try to copy-initialize a value of type
1922/// ToType from the expression From. Return the implicit conversion
1923/// sequence required to pass this argument, which may be a bad
1924/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001925/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redla55834a2009-04-12 17:16:29 +00001926/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1927/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump25cf7602009-09-09 15:08:12 +00001928ImplicitConversionSequence
1929Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlssone0f3ee62009-08-27 17:37:39 +00001930 bool SuppressUserConversions, bool ForceRValue,
1931 bool InOverloadResolution) {
Douglas Gregorfcb19192009-02-11 23:02:49 +00001932 if (ToType->isReferenceType()) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001933 ImplicitConversionSequence ICS;
Mike Stump25cf7602009-09-09 15:08:12 +00001934 CheckReferenceInit(From, ToType,
Anders Carlsson8f809f92009-08-27 17:30:43 +00001935 SuppressUserConversions,
1936 /*AllowExplicit=*/false,
1937 ForceRValue,
1938 &ICS);
Douglas Gregor81c29152008-10-29 00:13:59 +00001939 return ICS;
1940 } else {
Mike Stump25cf7602009-09-09 15:08:12 +00001941 return TryImplicitConversion(From, ToType,
Anders Carlsson6ed4a612009-08-27 17:24:15 +00001942 SuppressUserConversions,
1943 /*AllowExplicit=*/false,
Anders Carlsson8e4c1692009-08-28 15:33:32 +00001944 ForceRValue,
1945 InOverloadResolution);
Douglas Gregor81c29152008-10-29 00:13:59 +00001946 }
1947}
1948
Sebastian Redla55834a2009-04-12 17:16:29 +00001949/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1950/// the expression @p From. Returns true (and emits a diagnostic) if there was
1951/// an error, returns false if the initialization succeeded. Elidable should
1952/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1953/// differently in C++0x for this case.
Mike Stump25cf7602009-09-09 15:08:12 +00001954bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redla55834a2009-04-12 17:16:29 +00001955 const char* Flavor, bool Elidable) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001956 if (!getLangOptions().CPlusPlus) {
1957 // In C, argument passing is the same as performing an assignment.
1958 QualType FromType = From->getType();
Mike Stump25cf7602009-09-09 15:08:12 +00001959
Douglas Gregor81c29152008-10-29 00:13:59 +00001960 AssignConvertType ConvTy =
1961 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor144b06c2009-04-29 22:16:16 +00001962 if (ConvTy != Compatible &&
1963 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
1964 ConvTy = Compatible;
Mike Stump25cf7602009-09-09 15:08:12 +00001965
Douglas Gregor81c29152008-10-29 00:13:59 +00001966 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1967 FromType, From, Flavor);
Douglas Gregor81c29152008-10-29 00:13:59 +00001968 }
Sebastian Redla55834a2009-04-12 17:16:29 +00001969
Chris Lattner271d4c22008-11-24 05:29:24 +00001970 if (ToType->isReferenceType())
Anders Carlsson8f809f92009-08-27 17:30:43 +00001971 return CheckReferenceInit(From, ToType,
1972 /*SuppressUserConversions=*/false,
1973 /*AllowExplicit=*/false,
1974 /*ForceRValue=*/false);
Chris Lattner271d4c22008-11-24 05:29:24 +00001975
Sebastian Redla55834a2009-04-12 17:16:29 +00001976 if (!PerformImplicitConversion(From, ToType, Flavor,
1977 /*AllowExplicit=*/false, Elidable))
Chris Lattner271d4c22008-11-24 05:29:24 +00001978 return false;
Sebastian Redla55834a2009-04-12 17:16:29 +00001979
Chris Lattner271d4c22008-11-24 05:29:24 +00001980 return Diag(From->getSourceRange().getBegin(),
1981 diag::err_typecheck_convert_incompatible)
1982 << ToType << From->getType() << Flavor << From->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001983}
1984
Douglas Gregor5ed15042008-11-18 23:14:02 +00001985/// TryObjectArgumentInitialization - Try to initialize the object
1986/// parameter of the given member function (@c Method) from the
1987/// expression @p From.
1988ImplicitConversionSequence
1989Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1990 QualType ClassType = Context.getTypeDeclType(Method->getParent());
1991 unsigned MethodQuals = Method->getTypeQualifiers();
1992 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1993
1994 // Set up the conversion sequence as a "bad" conversion, to allow us
1995 // to exit early.
1996 ImplicitConversionSequence ICS;
1997 ICS.Standard.setAsIdentityConversion();
1998 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1999
2000 // We need to have an object of class type.
2001 QualType FromType = From->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002002 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002003 FromType = PT->getPointeeType();
2004
2005 assert(FromType->isRecordType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00002006
2007 // The implicit object parmeter is has the type "reference to cv X",
2008 // where X is the class of which the function is a member
2009 // (C++ [over.match.funcs]p4). However, when finding an implicit
2010 // conversion sequence for the argument, we are not allowed to
Mike Stump25cf7602009-09-09 15:08:12 +00002011 // create temporaries or perform user-defined conversions
Douglas Gregor5ed15042008-11-18 23:14:02 +00002012 // (C++ [over.match.funcs]p5). We perform a simplified version of
2013 // reference binding here, that allows class rvalues to bind to
2014 // non-constant references.
2015
2016 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2017 // with the implicit object parameter (C++ [over.match.funcs]p5).
2018 QualType FromTypeCanon = Context.getCanonicalType(FromType);
2019 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
2020 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
2021 return ICS;
2022
2023 // Check that we have either the same type or a derived type. It
2024 // affects the conversion rank.
2025 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2026 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2027 ICS.Standard.Second = ICK_Identity;
2028 else if (IsDerivedFrom(FromType, ClassType))
2029 ICS.Standard.Second = ICK_Derived_To_Base;
2030 else
2031 return ICS;
2032
2033 // Success. Mark this as a reference binding.
2034 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2035 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2036 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2037 ICS.Standard.ReferenceBinding = true;
2038 ICS.Standard.DirectBinding = true;
Sebastian Redl9bc16ad2009-03-29 22:46:24 +00002039 ICS.Standard.RRefBinding = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002040 return ICS;
2041}
2042
2043/// PerformObjectArgumentInitialization - Perform initialization of
2044/// the implicit object parameter for the given Method with the given
2045/// expression.
2046bool
2047Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002048 QualType FromRecordType, DestType;
Mike Stump25cf7602009-09-09 15:08:12 +00002049 QualType ImplicitParamRecordType =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002050 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump25cf7602009-09-09 15:08:12 +00002051
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002052 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002053 FromRecordType = PT->getPointeeType();
2054 DestType = Method->getThisType(Context);
2055 } else {
2056 FromRecordType = From->getType();
2057 DestType = ImplicitParamRecordType;
2058 }
2059
Mike Stump25cf7602009-09-09 15:08:12 +00002060 ImplicitConversionSequence ICS
Douglas Gregor5ed15042008-11-18 23:14:02 +00002061 = TryObjectArgumentInitialization(From, Method);
2062 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2063 return Diag(From->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002064 diag::err_implicit_object_parameter_init)
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002065 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump25cf7602009-09-09 15:08:12 +00002066
Douglas Gregor5ed15042008-11-18 23:14:02 +00002067 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00002068 CheckDerivedToBaseConversion(FromRecordType,
2069 ImplicitParamRecordType,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002070 From->getSourceRange().getBegin(),
2071 From->getSourceRange()))
2072 return true;
2073
Mike Stump25cf7602009-09-09 15:08:12 +00002074 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlssone25b6cd2009-08-07 18:45:49 +00002075 /*isLvalue=*/true);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002076 return false;
2077}
2078
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002079/// TryContextuallyConvertToBool - Attempt to contextually convert the
2080/// expression From to bool (C++0x [conv]p3).
2081ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump25cf7602009-09-09 15:08:12 +00002082 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlsson6ed4a612009-08-27 17:24:15 +00002083 // FIXME: Are these flags correct?
2084 /*SuppressUserConversions=*/false,
Mike Stump25cf7602009-09-09 15:08:12 +00002085 /*AllowExplicit=*/true,
Anders Carlsson8e4c1692009-08-28 15:33:32 +00002086 /*ForceRValue=*/false,
2087 /*InOverloadResolution=*/false);
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002088}
2089
2090/// PerformContextuallyConvertToBool - Perform a contextual conversion
2091/// of the expression From to bool (C++0x [conv]p3).
2092bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2093 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2094 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2095 return false;
2096
Mike Stump25cf7602009-09-09 15:08:12 +00002097 return Diag(From->getSourceRange().getBegin(),
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002098 diag::err_typecheck_bool_condition)
2099 << From->getType() << From->getSourceRange();
2100}
2101
Douglas Gregord2baafd2008-10-21 16:13:35 +00002102/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002103/// candidate functions, using the given function call arguments. If
2104/// @p SuppressUserConversions, then don't allow user-defined
2105/// conversions via constructors or conversion operators.
Sebastian Redla55834a2009-04-12 17:16:29 +00002106/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2107/// hacky way to implement the overloading rules for elidable copy
2108/// initialization in C++0x (C++0x 12.8p15).
Mike Stump25cf7602009-09-09 15:08:12 +00002109void
2110Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregord2baafd2008-10-21 16:13:35 +00002111 Expr **Args, unsigned NumArgs,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002112 OverloadCandidateSet& CandidateSet,
Sebastian Redla55834a2009-04-12 17:16:29 +00002113 bool SuppressUserConversions,
Mike Stump25cf7602009-09-09 15:08:12 +00002114 bool ForceRValue) {
2115 const FunctionProtoType* Proto
Douglas Gregor4fa58902009-02-26 23:50:07 +00002116 = dyn_cast<FunctionProtoType>(Function->getType()->getAsFunctionType());
Douglas Gregord2baafd2008-10-21 16:13:35 +00002117 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump25cf7602009-09-09 15:08:12 +00002118 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregor60714f92008-11-07 22:36:19 +00002119 "Use AddConversionCandidate for conversion functions");
Mike Stump25cf7602009-09-09 15:08:12 +00002120 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorb60eb752009-06-25 22:08:12 +00002121 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump25cf7602009-09-09 15:08:12 +00002122
Douglas Gregor3257fb52008-12-22 05:46:06 +00002123 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00002124 if (!isa<CXXConstructorDecl>(Method)) {
2125 // If we get here, it's because we're calling a member function
2126 // that is named without a member access expression (e.g.,
2127 // "this->f") that was either written explicitly or created
2128 // implicitly. This can happen with a qualified call to a member
2129 // function, e.g., X::f(). We use a NULL object as the implied
2130 // object argument (C++ [over.call.func]p3).
Mike Stump25cf7602009-09-09 15:08:12 +00002131 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
Sebastian Redlbd261962009-04-16 17:51:27 +00002132 SuppressUserConversions, ForceRValue);
2133 return;
2134 }
2135 // We treat a constructor like a non-member function, since its object
2136 // argument doesn't participate in overload resolution.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002137 }
2138
2139
Douglas Gregord2baafd2008-10-21 16:13:35 +00002140 // Add this candidate
2141 CandidateSet.push_back(OverloadCandidate());
2142 OverloadCandidate& Candidate = CandidateSet.back();
2143 Candidate.Function = Function;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002144 Candidate.Viable = true;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002145 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002146 Candidate.IgnoreObjectArgument = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00002147
2148 unsigned NumArgsInProto = Proto->getNumArgs();
2149
2150 // (C++ 13.3.2p2): A candidate function having fewer than m
2151 // parameters is viable only if it has an ellipsis in its parameter
2152 // list (8.3.5).
2153 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2154 Candidate.Viable = false;
2155 return;
2156 }
2157
2158 // (C++ 13.3.2p2): A candidate function having more than m parameters
2159 // is viable only if the (m+1)st parameter has a default argument
2160 // (8.3.6). For the purposes of overload resolution, the
2161 // parameter list is truncated on the right, so that there are
2162 // exactly m parameters.
2163 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2164 if (NumArgs < MinRequiredArgs) {
2165 // Not enough arguments.
2166 Candidate.Viable = false;
2167 return;
2168 }
2169
2170 // Determine the implicit conversion sequences for each of the
2171 // arguments.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002172 Candidate.Conversions.resize(NumArgs);
2173 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2174 if (ArgIdx < NumArgsInProto) {
2175 // (C++ 13.3.2p3): for F to be a viable function, there shall
2176 // exist for each argument an implicit conversion sequence
2177 // (13.3.3.1) that converts that argument to the corresponding
2178 // parameter of F.
2179 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump25cf7602009-09-09 15:08:12 +00002180 Candidate.Conversions[ArgIdx]
2181 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlssone0f3ee62009-08-27 17:37:39 +00002182 SuppressUserConversions, ForceRValue,
2183 /*InOverloadResolution=*/true);
Mike Stump25cf7602009-09-09 15:08:12 +00002184 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002185 == ImplicitConversionSequence::BadConversion) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00002186 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002187 break;
2188 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002189 } else {
2190 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2191 // argument for which there is no corresponding parameter is
2192 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump25cf7602009-09-09 15:08:12 +00002193 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregord2baafd2008-10-21 16:13:35 +00002194 = ImplicitConversionSequence::EllipsisConversion;
2195 }
2196 }
2197}
2198
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002199/// \brief Add all of the function declarations in the given function set to
2200/// the overload canddiate set.
2201void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2202 Expr **Args, unsigned NumArgs,
2203 OverloadCandidateSet& CandidateSet,
2204 bool SuppressUserConversions) {
Mike Stump25cf7602009-09-09 15:08:12 +00002205 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002206 FEnd = Functions.end();
Douglas Gregor993a0602009-06-27 21:05:07 +00002207 F != FEnd; ++F) {
2208 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F))
Mike Stump25cf7602009-09-09 15:08:12 +00002209 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
Douglas Gregor993a0602009-06-27 21:05:07 +00002210 SuppressUserConversions);
2211 else
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002212 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*F),
2213 /*FIXME: explicit args */false, 0, 0,
Mike Stump25cf7602009-09-09 15:08:12 +00002214 Args, NumArgs, CandidateSet,
Douglas Gregor993a0602009-06-27 21:05:07 +00002215 SuppressUserConversions);
2216 }
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002217}
2218
Douglas Gregor5ed15042008-11-18 23:14:02 +00002219/// AddMethodCandidate - Adds the given C++ member function to the set
2220/// of candidate functions, using the given function call arguments
2221/// and the object argument (@c Object). For example, in a call
2222/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2223/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2224/// allow user-defined conversions via constructors or conversion
Sebastian Redla55834a2009-04-12 17:16:29 +00002225/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2226/// a slightly hacky way to implement the overloading rules for elidable copy
2227/// initialization in C++0x (C++0x 12.8p15).
Mike Stump25cf7602009-09-09 15:08:12 +00002228void
Douglas Gregor5ed15042008-11-18 23:14:02 +00002229Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2230 Expr **Args, unsigned NumArgs,
2231 OverloadCandidateSet& CandidateSet,
Mike Stump25cf7602009-09-09 15:08:12 +00002232 bool SuppressUserConversions, bool ForceRValue) {
2233 const FunctionProtoType* Proto
Douglas Gregor4fa58902009-02-26 23:50:07 +00002234 = dyn_cast<FunctionProtoType>(Method->getType()->getAsFunctionType());
Douglas Gregor5ed15042008-11-18 23:14:02 +00002235 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redlbd261962009-04-16 17:51:27 +00002236 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor5ed15042008-11-18 23:14:02 +00002237 "Use AddConversionCandidate for conversion functions");
Sebastian Redlbd261962009-04-16 17:51:27 +00002238 assert(!isa<CXXConstructorDecl>(Method) &&
2239 "Use AddOverloadCandidate for constructors");
Douglas Gregor5ed15042008-11-18 23:14:02 +00002240
2241 // Add this candidate
2242 CandidateSet.push_back(OverloadCandidate());
2243 OverloadCandidate& Candidate = CandidateSet.back();
2244 Candidate.Function = Method;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002245 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002246 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002247
2248 unsigned NumArgsInProto = Proto->getNumArgs();
2249
2250 // (C++ 13.3.2p2): A candidate function having fewer than m
2251 // parameters is viable only if it has an ellipsis in its parameter
2252 // list (8.3.5).
2253 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2254 Candidate.Viable = false;
2255 return;
2256 }
2257
2258 // (C++ 13.3.2p2): A candidate function having more than m parameters
2259 // is viable only if the (m+1)st parameter has a default argument
2260 // (8.3.6). For the purposes of overload resolution, the
2261 // parameter list is truncated on the right, so that there are
2262 // exactly m parameters.
2263 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2264 if (NumArgs < MinRequiredArgs) {
2265 // Not enough arguments.
2266 Candidate.Viable = false;
2267 return;
2268 }
2269
2270 Candidate.Viable = true;
2271 Candidate.Conversions.resize(NumArgs + 1);
2272
Douglas Gregor3257fb52008-12-22 05:46:06 +00002273 if (Method->isStatic() || !Object)
2274 // The implicit object argument is ignored.
2275 Candidate.IgnoreObjectArgument = true;
2276 else {
2277 // Determine the implicit conversion sequence for the object
2278 // parameter.
2279 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
Mike Stump25cf7602009-09-09 15:08:12 +00002280 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor3257fb52008-12-22 05:46:06 +00002281 == ImplicitConversionSequence::BadConversion) {
2282 Candidate.Viable = false;
2283 return;
2284 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002285 }
2286
2287 // Determine the implicit conversion sequences for each of the
2288 // arguments.
2289 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2290 if (ArgIdx < NumArgsInProto) {
2291 // (C++ 13.3.2p3): for F to be a viable function, there shall
2292 // exist for each argument an implicit conversion sequence
2293 // (13.3.3.1) that converts that argument to the corresponding
2294 // parameter of F.
2295 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump25cf7602009-09-09 15:08:12 +00002296 Candidate.Conversions[ArgIdx + 1]
2297 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlssone0f3ee62009-08-27 17:37:39 +00002298 SuppressUserConversions, ForceRValue,
Anders Carlsson8e4c1692009-08-28 15:33:32 +00002299 /*InOverloadResolution=*/true);
Mike Stump25cf7602009-09-09 15:08:12 +00002300 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002301 == ImplicitConversionSequence::BadConversion) {
2302 Candidate.Viable = false;
2303 break;
2304 }
2305 } else {
2306 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2307 // argument for which there is no corresponding parameter is
2308 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump25cf7602009-09-09 15:08:12 +00002309 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002310 = ImplicitConversionSequence::EllipsisConversion;
2311 }
2312 }
2313}
2314
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002315/// \brief Add a C++ member function template as a candidate to the candidate
2316/// set, using template argument deduction to produce an appropriate member
2317/// function template specialization.
Mike Stump25cf7602009-09-09 15:08:12 +00002318void
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002319Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2320 bool HasExplicitTemplateArgs,
2321 const TemplateArgument *ExplicitTemplateArgs,
2322 unsigned NumExplicitTemplateArgs,
2323 Expr *Object, Expr **Args, unsigned NumArgs,
2324 OverloadCandidateSet& CandidateSet,
2325 bool SuppressUserConversions,
2326 bool ForceRValue) {
2327 // C++ [over.match.funcs]p7:
Mike Stump25cf7602009-09-09 15:08:12 +00002328 // In each case where a candidate is a function template, candidate
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002329 // function template specializations are generated using template argument
Mike Stump25cf7602009-09-09 15:08:12 +00002330 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002331 // candidate functions in the usual way.113) A given name can refer to one
2332 // or more function templates and also to a set of overloaded non-template
2333 // functions. In such a case, the candidate functions generated from each
2334 // function template are combined with the set of non-template candidate
2335 // functions.
2336 TemplateDeductionInfo Info(Context);
2337 FunctionDecl *Specialization = 0;
2338 if (TemplateDeductionResult Result
2339 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2340 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2341 Args, NumArgs, Specialization, Info)) {
2342 // FIXME: Record what happened with template argument deduction, so
2343 // that we can give the user a beautiful diagnostic.
2344 (void)Result;
2345 return;
2346 }
Mike Stump25cf7602009-09-09 15:08:12 +00002347
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002348 // Add the function template specialization produced by template argument
2349 // deduction as a candidate.
2350 assert(Specialization && "Missing member function template specialization?");
Mike Stump25cf7602009-09-09 15:08:12 +00002351 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002352 "Specialization is not a member function?");
Mike Stump25cf7602009-09-09 15:08:12 +00002353 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00002354 CandidateSet, SuppressUserConversions, ForceRValue);
2355}
2356
Douglas Gregor8c860df2009-08-21 23:19:43 +00002357/// \brief Add a C++ function template specialization as a candidate
2358/// in the candidate set, using template argument deduction to produce
2359/// an appropriate function template specialization.
Mike Stump25cf7602009-09-09 15:08:12 +00002360void
Douglas Gregorb60eb752009-06-25 22:08:12 +00002361Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002362 bool HasExplicitTemplateArgs,
2363 const TemplateArgument *ExplicitTemplateArgs,
2364 unsigned NumExplicitTemplateArgs,
Douglas Gregorb60eb752009-06-25 22:08:12 +00002365 Expr **Args, unsigned NumArgs,
2366 OverloadCandidateSet& CandidateSet,
2367 bool SuppressUserConversions,
2368 bool ForceRValue) {
2369 // C++ [over.match.funcs]p7:
Mike Stump25cf7602009-09-09 15:08:12 +00002370 // In each case where a candidate is a function template, candidate
Douglas Gregorb60eb752009-06-25 22:08:12 +00002371 // function template specializations are generated using template argument
Mike Stump25cf7602009-09-09 15:08:12 +00002372 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorb60eb752009-06-25 22:08:12 +00002373 // candidate functions in the usual way.113) A given name can refer to one
2374 // or more function templates and also to a set of overloaded non-template
2375 // functions. In such a case, the candidate functions generated from each
2376 // function template are combined with the set of non-template candidate
2377 // functions.
2378 TemplateDeductionInfo Info(Context);
2379 FunctionDecl *Specialization = 0;
2380 if (TemplateDeductionResult Result
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002381 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2382 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2383 Args, NumArgs, Specialization, Info)) {
Douglas Gregorb60eb752009-06-25 22:08:12 +00002384 // FIXME: Record what happened with template argument deduction, so
2385 // that we can give the user a beautiful diagnostic.
2386 (void)Result;
2387 return;
2388 }
Mike Stump25cf7602009-09-09 15:08:12 +00002389
Douglas Gregorb60eb752009-06-25 22:08:12 +00002390 // Add the function template specialization produced by template argument
2391 // deduction as a candidate.
2392 assert(Specialization && "Missing function template specialization?");
2393 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2394 SuppressUserConversions, ForceRValue);
2395}
Mike Stump25cf7602009-09-09 15:08:12 +00002396
Douglas Gregor60714f92008-11-07 22:36:19 +00002397/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump25cf7602009-09-09 15:08:12 +00002398/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregor60714f92008-11-07 22:36:19 +00002399/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump25cf7602009-09-09 15:08:12 +00002400/// and ToType is the type that we're eventually trying to convert to
Douglas Gregor60714f92008-11-07 22:36:19 +00002401/// (which may or may not be the same type as the type that the
2402/// conversion function produces).
2403void
2404Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2405 Expr *From, QualType ToType,
2406 OverloadCandidateSet& CandidateSet) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00002407 assert(!Conversion->getDescribedFunctionTemplate() &&
2408 "Conversion function templates use AddTemplateConversionCandidate");
2409
Douglas Gregor60714f92008-11-07 22:36:19 +00002410 // Add this candidate
2411 CandidateSet.push_back(OverloadCandidate());
2412 OverloadCandidate& Candidate = CandidateSet.back();
2413 Candidate.Function = Conversion;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002414 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002415 Candidate.IgnoreObjectArgument = false;
Douglas Gregor60714f92008-11-07 22:36:19 +00002416 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump25cf7602009-09-09 15:08:12 +00002417 Candidate.FinalConversion.FromTypePtr
Douglas Gregor60714f92008-11-07 22:36:19 +00002418 = Conversion->getConversionType().getAsOpaquePtr();
2419 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2420
Douglas Gregor5ed15042008-11-18 23:14:02 +00002421 // Determine the implicit conversion sequence for the implicit
2422 // object parameter.
Douglas Gregor60714f92008-11-07 22:36:19 +00002423 Candidate.Viable = true;
2424 Candidate.Conversions.resize(1);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002425 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Douglas Gregor60714f92008-11-07 22:36:19 +00002426
Mike Stump25cf7602009-09-09 15:08:12 +00002427 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor60714f92008-11-07 22:36:19 +00002428 == ImplicitConversionSequence::BadConversion) {
2429 Candidate.Viable = false;
2430 return;
2431 }
2432
2433 // To determine what the conversion from the result of calling the
2434 // conversion function to the type we're eventually trying to
2435 // convert to (ToType), we need to synthesize a call to the
2436 // conversion function and attempt copy initialization from it. This
2437 // makes sure that we get the right semantics with respect to
2438 // lvalues/rvalues and the type. Fortunately, we can allocate this
2439 // call on the stack and we don't need its arguments to be
2440 // well-formed.
Mike Stump25cf7602009-09-09 15:08:12 +00002441 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregor60714f92008-11-07 22:36:19 +00002442 SourceLocation());
2443 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002444 CastExpr::CK_Unknown,
Douglas Gregor70d26122008-11-12 17:17:38 +00002445 &ConversionRef, false);
Mike Stump25cf7602009-09-09 15:08:12 +00002446
2447 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek362abcd2009-02-09 20:51:47 +00002448 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2449 // allocator).
Mike Stump25cf7602009-09-09 15:08:12 +00002450 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregor60714f92008-11-07 22:36:19 +00002451 Conversion->getConversionType().getNonReferenceType(),
2452 SourceLocation());
Mike Stump25cf7602009-09-09 15:08:12 +00002453 ImplicitConversionSequence ICS =
2454 TryCopyInitialization(&Call, ToType,
Anders Carlsson06386552009-08-27 17:18:13 +00002455 /*SuppressUserConversions=*/true,
Anders Carlssone0f3ee62009-08-27 17:37:39 +00002456 /*ForceRValue=*/false,
2457 /*InOverloadResolution=*/false);
Mike Stump25cf7602009-09-09 15:08:12 +00002458
Douglas Gregor60714f92008-11-07 22:36:19 +00002459 switch (ICS.ConversionKind) {
2460 case ImplicitConversionSequence::StandardConversion:
2461 Candidate.FinalConversion = ICS.Standard;
2462 break;
2463
2464 case ImplicitConversionSequence::BadConversion:
2465 Candidate.Viable = false;
2466 break;
2467
2468 default:
Mike Stump25cf7602009-09-09 15:08:12 +00002469 assert(false &&
Douglas Gregor60714f92008-11-07 22:36:19 +00002470 "Can only end up with a standard conversion sequence or failure");
2471 }
2472}
2473
Douglas Gregor8c860df2009-08-21 23:19:43 +00002474/// \brief Adds a conversion function template specialization
2475/// candidate to the overload set, using template argument deduction
2476/// to deduce the template arguments of the conversion function
2477/// template from the type that we are converting to (C++
2478/// [temp.deduct.conv]).
Mike Stump25cf7602009-09-09 15:08:12 +00002479void
Douglas Gregor8c860df2009-08-21 23:19:43 +00002480Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2481 Expr *From, QualType ToType,
2482 OverloadCandidateSet &CandidateSet) {
2483 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2484 "Only conversion function templates permitted here");
2485
2486 TemplateDeductionInfo Info(Context);
2487 CXXConversionDecl *Specialization = 0;
2488 if (TemplateDeductionResult Result
Mike Stump25cf7602009-09-09 15:08:12 +00002489 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor8c860df2009-08-21 23:19:43 +00002490 Specialization, Info)) {
2491 // FIXME: Record what happened with template argument deduction, so
2492 // that we can give the user a beautiful diagnostic.
2493 (void)Result;
2494 return;
2495 }
Mike Stump25cf7602009-09-09 15:08:12 +00002496
Douglas Gregor8c860df2009-08-21 23:19:43 +00002497 // Add the conversion function template specialization produced by
2498 // template argument deduction as a candidate.
2499 assert(Specialization && "Missing function template specialization?");
2500 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2501}
2502
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002503/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2504/// converts the given @c Object to a function pointer via the
2505/// conversion function @c Conversion, and then attempts to call it
2506/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2507/// the type of function that we'll eventually be calling.
2508void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002509 const FunctionProtoType *Proto,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002510 Expr *Object, Expr **Args, unsigned NumArgs,
2511 OverloadCandidateSet& CandidateSet) {
2512 CandidateSet.push_back(OverloadCandidate());
2513 OverloadCandidate& Candidate = CandidateSet.back();
2514 Candidate.Function = 0;
2515 Candidate.Surrogate = Conversion;
2516 Candidate.Viable = true;
2517 Candidate.IsSurrogate = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002518 Candidate.IgnoreObjectArgument = false;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002519 Candidate.Conversions.resize(NumArgs + 1);
2520
2521 // Determine the implicit conversion sequence for the implicit
2522 // object parameter.
Mike Stump25cf7602009-09-09 15:08:12 +00002523 ImplicitConversionSequence ObjectInit
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002524 = TryObjectArgumentInitialization(Object, Conversion);
2525 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2526 Candidate.Viable = false;
2527 return;
2528 }
2529
2530 // The first conversion is actually a user-defined conversion whose
2531 // first conversion is ObjectInit's standard conversion (which is
2532 // effectively a reference binding). Record it as such.
Mike Stump25cf7602009-09-09 15:08:12 +00002533 Candidate.Conversions[0].ConversionKind
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002534 = ImplicitConversionSequence::UserDefinedConversion;
2535 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2536 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump25cf7602009-09-09 15:08:12 +00002537 Candidate.Conversions[0].UserDefined.After
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002538 = Candidate.Conversions[0].UserDefined.Before;
2539 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2540
Mike Stump25cf7602009-09-09 15:08:12 +00002541 // Find the
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002542 unsigned NumArgsInProto = Proto->getNumArgs();
2543
2544 // (C++ 13.3.2p2): A candidate function having fewer than m
2545 // parameters is viable only if it has an ellipsis in its parameter
2546 // list (8.3.5).
2547 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2548 Candidate.Viable = false;
2549 return;
2550 }
2551
2552 // Function types don't have any default arguments, so just check if
2553 // we have enough arguments.
2554 if (NumArgs < NumArgsInProto) {
2555 // Not enough arguments.
2556 Candidate.Viable = false;
2557 return;
2558 }
2559
2560 // Determine the implicit conversion sequences for each of the
2561 // arguments.
2562 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2563 if (ArgIdx < NumArgsInProto) {
2564 // (C++ 13.3.2p3): for F to be a viable function, there shall
2565 // exist for each argument an implicit conversion sequence
2566 // (13.3.3.1) that converts that argument to the corresponding
2567 // parameter of F.
2568 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump25cf7602009-09-09 15:08:12 +00002569 Candidate.Conversions[ArgIdx + 1]
2570 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson06386552009-08-27 17:18:13 +00002571 /*SuppressUserConversions=*/false,
Anders Carlssone0f3ee62009-08-27 17:37:39 +00002572 /*ForceRValue=*/false,
2573 /*InOverloadResolution=*/false);
Mike Stump25cf7602009-09-09 15:08:12 +00002574 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002575 == ImplicitConversionSequence::BadConversion) {
2576 Candidate.Viable = false;
2577 break;
2578 }
2579 } else {
2580 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2581 // argument for which there is no corresponding parameter is
2582 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump25cf7602009-09-09 15:08:12 +00002583 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00002584 = ImplicitConversionSequence::EllipsisConversion;
2585 }
2586 }
2587}
2588
Mike Stumpe127ae32009-05-16 07:39:55 +00002589// FIXME: This will eventually be removed, once we've migrated all of the
2590// operator overloading logic over to the scheme used by binary operators, which
2591// works for template instantiation.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002592void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor48a87322009-02-04 16:44:47 +00002593 SourceLocation OpLoc,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002594 Expr **Args, unsigned NumArgs,
Douglas Gregor48a87322009-02-04 16:44:47 +00002595 OverloadCandidateSet& CandidateSet,
2596 SourceRange OpRange) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002597
2598 FunctionSet Functions;
2599
2600 QualType T1 = Args[0]->getType();
2601 QualType T2;
2602 if (NumArgs > 1)
2603 T2 = Args[1]->getType();
2604
2605 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregorde72f3e2009-05-19 00:01:19 +00002606 if (S)
2607 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002608 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2609 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2610 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2611 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2612}
2613
2614/// \brief Add overload candidates for overloaded operators that are
2615/// member functions.
2616///
2617/// Add the overloaded operator candidates that are member functions
2618/// for the operator Op that was used in an operator expression such
2619/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2620/// CandidateSet will store the added overload candidates. (C++
2621/// [over.match.oper]).
2622void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2623 SourceLocation OpLoc,
2624 Expr **Args, unsigned NumArgs,
2625 OverloadCandidateSet& CandidateSet,
2626 SourceRange OpRange) {
Douglas Gregor5ed15042008-11-18 23:14:02 +00002627 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2628
2629 // C++ [over.match.oper]p3:
2630 // For a unary operator @ with an operand of a type whose
2631 // cv-unqualified version is T1, and for a binary operator @ with
2632 // a left operand of a type whose cv-unqualified version is T1 and
2633 // a right operand of a type whose cv-unqualified version is T2,
2634 // three sets of candidate functions, designated member
2635 // candidates, non-member candidates and built-in candidates, are
2636 // constructed as follows:
2637 QualType T1 = Args[0]->getType();
2638 QualType T2;
2639 if (NumArgs > 1)
2640 T2 = Args[1]->getType();
2641
2642 // -- If T1 is a class type, the set of member candidates is the
2643 // result of the qualified lookup of T1::operator@
2644 // (13.3.1.1.1); otherwise, the set of member candidates is
2645 // empty.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002646 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor2993edd2009-08-27 23:35:55 +00002647 // Complete the type if it can be completed. Otherwise, we're done.
2648 if (RequireCompleteType(OpLoc, T1, PartialDiagnostic(0)))
2649 return;
Mike Stump25cf7602009-09-09 15:08:12 +00002650
2651 LookupResult Operators = LookupQualifiedName(T1Rec->getDecl(), OpName,
Douglas Gregor2993edd2009-08-27 23:35:55 +00002652 LookupOrdinaryName, false);
Mike Stump25cf7602009-09-09 15:08:12 +00002653 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor2993edd2009-08-27 23:35:55 +00002654 OperEnd = Operators.end();
2655 Oper != OperEnd;
2656 ++Oper)
Mike Stump25cf7602009-09-09 15:08:12 +00002657 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002658 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor5ed15042008-11-18 23:14:02 +00002659 /*SuppressUserConversions=*/false);
Douglas Gregor5ed15042008-11-18 23:14:02 +00002660 }
Douglas Gregor5ed15042008-11-18 23:14:02 +00002661}
2662
Douglas Gregor70d26122008-11-12 17:17:38 +00002663/// AddBuiltinCandidate - Add a candidate for a built-in
2664/// operator. ResultTy and ParamTys are the result and parameter types
2665/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorab141112009-01-13 00:52:54 +00002666/// arguments being passed to the candidate. IsAssignmentOperator
2667/// should be true when this built-in candidate is an assignment
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002668/// operator. NumContextualBoolArguments is the number of arguments
2669/// (at the beginning of the argument list) that will be contextually
2670/// converted to bool.
Mike Stump25cf7602009-09-09 15:08:12 +00002671void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregor70d26122008-11-12 17:17:38 +00002672 Expr **Args, unsigned NumArgs,
Douglas Gregorab141112009-01-13 00:52:54 +00002673 OverloadCandidateSet& CandidateSet,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002674 bool IsAssignmentOperator,
2675 unsigned NumContextualBoolArguments) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002676 // Add this candidate
2677 CandidateSet.push_back(OverloadCandidate());
2678 OverloadCandidate& Candidate = CandidateSet.back();
2679 Candidate.Function = 0;
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00002680 Candidate.IsSurrogate = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002681 Candidate.IgnoreObjectArgument = false;
Douglas Gregor70d26122008-11-12 17:17:38 +00002682 Candidate.BuiltinTypes.ResultTy = ResultTy;
2683 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2684 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2685
2686 // Determine the implicit conversion sequences for each of the
2687 // arguments.
2688 Candidate.Viable = true;
2689 Candidate.Conversions.resize(NumArgs);
2690 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorab141112009-01-13 00:52:54 +00002691 // C++ [over.match.oper]p4:
2692 // For the built-in assignment operators, conversions of the
2693 // left operand are restricted as follows:
2694 // -- no temporaries are introduced to hold the left operand, and
2695 // -- no user-defined conversions are applied to the left
2696 // operand to achieve a type match with the left-most
Mike Stump25cf7602009-09-09 15:08:12 +00002697 // parameter of a built-in candidate.
Douglas Gregorab141112009-01-13 00:52:54 +00002698 //
2699 // We block these conversions by turning off user-defined
2700 // conversions, since that is the only way that initialization of
2701 // a reference to a non-class type can occur from something that
2702 // is not of the same type.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002703 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump25cf7602009-09-09 15:08:12 +00002704 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002705 "Contextual conversion to bool requires bool type");
2706 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2707 } else {
Mike Stump25cf7602009-09-09 15:08:12 +00002708 Candidate.Conversions[ArgIdx]
2709 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson06386552009-08-27 17:18:13 +00002710 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlssone0f3ee62009-08-27 17:37:39 +00002711 /*ForceRValue=*/false,
2712 /*InOverloadResolution=*/false);
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002713 }
Mike Stump25cf7602009-09-09 15:08:12 +00002714 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5ed15042008-11-18 23:14:02 +00002715 == ImplicitConversionSequence::BadConversion) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002716 Candidate.Viable = false;
Douglas Gregor5ed15042008-11-18 23:14:02 +00002717 break;
2718 }
Douglas Gregor70d26122008-11-12 17:17:38 +00002719 }
2720}
2721
2722/// BuiltinCandidateTypeSet - A set of types that will be used for the
2723/// candidate operator functions for built-in operators (C++
2724/// [over.built]). The types are separated into pointer types and
2725/// enumeration types.
2726class BuiltinCandidateTypeSet {
2727 /// TypeSet - A set of types.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002728 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregor70d26122008-11-12 17:17:38 +00002729
2730 /// PointerTypes - The set of pointer types that will be used in the
2731 /// built-in candidates.
2732 TypeSet PointerTypes;
2733
Sebastian Redl674d1b72009-04-19 21:53:20 +00002734 /// MemberPointerTypes - The set of member pointer types that will be
2735 /// used in the built-in candidates.
2736 TypeSet MemberPointerTypes;
2737
Douglas Gregor70d26122008-11-12 17:17:38 +00002738 /// EnumerationTypes - The set of enumeration types that will be
2739 /// used in the built-in candidates.
2740 TypeSet EnumerationTypes;
2741
Douglas Gregorb35c7992009-08-24 15:23:48 +00002742 /// Sema - The semantic analysis instance where we are building the
2743 /// candidate type set.
2744 Sema &SemaRef;
Mike Stump25cf7602009-09-09 15:08:12 +00002745
Douglas Gregor70d26122008-11-12 17:17:38 +00002746 /// Context - The AST context in which we will build the type sets.
2747 ASTContext &Context;
2748
Sebastian Redl674d1b72009-04-19 21:53:20 +00002749 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2750 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002751
2752public:
2753 /// iterator - Iterates through the types that are part of the set.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002754 typedef TypeSet::iterator iterator;
Douglas Gregor70d26122008-11-12 17:17:38 +00002755
Mike Stump25cf7602009-09-09 15:08:12 +00002756 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregorb35c7992009-08-24 15:23:48 +00002757 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregor70d26122008-11-12 17:17:38 +00002758
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002759 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2760 bool AllowExplicitConversions);
Douglas Gregor70d26122008-11-12 17:17:38 +00002761
2762 /// pointer_begin - First pointer type found;
2763 iterator pointer_begin() { return PointerTypes.begin(); }
2764
Sebastian Redl674d1b72009-04-19 21:53:20 +00002765 /// pointer_end - Past the last pointer type found;
Douglas Gregor70d26122008-11-12 17:17:38 +00002766 iterator pointer_end() { return PointerTypes.end(); }
2767
Sebastian Redl674d1b72009-04-19 21:53:20 +00002768 /// member_pointer_begin - First member pointer type found;
2769 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2770
2771 /// member_pointer_end - Past the last member pointer type found;
2772 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2773
Douglas Gregor70d26122008-11-12 17:17:38 +00002774 /// enumeration_begin - First enumeration type found;
2775 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2776
Sebastian Redl674d1b72009-04-19 21:53:20 +00002777 /// enumeration_end - Past the last enumeration type found;
Douglas Gregor70d26122008-11-12 17:17:38 +00002778 iterator enumeration_end() { return EnumerationTypes.end(); }
2779};
2780
Sebastian Redl674d1b72009-04-19 21:53:20 +00002781/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregor70d26122008-11-12 17:17:38 +00002782/// the set of pointer types along with any more-qualified variants of
2783/// that type. For example, if @p Ty is "int const *", this routine
2784/// will add "int const *", "int const volatile *", "int const
2785/// restrict *", and "int const volatile restrict *" to the set of
2786/// pointer types. Returns true if the add of @p Ty itself succeeded,
2787/// false otherwise.
Sebastian Redl674d1b72009-04-19 21:53:20 +00002788bool
2789BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002790 // Insert this type.
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002791 if (!PointerTypes.insert(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002792 return false;
2793
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002794 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002795 QualType PointeeTy = PointerTy->getPointeeType();
2796 // FIXME: Optimize this so that we don't keep trying to add the same types.
2797
Mike Stumpe127ae32009-05-16 07:39:55 +00002798 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal with all
2799 // pointer conversions that don't cast away constness?
Douglas Gregor70d26122008-11-12 17:17:38 +00002800 if (!PointeeTy.isConstQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002801 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002802 (Context.getPointerType(PointeeTy.withConst()));
2803 if (!PointeeTy.isVolatileQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002804 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002805 (Context.getPointerType(PointeeTy.withVolatile()));
2806 if (!PointeeTy.isRestrictQualified())
Sebastian Redl674d1b72009-04-19 21:53:20 +00002807 AddPointerWithMoreQualifiedTypeVariants
Douglas Gregor70d26122008-11-12 17:17:38 +00002808 (Context.getPointerType(PointeeTy.withRestrict()));
2809 }
2810
2811 return true;
2812}
2813
Sebastian Redl674d1b72009-04-19 21:53:20 +00002814/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2815/// to the set of pointer types along with any more-qualified variants of
2816/// that type. For example, if @p Ty is "int const *", this routine
2817/// will add "int const *", "int const volatile *", "int const
2818/// restrict *", and "int const volatile restrict *" to the set of
2819/// pointer types. Returns true if the add of @p Ty itself succeeded,
2820/// false otherwise.
2821bool
2822BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2823 QualType Ty) {
2824 // Insert this type.
2825 if (!MemberPointerTypes.insert(Ty))
2826 return false;
2827
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002828 if (const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>()) {
Sebastian Redl674d1b72009-04-19 21:53:20 +00002829 QualType PointeeTy = PointerTy->getPointeeType();
2830 const Type *ClassTy = PointerTy->getClass();
2831 // FIXME: Optimize this so that we don't keep trying to add the same types.
2832
2833 if (!PointeeTy.isConstQualified())
2834 AddMemberPointerWithMoreQualifiedTypeVariants
2835 (Context.getMemberPointerType(PointeeTy.withConst(), ClassTy));
2836 if (!PointeeTy.isVolatileQualified())
2837 AddMemberPointerWithMoreQualifiedTypeVariants
2838 (Context.getMemberPointerType(PointeeTy.withVolatile(), ClassTy));
2839 if (!PointeeTy.isRestrictQualified())
2840 AddMemberPointerWithMoreQualifiedTypeVariants
2841 (Context.getMemberPointerType(PointeeTy.withRestrict(), ClassTy));
2842 }
2843
2844 return true;
2845}
2846
Douglas Gregor70d26122008-11-12 17:17:38 +00002847/// AddTypesConvertedFrom - Add each of the types to which the type @p
2848/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl674d1b72009-04-19 21:53:20 +00002849/// primarily interested in pointer types and enumeration types. We also
2850/// take member pointer types, for the conditional operator.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002851/// AllowUserConversions is true if we should look at the conversion
2852/// functions of a class type, and AllowExplicitConversions if we
2853/// should also include the explicit conversion functions of a class
2854/// type.
Mike Stump25cf7602009-09-09 15:08:12 +00002855void
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002856BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2857 bool AllowUserConversions,
2858 bool AllowExplicitConversions) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002859 // Only deal with canonical types.
2860 Ty = Context.getCanonicalType(Ty);
2861
2862 // Look through reference types; they aren't part of the type of an
2863 // expression for the purposes of conversions.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002864 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregor70d26122008-11-12 17:17:38 +00002865 Ty = RefTy->getPointeeType();
2866
2867 // We don't care about qualifiers on the type.
2868 Ty = Ty.getUnqualifiedType();
2869
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002870 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002871 QualType PointeeTy = PointerTy->getPointeeType();
2872
2873 // Insert our type, and its more-qualified variants, into the set
2874 // of types.
Sebastian Redl674d1b72009-04-19 21:53:20 +00002875 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregor70d26122008-11-12 17:17:38 +00002876 return;
2877
2878 // Add 'cv void*' to our set of types.
2879 if (!Ty->isVoidType()) {
Mike Stump25cf7602009-09-09 15:08:12 +00002880 QualType QualVoid
Douglas Gregor70d26122008-11-12 17:17:38 +00002881 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
Sebastian Redl674d1b72009-04-19 21:53:20 +00002882 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregor70d26122008-11-12 17:17:38 +00002883 }
2884
2885 // If this is a pointer to a class type, add pointers to its bases
2886 // (with the same level of cv-qualification as the original
2887 // derived class, of course).
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002888 if (const RecordType *PointeeRec = PointeeTy->getAs<RecordType>()) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002889 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2890 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2891 Base != ClassDecl->bases_end(); ++Base) {
2892 QualType BaseTy = Context.getCanonicalType(Base->getType());
2893 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2894
2895 // Add the pointer type, recursively, so that we get all of
2896 // the indirect base classes, too.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002897 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002898 }
2899 }
Sebastian Redl674d1b72009-04-19 21:53:20 +00002900 } else if (Ty->isMemberPointerType()) {
2901 // Member pointers are far easier, since the pointee can't be converted.
2902 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
2903 return;
Douglas Gregor70d26122008-11-12 17:17:38 +00002904 } else if (Ty->isEnumeralType()) {
Chris Lattnerf0bb03c2009-03-29 00:04:01 +00002905 EnumerationTypes.insert(Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +00002906 } else if (AllowUserConversions) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002907 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorb35c7992009-08-24 15:23:48 +00002908 if (SemaRef.RequireCompleteType(SourceLocation(), Ty, 0)) {
2909 // No conversion functions in incomplete types.
2910 return;
2911 }
Mike Stump25cf7602009-09-09 15:08:12 +00002912
Douglas Gregor70d26122008-11-12 17:17:38 +00002913 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2914 // FIXME: Visit conversion functions in the base classes, too.
Mike Stump25cf7602009-09-09 15:08:12 +00002915 OverloadedFunctionDecl *Conversions
Douglas Gregor70d26122008-11-12 17:17:38 +00002916 = ClassDecl->getConversionFunctions();
Mike Stump25cf7602009-09-09 15:08:12 +00002917 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregor70d26122008-11-12 17:17:38 +00002918 = Conversions->function_begin();
2919 Func != Conversions->function_end(); ++Func) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00002920 CXXConversionDecl *Conv;
2921 FunctionTemplateDecl *ConvTemplate;
2922 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
2923
Mike Stump25cf7602009-09-09 15:08:12 +00002924 // Skip conversion function templates; they don't tell us anything
Douglas Gregor8c860df2009-08-21 23:19:43 +00002925 // about which builtin types we can convert to.
2926 if (ConvTemplate)
2927 continue;
2928
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002929 if (AllowExplicitConversions || !Conv->isExplicit())
2930 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregor70d26122008-11-12 17:17:38 +00002931 }
2932 }
2933 }
2934}
2935
Douglas Gregor9a375942009-08-24 13:43:27 +00002936/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
2937/// the volatile- and non-volatile-qualified assignment operators for the
2938/// given type to the candidate set.
2939static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
2940 QualType T,
Mike Stump25cf7602009-09-09 15:08:12 +00002941 Expr **Args,
Douglas Gregor9a375942009-08-24 13:43:27 +00002942 unsigned NumArgs,
2943 OverloadCandidateSet &CandidateSet) {
2944 QualType ParamTypes[2];
Mike Stump25cf7602009-09-09 15:08:12 +00002945
Douglas Gregor9a375942009-08-24 13:43:27 +00002946 // T& operator=(T&, T)
2947 ParamTypes[0] = S.Context.getLValueReferenceType(T);
2948 ParamTypes[1] = T;
2949 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
2950 /*IsAssignmentOperator=*/true);
Mike Stump25cf7602009-09-09 15:08:12 +00002951
Douglas Gregor9a375942009-08-24 13:43:27 +00002952 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
2953 // volatile T& operator=(volatile T&, T)
2954 ParamTypes[0] = S.Context.getLValueReferenceType(T.withVolatile());
2955 ParamTypes[1] = T;
2956 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump25cf7602009-09-09 15:08:12 +00002957 /*IsAssignmentOperator=*/true);
Douglas Gregor9a375942009-08-24 13:43:27 +00002958 }
2959}
Mike Stump25cf7602009-09-09 15:08:12 +00002960
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002961/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2962/// operator overloads to the candidate set (C++ [over.built]), based
2963/// on the operator @p Op and the arguments given. For example, if the
2964/// operator is a binary '+', this routine might add "int
2965/// operator+(int, int)" to cover integer addition.
Douglas Gregor70d26122008-11-12 17:17:38 +00002966void
Mike Stump25cf7602009-09-09 15:08:12 +00002967Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002968 Expr **Args, unsigned NumArgs,
2969 OverloadCandidateSet& CandidateSet) {
Douglas Gregor70d26122008-11-12 17:17:38 +00002970 // The set of "promoted arithmetic types", which are the arithmetic
2971 // types are that preserved by promotion (C++ [over.built]p2). Note
2972 // that the first few of these types are the promoted integral
2973 // types; these types need to be first.
2974 // FIXME: What about complex?
2975 const unsigned FirstIntegralType = 0;
2976 const unsigned LastIntegralType = 13;
Mike Stump25cf7602009-09-09 15:08:12 +00002977 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregor70d26122008-11-12 17:17:38 +00002978 LastPromotedIntegralType = 13;
2979 const unsigned FirstPromotedArithmeticType = 7,
2980 LastPromotedArithmeticType = 16;
2981 const unsigned NumArithmeticTypes = 16;
2982 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump25cf7602009-09-09 15:08:12 +00002983 Context.BoolTy, Context.CharTy, Context.WCharTy,
2984// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregor70d26122008-11-12 17:17:38 +00002985 Context.SignedCharTy, Context.ShortTy,
2986 Context.UnsignedCharTy, Context.UnsignedShortTy,
2987 Context.IntTy, Context.LongTy, Context.LongLongTy,
2988 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2989 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2990 };
2991
2992 // Find all of the types that the arguments can convert to, but only
2993 // if the operator we're looking at has built-in operator candidates
2994 // that make use of these types.
Douglas Gregorb35c7992009-08-24 15:23:48 +00002995 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregor70d26122008-11-12 17:17:38 +00002996 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2997 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00002998 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregor70d26122008-11-12 17:17:38 +00002999 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003000 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redlbd261962009-04-16 17:51:27 +00003001 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003002 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003003 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
3004 true,
3005 (Op == OO_Exclaim ||
3006 Op == OO_AmpAmp ||
3007 Op == OO_PipePipe));
Douglas Gregor70d26122008-11-12 17:17:38 +00003008 }
3009
3010 bool isComparison = false;
3011 switch (Op) {
3012 case OO_None:
3013 case NUM_OVERLOADED_OPERATORS:
3014 assert(false && "Expected an overloaded operator");
3015 break;
3016
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003017 case OO_Star: // '*' is either unary or binary
Mike Stump25cf7602009-09-09 15:08:12 +00003018 if (NumArgs == 1)
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003019 goto UnaryStar;
3020 else
3021 goto BinaryStar;
3022 break;
3023
3024 case OO_Plus: // '+' is either unary or binary
3025 if (NumArgs == 1)
3026 goto UnaryPlus;
3027 else
3028 goto BinaryPlus;
3029 break;
3030
3031 case OO_Minus: // '-' is either unary or binary
3032 if (NumArgs == 1)
3033 goto UnaryMinus;
3034 else
3035 goto BinaryMinus;
3036 break;
3037
3038 case OO_Amp: // '&' is either unary or binary
3039 if (NumArgs == 1)
3040 goto UnaryAmp;
3041 else
3042 goto BinaryAmp;
3043
3044 case OO_PlusPlus:
3045 case OO_MinusMinus:
3046 // C++ [over.built]p3:
3047 //
3048 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3049 // is either volatile or empty, there exist candidate operator
3050 // functions of the form
3051 //
3052 // VQ T& operator++(VQ T&);
3053 // T operator++(VQ T&, int);
3054 //
3055 // C++ [over.built]p4:
3056 //
3057 // For every pair (T, VQ), where T is an arithmetic type other
3058 // than bool, and VQ is either volatile or empty, there exist
3059 // candidate operator functions of the form
3060 //
3061 // VQ T& operator--(VQ T&);
3062 // T operator--(VQ T&, int);
Mike Stump25cf7602009-09-09 15:08:12 +00003063 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003064 Arith < NumArithmeticTypes; ++Arith) {
3065 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump25cf7602009-09-09 15:08:12 +00003066 QualType ParamTypes[2]
Sebastian Redlce6fff02009-03-16 23:22:08 +00003067 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003068
3069 // Non-volatile version.
3070 if (NumArgs == 1)
3071 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3072 else
3073 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3074
3075 // Volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003076 ParamTypes[0] = Context.getLValueReferenceType(ArithTy.withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003077 if (NumArgs == 1)
3078 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3079 else
3080 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3081 }
3082
3083 // C++ [over.built]p5:
3084 //
3085 // For every pair (T, VQ), where T is a cv-qualified or
3086 // cv-unqualified object type, and VQ is either volatile or
3087 // empty, there exist candidate operator functions of the form
3088 //
3089 // T*VQ& operator++(T*VQ&);
3090 // T*VQ& operator--(T*VQ&);
3091 // T* operator++(T*VQ&, int);
3092 // T* operator--(T*VQ&, int);
3093 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3094 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3095 // Skip pointer types that aren't pointers to object types.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003096 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003097 continue;
3098
Mike Stump25cf7602009-09-09 15:08:12 +00003099 QualType ParamTypes[2] = {
3100 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003101 };
Mike Stump25cf7602009-09-09 15:08:12 +00003102
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003103 // Without volatile
3104 if (NumArgs == 1)
3105 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3106 else
3107 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3108
3109 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3110 // With volatile
Sebastian Redlce6fff02009-03-16 23:22:08 +00003111 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003112 if (NumArgs == 1)
3113 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3114 else
3115 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3116 }
3117 }
3118 break;
3119
3120 UnaryStar:
3121 // C++ [over.built]p6:
3122 // For every cv-qualified or cv-unqualified object type T, there
3123 // exist candidate operator functions of the form
3124 //
3125 // T& operator*(T*);
3126 //
3127 // C++ [over.built]p7:
3128 // For every function type T, there exist candidate operator
3129 // functions of the form
3130 // T& operator*(T*);
3131 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3132 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3133 QualType ParamTy = *Ptr;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003134 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump25cf7602009-09-09 15:08:12 +00003135 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003136 &ParamTy, Args, 1, CandidateSet);
3137 }
3138 break;
3139
3140 UnaryPlus:
3141 // C++ [over.built]p8:
3142 // For every type T, there exist candidate operator functions of
3143 // the form
3144 //
3145 // T* operator+(T*);
3146 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3147 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3148 QualType ParamTy = *Ptr;
3149 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3150 }
Mike Stump25cf7602009-09-09 15:08:12 +00003151
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003152 // Fall through
3153
3154 UnaryMinus:
3155 // C++ [over.built]p9:
3156 // For every promoted arithmetic type T, there exist candidate
3157 // operator functions of the form
3158 //
3159 // T operator+(T);
3160 // T operator-(T);
Mike Stump25cf7602009-09-09 15:08:12 +00003161 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003162 Arith < LastPromotedArithmeticType; ++Arith) {
3163 QualType ArithTy = ArithmeticTypes[Arith];
3164 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3165 }
3166 break;
3167
3168 case OO_Tilde:
3169 // C++ [over.built]p10:
3170 // For every promoted integral type T, there exist candidate
3171 // operator functions of the form
3172 //
3173 // T operator~(T);
Mike Stump25cf7602009-09-09 15:08:12 +00003174 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003175 Int < LastPromotedIntegralType; ++Int) {
3176 QualType IntTy = ArithmeticTypes[Int];
3177 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3178 }
3179 break;
3180
Douglas Gregor70d26122008-11-12 17:17:38 +00003181 case OO_New:
3182 case OO_Delete:
3183 case OO_Array_New:
3184 case OO_Array_Delete:
Douglas Gregor70d26122008-11-12 17:17:38 +00003185 case OO_Call:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003186 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregor70d26122008-11-12 17:17:38 +00003187 break;
3188
3189 case OO_Comma:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003190 UnaryAmp:
3191 case OO_Arrow:
Douglas Gregor70d26122008-11-12 17:17:38 +00003192 // C++ [over.match.oper]p3:
3193 // -- For the operator ',', the unary operator '&', or the
3194 // operator '->', the built-in candidates set is empty.
Douglas Gregor70d26122008-11-12 17:17:38 +00003195 break;
3196
Douglas Gregor9a375942009-08-24 13:43:27 +00003197 case OO_EqualEqual:
3198 case OO_ExclaimEqual:
3199 // C++ [over.match.oper]p16:
Mike Stump25cf7602009-09-09 15:08:12 +00003200 // For every pointer to member type T, there exist candidate operator
3201 // functions of the form
Douglas Gregor9a375942009-08-24 13:43:27 +00003202 //
3203 // bool operator==(T,T);
3204 // bool operator!=(T,T);
Mike Stump25cf7602009-09-09 15:08:12 +00003205 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor9a375942009-08-24 13:43:27 +00003206 MemPtr = CandidateTypes.member_pointer_begin(),
3207 MemPtrEnd = CandidateTypes.member_pointer_end();
3208 MemPtr != MemPtrEnd;
3209 ++MemPtr) {
3210 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3211 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3212 }
Mike Stump25cf7602009-09-09 15:08:12 +00003213
Douglas Gregor9a375942009-08-24 13:43:27 +00003214 // Fall through
Mike Stump25cf7602009-09-09 15:08:12 +00003215
Douglas Gregor70d26122008-11-12 17:17:38 +00003216 case OO_Less:
3217 case OO_Greater:
3218 case OO_LessEqual:
3219 case OO_GreaterEqual:
Douglas Gregor70d26122008-11-12 17:17:38 +00003220 // C++ [over.built]p15:
3221 //
3222 // For every pointer or enumeration type T, there exist
3223 // candidate operator functions of the form
Mike Stump25cf7602009-09-09 15:08:12 +00003224 //
Douglas Gregor70d26122008-11-12 17:17:38 +00003225 // bool operator<(T, T);
3226 // bool operator>(T, T);
3227 // bool operator<=(T, T);
3228 // bool operator>=(T, T);
3229 // bool operator==(T, T);
3230 // bool operator!=(T, T);
3231 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3232 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3233 QualType ParamTypes[2] = { *Ptr, *Ptr };
3234 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3235 }
Mike Stump25cf7602009-09-09 15:08:12 +00003236 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregor70d26122008-11-12 17:17:38 +00003237 = CandidateTypes.enumeration_begin();
3238 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3239 QualType ParamTypes[2] = { *Enum, *Enum };
3240 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3241 }
3242
3243 // Fall through.
3244 isComparison = true;
3245
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003246 BinaryPlus:
3247 BinaryMinus:
Douglas Gregor70d26122008-11-12 17:17:38 +00003248 if (!isComparison) {
3249 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3250
3251 // C++ [over.built]p13:
3252 //
3253 // For every cv-qualified or cv-unqualified object type T
3254 // there exist candidate operator functions of the form
Mike Stump25cf7602009-09-09 15:08:12 +00003255 //
Douglas Gregor70d26122008-11-12 17:17:38 +00003256 // T* operator+(T*, ptrdiff_t);
3257 // T& operator[](T*, ptrdiff_t); [BELOW]
3258 // T* operator-(T*, ptrdiff_t);
3259 // T* operator+(ptrdiff_t, T*);
3260 // T& operator[](ptrdiff_t, T*); [BELOW]
3261 //
3262 // C++ [over.built]p14:
3263 //
3264 // For every T, where T is a pointer to object type, there
3265 // exist candidate operator functions of the form
3266 //
3267 // ptrdiff_t operator-(T, T);
Mike Stump25cf7602009-09-09 15:08:12 +00003268 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregor70d26122008-11-12 17:17:38 +00003269 = CandidateTypes.pointer_begin();
3270 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3271 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3272
3273 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3274 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3275
3276 if (Op == OO_Plus) {
3277 // T* operator+(ptrdiff_t, T*);
3278 ParamTypes[0] = ParamTypes[1];
3279 ParamTypes[1] = *Ptr;
3280 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3281 } else {
3282 // ptrdiff_t operator-(T, T);
3283 ParamTypes[1] = *Ptr;
3284 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3285 Args, 2, CandidateSet);
3286 }
3287 }
3288 }
3289 // Fall through
3290
Douglas Gregor70d26122008-11-12 17:17:38 +00003291 case OO_Slash:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003292 BinaryStar:
Sebastian Redlbd261962009-04-16 17:51:27 +00003293 Conditional:
Douglas Gregor70d26122008-11-12 17:17:38 +00003294 // C++ [over.built]p12:
3295 //
3296 // For every pair of promoted arithmetic types L and R, there
3297 // exist candidate operator functions of the form
3298 //
3299 // LR operator*(L, R);
3300 // LR operator/(L, R);
3301 // LR operator+(L, R);
3302 // LR operator-(L, R);
3303 // bool operator<(L, R);
3304 // bool operator>(L, R);
3305 // bool operator<=(L, R);
3306 // bool operator>=(L, R);
3307 // bool operator==(L, R);
3308 // bool operator!=(L, R);
3309 //
3310 // where LR is the result of the usual arithmetic conversions
3311 // between types L and R.
Sebastian Redlbd261962009-04-16 17:51:27 +00003312 //
3313 // C++ [over.built]p24:
3314 //
3315 // For every pair of promoted arithmetic types L and R, there exist
3316 // candidate operator functions of the form
3317 //
3318 // LR operator?(bool, L, R);
3319 //
3320 // where LR is the result of the usual arithmetic conversions
3321 // between types L and R.
3322 // Our candidates ignore the first parameter.
Mike Stump25cf7602009-09-09 15:08:12 +00003323 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003324 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump25cf7602009-09-09 15:08:12 +00003325 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003326 Right < LastPromotedArithmeticType; ++Right) {
3327 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman6ae7d112009-08-19 07:44:53 +00003328 QualType Result
3329 = isComparison
3330 ? Context.BoolTy
3331 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003332 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3333 }
3334 }
3335 break;
3336
3337 case OO_Percent:
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003338 BinaryAmp:
Douglas Gregor70d26122008-11-12 17:17:38 +00003339 case OO_Caret:
3340 case OO_Pipe:
3341 case OO_LessLess:
3342 case OO_GreaterGreater:
3343 // C++ [over.built]p17:
3344 //
3345 // For every pair of promoted integral types L and R, there
3346 // exist candidate operator functions of the form
3347 //
3348 // LR operator%(L, R);
3349 // LR operator&(L, R);
3350 // LR operator^(L, R);
3351 // LR operator|(L, R);
3352 // L operator<<(L, R);
3353 // L operator>>(L, R);
3354 //
3355 // where LR is the result of the usual arithmetic conversions
3356 // between types L and R.
Mike Stump25cf7602009-09-09 15:08:12 +00003357 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003358 Left < LastPromotedIntegralType; ++Left) {
Mike Stump25cf7602009-09-09 15:08:12 +00003359 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003360 Right < LastPromotedIntegralType; ++Right) {
3361 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3362 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3363 ? LandR[0]
Eli Friedman6ae7d112009-08-19 07:44:53 +00003364 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003365 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3366 }
3367 }
3368 break;
3369
3370 case OO_Equal:
3371 // C++ [over.built]p20:
3372 //
3373 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor9a375942009-08-24 13:43:27 +00003374 // pointer to member type and VQ is either volatile or
Douglas Gregor70d26122008-11-12 17:17:38 +00003375 // empty, there exist candidate operator functions of the form
3376 //
3377 // VQ T& operator=(VQ T&, T);
Douglas Gregor9a375942009-08-24 13:43:27 +00003378 for (BuiltinCandidateTypeSet::iterator
3379 Enum = CandidateTypes.enumeration_begin(),
3380 EnumEnd = CandidateTypes.enumeration_end();
3381 Enum != EnumEnd; ++Enum)
Mike Stump25cf7602009-09-09 15:08:12 +00003382 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor9a375942009-08-24 13:43:27 +00003383 CandidateSet);
3384 for (BuiltinCandidateTypeSet::iterator
3385 MemPtr = CandidateTypes.member_pointer_begin(),
3386 MemPtrEnd = CandidateTypes.member_pointer_end();
3387 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump25cf7602009-09-09 15:08:12 +00003388 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor9a375942009-08-24 13:43:27 +00003389 CandidateSet);
3390 // Fall through.
Douglas Gregor70d26122008-11-12 17:17:38 +00003391
3392 case OO_PlusEqual:
3393 case OO_MinusEqual:
3394 // C++ [over.built]p19:
3395 //
3396 // For every pair (T, VQ), where T is any type and VQ is either
3397 // volatile or empty, there exist candidate operator functions
3398 // of the form
3399 //
3400 // T*VQ& operator=(T*VQ&, T*);
3401 //
3402 // C++ [over.built]p21:
3403 //
3404 // For every pair (T, VQ), where T is a cv-qualified or
3405 // cv-unqualified object type and VQ is either volatile or
3406 // empty, there exist candidate operator functions of the form
3407 //
3408 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3409 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3410 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3411 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3412 QualType ParamTypes[2];
3413 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3414
3415 // non-volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003416 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorab141112009-01-13 00:52:54 +00003417 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3418 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003419
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003420 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3421 // volatile version
Sebastian Redlce6fff02009-03-16 23:22:08 +00003422 ParamTypes[0] = Context.getLValueReferenceType((*Ptr).withVolatile());
Douglas Gregorab141112009-01-13 00:52:54 +00003423 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3424 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003425 }
Douglas Gregor70d26122008-11-12 17:17:38 +00003426 }
3427 // Fall through.
3428
3429 case OO_StarEqual:
3430 case OO_SlashEqual:
3431 // C++ [over.built]p18:
3432 //
3433 // For every triple (L, VQ, R), where L is an arithmetic type,
3434 // VQ is either volatile or empty, and R is a promoted
3435 // arithmetic type, there exist candidate operator functions of
3436 // the form
3437 //
3438 // VQ L& operator=(VQ L&, R);
3439 // VQ L& operator*=(VQ L&, R);
3440 // VQ L& operator/=(VQ L&, R);
3441 // VQ L& operator+=(VQ L&, R);
3442 // VQ L& operator-=(VQ L&, R);
3443 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump25cf7602009-09-09 15:08:12 +00003444 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003445 Right < LastPromotedArithmeticType; ++Right) {
3446 QualType ParamTypes[2];
3447 ParamTypes[1] = ArithmeticTypes[Right];
3448
3449 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003450 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorab141112009-01-13 00:52:54 +00003451 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3452 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003453
3454 // Add this built-in operator as a candidate (VQ is 'volatile').
3455 ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003456 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregorab141112009-01-13 00:52:54 +00003457 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3458 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor70d26122008-11-12 17:17:38 +00003459 }
3460 }
3461 break;
3462
3463 case OO_PercentEqual:
3464 case OO_LessLessEqual:
3465 case OO_GreaterGreaterEqual:
3466 case OO_AmpEqual:
3467 case OO_CaretEqual:
3468 case OO_PipeEqual:
3469 // C++ [over.built]p22:
3470 //
3471 // For every triple (L, VQ, R), where L is an integral type, VQ
3472 // is either volatile or empty, and R is a promoted integral
3473 // type, there exist candidate operator functions of the form
3474 //
3475 // VQ L& operator%=(VQ L&, R);
3476 // VQ L& operator<<=(VQ L&, R);
3477 // VQ L& operator>>=(VQ L&, R);
3478 // VQ L& operator&=(VQ L&, R);
3479 // VQ L& operator^=(VQ L&, R);
3480 // VQ L& operator|=(VQ L&, R);
3481 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump25cf7602009-09-09 15:08:12 +00003482 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003483 Right < LastPromotedIntegralType; ++Right) {
3484 QualType ParamTypes[2];
3485 ParamTypes[1] = ArithmeticTypes[Right];
3486
3487 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redlce6fff02009-03-16 23:22:08 +00003488 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003489 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3490
3491 // Add this built-in operator as a candidate (VQ is 'volatile').
3492 ParamTypes[0] = ArithmeticTypes[Left];
3493 ParamTypes[0].addVolatile();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003494 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregor70d26122008-11-12 17:17:38 +00003495 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3496 }
3497 }
3498 break;
3499
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003500 case OO_Exclaim: {
3501 // C++ [over.operator]p23:
3502 //
3503 // There also exist candidate operator functions of the form
3504 //
Mike Stump25cf7602009-09-09 15:08:12 +00003505 // bool operator!(bool);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003506 // bool operator&&(bool, bool); [BELOW]
3507 // bool operator||(bool, bool); [BELOW]
3508 QualType ParamTy = Context.BoolTy;
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003509 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3510 /*IsAssignmentOperator=*/false,
3511 /*NumContextualBoolArguments=*/1);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003512 break;
3513 }
3514
Douglas Gregor70d26122008-11-12 17:17:38 +00003515 case OO_AmpAmp:
3516 case OO_PipePipe: {
3517 // C++ [over.operator]p23:
3518 //
3519 // There also exist candidate operator functions of the form
3520 //
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003521 // bool operator!(bool); [ABOVE]
Douglas Gregor70d26122008-11-12 17:17:38 +00003522 // bool operator&&(bool, bool);
3523 // bool operator||(bool, bool);
3524 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003525 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3526 /*IsAssignmentOperator=*/false,
3527 /*NumContextualBoolArguments=*/2);
Douglas Gregor70d26122008-11-12 17:17:38 +00003528 break;
3529 }
3530
3531 case OO_Subscript:
3532 // C++ [over.built]p13:
3533 //
3534 // For every cv-qualified or cv-unqualified object type T there
3535 // exist candidate operator functions of the form
Mike Stump25cf7602009-09-09 15:08:12 +00003536 //
Douglas Gregor70d26122008-11-12 17:17:38 +00003537 // T* operator+(T*, ptrdiff_t); [ABOVE]
3538 // T& operator[](T*, ptrdiff_t);
3539 // T* operator-(T*, ptrdiff_t); [ABOVE]
3540 // T* operator+(ptrdiff_t, T*); [ABOVE]
3541 // T& operator[](ptrdiff_t, T*);
3542 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3543 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3544 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003545 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003546 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregor70d26122008-11-12 17:17:38 +00003547
3548 // T& operator[](T*, ptrdiff_t)
3549 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3550
3551 // T& operator[](ptrdiff_t, T*);
3552 ParamTypes[0] = ParamTypes[1];
3553 ParamTypes[1] = *Ptr;
3554 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3555 }
3556 break;
3557
3558 case OO_ArrowStar:
3559 // FIXME: No support for pointer-to-members yet.
3560 break;
Sebastian Redlbd261962009-04-16 17:51:27 +00003561
3562 case OO_Conditional:
3563 // Note that we don't consider the first argument, since it has been
3564 // contextually converted to bool long ago. The candidates below are
3565 // therefore added as binary.
3566 //
3567 // C++ [over.built]p24:
3568 // For every type T, where T is a pointer or pointer-to-member type,
3569 // there exist candidate operator functions of the form
3570 //
3571 // T operator?(bool, T, T);
3572 //
Sebastian Redlbd261962009-04-16 17:51:27 +00003573 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3574 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3575 QualType ParamTypes[2] = { *Ptr, *Ptr };
3576 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3577 }
Sebastian Redl674d1b72009-04-19 21:53:20 +00003578 for (BuiltinCandidateTypeSet::iterator Ptr =
3579 CandidateTypes.member_pointer_begin(),
3580 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3581 QualType ParamTypes[2] = { *Ptr, *Ptr };
3582 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3583 }
Sebastian Redlbd261962009-04-16 17:51:27 +00003584 goto Conditional;
Douglas Gregor70d26122008-11-12 17:17:38 +00003585 }
3586}
3587
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003588/// \brief Add function candidates found via argument-dependent lookup
3589/// to the set of overloading candidates.
3590///
3591/// This routine performs argument-dependent name lookup based on the
3592/// given function name (which may also be an operator name) and adds
3593/// all of the overload candidates found by ADL to the overload
3594/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump25cf7602009-09-09 15:08:12 +00003595void
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003596Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3597 Expr **Args, unsigned NumArgs,
3598 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003599 FunctionSet Functions;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003600
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003601 // Record all of the function candidates that we've already
3602 // added to the overload set, so that we don't add those same
3603 // candidates a second time.
3604 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3605 CandEnd = CandidateSet.end();
3606 Cand != CandEnd; ++Cand)
Douglas Gregor993a0602009-06-27 21:05:07 +00003607 if (Cand->Function) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003608 Functions.insert(Cand->Function);
Douglas Gregor993a0602009-06-27 21:05:07 +00003609 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3610 Functions.insert(FunTmpl);
3611 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003612
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003613 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003614
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003615 // Erase all of the candidates we already knew about.
3616 // FIXME: This is suboptimal. Is there a better way?
3617 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3618 CandEnd = CandidateSet.end();
3619 Cand != CandEnd; ++Cand)
Douglas Gregor993a0602009-06-27 21:05:07 +00003620 if (Cand->Function) {
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003621 Functions.erase(Cand->Function);
Douglas Gregor993a0602009-06-27 21:05:07 +00003622 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3623 Functions.erase(FunTmpl);
3624 }
Douglas Gregor3fc092f2009-03-13 00:33:25 +00003625
3626 // For each of the ADL candidates we found, add it to the overload
3627 // set.
3628 for (FunctionSet::iterator Func = Functions.begin(),
3629 FuncEnd = Functions.end();
Douglas Gregor993a0602009-06-27 21:05:07 +00003630 Func != FuncEnd; ++Func) {
3631 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
3632 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet);
3633 else
Mike Stump25cf7602009-09-09 15:08:12 +00003634 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregorc9a03b72009-06-30 23:57:56 +00003635 /*FIXME: explicit args */false, 0, 0,
3636 Args, NumArgs, CandidateSet);
Douglas Gregor993a0602009-06-27 21:05:07 +00003637 }
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00003638}
3639
Douglas Gregord2baafd2008-10-21 16:13:35 +00003640/// isBetterOverloadCandidate - Determines whether the first overload
3641/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump25cf7602009-09-09 15:08:12 +00003642bool
Douglas Gregord2baafd2008-10-21 16:13:35 +00003643Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump25cf7602009-09-09 15:08:12 +00003644 const OverloadCandidate& Cand2) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00003645 // Define viable functions to be better candidates than non-viable
3646 // functions.
3647 if (!Cand2.Viable)
3648 return Cand1.Viable;
3649 else if (!Cand1.Viable)
3650 return false;
3651
Douglas Gregor3257fb52008-12-22 05:46:06 +00003652 // C++ [over.match.best]p1:
3653 //
3654 // -- if F is a static member function, ICS1(F) is defined such
3655 // that ICS1(F) is neither better nor worse than ICS1(G) for
3656 // any function G, and, symmetrically, ICS1(G) is neither
3657 // better nor worse than ICS1(F).
3658 unsigned StartArg = 0;
3659 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3660 StartArg = 1;
Douglas Gregord2baafd2008-10-21 16:13:35 +00003661
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003662 // C++ [over.match.best]p1:
Mike Stump25cf7602009-09-09 15:08:12 +00003663 // A viable function F1 is defined to be a better function than another
3664 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003665 // conversion sequence than ICSi(F2), and then...
Douglas Gregord2baafd2008-10-21 16:13:35 +00003666 unsigned NumArgs = Cand1.Conversions.size();
3667 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3668 bool HasBetterConversion = false;
Douglas Gregor3257fb52008-12-22 05:46:06 +00003669 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00003670 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3671 Cand2.Conversions[ArgIdx])) {
3672 case ImplicitConversionSequence::Better:
3673 // Cand1 has a better conversion sequence.
3674 HasBetterConversion = true;
3675 break;
3676
3677 case ImplicitConversionSequence::Worse:
3678 // Cand1 can't be better than Cand2.
3679 return false;
3680
3681 case ImplicitConversionSequence::Indistinguishable:
3682 // Do nothing.
3683 break;
3684 }
3685 }
3686
Mike Stump25cf7602009-09-09 15:08:12 +00003687 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003688 // ICSj(F2), or, if not that,
Douglas Gregord2baafd2008-10-21 16:13:35 +00003689 if (HasBetterConversion)
3690 return true;
3691
Mike Stump25cf7602009-09-09 15:08:12 +00003692 // - F1 is a non-template function and F2 is a function template
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003693 // specialization, or, if not that,
3694 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3695 Cand2.Function && Cand2.Function->getPrimaryTemplate())
3696 return true;
Mike Stump25cf7602009-09-09 15:08:12 +00003697
3698 // -- F1 and F2 are function template specializations, and the function
3699 // template for F1 is more specialized than the template for F2
3700 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor8aef85a2009-07-07 23:38:56 +00003701 // if not that,
Douglas Gregorf8e51672009-08-02 23:46:29 +00003702 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
3703 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor8c860df2009-08-21 23:19:43 +00003704 if (FunctionTemplateDecl *BetterTemplate
3705 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
3706 Cand2.Function->getPrimaryTemplate(),
3707 true))
3708 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregord2baafd2008-10-21 16:13:35 +00003709
Douglas Gregor60714f92008-11-07 22:36:19 +00003710 // -- the context is an initialization by user-defined conversion
3711 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3712 // from the return type of F1 to the destination type (i.e.,
3713 // the type of the entity being initialized) is a better
3714 // conversion sequence than the standard conversion sequence
3715 // from the return type of F2 to the destination type.
Mike Stump25cf7602009-09-09 15:08:12 +00003716 if (Cand1.Function && Cand2.Function &&
3717 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregor60714f92008-11-07 22:36:19 +00003718 isa<CXXConversionDecl>(Cand2.Function)) {
3719 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3720 Cand2.FinalConversion)) {
3721 case ImplicitConversionSequence::Better:
3722 // Cand1 has a better conversion sequence.
3723 return true;
3724
3725 case ImplicitConversionSequence::Worse:
3726 // Cand1 can't be better than Cand2.
3727 return false;
3728
3729 case ImplicitConversionSequence::Indistinguishable:
3730 // Do nothing
3731 break;
3732 }
3733 }
3734
Douglas Gregord2baafd2008-10-21 16:13:35 +00003735 return false;
3736}
3737
Mike Stump25cf7602009-09-09 15:08:12 +00003738/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregor98189262009-06-19 23:52:42 +00003739/// within an overload candidate set.
3740///
3741/// \param CandidateSet the set of candidate functions.
3742///
3743/// \param Loc the location of the function name (or operator symbol) for
3744/// which overload resolution occurs.
3745///
Mike Stump25cf7602009-09-09 15:08:12 +00003746/// \param Best f overload resolution was successful or found a deleted
Douglas Gregor98189262009-06-19 23:52:42 +00003747/// function, Best points to the candidate function found.
3748///
3749/// \returns The result of overload resolution.
Mike Stump25cf7602009-09-09 15:08:12 +00003750Sema::OverloadingResult
Douglas Gregord2baafd2008-10-21 16:13:35 +00003751Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregor98189262009-06-19 23:52:42 +00003752 SourceLocation Loc,
Mike Stump25cf7602009-09-09 15:08:12 +00003753 OverloadCandidateSet::iterator& Best) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00003754 // Find the best viable function.
3755 Best = CandidateSet.end();
3756 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3757 Cand != CandidateSet.end(); ++Cand) {
3758 if (Cand->Viable) {
3759 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3760 Best = Cand;
3761 }
3762 }
3763
3764 // If we didn't find any viable functions, abort.
3765 if (Best == CandidateSet.end())
3766 return OR_No_Viable_Function;
3767
3768 // Make sure that this function is better than every other viable
3769 // function. If not, we have an ambiguity.
3770 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3771 Cand != CandidateSet.end(); ++Cand) {
Mike Stump25cf7602009-09-09 15:08:12 +00003772 if (Cand->Viable &&
Douglas Gregord2baafd2008-10-21 16:13:35 +00003773 Cand != Best &&
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003774 !isBetterOverloadCandidate(*Best, *Cand)) {
3775 Best = CandidateSet.end();
Douglas Gregord2baafd2008-10-21 16:13:35 +00003776 return OR_Ambiguous;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003777 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003778 }
Mike Stump25cf7602009-09-09 15:08:12 +00003779
Douglas Gregord2baafd2008-10-21 16:13:35 +00003780 // Best is the best viable function.
Douglas Gregoraa57e862009-02-18 21:56:37 +00003781 if (Best->Function &&
Mike Stump25cf7602009-09-09 15:08:12 +00003782 (Best->Function->isDeleted() ||
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003783 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregoraa57e862009-02-18 21:56:37 +00003784 return OR_Deleted;
3785
Douglas Gregor98189262009-06-19 23:52:42 +00003786 // C++ [basic.def.odr]p2:
3787 // An overloaded function is used if it is selected by overload resolution
Mike Stump25cf7602009-09-09 15:08:12 +00003788 // when referred to from a potentially-evaluated expression. [Note: this
3789 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregor98189262009-06-19 23:52:42 +00003790 // (clause 13), user-defined conversions (12.3.2), allocation function for
3791 // placement new (5.3.4), as well as non-default initialization (8.5).
3792 if (Best->Function)
3793 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregord2baafd2008-10-21 16:13:35 +00003794 return OR_Success;
3795}
3796
3797/// PrintOverloadCandidates - When overload resolution fails, prints
3798/// diagnostic messages containing the candidates in the candidate
3799/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump25cf7602009-09-09 15:08:12 +00003800void
Douglas Gregord2baafd2008-10-21 16:13:35 +00003801Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Mike Stump25cf7602009-09-09 15:08:12 +00003802 bool OnlyViable) {
Douglas Gregord2baafd2008-10-21 16:13:35 +00003803 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3804 LastCand = CandidateSet.end();
3805 for (; Cand != LastCand; ++Cand) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003806 if (Cand->Viable || !OnlyViable) {
3807 if (Cand->Function) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003808 if (Cand->Function->isDeleted() ||
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003809 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00003810 // Deleted or "unavailable" function.
3811 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3812 << Cand->Function->isDeleted();
3813 } else {
3814 // Normal function
3815 // FIXME: Give a better reason!
3816 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3817 }
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003818 } else if (Cand->IsSurrogate) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003819 // Desugar the type of the surrogate down to a function type,
3820 // retaining as many typedefs as possible while still showing
3821 // the function type (and, therefore, its parameter types).
3822 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003823 bool isLValueReference = false;
3824 bool isRValueReference = false;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003825 bool isPointer = false;
Sebastian Redlce6fff02009-03-16 23:22:08 +00003826 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003827 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003828 FnType = FnTypeRef->getPointeeType();
Sebastian Redlce6fff02009-03-16 23:22:08 +00003829 isLValueReference = true;
3830 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003831 FnType->getAs<RValueReferenceType>()) {
Sebastian Redlce6fff02009-03-16 23:22:08 +00003832 FnType = FnTypeRef->getPointeeType();
3833 isRValueReference = true;
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003834 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003835 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003836 FnType = FnTypePtr->getPointeeType();
3837 isPointer = true;
3838 }
3839 // Desugar down to a function type.
3840 FnType = QualType(FnType->getAsFunctionType(), 0);
3841 // Reconstruct the pointer/reference as appropriate.
3842 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redlce6fff02009-03-16 23:22:08 +00003843 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3844 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor30c8ddf2008-11-21 02:54:28 +00003845
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00003846 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003847 << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003848 } else {
3849 // FIXME: We need to get the identifier in here
Mike Stumpe127ae32009-05-16 07:39:55 +00003850 // FIXME: Do we want the error message to point at the operator?
3851 // (built-ins won't have a location)
Mike Stump25cf7602009-09-09 15:08:12 +00003852 QualType FnType
Douglas Gregor70d26122008-11-12 17:17:38 +00003853 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
3854 Cand->BuiltinTypes.ParamTypes,
3855 Cand->Conversions.size(),
3856 false, 0);
3857
Chris Lattner4bfd2232008-11-24 06:25:27 +00003858 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
Douglas Gregor70d26122008-11-12 17:17:38 +00003859 }
3860 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003861 }
3862}
3863
Douglas Gregor45014fd2008-11-10 20:40:00 +00003864/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
3865/// an overloaded function (C++ [over.over]), where @p From is an
3866/// expression with overloaded function type and @p ToType is the type
3867/// we're trying to resolve to. For example:
3868///
3869/// @code
3870/// int f(double);
3871/// int f(int);
Mike Stump25cf7602009-09-09 15:08:12 +00003872///
Douglas Gregor45014fd2008-11-10 20:40:00 +00003873/// int (*pfd)(double) = f; // selects f(double)
3874/// @endcode
3875///
3876/// This routine returns the resulting FunctionDecl if it could be
3877/// resolved, and NULL otherwise. When @p Complain is true, this
3878/// routine will emit diagnostics if there is an error.
3879FunctionDecl *
Sebastian Redl7434fc32009-02-04 21:23:32 +00003880Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor45014fd2008-11-10 20:40:00 +00003881 bool Complain) {
3882 QualType FunctionType = ToType;
Sebastian Redl7434fc32009-02-04 21:23:32 +00003883 bool IsMember = false;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003884 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor45014fd2008-11-10 20:40:00 +00003885 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003886 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarf6c06ce2009-02-26 19:13:44 +00003887 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl7434fc32009-02-04 21:23:32 +00003888 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003889 ToType->getAs<MemberPointerType>()) {
Sebastian Redl7434fc32009-02-04 21:23:32 +00003890 FunctionType = MemTypePtr->getPointeeType();
3891 IsMember = true;
3892 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003893
3894 // We only look at pointers or references to functions.
Douglas Gregor72bb4992009-07-09 17:16:51 +00003895 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor62f78762009-07-08 20:55:45 +00003896 if (!FunctionType->isFunctionType())
Douglas Gregor45014fd2008-11-10 20:40:00 +00003897 return 0;
3898
3899 // Find the actual overloaded function declaration.
3900 OverloadedFunctionDecl *Ovl = 0;
Mike Stump25cf7602009-09-09 15:08:12 +00003901
Douglas Gregor45014fd2008-11-10 20:40:00 +00003902 // C++ [over.over]p1:
3903 // [...] [Note: any redundant set of parentheses surrounding the
3904 // overloaded function name is ignored (5.1). ]
3905 Expr *OvlExpr = From->IgnoreParens();
3906
3907 // C++ [over.over]p1:
3908 // [...] The overloaded function name can be preceded by the &
3909 // operator.
3910 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
3911 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
3912 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
3913 }
3914
3915 // Try to dig out the overloaded function.
Douglas Gregor62f78762009-07-08 20:55:45 +00003916 FunctionTemplateDecl *FunctionTemplate = 0;
3917 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003918 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor62f78762009-07-08 20:55:45 +00003919 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
3920 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003921
Mike Stump25cf7602009-09-09 15:08:12 +00003922 // If there's no overloaded function declaration or function template,
Douglas Gregor62f78762009-07-08 20:55:45 +00003923 // we're done.
3924 if (!Ovl && !FunctionTemplate)
Douglas Gregor45014fd2008-11-10 20:40:00 +00003925 return 0;
Mike Stump25cf7602009-09-09 15:08:12 +00003926
Douglas Gregor62f78762009-07-08 20:55:45 +00003927 OverloadIterator Fun;
3928 if (Ovl)
3929 Fun = Ovl;
3930 else
3931 Fun = FunctionTemplate;
Mike Stump25cf7602009-09-09 15:08:12 +00003932
Douglas Gregor45014fd2008-11-10 20:40:00 +00003933 // Look through all of the overloaded functions, searching for one
3934 // whose type matches exactly.
Douglas Gregora142a052009-07-08 23:33:52 +00003935 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Mike Stump25cf7602009-09-09 15:08:12 +00003936
Douglas Gregora142a052009-07-08 23:33:52 +00003937 bool FoundNonTemplateFunction = false;
Douglas Gregor62f78762009-07-08 20:55:45 +00003938 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003939 // C++ [over.over]p3:
3940 // Non-member functions and static member functions match
Sebastian Redl3a75abf2009-02-05 12:33:33 +00003941 // targets of type "pointer-to-function" or "reference-to-function."
3942 // Nonstatic member functions match targets of
Sebastian Redl7434fc32009-02-04 21:23:32 +00003943 // type "pointer-to-member-function."
3944 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor62f78762009-07-08 20:55:45 +00003945
Mike Stump25cf7602009-09-09 15:08:12 +00003946 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregor62f78762009-07-08 20:55:45 +00003947 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Mike Stump25cf7602009-09-09 15:08:12 +00003948 if (CXXMethodDecl *Method
Douglas Gregora142a052009-07-08 23:33:52 +00003949 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump25cf7602009-09-09 15:08:12 +00003950 // Skip non-static function templates when converting to pointer, and
Douglas Gregora142a052009-07-08 23:33:52 +00003951 // static when converting to member pointer.
3952 if (Method->isStatic() == IsMember)
3953 continue;
3954 } else if (IsMember)
3955 continue;
Mike Stump25cf7602009-09-09 15:08:12 +00003956
Douglas Gregora142a052009-07-08 23:33:52 +00003957 // C++ [over.over]p2:
Mike Stump25cf7602009-09-09 15:08:12 +00003958 // If the name is a function template, template argument deduction is
3959 // done (14.8.2.2), and if the argument deduction succeeds, the
3960 // resulting template argument list is used to generate a single
3961 // function template specialization, which is added to the set of
Douglas Gregora142a052009-07-08 23:33:52 +00003962 // overloaded functions considered.
Douglas Gregor62f78762009-07-08 20:55:45 +00003963 FunctionDecl *Specialization = 0;
3964 TemplateDeductionInfo Info(Context);
3965 if (TemplateDeductionResult Result
3966 = DeduceTemplateArguments(FunctionTemplate, /*FIXME*/false,
3967 /*FIXME:*/0, /*FIXME:*/0,
3968 FunctionType, Specialization, Info)) {
3969 // FIXME: make a note of the failed deduction for diagnostics.
3970 (void)Result;
3971 } else {
Mike Stump25cf7602009-09-09 15:08:12 +00003972 assert(FunctionType
Douglas Gregor62f78762009-07-08 20:55:45 +00003973 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregora142a052009-07-08 23:33:52 +00003974 Matches.insert(
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00003975 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor62f78762009-07-08 20:55:45 +00003976 }
3977 }
Mike Stump25cf7602009-09-09 15:08:12 +00003978
Sebastian Redl7434fc32009-02-04 21:23:32 +00003979 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
3980 // Skip non-static functions when converting to pointer, and static
3981 // when converting to member pointer.
3982 if (Method->isStatic() == IsMember)
Douglas Gregor45014fd2008-11-10 20:40:00 +00003983 continue;
Douglas Gregora142a052009-07-08 23:33:52 +00003984 } else if (IsMember)
Sebastian Redl7434fc32009-02-04 21:23:32 +00003985 continue;
Douglas Gregor45014fd2008-11-10 20:40:00 +00003986
Douglas Gregorb60eb752009-06-25 22:08:12 +00003987 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregora142a052009-07-08 23:33:52 +00003988 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argiris Kirtzidis17c7cab2009-07-18 00:34:25 +00003989 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregora142a052009-07-08 23:33:52 +00003990 FoundNonTemplateFunction = true;
3991 }
Mike Stump25cf7602009-09-09 15:08:12 +00003992 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00003993 }
3994
Douglas Gregora142a052009-07-08 23:33:52 +00003995 // If there were 0 or 1 matches, we're done.
3996 if (Matches.empty())
3997 return 0;
3998 else if (Matches.size() == 1)
3999 return *Matches.begin();
4000
4001 // C++ [over.over]p4:
4002 // If more than one function is selected, [...]
4003 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
Douglas Gregor8c860df2009-08-21 23:19:43 +00004004 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregora142a052009-07-08 23:33:52 +00004005 if (FoundNonTemplateFunction) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00004006 // [...] any function template specializations in the set are
4007 // eliminated if the set also contains a non-template function, [...]
4008 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
Douglas Gregora142a052009-07-08 23:33:52 +00004009 if ((*M)->getPrimaryTemplate() == 0)
4010 RemainingMatches.push_back(*M);
4011 } else {
Douglas Gregor8c860df2009-08-21 23:19:43 +00004012 // [...] and any given function template specialization F1 is
4013 // eliminated if the set contains a second function template
4014 // specialization whose function template is more specialized
4015 // than the function template of F1 according to the partial
4016 // ordering rules of 14.5.5.2.
4017
4018 // The algorithm specified above is quadratic. We instead use a
4019 // two-pass algorithm (similar to the one used to identify the
4020 // best viable function in an overload set) that identifies the
4021 // best function template (if it exists).
4022 MatchIter Best = Matches.begin();
4023 MatchIter M = Best, MEnd = Matches.end();
4024 // Find the most specialized function.
4025 for (++M; M != MEnd; ++M)
4026 if (getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4027 (*Best)->getPrimaryTemplate(),
Mike Stump25cf7602009-09-09 15:08:12 +00004028 false)
Douglas Gregor8c860df2009-08-21 23:19:43 +00004029 == (*M)->getPrimaryTemplate())
4030 Best = M;
4031
4032 // Determine whether this function template is more specialized
4033 // that all of the others.
4034 bool Ambiguous = false;
4035 for (M = Matches.begin(); M != MEnd; ++M) {
4036 if (M != Best &&
4037 getMoreSpecializedTemplate((*M)->getPrimaryTemplate(),
4038 (*Best)->getPrimaryTemplate(),
4039 false)
4040 != (*Best)->getPrimaryTemplate()) {
4041 Ambiguous = true;
4042 break;
4043 }
4044 }
4045
4046 // If one function template was more specialized than all of the
4047 // others, return it.
4048 if (!Ambiguous)
4049 return *Best;
4050
4051 // We could not find a most-specialized function template, which
4052 // is equivalent to having a set of function templates with more
4053 // than one such template. So, we place all of the function
4054 // templates into the set of remaining matches and produce a
4055 // diagnostic below. FIXME: we could perform the quadratic
4056 // algorithm here, pruning the result set to limit the number of
4057 // candidates output later.
4058 RemainingMatches.append(Matches.begin(), Matches.end());
Douglas Gregora142a052009-07-08 23:33:52 +00004059 }
Mike Stump25cf7602009-09-09 15:08:12 +00004060
4061 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregora142a052009-07-08 23:33:52 +00004062 // selected function.
4063 if (RemainingMatches.size() == 1)
4064 return RemainingMatches.front();
Mike Stump25cf7602009-09-09 15:08:12 +00004065
Douglas Gregora142a052009-07-08 23:33:52 +00004066 // FIXME: We should probably return the same thing that BestViableFunction
4067 // returns (even if we issue the diagnostics here).
4068 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4069 << RemainingMatches[0]->getDeclName();
4070 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4071 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregor45014fd2008-11-10 20:40:00 +00004072 return 0;
4073}
4074
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004075/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004076/// (which eventually refers to the declaration Func) and the call
4077/// arguments Args/NumArgs, attempt to resolve the function call down
4078/// to a specific function. If overload resolution succeeds, returns
4079/// the function declaration produced by overload
Douglas Gregorbf4f0582008-11-26 06:01:48 +00004080/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004081/// arguments and Fn, and returns NULL.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004082FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004083 DeclarationName UnqualifiedName,
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004084 bool HasExplicitTemplateArgs,
4085 const TemplateArgument *ExplicitTemplateArgs,
4086 unsigned NumExplicitTemplateArgs,
Douglas Gregorbf4f0582008-11-26 06:01:48 +00004087 SourceLocation LParenLoc,
4088 Expr **Args, unsigned NumArgs,
Mike Stump25cf7602009-09-09 15:08:12 +00004089 SourceLocation *CommaLocs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004090 SourceLocation RParenLoc,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004091 bool &ArgumentDependentLookup) {
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004092 OverloadCandidateSet CandidateSet;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004093
4094 // Add the functions denoted by Callee to the set of candidate
4095 // functions. While we're doing so, track whether argument-dependent
4096 // lookup still applies, per:
4097 //
4098 // C++0x [basic.lookup.argdep]p3:
4099 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4100 // and let Y be the lookup set produced by argument dependent
4101 // lookup (defined as follows). If X contains
4102 //
Mike Stump25cf7602009-09-09 15:08:12 +00004103 // -- a declaration of a class member, or
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004104 //
4105 // -- a block-scope function declaration that is not a
Mike Stump25cf7602009-09-09 15:08:12 +00004106 // using-declaration, or
4107 //
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004108 // -- a declaration that is neither a function or a function
4109 // template
4110 //
Mike Stump25cf7602009-09-09 15:08:12 +00004111 // then Y is empty.
4112 if (OverloadedFunctionDecl *Ovl
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004113 = dyn_cast_or_null<OverloadedFunctionDecl>(Callee)) {
4114 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4115 FuncEnd = Ovl->function_end();
4116 Func != FuncEnd; ++Func) {
Douglas Gregorb60eb752009-06-25 22:08:12 +00004117 DeclContext *Ctx = 0;
4118 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Func)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004119 if (HasExplicitTemplateArgs)
4120 continue;
Mike Stump25cf7602009-09-09 15:08:12 +00004121
Douglas Gregorb60eb752009-06-25 22:08:12 +00004122 AddOverloadCandidate(FunDecl, Args, NumArgs, CandidateSet);
4123 Ctx = FunDecl->getDeclContext();
4124 } else {
4125 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*Func);
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004126 AddTemplateOverloadCandidate(FunTmpl, HasExplicitTemplateArgs,
4127 ExplicitTemplateArgs,
4128 NumExplicitTemplateArgs,
4129 Args, NumArgs, CandidateSet);
Douglas Gregorb60eb752009-06-25 22:08:12 +00004130 Ctx = FunTmpl->getDeclContext();
4131 }
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004132
Douglas Gregorb60eb752009-06-25 22:08:12 +00004133
4134 if (Ctx->isRecord() || Ctx->isFunctionOrMethod())
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004135 ArgumentDependentLookup = false;
4136 }
4137 } else if (FunctionDecl *Func = dyn_cast_or_null<FunctionDecl>(Callee)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004138 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004139 AddOverloadCandidate(Func, Args, NumArgs, CandidateSet);
4140
4141 if (Func->getDeclContext()->isRecord() ||
4142 Func->getDeclContext()->isFunctionOrMethod())
4143 ArgumentDependentLookup = false;
Mike Stump25cf7602009-09-09 15:08:12 +00004144 } else if (FunctionTemplateDecl *FuncTemplate
Douglas Gregorb60eb752009-06-25 22:08:12 +00004145 = dyn_cast_or_null<FunctionTemplateDecl>(Callee)) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004146 AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4147 ExplicitTemplateArgs,
Mike Stump25cf7602009-09-09 15:08:12 +00004148 NumExplicitTemplateArgs,
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004149 Args, NumArgs, CandidateSet);
Douglas Gregorb60eb752009-06-25 22:08:12 +00004150
4151 if (FuncTemplate->getDeclContext()->isRecord())
4152 ArgumentDependentLookup = false;
4153 }
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004154
4155 if (Callee)
4156 UnqualifiedName = Callee->getDeclName();
4157
Douglas Gregorc9a03b72009-06-30 23:57:56 +00004158 // FIXME: Pass explicit template arguments through for ADL
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004159 if (ArgumentDependentLookup)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004160 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00004161 CandidateSet);
4162
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004163 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004164 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00004165 case OR_Success:
4166 return Best->Function;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004167
4168 case OR_No_Viable_Function:
Chris Lattner4a526112009-02-17 07:29:20 +00004169 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004170 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004171 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004172 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4173 break;
4174
4175 case OR_Ambiguous:
4176 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor4646f9c2009-02-04 15:01:18 +00004177 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004178 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4179 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004180
4181 case OR_Deleted:
4182 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4183 << Best->Function->isDeleted()
4184 << UnqualifiedName
4185 << Fn->getSourceRange();
4186 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4187 break;
Douglas Gregor3ed006b2008-11-26 05:54:23 +00004188 }
4189
4190 // Overload resolution failed. Destroy all of the subexpressions and
4191 // return NULL.
4192 Fn->Destroy(Context);
4193 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4194 Args[Arg]->Destroy(Context);
4195 return 0;
4196}
4197
Douglas Gregorc78182d2009-03-13 23:49:33 +00004198/// \brief Create a unary operation that may resolve to an overloaded
4199/// operator.
4200///
4201/// \param OpLoc The location of the operator itself (e.g., '*').
4202///
4203/// \param OpcIn The UnaryOperator::Opcode that describes this
4204/// operator.
4205///
4206/// \param Functions The set of non-member functions that will be
4207/// considered by overload resolution. The caller needs to build this
4208/// set based on the context using, e.g.,
4209/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4210/// set should not contain any member functions; those will be added
4211/// by CreateOverloadedUnaryOp().
4212///
4213/// \param input The input argument.
4214Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4215 unsigned OpcIn,
4216 FunctionSet &Functions,
Mike Stump25cf7602009-09-09 15:08:12 +00004217 ExprArg input) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00004218 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4219 Expr *Input = (Expr *)input.get();
4220
4221 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4222 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4223 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4224
4225 Expr *Args[2] = { Input, 0 };
4226 unsigned NumArgs = 1;
Mike Stump25cf7602009-09-09 15:08:12 +00004227
Douglas Gregorc78182d2009-03-13 23:49:33 +00004228 // For post-increment and post-decrement, add the implicit '0' as
4229 // the second argument, so that we know this is a post-increment or
4230 // post-decrement.
4231 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4232 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump25cf7602009-09-09 15:08:12 +00004233 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregorc78182d2009-03-13 23:49:33 +00004234 SourceLocation());
4235 NumArgs = 2;
4236 }
4237
4238 if (Input->isTypeDependent()) {
Mike Stump25cf7602009-09-09 15:08:12 +00004239 OverloadedFunctionDecl *Overloads
Douglas Gregorc78182d2009-03-13 23:49:33 +00004240 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump25cf7602009-09-09 15:08:12 +00004241 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregorc78182d2009-03-13 23:49:33 +00004242 FuncEnd = Functions.end();
4243 Func != FuncEnd; ++Func)
4244 Overloads->addOverload(*Func);
4245
4246 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4247 OpLoc, false, false);
Mike Stump25cf7602009-09-09 15:08:12 +00004248
Douglas Gregorc78182d2009-03-13 23:49:33 +00004249 input.release();
4250 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4251 &Args[0], NumArgs,
4252 Context.DependentTy,
4253 OpLoc));
4254 }
4255
4256 // Build an empty overload set.
4257 OverloadCandidateSet CandidateSet;
4258
4259 // Add the candidates from the given function set.
4260 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4261
4262 // Add operator candidates that are member functions.
4263 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4264
4265 // Add builtin operator candidates.
4266 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
4267
4268 // Perform overload resolution.
4269 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004270 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00004271 case OR_Success: {
4272 // We found a built-in operator or an overloaded operator.
4273 FunctionDecl *FnDecl = Best->Function;
Mike Stump25cf7602009-09-09 15:08:12 +00004274
Douglas Gregorc78182d2009-03-13 23:49:33 +00004275 if (FnDecl) {
4276 // We matched an overloaded operator. Build a call to that
4277 // operator.
Mike Stump25cf7602009-09-09 15:08:12 +00004278
Douglas Gregorc78182d2009-03-13 23:49:33 +00004279 // Convert the arguments.
4280 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4281 if (PerformObjectArgumentInitialization(Input, Method))
4282 return ExprError();
4283 } else {
4284 // Convert the arguments.
4285 if (PerformCopyInitialization(Input,
4286 FnDecl->getParamDecl(0)->getType(),
4287 "passing"))
4288 return ExprError();
4289 }
4290
4291 // Determine the result type
4292 QualType ResultTy
4293 = FnDecl->getType()->getAsFunctionType()->getResultType();
4294 ResultTy = ResultTy.getNonReferenceType();
Mike Stump25cf7602009-09-09 15:08:12 +00004295
Douglas Gregorc78182d2009-03-13 23:49:33 +00004296 // Build the actual expression node.
4297 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4298 SourceLocation());
4299 UsualUnaryConversions(FnExpr);
Mike Stump25cf7602009-09-09 15:08:12 +00004300
Douglas Gregorc78182d2009-03-13 23:49:33 +00004301 input.release();
Mike Stump25cf7602009-09-09 15:08:12 +00004302
4303 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Anders Carlsson16497742009-08-16 04:11:06 +00004304 &Input, 1, ResultTy, OpLoc);
4305 return MaybeBindToTemporary(CE);
Douglas Gregorc78182d2009-03-13 23:49:33 +00004306 } else {
4307 // We matched a built-in operator. Convert the arguments, then
4308 // break out so that we will build the appropriate built-in
4309 // operator node.
4310 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4311 Best->Conversions[0], "passing"))
4312 return ExprError();
4313
4314 break;
4315 }
4316 }
4317
4318 case OR_No_Viable_Function:
4319 // No viable function; fall through to handling this as a
4320 // built-in operator, which will produce an error message for us.
4321 break;
4322
4323 case OR_Ambiguous:
4324 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4325 << UnaryOperator::getOpcodeStr(Opc)
4326 << Input->getSourceRange();
4327 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4328 return ExprError();
4329
4330 case OR_Deleted:
4331 Diag(OpLoc, diag::err_ovl_deleted_oper)
4332 << Best->Function->isDeleted()
4333 << UnaryOperator::getOpcodeStr(Opc)
4334 << Input->getSourceRange();
4335 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4336 return ExprError();
4337 }
4338
4339 // Either we found no viable overloaded operator or we matched a
4340 // built-in operator. In either case, fall through to trying to
4341 // build a built-in operation.
4342 input.release();
4343 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4344}
4345
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004346/// \brief Create a binary operation that may resolve to an overloaded
4347/// operator.
4348///
4349/// \param OpLoc The location of the operator itself (e.g., '+').
4350///
4351/// \param OpcIn The BinaryOperator::Opcode that describes this
4352/// operator.
4353///
4354/// \param Functions The set of non-member functions that will be
4355/// considered by overload resolution. The caller needs to build this
4356/// set based on the context using, e.g.,
4357/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4358/// set should not contain any member functions; those will be added
4359/// by CreateOverloadedBinOp().
4360///
4361/// \param LHS Left-hand argument.
4362/// \param RHS Right-hand argument.
Mike Stump25cf7602009-09-09 15:08:12 +00004363Sema::OwningExprResult
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004364Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump25cf7602009-09-09 15:08:12 +00004365 unsigned OpcIn,
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004366 FunctionSet &Functions,
4367 Expr *LHS, Expr *RHS) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004368 Expr *Args[2] = { LHS, RHS };
Douglas Gregor114c6192009-08-26 17:08:25 +00004369 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004370
4371 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4372 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4373 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4374
4375 // If either side is type-dependent, create an appropriate dependent
4376 // expression.
Douglas Gregor114c6192009-08-26 17:08:25 +00004377 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004378 // .* cannot be overloaded.
4379 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregor114c6192009-08-26 17:08:25 +00004380 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004381 Context.DependentTy, OpLoc));
4382
Mike Stump25cf7602009-09-09 15:08:12 +00004383 OverloadedFunctionDecl *Overloads
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004384 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump25cf7602009-09-09 15:08:12 +00004385 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004386 FuncEnd = Functions.end();
4387 Func != FuncEnd; ++Func)
4388 Overloads->addOverload(*Func);
4389
4390 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4391 OpLoc, false, false);
Mike Stump25cf7602009-09-09 15:08:12 +00004392
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004393 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump25cf7602009-09-09 15:08:12 +00004394 Args, 2,
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004395 Context.DependentTy,
4396 OpLoc));
4397 }
4398
4399 // If this is the .* operator, which is not overloadable, just
4400 // create a built-in binary operator.
4401 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregor114c6192009-08-26 17:08:25 +00004402 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004403
4404 // If this is one of the assignment operators, we only perform
4405 // overload resolution if the left-hand side is a class or
4406 // enumeration type (C++ [expr.ass]p3).
4407 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
Douglas Gregor114c6192009-08-26 17:08:25 +00004408 !Args[0]->getType()->isOverloadableType())
4409 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004410
Douglas Gregorc78182d2009-03-13 23:49:33 +00004411 // Build an empty overload set.
4412 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004413
4414 // Add the candidates from the given function set.
4415 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4416
4417 // Add operator candidates that are member functions.
4418 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4419
4420 // Add builtin operator candidates.
4421 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4422
4423 // Perform overload resolution.
4424 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004425 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redlbd261962009-04-16 17:51:27 +00004426 case OR_Success: {
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004427 // We found a built-in operator or an overloaded operator.
4428 FunctionDecl *FnDecl = Best->Function;
4429
4430 if (FnDecl) {
4431 // We matched an overloaded operator. Build a call to that
4432 // operator.
4433
4434 // Convert the arguments.
4435 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregor114c6192009-08-26 17:08:25 +00004436 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4437 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004438 "passing"))
4439 return ExprError();
4440 } else {
4441 // Convert the arguments.
Douglas Gregor114c6192009-08-26 17:08:25 +00004442 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004443 "passing") ||
Douglas Gregor114c6192009-08-26 17:08:25 +00004444 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004445 "passing"))
4446 return ExprError();
4447 }
4448
4449 // Determine the result type
4450 QualType ResultTy
4451 = FnDecl->getType()->getAsFunctionType()->getResultType();
4452 ResultTy = ResultTy.getNonReferenceType();
4453
4454 // Build the actual expression node.
4455 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argiris Kirtzidiscca21b82009-07-14 03:19:38 +00004456 OpLoc);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004457 UsualUnaryConversions(FnExpr);
4458
Mike Stump25cf7602009-09-09 15:08:12 +00004459 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Anders Carlsson16497742009-08-16 04:11:06 +00004460 Args, 2, ResultTy, OpLoc);
4461 return MaybeBindToTemporary(CE);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004462 } else {
4463 // We matched a built-in operator. Convert the arguments, then
4464 // break out so that we will build the appropriate built-in
4465 // operator node.
Douglas Gregor114c6192009-08-26 17:08:25 +00004466 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004467 Best->Conversions[0], "passing") ||
Douglas Gregor114c6192009-08-26 17:08:25 +00004468 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004469 Best->Conversions[1], "passing"))
4470 return ExprError();
4471
4472 break;
4473 }
4474 }
4475
4476 case OR_No_Viable_Function:
Sebastian Redl35196b42009-05-21 11:50:50 +00004477 // For class as left operand for assignment or compound assigment operator
4478 // do not fall through to handling in built-in, but report that no overloaded
4479 // assignment operator found
Douglas Gregor114c6192009-08-26 17:08:25 +00004480 if (Args[0]->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl35196b42009-05-21 11:50:50 +00004481 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4482 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor114c6192009-08-26 17:08:25 +00004483 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Sebastian Redl35196b42009-05-21 11:50:50 +00004484 return ExprError();
4485 }
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004486 // No viable function; fall through to handling this as a
4487 // built-in operator, which will produce an error message for us.
4488 break;
4489
4490 case OR_Ambiguous:
4491 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4492 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor114c6192009-08-26 17:08:25 +00004493 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004494 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4495 return ExprError();
4496
4497 case OR_Deleted:
4498 Diag(OpLoc, diag::err_ovl_deleted_oper)
4499 << Best->Function->isDeleted()
4500 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor114c6192009-08-26 17:08:25 +00004501 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004502 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4503 return ExprError();
4504 }
4505
4506 // Either we found no viable overloaded operator or we matched a
4507 // built-in operator. In either case, try to build a built-in
4508 // operation.
Douglas Gregor114c6192009-08-26 17:08:25 +00004509 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004510}
4511
Douglas Gregor3257fb52008-12-22 05:46:06 +00004512/// BuildCallToMemberFunction - Build a call to a member
4513/// function. MemExpr is the expression that refers to the member
4514/// function (and includes the object parameter), Args/NumArgs are the
4515/// arguments to the function call (not including the object
4516/// parameter). The caller needs to validate that the member
4517/// expression refers to a member function or an overloaded member
4518/// function.
4519Sema::ExprResult
Mike Stump25cf7602009-09-09 15:08:12 +00004520Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4521 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00004522 unsigned NumArgs, SourceLocation *CommaLocs,
4523 SourceLocation RParenLoc) {
4524 // Dig out the member expression. This holds both the object
4525 // argument and the member function we're referring to.
4526 MemberExpr *MemExpr = 0;
4527 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4528 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4529 else
4530 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4531 assert(MemExpr && "Building member call without member expression");
4532
4533 // Extract the object argument.
4534 Expr *ObjectArg = MemExpr->getBase();
Anders Carlsson2d30f6b2009-05-01 18:34:30 +00004535
Douglas Gregor3257fb52008-12-22 05:46:06 +00004536 CXXMethodDecl *Method = 0;
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004537 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
4538 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00004539 // Add overload candidates
4540 OverloadCandidateSet CandidateSet;
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004541 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
Mike Stump25cf7602009-09-09 15:08:12 +00004542
Douglas Gregor050cabf2009-08-21 18:42:58 +00004543 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
4544 Func != FuncEnd; ++Func) {
4545 if ((Method = dyn_cast<CXXMethodDecl>(*Func)))
Mike Stump25cf7602009-09-09 15:08:12 +00004546 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
Douglas Gregor050cabf2009-08-21 18:42:58 +00004547 /*SuppressUserConversions=*/false);
4548 else
Douglas Gregord33e3282009-09-01 00:37:14 +00004549 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
4550 MemExpr->hasExplicitTemplateArgumentList(),
4551 MemExpr->getTemplateArgs(),
4552 MemExpr->getNumTemplateArgs(),
4553 ObjectArg, Args, NumArgs,
Douglas Gregor050cabf2009-08-21 18:42:58 +00004554 CandidateSet,
4555 /*SuppressUsedConversions=*/false);
4556 }
Mike Stump25cf7602009-09-09 15:08:12 +00004557
Douglas Gregor3257fb52008-12-22 05:46:06 +00004558 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004559 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00004560 case OR_Success:
4561 Method = cast<CXXMethodDecl>(Best->Function);
4562 break;
4563
4564 case OR_No_Viable_Function:
Mike Stump25cf7602009-09-09 15:08:12 +00004565 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor3257fb52008-12-22 05:46:06 +00004566 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004567 << DeclName << MemExprE->getSourceRange();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004568 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4569 // FIXME: Leaking incoming expressions!
4570 return true;
4571
4572 case OR_Ambiguous:
Mike Stump25cf7602009-09-09 15:08:12 +00004573 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor3257fb52008-12-22 05:46:06 +00004574 diag::err_ovl_ambiguous_member_call)
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004575 << DeclName << MemExprE->getSourceRange();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004576 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4577 // FIXME: Leaking incoming expressions!
4578 return true;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004579
4580 case OR_Deleted:
Mike Stump25cf7602009-09-09 15:08:12 +00004581 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregoraa57e862009-02-18 21:56:37 +00004582 diag::err_ovl_deleted_member_call)
4583 << Best->Function->isDeleted()
Douglas Gregor4fdcdda2009-08-21 00:16:32 +00004584 << DeclName << MemExprE->getSourceRange();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004585 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4586 // FIXME: Leaking incoming expressions!
4587 return true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00004588 }
4589
4590 FixOverloadedFunctionReference(MemExpr, Method);
4591 } else {
4592 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4593 }
4594
4595 assert(Method && "Member call to something that isn't a method?");
Mike Stump25cf7602009-09-09 15:08:12 +00004596 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek362abcd2009-02-09 20:51:47 +00004597 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
Mike Stump25cf7602009-09-09 15:08:12 +00004598 NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00004599 Method->getResultType().getNonReferenceType(),
4600 RParenLoc));
4601
4602 // Convert the object argument (for a non-static member function call).
Mike Stump25cf7602009-09-09 15:08:12 +00004603 if (!Method->isStatic() &&
Douglas Gregor3257fb52008-12-22 05:46:06 +00004604 PerformObjectArgumentInitialization(ObjectArg, Method))
4605 return true;
4606 MemExpr->setBase(ObjectArg);
4607
4608 // Convert the rest of the arguments
Douglas Gregor4fa58902009-02-26 23:50:07 +00004609 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump25cf7602009-09-09 15:08:12 +00004610 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00004611 RParenLoc))
4612 return true;
4613
Anders Carlsson7fb13802009-08-16 01:56:34 +00004614 if (CheckFunctionCall(Method, TheCall.get()))
4615 return true;
Anders Carlssonb8ff3402009-08-16 03:42:12 +00004616
4617 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor3257fb52008-12-22 05:46:06 +00004618}
4619
Douglas Gregor10f3c502008-11-19 21:05:33 +00004620/// BuildCallToObjectOfClassType - Build a call to an object of class
4621/// type (C++ [over.call.object]), which can end up invoking an
4622/// overloaded function call operator (@c operator()) or performing a
4623/// user-defined conversion on the object argument.
Mike Stump25cf7602009-09-09 15:08:12 +00004624Sema::ExprResult
4625Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregora133e262008-12-06 00:22:45 +00004626 SourceLocation LParenLoc,
Douglas Gregor10f3c502008-11-19 21:05:33 +00004627 Expr **Args, unsigned NumArgs,
Mike Stump25cf7602009-09-09 15:08:12 +00004628 SourceLocation *CommaLocs,
Douglas Gregor10f3c502008-11-19 21:05:33 +00004629 SourceLocation RParenLoc) {
4630 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004631 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump25cf7602009-09-09 15:08:12 +00004632
Douglas Gregor10f3c502008-11-19 21:05:33 +00004633 // C++ [over.call.object]p1:
4634 // If the primary-expression E in the function call syntax
Eli Friedmand5a72f02009-08-05 19:21:58 +00004635 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor10f3c502008-11-19 21:05:33 +00004636 // candidate functions includes at least the function call
4637 // operators of T. The function call operators of T are obtained by
4638 // ordinary lookup of the name operator() in the context of
4639 // (E).operator().
4640 OverloadCandidateSet CandidateSet;
Douglas Gregor8acb7272008-12-11 16:49:14 +00004641 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004642 DeclContext::lookup_const_iterator Oper, OperEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00004643 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004644 Oper != OperEnd; ++Oper)
Mike Stump25cf7602009-09-09 15:08:12 +00004645 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004646 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004647
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004648 // C++ [over.call.object]p2:
4649 // In addition, for each conversion function declared in T of the
4650 // form
4651 //
4652 // operator conversion-type-id () cv-qualifier;
4653 //
4654 // where cv-qualifier is the same cv-qualification as, or a
4655 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregor261afa72008-11-20 13:33:37 +00004656 // denotes the type "pointer to function of (P1,...,Pn) returning
4657 // R", or the type "reference to pointer to function of
4658 // (P1,...,Pn) returning R", or the type "reference to function
4659 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004660 // is also considered as a candidate function. Similarly,
4661 // surrogate call functions are added to the set of candidate
4662 // functions for each conversion function declared in an
4663 // accessible base class provided the function is not hidden
4664 // within T by another intervening declaration.
Mike Stump25cf7602009-09-09 15:08:12 +00004665
Douglas Gregorb35c7992009-08-24 15:23:48 +00004666 if (!RequireCompleteType(SourceLocation(), Object->getType(), 0)) {
4667 // FIXME: Look in base classes for more conversion operators!
Mike Stump25cf7602009-09-09 15:08:12 +00004668 OverloadedFunctionDecl *Conversions
Douglas Gregorb35c7992009-08-24 15:23:48 +00004669 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Mike Stump25cf7602009-09-09 15:08:12 +00004670 for (OverloadedFunctionDecl::function_iterator
Douglas Gregorb35c7992009-08-24 15:23:48 +00004671 Func = Conversions->function_begin(),
4672 FuncEnd = Conversions->function_end();
4673 Func != FuncEnd; ++Func) {
4674 CXXConversionDecl *Conv;
4675 FunctionTemplateDecl *ConvTemplate;
4676 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
Douglas Gregor8c860df2009-08-21 23:19:43 +00004677
Douglas Gregorb35c7992009-08-24 15:23:48 +00004678 // Skip over templated conversion functions; they aren't
4679 // surrogates.
4680 if (ConvTemplate)
4681 continue;
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004682
Douglas Gregorb35c7992009-08-24 15:23:48 +00004683 // Strip the reference type (if any) and then the pointer type (if
4684 // any) to get down to what might be a function type.
4685 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4686 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4687 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004688
Douglas Gregorb35c7992009-08-24 15:23:48 +00004689 if (const FunctionProtoType *Proto = ConvType->getAsFunctionProtoType())
4690 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4691 }
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004692 }
Mike Stump25cf7602009-09-09 15:08:12 +00004693
Douglas Gregor10f3c502008-11-19 21:05:33 +00004694 // Perform overload resolution.
4695 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004696 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004697 case OR_Success:
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004698 // Overload resolution succeeded; we'll build the appropriate call
4699 // below.
Douglas Gregor10f3c502008-11-19 21:05:33 +00004700 break;
4701
4702 case OR_No_Viable_Function:
Mike Stump25cf7602009-09-09 15:08:12 +00004703 Diag(Object->getSourceRange().getBegin(),
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004704 diag::err_ovl_no_viable_object_call)
Chris Lattner4a526112009-02-17 07:29:20 +00004705 << Object->getType() << Object->getSourceRange();
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00004706 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004707 break;
4708
4709 case OR_Ambiguous:
4710 Diag(Object->getSourceRange().getBegin(),
4711 diag::err_ovl_ambiguous_object_call)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004712 << Object->getType() << Object->getSourceRange();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004713 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4714 break;
Douglas Gregoraa57e862009-02-18 21:56:37 +00004715
4716 case OR_Deleted:
4717 Diag(Object->getSourceRange().getBegin(),
4718 diag::err_ovl_deleted_object_call)
4719 << Best->Function->isDeleted()
4720 << Object->getType() << Object->getSourceRange();
4721 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4722 break;
Mike Stump25cf7602009-09-09 15:08:12 +00004723 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004724
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004725 if (Best == CandidateSet.end()) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004726 // We had an error; delete all of the subexpressions and return
4727 // the error.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004728 Object->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004729 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004730 Args[ArgIdx]->Destroy(Context);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004731 return true;
4732 }
4733
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004734 if (Best->Function == 0) {
4735 // Since there is no function declaration, this is one of the
4736 // surrogate candidates. Dig out the conversion function.
Mike Stump25cf7602009-09-09 15:08:12 +00004737 CXXConversionDecl *Conv
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004738 = cast<CXXConversionDecl>(
4739 Best->Conversions[0].UserDefined.ConversionFunction);
4740
4741 // We selected one of the surrogate functions that converts the
4742 // object parameter to a function pointer. Perform the conversion
4743 // on the object argument, then let ActOnCallExpr finish the job.
4744 // FIXME: Represent the user-defined conversion in the AST!
Sebastian Redl8b769972009-01-19 00:08:26 +00004745 ImpCastExprToType(Object,
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004746 Conv->getConversionType().getNonReferenceType(),
Anders Carlsson85186942009-07-31 01:23:52 +00004747 CastExpr::CK_Unknown,
Sebastian Redlce6fff02009-03-16 23:22:08 +00004748 Conv->getConversionType()->isLValueReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00004749 return ActOnCallExpr(S, ExprArg(*this, Object), LParenLoc,
4750 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4751 CommaLocs, RParenLoc).release();
Douglas Gregor67fdb5b2008-11-19 22:57:39 +00004752 }
4753
4754 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4755 // that calls this method, using Object for the implicit object
4756 // parameter and passing along the remaining arguments.
4757 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor4fa58902009-02-26 23:50:07 +00004758 const FunctionProtoType *Proto = Method->getType()->getAsFunctionProtoType();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004759
4760 unsigned NumArgsInProto = Proto->getNumArgs();
4761 unsigned NumArgsToCheck = NumArgs;
4762
4763 // Build the full argument list for the method call (the
4764 // implicit object parameter is placed at the beginning of the
4765 // list).
4766 Expr **MethodArgs;
4767 if (NumArgs < NumArgsInProto) {
4768 NumArgsToCheck = NumArgsInProto;
4769 MethodArgs = new Expr*[NumArgsInProto + 1];
4770 } else {
4771 MethodArgs = new Expr*[NumArgs + 1];
4772 }
4773 MethodArgs[0] = Object;
4774 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4775 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump25cf7602009-09-09 15:08:12 +00004776
4777 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek0c97e042009-02-07 01:47:29 +00004778 SourceLocation());
Douglas Gregor10f3c502008-11-19 21:05:33 +00004779 UsualUnaryConversions(NewFn);
4780
4781 // Once we've built TheCall, all of the expressions are properly
4782 // owned.
4783 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump25cf7602009-09-09 15:08:12 +00004784 ExprOwningPtr<CXXOperatorCallExpr>
4785 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004786 MethodArgs, NumArgs + 1,
Ted Kremenek0c97e042009-02-07 01:47:29 +00004787 ResultTy, RParenLoc));
Douglas Gregor10f3c502008-11-19 21:05:33 +00004788 delete [] MethodArgs;
4789
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004790 // We may have default arguments. If so, we need to allocate more
4791 // slots in the call for them.
4792 if (NumArgs < NumArgsInProto)
Ted Kremenek0c97e042009-02-07 01:47:29 +00004793 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004794 else if (NumArgs > NumArgsInProto)
4795 NumArgsToCheck = NumArgsInProto;
4796
Chris Lattner81f00ed2009-04-12 08:11:20 +00004797 bool IsError = false;
4798
Douglas Gregor10f3c502008-11-19 21:05:33 +00004799 // Initialize the implicit object parameter.
Chris Lattner81f00ed2009-04-12 08:11:20 +00004800 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004801 TheCall->setArg(0, Object);
4802
Chris Lattner81f00ed2009-04-12 08:11:20 +00004803
Douglas Gregor10f3c502008-11-19 21:05:33 +00004804 // Check the argument types.
4805 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004806 Expr *Arg;
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004807 if (i < NumArgs) {
Douglas Gregor10f3c502008-11-19 21:05:33 +00004808 Arg = Args[i];
Mike Stump25cf7602009-09-09 15:08:12 +00004809
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004810 // Pass the argument.
4811 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner81f00ed2009-04-12 08:11:20 +00004812 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004813 } else {
Anders Carlsson3d752db2009-08-14 18:30:22 +00004814 Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
Douglas Gregordb0ae4a2009-01-13 05:10:00 +00004815 }
Douglas Gregor10f3c502008-11-19 21:05:33 +00004816
4817 TheCall->setArg(i + 1, Arg);
4818 }
4819
4820 // If this is a variadic call, handle args passed through "...".
4821 if (Proto->isVariadic()) {
4822 // Promote the arguments (C99 6.5.2.2p7).
4823 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4824 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00004825 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor10f3c502008-11-19 21:05:33 +00004826 TheCall->setArg(i + 1, Arg);
4827 }
4828 }
4829
Chris Lattner81f00ed2009-04-12 08:11:20 +00004830 if (IsError) return true;
4831
Anders Carlsson7fb13802009-08-16 01:56:34 +00004832 if (CheckFunctionCall(Method, TheCall.get()))
4833 return true;
4834
Anders Carlsson422a5fe2009-08-16 03:53:54 +00004835 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor10f3c502008-11-19 21:05:33 +00004836}
4837
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004838/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump25cf7602009-09-09 15:08:12 +00004839/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004840/// @c Member is the name of the member we're trying to find.
Douglas Gregorda61ad22009-08-06 03:17:00 +00004841Sema::OwningExprResult
4842Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
4843 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004844 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump25cf7602009-09-09 15:08:12 +00004845
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004846 // C++ [over.ref]p1:
4847 //
4848 // [...] An expression x->m is interpreted as (x.operator->())->m
4849 // for a class object x of type T if T::operator->() exists and if
4850 // the operator is selected as the best match function by the
4851 // overload resolution mechanism (13.3).
4852 // FIXME: look in base classes.
4853 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
4854 OverloadCandidateSet CandidateSet;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004855 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorda61ad22009-08-06 03:17:00 +00004856
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004857 DeclContext::lookup_const_iterator Oper, OperEnd;
Mike Stump25cf7602009-09-09 15:08:12 +00004858 for (llvm::tie(Oper, OperEnd)
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00004859 = BaseRecord->getDecl()->lookup(OpName); Oper != OperEnd; ++Oper)
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004860 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004861 /*SuppressUserConversions=*/false);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004862
4863 // Perform overload resolution.
4864 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00004865 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004866 case OR_Success:
4867 // Overload resolution succeeded; we'll build the call below.
4868 break;
4869
4870 case OR_No_Viable_Function:
4871 if (CandidateSet.empty())
4872 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004873 << Base->getType() << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004874 else
4875 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004876 << "operator->" << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004877 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004878 return ExprError();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004879
4880 case OR_Ambiguous:
4881 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Douglas Gregorda61ad22009-08-06 03:17:00 +00004882 << "operator->" << Base->getSourceRange();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004883 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004884 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004885
4886 case OR_Deleted:
4887 Diag(OpLoc, diag::err_ovl_deleted_oper)
4888 << Best->Function->isDeleted()
Douglas Gregorda61ad22009-08-06 03:17:00 +00004889 << "operator->" << Base->getSourceRange();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004890 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004891 return ExprError();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004892 }
4893
4894 // Convert the object parameter.
4895 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9c690e92008-11-21 03:04:22 +00004896 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregorda61ad22009-08-06 03:17:00 +00004897 return ExprError();
Douglas Gregor9c690e92008-11-21 03:04:22 +00004898
4899 // No concerns about early exits now.
Douglas Gregorda61ad22009-08-06 03:17:00 +00004900 BaseIn.release();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004901
4902 // Build the operator call.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004903 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
4904 SourceLocation());
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004905 UsualUnaryConversions(FnExpr);
Mike Stump25cf7602009-09-09 15:08:12 +00004906 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004907 Method->getResultType().getNonReferenceType(),
4908 OpLoc);
Douglas Gregorda61ad22009-08-06 03:17:00 +00004909 return Owned(Base);
Douglas Gregor7f3fec52008-11-20 16:27:02 +00004910}
4911
Douglas Gregor45014fd2008-11-10 20:40:00 +00004912/// FixOverloadedFunctionReference - E is an expression that refers to
4913/// a C++ overloaded function (possibly with some parentheses and
4914/// perhaps a '&' around it). We have resolved the overloaded function
4915/// to the function declaration Fn, so patch up the expression E to
4916/// refer (possibly indirectly) to Fn.
4917void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
4918 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4919 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
4920 E->setType(PE->getSubExpr()->getType());
4921 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump25cf7602009-09-09 15:08:12 +00004922 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregor45014fd2008-11-10 20:40:00 +00004923 "Can only take the address of an overloaded function");
Douglas Gregor3f411962009-02-11 01:18:59 +00004924 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
4925 if (Method->isStatic()) {
4926 // Do nothing: static member functions aren't any different
4927 // from non-member functions.
Mike Stump25cf7602009-09-09 15:08:12 +00004928 } else if (QualifiedDeclRefExpr *DRE
Douglas Gregor3f411962009-02-11 01:18:59 +00004929 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
4930 // We have taken the address of a pointer to member
4931 // function. Perform the computation here so that we get the
4932 // appropriate pointer to member type.
4933 DRE->setDecl(Fn);
4934 DRE->setType(Fn->getType());
4935 QualType ClassType
4936 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
Mike Stump25cf7602009-09-09 15:08:12 +00004937 E->setType(Context.getMemberPointerType(Fn->getType(),
Douglas Gregor3f411962009-02-11 01:18:59 +00004938 ClassType.getTypePtr()));
4939 return;
4940 }
4941 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00004942 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregor2eedd992009-02-11 00:19:33 +00004943 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregor45014fd2008-11-10 20:40:00 +00004944 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor62f78762009-07-08 20:55:45 +00004945 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
Mike Stump25cf7602009-09-09 15:08:12 +00004946 isa<FunctionTemplateDecl>(DR->getDecl())) &&
Douglas Gregor62f78762009-07-08 20:55:45 +00004947 "Expected overloaded function or function template");
Douglas Gregor45014fd2008-11-10 20:40:00 +00004948 DR->setDecl(Fn);
4949 E->setType(Fn->getType());
Douglas Gregor3257fb52008-12-22 05:46:06 +00004950 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
4951 MemExpr->setMemberDecl(Fn);
4952 E->setType(Fn->getType());
Douglas Gregor45014fd2008-11-10 20:40:00 +00004953 } else {
4954 assert(false && "Invalid reference to overloaded function");
4955 }
4956}
4957
Douglas Gregord2baafd2008-10-21 16:13:35 +00004958} // end namespace clang