blob: 769adb51cfaac7c036def2fc1995b851d654d2be [file] [log] [blame]
Douglas Gregor5251f1b2008-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"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000020#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000022#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000024#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000025#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000026#include <algorithm>
Torok Edwindb714922009-08-24 13:25:12 +000027#include <cstdio>
Douglas Gregor5251f1b2008-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 Stump11289f42009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor5251f1b2008-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 Gregor78ca74d2009-02-12 00:15:05 +000044 ICC_Promotion,
45 ICC_Conversion,
46 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000047 ICC_Conversion,
48 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000052 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000053 ICC_Conversion,
Douglas Gregor5251f1b2008-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 Gregor78ca74d2009-02-12 00:15:05 +000071 ICR_Promotion,
72 ICR_Conversion,
73 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000074 ICR_Conversion,
75 ICR_Conversion,
76 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000079 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000080 ICR_Conversion,
Douglas Gregor5251f1b2008-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 Gregor78ca74d2009-02-12 00:15:05 +000097 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +000098 "Integral conversion",
99 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000100 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000101 "Floating-integral conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000102 "Complex-real conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000103 "Pointer conversion",
104 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000105 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000106 "Compatible-types conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000107 "Derived-to-base conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000108 };
109 return Name[Kind];
110}
111
Douglas Gregor26bee0b2008-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 Redlf69a94a2009-03-29 22:46:24 +0000121 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000122 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000123}
124
Douglas Gregor5251f1b2008-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 Stump11289f42009-09-09 15:08:12 +0000141/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000142/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000143bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-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 Gregor033f56d2008-12-23 00:53:59 +0000152 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregor5251f1b2008-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 Gregor5c407d92008-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 Stump11289f42009-09-09 15:08:12 +0000163bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000164StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000165isPointerConversionToVoidPointer(ASTContext& Context) const {
Douglas Gregor5c407d92008-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 Kremenekc23c7e62009-07-29 21:53:49 +0000176 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregor5251f1b2008-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 Gregor2fe98832008-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 Gregor5251f1b2008-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 Lattnerf3d3fae2008-11-24 05:29:24 +0000227 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor5251f1b2008-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
John McCall3d988d92009-12-02 08:47:38 +0000258// overload of the declarations in Old. This routine returns false if
259// New and Old cannot be overloaded, e.g., if New has the same
260// signature as some function in Old (C++ 1.3.10) or if the Old
261// declarations aren't functions (or function templates) at all. When
262// it does return false and Old is an overload set, MatchedDecl will
263// be set to point to the FunctionDecl that New cannot be overloaded
264// with.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000265//
266// Example: Given the following input:
267//
268// void f(int, float); // #1
269// void f(int, int); // #2
270// int f(int, int); // #3
271//
272// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000273// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000274//
John McCall3d988d92009-12-02 08:47:38 +0000275// When we process #2, Old contains only the FunctionDecl for #1. By
276// comparing the parameter types, we see that #1 and #2 are overloaded
277// (since they have different signatures), so this routine returns
278// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000279//
John McCall3d988d92009-12-02 08:47:38 +0000280// When we process #3, Old is an overload set containing #1 and #2. We
281// compare the signatures of #3 to #1 (they're overloaded, so we do
282// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
283// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000284// signature), IsOverload returns false and MatchedDecl will be set to
285// point to the FunctionDecl for #2.
286bool
John McCall3d988d92009-12-02 08:47:38 +0000287Sema::IsOverload(FunctionDecl *New, LookupResult &Old, NamedDecl *&Match) {
288 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000289 I != E; ++I) {
John McCall3d988d92009-12-02 08:47:38 +0000290 NamedDecl *OldD = (*I)->getUnderlyingDecl();
291 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000292 if (!IsOverload(New, OldT->getTemplatedDecl())) {
John McCall3d988d92009-12-02 08:47:38 +0000293 Match = OldT;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000294 return false;
295 }
John McCall3d988d92009-12-02 08:47:38 +0000296 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000297 if (!IsOverload(New, OldF)) {
John McCall3d988d92009-12-02 08:47:38 +0000298 Match = OldF;
John McCall1f82f242009-11-18 22:49:29 +0000299 return false;
300 }
301 } else {
302 // (C++ 13p1):
303 // Only function declarations can be overloaded; object and type
304 // declarations cannot be overloaded.
John McCall3d988d92009-12-02 08:47:38 +0000305 Match = OldD;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000306 return false;
John McCall1f82f242009-11-18 22:49:29 +0000307 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000308 }
John McCall1f82f242009-11-18 22:49:29 +0000309
310 return true;
311}
312
313bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
314 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
315 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
316
317 // C++ [temp.fct]p2:
318 // A function template can be overloaded with other function templates
319 // and with normal (non-template) functions.
320 if ((OldTemplate == 0) != (NewTemplate == 0))
321 return true;
322
323 // Is the function New an overload of the function Old?
324 QualType OldQType = Context.getCanonicalType(Old->getType());
325 QualType NewQType = Context.getCanonicalType(New->getType());
326
327 // Compare the signatures (C++ 1.3.10) of the two functions to
328 // determine whether they are overloads. If we find any mismatch
329 // in the signature, they are overloads.
330
331 // If either of these functions is a K&R-style function (no
332 // prototype), then we consider them to have matching signatures.
333 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
334 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
335 return false;
336
337 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
338 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
339
340 // The signature of a function includes the types of its
341 // parameters (C++ 1.3.10), which includes the presence or absence
342 // of the ellipsis; see C++ DR 357).
343 if (OldQType != NewQType &&
344 (OldType->getNumArgs() != NewType->getNumArgs() ||
345 OldType->isVariadic() != NewType->isVariadic() ||
346 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
347 NewType->arg_type_begin())))
348 return true;
349
350 // C++ [temp.over.link]p4:
351 // The signature of a function template consists of its function
352 // signature, its return type and its template parameter list. The names
353 // of the template parameters are significant only for establishing the
354 // relationship between the template parameters and the rest of the
355 // signature.
356 //
357 // We check the return type and template parameter lists for function
358 // templates first; the remaining checks follow.
359 if (NewTemplate &&
360 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
361 OldTemplate->getTemplateParameters(),
362 false, TPL_TemplateMatch) ||
363 OldType->getResultType() != NewType->getResultType()))
364 return true;
365
366 // If the function is a class member, its signature includes the
367 // cv-qualifiers (if any) on the function itself.
368 //
369 // As part of this, also check whether one of the member functions
370 // is static, in which case they are not overloads (C++
371 // 13.1p2). While not part of the definition of the signature,
372 // this check is important to determine whether these functions
373 // can be overloaded.
374 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
375 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
376 if (OldMethod && NewMethod &&
377 !OldMethod->isStatic() && !NewMethod->isStatic() &&
378 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
379 return true;
380
381 // The signatures match; this is not an overload.
382 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000383}
384
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000385/// TryImplicitConversion - Attempt to perform an implicit conversion
386/// from the given expression (Expr) to the given type (ToType). This
387/// function returns an implicit conversion sequence that can be used
388/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000389///
390/// void f(float f);
391/// void g(int i) { f(i); }
392///
393/// this routine would produce an implicit conversion sequence to
394/// describe the initialization of f from i, which will be a standard
395/// conversion sequence containing an lvalue-to-rvalue conversion (C++
396/// 4.1) followed by a floating-integral conversion (C++ 4.9).
397//
398/// Note that this routine only determines how the conversion can be
399/// performed; it does not actually perform the conversion. As such,
400/// it will not produce any diagnostics if no conversion is available,
401/// but will instead return an implicit conversion sequence of kind
402/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000403///
404/// If @p SuppressUserConversions, then user-defined conversions are
405/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000406/// If @p AllowExplicit, then explicit user-defined conversions are
407/// permitted.
Sebastian Redl42e92c42009-04-12 17:16:29 +0000408/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
409/// no matter its actual lvalueness.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000410/// If @p UserCast, the implicit conversion is being done for a user-specified
411/// cast.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000412ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000413Sema::TryImplicitConversion(Expr* From, QualType ToType,
414 bool SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +0000415 bool AllowExplicit, bool ForceRValue,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000416 bool InOverloadResolution,
417 bool UserCast) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000418 ImplicitConversionSequence ICS;
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000419 OverloadCandidateSet Conversions;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000420 OverloadingResult UserDefResult = OR_Success;
Anders Carlsson228eea32009-08-28 15:33:32 +0000421 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000422 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000423 else if (getLangOptions().CPlusPlus &&
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000424 (UserDefResult = IsUserDefinedConversion(From, ToType,
425 ICS.UserDefined,
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000426 Conversions,
Sebastian Redl42e92c42009-04-12 17:16:29 +0000427 !SuppressUserConversions, AllowExplicit,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000428 ForceRValue, UserCast)) == OR_Success) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000429 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor05379422008-11-03 17:51:48 +0000430 // C++ [over.ics.user]p4:
431 // A conversion of an expression of class type to the same class
432 // type is given Exact Match rank, and a conversion of an
433 // expression of class type to a base class of that type is
434 // given Conversion rank, in spite of the fact that a copy
435 // constructor (i.e., a user-defined conversion function) is
436 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000437 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000438 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000439 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000440 = Context.getCanonicalType(From->getType().getUnqualifiedType());
441 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
442 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000443 // Turn this into a "standard" conversion sequence, so that it
444 // gets ranked with standard conversion sequences.
Douglas Gregor05379422008-11-03 17:51:48 +0000445 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
446 ICS.Standard.setAsIdentityConversion();
447 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
448 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000449 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000450 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000451 ICS.Standard.Second = ICK_Derived_To_Base;
452 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000453 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000454
455 // C++ [over.best.ics]p4:
456 // However, when considering the argument of a user-defined
457 // conversion function that is a candidate by 13.3.1.3 when
458 // invoked for the copying of the temporary in the second step
459 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
460 // 13.3.1.6 in all cases, only standard conversion sequences and
461 // ellipsis conversion sequences are allowed.
462 if (SuppressUserConversions &&
463 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
464 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000465 } else {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000466 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000467 if (UserDefResult == OR_Ambiguous) {
468 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
469 Cand != Conversions.end(); ++Cand)
Fariborz Jahanian574de2c2009-10-12 17:51:19 +0000470 if (Cand->Viable)
471 ICS.ConversionFunctionSet.push_back(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000472 }
473 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000474
475 return ICS;
476}
477
478/// IsStandardConversion - Determines whether there is a standard
479/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
480/// expression From to the type ToType. Standard conversion sequences
481/// only consider non-class types; for conversions that involve class
482/// types, use TryImplicitConversion. If a conversion exists, SCS will
483/// contain the standard conversion sequence required to perform this
484/// conversion and this routine will return true. Otherwise, this
485/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000486bool
487Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000488 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000489 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000490 QualType FromType = From->getType();
491
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000492 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000493 SCS.setAsIdentityConversion();
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000494 SCS.Deprecated = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000495 SCS.IncompatibleObjC = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000496 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000497 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000498
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000499 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000500 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000501 if (FromType->isRecordType() || ToType->isRecordType()) {
502 if (getLangOptions().CPlusPlus)
503 return false;
504
Mike Stump11289f42009-09-09 15:08:12 +0000505 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000506 }
507
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000508 // The first conversion can be an lvalue-to-rvalue conversion,
509 // array-to-pointer conversion, or function-to-pointer conversion
510 // (C++ 4p1).
511
Mike Stump11289f42009-09-09 15:08:12 +0000512 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000513 // An lvalue (3.10) of a non-function, non-array type T can be
514 // converted to an rvalue.
515 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000516 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000517 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000518 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000519 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000520
521 // If T is a non-class type, the type of the rvalue is the
522 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000523 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
524 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000525 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000526 } else if (FromType->isArrayType()) {
527 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000528 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000529
530 // An lvalue or rvalue of type "array of N T" or "array of unknown
531 // bound of T" can be converted to an rvalue of type "pointer to
532 // T" (C++ 4.2p1).
533 FromType = Context.getArrayDecayedType(FromType);
534
535 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
536 // This conversion is deprecated. (C++ D.4).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000537 SCS.Deprecated = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000538
539 // For the purpose of ranking in overload resolution
540 // (13.3.3.1.1), this conversion is considered an
541 // array-to-pointer conversion followed by a qualification
542 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000543 SCS.Second = ICK_Identity;
544 SCS.Third = ICK_Qualification;
545 SCS.ToTypePtr = ToType.getAsOpaquePtr();
546 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000547 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000548 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
549 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000550 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000551
552 // An lvalue of function type T can be converted to an rvalue of
553 // type "pointer to T." The result is a pointer to the
554 // function. (C++ 4.3p1).
555 FromType = Context.getPointerType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000556 } else if (FunctionDecl *Fn
Douglas Gregorcd695e52008-11-10 20:40:00 +0000557 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000558 // Address of overloaded function (C++ [over.over]).
Douglas Gregorcd695e52008-11-10 20:40:00 +0000559 SCS.First = ICK_Function_To_Pointer;
560
561 // We were able to resolve the address of the overloaded function,
562 // so we can convert to the type of that function.
563 FromType = Fn->getType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000564 if (ToType->isLValueReferenceType())
565 FromType = Context.getLValueReferenceType(FromType);
566 else if (ToType->isRValueReferenceType())
567 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl18f8ff62009-02-04 21:23:32 +0000568 else if (ToType->isMemberPointerType()) {
569 // Resolve address only succeeds if both sides are member pointers,
570 // but it doesn't have to be the same class. See DR 247.
571 // Note that this means that the type of &Derived::fn can be
572 // Ret (Base::*)(Args) if the fn overload actually found is from the
573 // base class, even if it was brought into the derived class via a
574 // using declaration. The standard isn't clear on this issue at all.
575 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
576 FromType = Context.getMemberPointerType(FromType,
577 Context.getTypeDeclType(M->getParent()).getTypePtr());
578 } else
Douglas Gregorcd695e52008-11-10 20:40:00 +0000579 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000580 } else {
581 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000582 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000583 }
584
585 // The second conversion can be an integral promotion, floating
586 // point promotion, integral conversion, floating point conversion,
587 // floating-integral conversion, pointer conversion,
588 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000589 // For overloading in C, this can also be a "compatible-type"
590 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000591 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000592 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000593 // The unqualified versions of the types are the same: there's no
594 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000595 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000596 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000597 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000598 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000599 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000600 } else if (IsFloatingPointPromotion(FromType, ToType)) {
601 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000602 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000603 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000604 } else if (IsComplexPromotion(FromType, ToType)) {
605 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000606 SCS.Second = ICK_Complex_Promotion;
607 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000608 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000609 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000610 // Integral conversions (C++ 4.7).
611 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000612 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000613 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000614 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
615 // Floating point conversions (C++ 4.8).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000616 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000617 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000618 } else if (FromType->isComplexType() && ToType->isComplexType()) {
619 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000620 SCS.Second = ICK_Complex_Conversion;
621 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000622 } else if ((FromType->isFloatingType() &&
623 ToType->isIntegralType() && (!ToType->isBooleanType() &&
624 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000625 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000626 ToType->isFloatingType())) {
627 // Floating-integral conversions (C++ 4.9).
628 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000629 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000630 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000631 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
632 (ToType->isComplexType() && FromType->isArithmeticType())) {
633 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000634 SCS.Second = ICK_Complex_Real;
635 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000636 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
637 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000638 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000639 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000640 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000641 } else if (IsMemberPointerConversion(From, FromType, ToType,
642 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000643 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000644 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000645 } else if (ToType->isBooleanType() &&
646 (FromType->isArithmeticType() ||
647 FromType->isEnumeralType() ||
648 FromType->isPointerType() ||
649 FromType->isBlockPointerType() ||
650 FromType->isMemberPointerType() ||
651 FromType->isNullPtrType())) {
652 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000653 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000654 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000655 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000656 Context.typesAreCompatible(ToType, FromType)) {
657 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000658 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000659 } else {
660 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000661 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000662 }
663
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000664 QualType CanonFrom;
665 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000666 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000667 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000668 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000669 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000670 CanonFrom = Context.getCanonicalType(FromType);
671 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000672 } else {
673 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000674 SCS.Third = ICK_Identity;
675
Mike Stump11289f42009-09-09 15:08:12 +0000676 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000677 // [...] Any difference in top-level cv-qualification is
678 // subsumed by the initialization itself and does not constitute
679 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000680 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000681 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000682 if (CanonFrom.getLocalUnqualifiedType()
683 == CanonTo.getLocalUnqualifiedType() &&
684 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000685 FromType = ToType;
686 CanonFrom = CanonTo;
687 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000688 }
689
690 // If we have not converted the argument type to the parameter type,
691 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000692 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000693 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000694
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000695 SCS.ToTypePtr = FromType.getAsOpaquePtr();
696 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000697}
698
699/// IsIntegralPromotion - Determines whether the conversion from the
700/// expression From (whose potentially-adjusted type is FromType) to
701/// ToType is an integral promotion (C++ 4.5). If so, returns true and
702/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000703bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000704 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000705 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000706 if (!To) {
707 return false;
708 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000709
710 // An rvalue of type char, signed char, unsigned char, short int, or
711 // unsigned short int can be converted to an rvalue of type int if
712 // int can represent all the values of the source type; otherwise,
713 // the source rvalue can be converted to an rvalue of type unsigned
714 // int (C++ 4.5p1).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000715 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000716 if (// We can promote any signed, promotable integer type to an int
717 (FromType->isSignedIntegerType() ||
718 // We can promote any unsigned integer type whose size is
719 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000720 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000721 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000722 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000723 }
724
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000725 return To->getKind() == BuiltinType::UInt;
726 }
727
728 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
729 // can be converted to an rvalue of the first of the following types
730 // that can represent all the values of its underlying type: int,
731 // unsigned int, long, or unsigned long (C++ 4.5p2).
732 if ((FromType->isEnumeralType() || FromType->isWideCharType())
733 && ToType->isIntegerType()) {
734 // Determine whether the type we're converting from is signed or
735 // unsigned.
736 bool FromIsSigned;
737 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall9dd450b2009-09-21 23:43:11 +0000738 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000739 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
740 FromIsSigned = UnderlyingType->isSignedIntegerType();
741 } else {
742 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
743 FromIsSigned = true;
744 }
745
746 // The types we'll try to promote to, in the appropriate
747 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000748 QualType PromoteTypes[6] = {
749 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000750 Context.LongTy, Context.UnsignedLongTy ,
751 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000752 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000753 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000754 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
755 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000756 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000757 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
758 // We found the type that we can promote to. If this is the
759 // type we wanted, we have a promotion. Otherwise, no
760 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000761 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000762 }
763 }
764 }
765
766 // An rvalue for an integral bit-field (9.6) can be converted to an
767 // rvalue of type int if int can represent all the values of the
768 // bit-field; otherwise, it can be converted to unsigned int if
769 // unsigned int can represent all the values of the bit-field. If
770 // the bit-field is larger yet, no integral promotion applies to
771 // it. If the bit-field has an enumerated type, it is treated as any
772 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000773 // FIXME: We should delay checking of bit-fields until we actually perform the
774 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000775 using llvm::APSInt;
776 if (From)
777 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000778 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000779 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
780 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
781 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
782 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000783
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000784 // Are we promoting to an int from a bitfield that fits in an int?
785 if (BitWidth < ToSize ||
786 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
787 return To->getKind() == BuiltinType::Int;
788 }
Mike Stump11289f42009-09-09 15:08:12 +0000789
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000790 // Are we promoting to an unsigned int from an unsigned bitfield
791 // that fits into an unsigned int?
792 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
793 return To->getKind() == BuiltinType::UInt;
794 }
Mike Stump11289f42009-09-09 15:08:12 +0000795
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000796 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000797 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000798 }
Mike Stump11289f42009-09-09 15:08:12 +0000799
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000800 // An rvalue of type bool can be converted to an rvalue of type int,
801 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000802 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000803 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000804 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000805
806 return false;
807}
808
809/// IsFloatingPointPromotion - Determines whether the conversion from
810/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
811/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000812bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000813 /// An rvalue of type float can be converted to an rvalue of type
814 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000815 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
816 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000817 if (FromBuiltin->getKind() == BuiltinType::Float &&
818 ToBuiltin->getKind() == BuiltinType::Double)
819 return true;
820
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000821 // C99 6.3.1.5p1:
822 // When a float is promoted to double or long double, or a
823 // double is promoted to long double [...].
824 if (!getLangOptions().CPlusPlus &&
825 (FromBuiltin->getKind() == BuiltinType::Float ||
826 FromBuiltin->getKind() == BuiltinType::Double) &&
827 (ToBuiltin->getKind() == BuiltinType::LongDouble))
828 return true;
829 }
830
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000831 return false;
832}
833
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000834/// \brief Determine if a conversion is a complex promotion.
835///
836/// A complex promotion is defined as a complex -> complex conversion
837/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000838/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000839bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000840 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000841 if (!FromComplex)
842 return false;
843
John McCall9dd450b2009-09-21 23:43:11 +0000844 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000845 if (!ToComplex)
846 return false;
847
848 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000849 ToComplex->getElementType()) ||
850 IsIntegralPromotion(0, FromComplex->getElementType(),
851 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000852}
853
Douglas Gregor237f96c2008-11-26 23:31:11 +0000854/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
855/// the pointer type FromPtr to a pointer to type ToPointee, with the
856/// same type qualifiers as FromPtr has on its pointee type. ToType,
857/// if non-empty, will be a pointer to ToType that may or may not have
858/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000859static QualType
860BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000861 QualType ToPointee, QualType ToType,
862 ASTContext &Context) {
863 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
864 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +0000865 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000866
867 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000868 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +0000869 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +0000870 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +0000871 return ToType;
872
873 // Build a pointer to ToPointee. It has the right qualifiers
874 // already.
875 return Context.getPointerType(ToPointee);
876 }
877
878 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +0000879 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000880 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
881 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +0000882}
883
Mike Stump11289f42009-09-09 15:08:12 +0000884static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000885 bool InOverloadResolution,
886 ASTContext &Context) {
887 // Handle value-dependent integral null pointer constants correctly.
888 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
889 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
890 Expr->getType()->isIntegralType())
891 return !InOverloadResolution;
892
Douglas Gregor56751b52009-09-25 04:25:58 +0000893 return Expr->isNullPointerConstant(Context,
894 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
895 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +0000896}
Mike Stump11289f42009-09-09 15:08:12 +0000897
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000898/// IsPointerConversion - Determines whether the conversion of the
899/// expression From, which has the (possibly adjusted) type FromType,
900/// can be converted to the type ToType via a pointer conversion (C++
901/// 4.10). If so, returns true and places the converted type (that
902/// might differ from ToType in its cv-qualifiers at some level) into
903/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000904///
Douglas Gregora29dc052008-11-27 01:19:21 +0000905/// This routine also supports conversions to and from block pointers
906/// and conversions with Objective-C's 'id', 'id<protocols...>', and
907/// pointers to interfaces. FIXME: Once we've determined the
908/// appropriate overloading rules for Objective-C, we may want to
909/// split the Objective-C checks into a different routine; however,
910/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +0000911/// conversions, so for now they live here. IncompatibleObjC will be
912/// set if the conversion is an allowed Objective-C conversion that
913/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000914bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000915 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +0000916 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +0000917 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +0000918 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +0000919 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
920 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000921
Mike Stump11289f42009-09-09 15:08:12 +0000922 // Conversion from a null pointer constant to any Objective-C pointer type.
923 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000924 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +0000925 ConvertedType = ToType;
926 return true;
927 }
928
Douglas Gregor231d1c62008-11-27 00:15:41 +0000929 // Blocks: Block pointers can be converted to void*.
930 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000931 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000932 ConvertedType = ToType;
933 return true;
934 }
935 // Blocks: A null pointer constant can be converted to a block
936 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +0000937 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000938 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000939 ConvertedType = ToType;
940 return true;
941 }
942
Sebastian Redl576fd422009-05-10 18:38:11 +0000943 // If the left-hand-side is nullptr_t, the right side can be a null
944 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +0000945 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000946 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +0000947 ConvertedType = ToType;
948 return true;
949 }
950
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000951 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000952 if (!ToTypePtr)
953 return false;
954
955 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +0000956 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000957 ConvertedType = ToType;
958 return true;
959 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000960
Douglas Gregor237f96c2008-11-26 23:31:11 +0000961 // Beyond this point, both types need to be pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000962 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +0000963 if (!FromTypePtr)
964 return false;
965
966 QualType FromPointeeType = FromTypePtr->getPointeeType();
967 QualType ToPointeeType = ToTypePtr->getPointeeType();
968
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000969 // An rvalue of type "pointer to cv T," where T is an object type,
970 // can be converted to an rvalue of type "pointer to cv void" (C++
971 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +0000972 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000973 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +0000974 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000975 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000976 return true;
977 }
978
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000979 // When we're overloading in C, we allow a special kind of pointer
980 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +0000981 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000982 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000983 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000984 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +0000985 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000986 return true;
987 }
988
Douglas Gregor5c407d92008-10-23 00:40:37 +0000989 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +0000990 //
Douglas Gregor5c407d92008-10-23 00:40:37 +0000991 // An rvalue of type "pointer to cv D," where D is a class type,
992 // can be converted to an rvalue of type "pointer to cv B," where
993 // B is a base class (clause 10) of D. If B is an inaccessible
994 // (clause 11) or ambiguous (10.2) base class of D, a program that
995 // necessitates this conversion is ill-formed. The result of the
996 // conversion is a pointer to the base class sub-object of the
997 // derived class object. The null pointer value is converted to
998 // the null pointer value of the destination type.
999 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001000 // Note that we do not check for ambiguity or inaccessibility
1001 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001002 if (getLangOptions().CPlusPlus &&
1003 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001004 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001005 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001006 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001007 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001008 ToType, Context);
1009 return true;
1010 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001011
Douglas Gregora119f102008-12-19 19:13:09 +00001012 return false;
1013}
1014
1015/// isObjCPointerConversion - Determines whether this is an
1016/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1017/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001018bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001019 QualType& ConvertedType,
1020 bool &IncompatibleObjC) {
1021 if (!getLangOptions().ObjC1)
1022 return false;
1023
Steve Naroff7cae42b2009-07-10 23:34:53 +00001024 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001025 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001026 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001027 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001028
Steve Naroff7cae42b2009-07-10 23:34:53 +00001029 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001030 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001031 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001032 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001033 ConvertedType = ToType;
1034 return true;
1035 }
1036 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001037 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001038 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001039 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001040 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001041 ConvertedType = ToType;
1042 return true;
1043 }
1044 // Objective C++: We're able to convert from a pointer to an
1045 // interface to a pointer to a different interface.
1046 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1047 ConvertedType = ToType;
1048 return true;
1049 }
1050
1051 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1052 // Okay: this is some kind of implicit downcast of Objective-C
1053 // interfaces, which is permitted. However, we're going to
1054 // complain about it.
1055 IncompatibleObjC = true;
1056 ConvertedType = FromType;
1057 return true;
1058 }
Mike Stump11289f42009-09-09 15:08:12 +00001059 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001060 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001061 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001062 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001063 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001064 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001065 ToPointeeType = ToBlockPtr->getPointeeType();
1066 else
Douglas Gregora119f102008-12-19 19:13:09 +00001067 return false;
1068
Douglas Gregor033f56d2008-12-23 00:53:59 +00001069 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001070 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001071 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001072 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001073 FromPointeeType = FromBlockPtr->getPointeeType();
1074 else
Douglas Gregora119f102008-12-19 19:13:09 +00001075 return false;
1076
Douglas Gregora119f102008-12-19 19:13:09 +00001077 // If we have pointers to pointers, recursively check whether this
1078 // is an Objective-C conversion.
1079 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1080 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1081 IncompatibleObjC)) {
1082 // We always complain about this conversion.
1083 IncompatibleObjC = true;
1084 ConvertedType = ToType;
1085 return true;
1086 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001087 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001088 // differences in the argument and result types are in Objective-C
1089 // pointer conversions. If so, we permit the conversion (but
1090 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001091 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001092 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001093 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001094 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001095 if (FromFunctionType && ToFunctionType) {
1096 // If the function types are exactly the same, this isn't an
1097 // Objective-C pointer conversion.
1098 if (Context.getCanonicalType(FromPointeeType)
1099 == Context.getCanonicalType(ToPointeeType))
1100 return false;
1101
1102 // Perform the quick checks that will tell us whether these
1103 // function types are obviously different.
1104 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1105 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1106 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1107 return false;
1108
1109 bool HasObjCConversion = false;
1110 if (Context.getCanonicalType(FromFunctionType->getResultType())
1111 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1112 // Okay, the types match exactly. Nothing to do.
1113 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1114 ToFunctionType->getResultType(),
1115 ConvertedType, IncompatibleObjC)) {
1116 // Okay, we have an Objective-C pointer conversion.
1117 HasObjCConversion = true;
1118 } else {
1119 // Function types are too different. Abort.
1120 return false;
1121 }
Mike Stump11289f42009-09-09 15:08:12 +00001122
Douglas Gregora119f102008-12-19 19:13:09 +00001123 // Check argument types.
1124 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1125 ArgIdx != NumArgs; ++ArgIdx) {
1126 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1127 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1128 if (Context.getCanonicalType(FromArgType)
1129 == Context.getCanonicalType(ToArgType)) {
1130 // Okay, the types match exactly. Nothing to do.
1131 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1132 ConvertedType, IncompatibleObjC)) {
1133 // Okay, we have an Objective-C pointer conversion.
1134 HasObjCConversion = true;
1135 } else {
1136 // Argument types are too different. Abort.
1137 return false;
1138 }
1139 }
1140
1141 if (HasObjCConversion) {
1142 // We had an Objective-C conversion. Allow this pointer
1143 // conversion, but complain about it.
1144 ConvertedType = ToType;
1145 IncompatibleObjC = true;
1146 return true;
1147 }
1148 }
1149
Sebastian Redl72b597d2009-01-25 19:43:20 +00001150 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001151}
1152
Douglas Gregor39c16d42008-10-24 04:54:22 +00001153/// CheckPointerConversion - Check the pointer conversion from the
1154/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001155/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001156/// conversions for which IsPointerConversion has already returned
1157/// true. It returns true and produces a diagnostic if there was an
1158/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001159bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001160 CastExpr::CastKind &Kind,
1161 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001162 QualType FromType = From->getType();
1163
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001164 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1165 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001166 QualType FromPointeeType = FromPtrType->getPointeeType(),
1167 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001168
Douglas Gregor39c16d42008-10-24 04:54:22 +00001169 if (FromPointeeType->isRecordType() &&
1170 ToPointeeType->isRecordType()) {
1171 // We must have a derived-to-base conversion. Check an
1172 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001173 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1174 From->getExprLoc(),
Sebastian Redl7c353682009-11-14 21:15:49 +00001175 From->getSourceRange(),
1176 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001177 return true;
1178
1179 // The conversion was successful.
1180 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001181 }
1182 }
Mike Stump11289f42009-09-09 15:08:12 +00001183 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001184 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001185 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001186 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001187 // Objective-C++ conversions are always okay.
1188 // FIXME: We should have a different class of conversions for the
1189 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001190 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001191 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001192
Steve Naroff7cae42b2009-07-10 23:34:53 +00001193 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001194 return false;
1195}
1196
Sebastian Redl72b597d2009-01-25 19:43:20 +00001197/// IsMemberPointerConversion - Determines whether the conversion of the
1198/// expression From, which has the (possibly adjusted) type FromType, can be
1199/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1200/// If so, returns true and places the converted type (that might differ from
1201/// ToType in its cv-qualifiers at some level) into ConvertedType.
1202bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001203 QualType ToType,
1204 bool InOverloadResolution,
1205 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001206 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001207 if (!ToTypePtr)
1208 return false;
1209
1210 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001211 if (From->isNullPointerConstant(Context,
1212 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1213 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001214 ConvertedType = ToType;
1215 return true;
1216 }
1217
1218 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001219 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001220 if (!FromTypePtr)
1221 return false;
1222
1223 // A pointer to member of B can be converted to a pointer to member of D,
1224 // where D is derived from B (C++ 4.11p2).
1225 QualType FromClass(FromTypePtr->getClass(), 0);
1226 QualType ToClass(ToTypePtr->getClass(), 0);
1227 // FIXME: What happens when these are dependent? Is this function even called?
1228
1229 if (IsDerivedFrom(ToClass, FromClass)) {
1230 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1231 ToClass.getTypePtr());
1232 return true;
1233 }
1234
1235 return false;
1236}
1237
1238/// CheckMemberPointerConversion - Check the member pointer conversion from the
1239/// expression From to the type ToType. This routine checks for ambiguous or
1240/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1241/// for which IsMemberPointerConversion has already returned true. It returns
1242/// true and produces a diagnostic if there was an error, or returns false
1243/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001244bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001245 CastExpr::CastKind &Kind,
1246 bool IgnoreBaseAccess) {
1247 (void)IgnoreBaseAccess;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001248 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001249 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001250 if (!FromPtrType) {
1251 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001252 assert(From->isNullPointerConstant(Context,
1253 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001254 "Expr must be null pointer constant!");
1255 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001256 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001257 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001258
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001259 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001260 assert(ToPtrType && "No member pointer cast has a target type "
1261 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001262
Sebastian Redled8f2002009-01-28 18:33:18 +00001263 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1264 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001265
Sebastian Redled8f2002009-01-28 18:33:18 +00001266 // FIXME: What about dependent types?
1267 assert(FromClass->isRecordType() && "Pointer into non-class.");
1268 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001269
Douglas Gregor36d1b142009-10-06 17:59:45 +00001270 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1271 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001272 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1273 assert(DerivationOkay &&
1274 "Should not have been called if derivation isn't OK.");
1275 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001276
Sebastian Redled8f2002009-01-28 18:33:18 +00001277 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1278 getUnqualifiedType())) {
1279 // Derivation is ambiguous. Redo the check to find the exact paths.
1280 Paths.clear();
1281 Paths.setRecordingPaths(true);
1282 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1283 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1284 (void)StillOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001285
Sebastian Redled8f2002009-01-28 18:33:18 +00001286 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1287 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1288 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1289 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001290 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001291
Douglas Gregor89ee6822009-02-28 01:32:25 +00001292 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001293 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1294 << FromClass << ToClass << QualType(VBase, 0)
1295 << From->getSourceRange();
1296 return true;
1297 }
1298
Anders Carlssond7923c62009-08-22 23:33:40 +00001299 // Must be a base to derived member conversion.
1300 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001301 return false;
1302}
1303
Douglas Gregor9a657932008-10-21 23:43:52 +00001304/// IsQualificationConversion - Determines whether the conversion from
1305/// an rvalue of type FromType to ToType is a qualification conversion
1306/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001307bool
1308Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001309 FromType = Context.getCanonicalType(FromType);
1310 ToType = Context.getCanonicalType(ToType);
1311
1312 // If FromType and ToType are the same type, this is not a
1313 // qualification conversion.
1314 if (FromType == ToType)
1315 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001316
Douglas Gregor9a657932008-10-21 23:43:52 +00001317 // (C++ 4.4p4):
1318 // A conversion can add cv-qualifiers at levels other than the first
1319 // in multi-level pointers, subject to the following rules: [...]
1320 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001321 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001322 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001323 // Within each iteration of the loop, we check the qualifiers to
1324 // determine if this still looks like a qualification
1325 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001326 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001327 // until there are no more pointers or pointers-to-members left to
1328 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001329 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001330
1331 // -- for every j > 0, if const is in cv 1,j then const is in cv
1332 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001333 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001334 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001335
Douglas Gregor9a657932008-10-21 23:43:52 +00001336 // -- if the cv 1,j and cv 2,j are different, then const is in
1337 // every cv for 0 < k < j.
1338 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001339 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001340 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001341
Douglas Gregor9a657932008-10-21 23:43:52 +00001342 // Keep track of whether all prior cv-qualifiers in the "to" type
1343 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001344 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001345 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001346 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001347
1348 // We are left with FromType and ToType being the pointee types
1349 // after unwrapping the original FromType and ToType the same number
1350 // of types. If we unwrapped any pointers, and if FromType and
1351 // ToType have the same unqualified type (since we checked
1352 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001353 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001354}
1355
Douglas Gregor576e98c2009-01-30 23:27:23 +00001356/// Determines whether there is a user-defined conversion sequence
1357/// (C++ [over.ics.user]) that converts expression From to the type
1358/// ToType. If such a conversion exists, User will contain the
1359/// user-defined conversion sequence that performs such a conversion
1360/// and this routine will return true. Otherwise, this routine returns
1361/// false and User is unspecified.
1362///
1363/// \param AllowConversionFunctions true if the conversion should
1364/// consider conversion functions at all. If false, only constructors
1365/// will be considered.
1366///
1367/// \param AllowExplicit true if the conversion should consider C++0x
1368/// "explicit" conversion functions as well as non-explicit conversion
1369/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001370///
1371/// \param ForceRValue true if the expression should be treated as an rvalue
1372/// for overload resolution.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001373/// \param UserCast true if looking for user defined conversion for a static
1374/// cast.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001375Sema::OverloadingResult Sema::IsUserDefinedConversion(
1376 Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001377 UserDefinedConversionSequence& User,
Fariborz Jahanian19c73282009-09-15 00:10:11 +00001378 OverloadCandidateSet& CandidateSet,
Douglas Gregor576e98c2009-01-30 23:27:23 +00001379 bool AllowConversionFunctions,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001380 bool AllowExplicit, bool ForceRValue,
1381 bool UserCast) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001382 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001383 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1384 // We're not going to find any constructors.
1385 } else if (CXXRecordDecl *ToRecordDecl
1386 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001387 // C++ [over.match.ctor]p1:
1388 // When objects of class type are direct-initialized (8.5), or
1389 // copy-initialized from an expression of the same or a
1390 // derived class type (8.5), overload resolution selects the
1391 // constructor. [...] For copy-initialization, the candidate
1392 // functions are all the converting constructors (12.3.1) of
1393 // that class. The argument list is the expression-list within
1394 // the parentheses of the initializer.
Douglas Gregor379d84b2009-11-13 18:44:21 +00001395 bool SuppressUserConversions = !UserCast;
1396 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1397 IsDerivedFrom(From->getType(), ToType)) {
1398 SuppressUserConversions = false;
1399 AllowConversionFunctions = false;
1400 }
1401
Mike Stump11289f42009-09-09 15:08:12 +00001402 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001403 = Context.DeclarationNames.getCXXConstructorName(
1404 Context.getCanonicalType(ToType).getUnqualifiedType());
1405 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001406 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001407 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001408 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001409 // Find the constructor (which may be a template).
1410 CXXConstructorDecl *Constructor = 0;
1411 FunctionTemplateDecl *ConstructorTmpl
1412 = dyn_cast<FunctionTemplateDecl>(*Con);
1413 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001414 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001415 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1416 else
1417 Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001418
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001419 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001420 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001421 if (ConstructorTmpl)
John McCall6b51f282009-11-23 01:53:49 +00001422 AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
1423 &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001424 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001425 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001426 // Allow one user-defined conversion when user specifies a
1427 // From->ToType conversion via an static cast (c-style, etc).
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001428 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Douglas Gregor379d84b2009-11-13 18:44:21 +00001429 SuppressUserConversions, ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001430 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001431 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001432 }
1433 }
1434
Douglas Gregor576e98c2009-01-30 23:27:23 +00001435 if (!AllowConversionFunctions) {
1436 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001437 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1438 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001439 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001440 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001441 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001442 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001443 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001444 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1445 // Add all of the conversion functions as candidates.
John McCalld14a8642009-11-21 08:51:07 +00001446 const UnresolvedSet *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001447 = FromRecordDecl->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00001448 for (UnresolvedSet::iterator I = Conversions->begin(),
1449 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00001450 NamedDecl *D = *I;
1451 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1452 if (isa<UsingShadowDecl>(D))
1453 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1454
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001455 CXXConversionDecl *Conv;
1456 FunctionTemplateDecl *ConvTemplate;
John McCalld14a8642009-11-21 08:51:07 +00001457 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001458 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1459 else
John McCalld14a8642009-11-21 08:51:07 +00001460 Conv = dyn_cast<CXXConversionDecl>(*I);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001461
1462 if (AllowExplicit || !Conv->isExplicit()) {
1463 if (ConvTemplate)
John McCall6e9f8f62009-12-03 04:06:58 +00001464 AddTemplateConversionCandidate(ConvTemplate, ActingContext,
1465 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001466 else
John McCall6e9f8f62009-12-03 04:06:58 +00001467 AddConversionCandidate(Conv, ActingContext, From, ToType,
1468 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001469 }
1470 }
1471 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001472 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001473
1474 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001475 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001476 case OR_Success:
1477 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001478 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001479 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1480 // C++ [over.ics.user]p1:
1481 // If the user-defined conversion is specified by a
1482 // constructor (12.3.1), the initial standard conversion
1483 // sequence converts the source type to the type required by
1484 // the argument of the constructor.
1485 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001486 QualType ThisType = Constructor->getThisType(Context);
Fariborz Jahanian55824512009-11-06 00:23:08 +00001487 if (Best->Conversions[0].ConversionKind ==
1488 ImplicitConversionSequence::EllipsisConversion)
1489 User.EllipsisConversion = true;
1490 else {
1491 User.Before = Best->Conversions[0].Standard;
1492 User.EllipsisConversion = false;
1493 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001494 User.ConversionFunction = Constructor;
1495 User.After.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00001496 User.After.FromTypePtr
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001497 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001498 User.After.ToTypePtr = ToType.getAsOpaquePtr();
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001499 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001500 } else if (CXXConversionDecl *Conversion
1501 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1502 // C++ [over.ics.user]p1:
1503 //
1504 // [...] If the user-defined conversion is specified by a
1505 // conversion function (12.3.2), the initial standard
1506 // conversion sequence converts the source type to the
1507 // implicit object parameter of the conversion function.
1508 User.Before = Best->Conversions[0].Standard;
1509 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001510 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001511
1512 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001513 // The second standard conversion sequence converts the
1514 // result of the user-defined conversion to the target type
1515 // for the sequence. Since an implicit conversion sequence
1516 // is an initialization, the special rules for
1517 // initialization by user-defined conversion apply when
1518 // selecting the best user-defined conversion for a
1519 // user-defined conversion sequence (see 13.3.3 and
1520 // 13.3.3.1).
1521 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001522 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001523 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001524 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001525 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001526 }
Mike Stump11289f42009-09-09 15:08:12 +00001527
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001528 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001529 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001530 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001531 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001532 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001533
1534 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001535 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001536 }
1537
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001538 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001539}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001540
1541bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001542Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001543 ImplicitConversionSequence ICS;
1544 OverloadCandidateSet CandidateSet;
1545 OverloadingResult OvResult =
1546 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1547 CandidateSet, true, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001548 if (OvResult == OR_Ambiguous)
1549 Diag(From->getSourceRange().getBegin(),
1550 diag::err_typecheck_ambiguous_condition)
1551 << From->getType() << ToType << From->getSourceRange();
1552 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1553 Diag(From->getSourceRange().getBegin(),
1554 diag::err_typecheck_nonviable_condition)
1555 << From->getType() << ToType << From->getSourceRange();
1556 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001557 return false;
Fariborz Jahanian76197412009-11-18 18:26:29 +00001558 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001559 return true;
1560}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001561
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001562/// CompareImplicitConversionSequences - Compare two implicit
1563/// conversion sequences to determine whether one is better than the
1564/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001565ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001566Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1567 const ImplicitConversionSequence& ICS2)
1568{
1569 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1570 // conversion sequences (as defined in 13.3.3.1)
1571 // -- a standard conversion sequence (13.3.3.1.1) is a better
1572 // conversion sequence than a user-defined conversion sequence or
1573 // an ellipsis conversion sequence, and
1574 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1575 // conversion sequence than an ellipsis conversion sequence
1576 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001577 //
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001578 if (ICS1.ConversionKind < ICS2.ConversionKind)
1579 return ImplicitConversionSequence::Better;
1580 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1581 return ImplicitConversionSequence::Worse;
1582
1583 // Two implicit conversion sequences of the same form are
1584 // indistinguishable conversion sequences unless one of the
1585 // following rules apply: (C++ 13.3.3.2p3):
1586 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1587 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump11289f42009-09-09 15:08:12 +00001588 else if (ICS1.ConversionKind ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001589 ImplicitConversionSequence::UserDefinedConversion) {
1590 // User-defined conversion sequence U1 is a better conversion
1591 // sequence than another user-defined conversion sequence U2 if
1592 // they contain the same user-defined conversion function or
1593 // constructor and if the second standard conversion sequence of
1594 // U1 is better than the second standard conversion sequence of
1595 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001596 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001597 ICS2.UserDefined.ConversionFunction)
1598 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1599 ICS2.UserDefined.After);
1600 }
1601
1602 return ImplicitConversionSequence::Indistinguishable;
1603}
1604
1605/// CompareStandardConversionSequences - Compare two standard
1606/// conversion sequences to determine whether one is better than the
1607/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001608ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001609Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1610 const StandardConversionSequence& SCS2)
1611{
1612 // Standard conversion sequence S1 is a better conversion sequence
1613 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1614
1615 // -- S1 is a proper subsequence of S2 (comparing the conversion
1616 // sequences in the canonical form defined by 13.3.3.1.1,
1617 // excluding any Lvalue Transformation; the identity conversion
1618 // sequence is considered to be a subsequence of any
1619 // non-identity conversion sequence) or, if not that,
1620 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1621 // Neither is a proper subsequence of the other. Do nothing.
1622 ;
1623 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1624 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001625 (SCS1.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001626 SCS1.Third == ICK_Identity))
1627 // SCS1 is a proper subsequence of SCS2.
1628 return ImplicitConversionSequence::Better;
1629 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1630 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001631 (SCS2.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001632 SCS2.Third == ICK_Identity))
1633 // SCS2 is a proper subsequence of SCS1.
1634 return ImplicitConversionSequence::Worse;
1635
1636 // -- the rank of S1 is better than the rank of S2 (by the rules
1637 // defined below), or, if not that,
1638 ImplicitConversionRank Rank1 = SCS1.getRank();
1639 ImplicitConversionRank Rank2 = SCS2.getRank();
1640 if (Rank1 < Rank2)
1641 return ImplicitConversionSequence::Better;
1642 else if (Rank2 < Rank1)
1643 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001644
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001645 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1646 // are indistinguishable unless one of the following rules
1647 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001648
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001649 // A conversion that is not a conversion of a pointer, or
1650 // pointer to member, to bool is better than another conversion
1651 // that is such a conversion.
1652 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1653 return SCS2.isPointerConversionToBool()
1654 ? ImplicitConversionSequence::Better
1655 : ImplicitConversionSequence::Worse;
1656
Douglas Gregor5c407d92008-10-23 00:40:37 +00001657 // C++ [over.ics.rank]p4b2:
1658 //
1659 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001660 // conversion of B* to A* is better than conversion of B* to
1661 // void*, and conversion of A* to void* is better than conversion
1662 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001663 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001664 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001665 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001666 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001667 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1668 // Exactly one of the conversion sequences is a conversion to
1669 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001670 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1671 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001672 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1673 // Neither conversion sequence converts to a void pointer; compare
1674 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001675 if (ImplicitConversionSequence::CompareKind DerivedCK
1676 = CompareDerivedToBaseConversions(SCS1, SCS2))
1677 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001678 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1679 // Both conversion sequences are conversions to void
1680 // pointers. Compare the source types to determine if there's an
1681 // inheritance relationship in their sources.
1682 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1683 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1684
1685 // Adjust the types we're converting from via the array-to-pointer
1686 // conversion, if we need to.
1687 if (SCS1.First == ICK_Array_To_Pointer)
1688 FromType1 = Context.getArrayDecayedType(FromType1);
1689 if (SCS2.First == ICK_Array_To_Pointer)
1690 FromType2 = Context.getArrayDecayedType(FromType2);
1691
Mike Stump11289f42009-09-09 15:08:12 +00001692 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001693 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001694 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001695 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001696
1697 if (IsDerivedFrom(FromPointee2, FromPointee1))
1698 return ImplicitConversionSequence::Better;
1699 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1700 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001701
1702 // Objective-C++: If one interface is more specific than the
1703 // other, it is the better one.
John McCall9dd450b2009-09-21 23:43:11 +00001704 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1705 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001706 if (FromIface1 && FromIface1) {
1707 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1708 return ImplicitConversionSequence::Better;
1709 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1710 return ImplicitConversionSequence::Worse;
1711 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001712 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001713
1714 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1715 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001716 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001717 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001718 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001719
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001720 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001721 // C++0x [over.ics.rank]p3b4:
1722 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1723 // implicit object parameter of a non-static member function declared
1724 // without a ref-qualifier, and S1 binds an rvalue reference to an
1725 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001726 // FIXME: We don't know if we're dealing with the implicit object parameter,
1727 // or if the member function in this case has a ref qualifier.
1728 // (Of course, we don't have ref qualifiers yet.)
1729 if (SCS1.RRefBinding != SCS2.RRefBinding)
1730 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1731 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001732
1733 // C++ [over.ics.rank]p3b4:
1734 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1735 // which the references refer are the same type except for
1736 // top-level cv-qualifiers, and the type to which the reference
1737 // initialized by S2 refers is more cv-qualified than the type
1738 // to which the reference initialized by S1 refers.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001739 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1740 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001741 T1 = Context.getCanonicalType(T1);
1742 T2 = Context.getCanonicalType(T2);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001743 if (Context.hasSameUnqualifiedType(T1, T2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001744 if (T2.isMoreQualifiedThan(T1))
1745 return ImplicitConversionSequence::Better;
1746 else if (T1.isMoreQualifiedThan(T2))
1747 return ImplicitConversionSequence::Worse;
1748 }
1749 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001750
1751 return ImplicitConversionSequence::Indistinguishable;
1752}
1753
1754/// CompareQualificationConversions - Compares two standard conversion
1755/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001756/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1757ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001758Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001759 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001760 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001761 // -- S1 and S2 differ only in their qualification conversion and
1762 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1763 // cv-qualification signature of type T1 is a proper subset of
1764 // the cv-qualification signature of type T2, and S1 is not the
1765 // deprecated string literal array-to-pointer conversion (4.2).
1766 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1767 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1768 return ImplicitConversionSequence::Indistinguishable;
1769
1770 // FIXME: the example in the standard doesn't use a qualification
1771 // conversion (!)
1772 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1773 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1774 T1 = Context.getCanonicalType(T1);
1775 T2 = Context.getCanonicalType(T2);
1776
1777 // If the types are the same, we won't learn anything by unwrapped
1778 // them.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001779 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001780 return ImplicitConversionSequence::Indistinguishable;
1781
Mike Stump11289f42009-09-09 15:08:12 +00001782 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001783 = ImplicitConversionSequence::Indistinguishable;
1784 while (UnwrapSimilarPointerTypes(T1, T2)) {
1785 // Within each iteration of the loop, we check the qualifiers to
1786 // determine if this still looks like a qualification
1787 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001788 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001789 // until there are no more pointers or pointers-to-members left
1790 // to unwrap. This essentially mimics what
1791 // IsQualificationConversion does, but here we're checking for a
1792 // strict subset of qualifiers.
1793 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1794 // The qualifiers are the same, so this doesn't tell us anything
1795 // about how the sequences rank.
1796 ;
1797 else if (T2.isMoreQualifiedThan(T1)) {
1798 // T1 has fewer qualifiers, so it could be the better sequence.
1799 if (Result == ImplicitConversionSequence::Worse)
1800 // Neither has qualifiers that are a subset of the other's
1801 // qualifiers.
1802 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001803
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001804 Result = ImplicitConversionSequence::Better;
1805 } else if (T1.isMoreQualifiedThan(T2)) {
1806 // T2 has fewer qualifiers, so it could be the better sequence.
1807 if (Result == ImplicitConversionSequence::Better)
1808 // Neither has qualifiers that are a subset of the other's
1809 // qualifiers.
1810 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001811
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001812 Result = ImplicitConversionSequence::Worse;
1813 } else {
1814 // Qualifiers are disjoint.
1815 return ImplicitConversionSequence::Indistinguishable;
1816 }
1817
1818 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001819 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001820 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001821 }
1822
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001823 // Check that the winning standard conversion sequence isn't using
1824 // the deprecated string literal array to pointer conversion.
1825 switch (Result) {
1826 case ImplicitConversionSequence::Better:
1827 if (SCS1.Deprecated)
1828 Result = ImplicitConversionSequence::Indistinguishable;
1829 break;
1830
1831 case ImplicitConversionSequence::Indistinguishable:
1832 break;
1833
1834 case ImplicitConversionSequence::Worse:
1835 if (SCS2.Deprecated)
1836 Result = ImplicitConversionSequence::Indistinguishable;
1837 break;
1838 }
1839
1840 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001841}
1842
Douglas Gregor5c407d92008-10-23 00:40:37 +00001843/// CompareDerivedToBaseConversions - Compares two standard conversion
1844/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00001845/// various kinds of derived-to-base conversions (C++
1846/// [over.ics.rank]p4b3). As part of these checks, we also look at
1847/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001848ImplicitConversionSequence::CompareKind
1849Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1850 const StandardConversionSequence& SCS2) {
1851 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1852 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1853 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1854 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1855
1856 // Adjust the types we're converting from via the array-to-pointer
1857 // conversion, if we need to.
1858 if (SCS1.First == ICK_Array_To_Pointer)
1859 FromType1 = Context.getArrayDecayedType(FromType1);
1860 if (SCS2.First == ICK_Array_To_Pointer)
1861 FromType2 = Context.getArrayDecayedType(FromType2);
1862
1863 // Canonicalize all of the types.
1864 FromType1 = Context.getCanonicalType(FromType1);
1865 ToType1 = Context.getCanonicalType(ToType1);
1866 FromType2 = Context.getCanonicalType(FromType2);
1867 ToType2 = Context.getCanonicalType(ToType2);
1868
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001869 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00001870 //
1871 // If class B is derived directly or indirectly from class A and
1872 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001873 //
1874 // For Objective-C, we let A, B, and C also be Objective-C
1875 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001876
1877 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00001878 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00001879 SCS2.Second == ICK_Pointer_Conversion &&
1880 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1881 FromType1->isPointerType() && FromType2->isPointerType() &&
1882 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001883 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001884 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001885 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001886 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001887 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001888 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001889 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001890 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001891
John McCall9dd450b2009-09-21 23:43:11 +00001892 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1893 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1894 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1895 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001896
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001897 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00001898 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1899 if (IsDerivedFrom(ToPointee1, ToPointee2))
1900 return ImplicitConversionSequence::Better;
1901 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1902 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001903
1904 if (ToIface1 && ToIface2) {
1905 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1906 return ImplicitConversionSequence::Better;
1907 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1908 return ImplicitConversionSequence::Worse;
1909 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001910 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001911
1912 // -- conversion of B* to A* is better than conversion of C* to A*,
1913 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1914 if (IsDerivedFrom(FromPointee2, FromPointee1))
1915 return ImplicitConversionSequence::Better;
1916 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1917 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00001918
Douglas Gregor237f96c2008-11-26 23:31:11 +00001919 if (FromIface1 && FromIface2) {
1920 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1921 return ImplicitConversionSequence::Better;
1922 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1923 return ImplicitConversionSequence::Worse;
1924 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001925 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001926 }
1927
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001928 // Compare based on reference bindings.
1929 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1930 SCS1.Second == ICK_Derived_To_Base) {
1931 // -- binding of an expression of type C to a reference of type
1932 // B& is better than binding an expression of type C to a
1933 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001934 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1935 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001936 if (IsDerivedFrom(ToType1, ToType2))
1937 return ImplicitConversionSequence::Better;
1938 else if (IsDerivedFrom(ToType2, ToType1))
1939 return ImplicitConversionSequence::Worse;
1940 }
1941
Douglas Gregor2fe98832008-11-03 19:09:14 +00001942 // -- binding of an expression of type B to a reference of type
1943 // A& is better than binding an expression of type C to a
1944 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001945 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1946 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001947 if (IsDerivedFrom(FromType2, FromType1))
1948 return ImplicitConversionSequence::Better;
1949 else if (IsDerivedFrom(FromType1, FromType2))
1950 return ImplicitConversionSequence::Worse;
1951 }
1952 }
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00001953
1954 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00001955 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
1956 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
1957 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
1958 const MemberPointerType * FromMemPointer1 =
1959 FromType1->getAs<MemberPointerType>();
1960 const MemberPointerType * ToMemPointer1 =
1961 ToType1->getAs<MemberPointerType>();
1962 const MemberPointerType * FromMemPointer2 =
1963 FromType2->getAs<MemberPointerType>();
1964 const MemberPointerType * ToMemPointer2 =
1965 ToType2->getAs<MemberPointerType>();
1966 const Type *FromPointeeType1 = FromMemPointer1->getClass();
1967 const Type *ToPointeeType1 = ToMemPointer1->getClass();
1968 const Type *FromPointeeType2 = FromMemPointer2->getClass();
1969 const Type *ToPointeeType2 = ToMemPointer2->getClass();
1970 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
1971 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
1972 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
1973 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00001974 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00001975 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1976 if (IsDerivedFrom(ToPointee1, ToPointee2))
1977 return ImplicitConversionSequence::Worse;
1978 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1979 return ImplicitConversionSequence::Better;
1980 }
1981 // conversion of B::* to C::* is better than conversion of A::* to C::*
1982 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
1983 if (IsDerivedFrom(FromPointee1, FromPointee2))
1984 return ImplicitConversionSequence::Better;
1985 else if (IsDerivedFrom(FromPointee2, FromPointee1))
1986 return ImplicitConversionSequence::Worse;
1987 }
1988 }
1989
Douglas Gregor2fe98832008-11-03 19:09:14 +00001990 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1991 SCS1.Second == ICK_Derived_To_Base) {
1992 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001993 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1994 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00001995 if (IsDerivedFrom(ToType1, ToType2))
1996 return ImplicitConversionSequence::Better;
1997 else if (IsDerivedFrom(ToType2, ToType1))
1998 return ImplicitConversionSequence::Worse;
1999 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002000
Douglas Gregor2fe98832008-11-03 19:09:14 +00002001 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002002 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2003 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002004 if (IsDerivedFrom(FromType2, FromType1))
2005 return ImplicitConversionSequence::Better;
2006 else if (IsDerivedFrom(FromType1, FromType2))
2007 return ImplicitConversionSequence::Worse;
2008 }
2009 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002010
Douglas Gregor5c407d92008-10-23 00:40:37 +00002011 return ImplicitConversionSequence::Indistinguishable;
2012}
2013
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002014/// TryCopyInitialization - Try to copy-initialize a value of type
2015/// ToType from the expression From. Return the implicit conversion
2016/// sequence required to pass this argument, which may be a bad
2017/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002018/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00002019/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2020/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00002021ImplicitConversionSequence
2022Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002023 bool SuppressUserConversions, bool ForceRValue,
2024 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002025 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002026 ImplicitConversionSequence ICS;
Mike Stump11289f42009-09-09 15:08:12 +00002027 CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002028 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002029 SuppressUserConversions,
2030 /*AllowExplicit=*/false,
2031 ForceRValue,
2032 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002033 return ICS;
2034 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002035 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002036 SuppressUserConversions,
2037 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002038 ForceRValue,
2039 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002040 }
2041}
2042
Sebastian Redl42e92c42009-04-12 17:16:29 +00002043/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2044/// the expression @p From. Returns true (and emits a diagnostic) if there was
2045/// an error, returns false if the initialization succeeded. Elidable should
2046/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2047/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00002048bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002049 const char* Flavor, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002050 if (!getLangOptions().CPlusPlus) {
2051 // In C, argument passing is the same as performing an assignment.
2052 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002053
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002054 AssignConvertType ConvTy =
2055 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002056 if (ConvTy != Compatible &&
2057 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2058 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00002059
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002060 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
2061 FromType, From, Flavor);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002062 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00002063
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002064 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00002065 return CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002066 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002067 /*SuppressUserConversions=*/false,
2068 /*AllowExplicit=*/false,
2069 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002070
Sebastian Redl42e92c42009-04-12 17:16:29 +00002071 if (!PerformImplicitConversion(From, ToType, Flavor,
2072 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002073 return false;
Fariborz Jahanian76197412009-11-18 18:26:29 +00002074 if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002075 return Diag(From->getSourceRange().getBegin(),
2076 diag::err_typecheck_convert_incompatible)
2077 << ToType << From->getType() << Flavor << From->getSourceRange();
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002078 return true;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002079}
2080
Douglas Gregor436424c2008-11-18 23:14:02 +00002081/// TryObjectArgumentInitialization - Try to initialize the object
2082/// parameter of the given member function (@c Method) from the
2083/// expression @p From.
2084ImplicitConversionSequence
John McCall6e9f8f62009-12-03 04:06:58 +00002085Sema::TryObjectArgumentInitialization(QualType FromType,
2086 CXXMethodDecl *Method,
2087 CXXRecordDecl *ActingContext) {
2088 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002089 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2090 // const volatile object.
2091 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2092 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2093 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002094
2095 // Set up the conversion sequence as a "bad" conversion, to allow us
2096 // to exit early.
2097 ImplicitConversionSequence ICS;
2098 ICS.Standard.setAsIdentityConversion();
2099 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2100
2101 // We need to have an object of class type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002102 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002103 FromType = PT->getPointeeType();
2104
2105 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002106
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002107 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002108 // where X is the class of which the function is a member
2109 // (C++ [over.match.funcs]p4). However, when finding an implicit
2110 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002111 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002112 // (C++ [over.match.funcs]p5). We perform a simplified version of
2113 // reference binding here, that allows class rvalues to bind to
2114 // non-constant references.
2115
2116 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2117 // with the implicit object parameter (C++ [over.match.funcs]p5).
2118 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002119 if (ImplicitParamType.getCVRQualifiers()
2120 != FromTypeCanon.getLocalCVRQualifiers() &&
Douglas Gregor01df9462009-11-05 00:07:36 +00002121 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon))
Douglas Gregor436424c2008-11-18 23:14:02 +00002122 return ICS;
2123
2124 // Check that we have either the same type or a derived type. It
2125 // affects the conversion rank.
2126 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002127 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType())
Douglas Gregor436424c2008-11-18 23:14:02 +00002128 ICS.Standard.Second = ICK_Identity;
2129 else if (IsDerivedFrom(FromType, ClassType))
2130 ICS.Standard.Second = ICK_Derived_To_Base;
2131 else
2132 return ICS;
2133
2134 // Success. Mark this as a reference binding.
2135 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2136 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2137 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2138 ICS.Standard.ReferenceBinding = true;
2139 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002140 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002141 return ICS;
2142}
2143
2144/// PerformObjectArgumentInitialization - Perform initialization of
2145/// the implicit object parameter for the given Method with the given
2146/// expression.
2147bool
2148Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002149 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002150 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002151 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002152
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002153 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002154 FromRecordType = PT->getPointeeType();
2155 DestType = Method->getThisType(Context);
2156 } else {
2157 FromRecordType = From->getType();
2158 DestType = ImplicitParamRecordType;
2159 }
2160
John McCall6e9f8f62009-12-03 04:06:58 +00002161 // Note that we always use the true parent context when performing
2162 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002163 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002164 = TryObjectArgumentInitialization(From->getType(), Method,
2165 Method->getParent());
Douglas Gregor436424c2008-11-18 23:14:02 +00002166 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2167 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002168 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002169 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002170
Douglas Gregor436424c2008-11-18 23:14:02 +00002171 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002172 CheckDerivedToBaseConversion(FromRecordType,
2173 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002174 From->getSourceRange().getBegin(),
2175 From->getSourceRange()))
2176 return true;
2177
Mike Stump11289f42009-09-09 15:08:12 +00002178 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002179 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002180 return false;
2181}
2182
Douglas Gregor5fb53972009-01-14 15:45:31 +00002183/// TryContextuallyConvertToBool - Attempt to contextually convert the
2184/// expression From to bool (C++0x [conv]p3).
2185ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002186 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002187 // FIXME: Are these flags correct?
2188 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002189 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002190 /*ForceRValue=*/false,
2191 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002192}
2193
2194/// PerformContextuallyConvertToBool - Perform a contextual conversion
2195/// of the expression From to bool (C++0x [conv]p3).
2196bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2197 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2198 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2199 return false;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002200
Fariborz Jahanian76197412009-11-18 18:26:29 +00002201 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002202 return Diag(From->getSourceRange().getBegin(),
2203 diag::err_typecheck_bool_condition)
2204 << From->getType() << From->getSourceRange();
2205 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002206}
2207
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002208/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002209/// candidate functions, using the given function call arguments. If
2210/// @p SuppressUserConversions, then don't allow user-defined
2211/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002212/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2213/// hacky way to implement the overloading rules for elidable copy
2214/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002215///
2216/// \para PartialOverloading true if we are performing "partial" overloading
2217/// based on an incomplete set of function arguments. This feature is used by
2218/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002219void
2220Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002221 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002222 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002223 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002224 bool ForceRValue,
2225 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002226 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002227 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002228 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002229 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002230 "Use AddConversionCandidate for conversion functions");
Mike Stump11289f42009-09-09 15:08:12 +00002231 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002232 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002233
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002234 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002235 if (!isa<CXXConstructorDecl>(Method)) {
2236 // If we get here, it's because we're calling a member function
2237 // that is named without a member access expression (e.g.,
2238 // "this->f") that was either written explicitly or created
2239 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00002240 // function, e.g., X::f(). We use an empty type for the implied
2241 // object argument (C++ [over.call.func]p3), and the acting context
2242 // is irrelevant.
2243 AddMethodCandidate(Method, Method->getParent(),
2244 QualType(), Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002245 SuppressUserConversions, ForceRValue);
2246 return;
2247 }
2248 // We treat a constructor like a non-member function, since its object
2249 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002250 }
2251
Douglas Gregorff7028a2009-11-13 23:59:09 +00002252 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002253 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002254
Douglas Gregor27381f32009-11-23 12:27:39 +00002255 // Overload resolution is always an unevaluated context.
2256 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2257
Douglas Gregorffe14e32009-11-14 01:20:54 +00002258 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2259 // C++ [class.copy]p3:
2260 // A member function template is never instantiated to perform the copy
2261 // of a class object to an object of its class type.
2262 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2263 if (NumArgs == 1 &&
2264 Constructor->isCopyConstructorLikeSpecialization() &&
2265 Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2266 return;
2267 }
2268
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002269 // Add this candidate
2270 CandidateSet.push_back(OverloadCandidate());
2271 OverloadCandidate& Candidate = CandidateSet.back();
2272 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002273 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002274 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002275 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002276
2277 unsigned NumArgsInProto = Proto->getNumArgs();
2278
2279 // (C++ 13.3.2p2): A candidate function having fewer than m
2280 // parameters is viable only if it has an ellipsis in its parameter
2281 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002282 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2283 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002284 Candidate.Viable = false;
2285 return;
2286 }
2287
2288 // (C++ 13.3.2p2): A candidate function having more than m parameters
2289 // is viable only if the (m+1)st parameter has a default argument
2290 // (8.3.6). For the purposes of overload resolution, the
2291 // parameter list is truncated on the right, so that there are
2292 // exactly m parameters.
2293 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002294 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002295 // Not enough arguments.
2296 Candidate.Viable = false;
2297 return;
2298 }
2299
2300 // Determine the implicit conversion sequences for each of the
2301 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002302 Candidate.Conversions.resize(NumArgs);
2303 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2304 if (ArgIdx < NumArgsInProto) {
2305 // (C++ 13.3.2p3): for F to be a viable function, there shall
2306 // exist for each argument an implicit conversion sequence
2307 // (13.3.3.1) that converts that argument to the corresponding
2308 // parameter of F.
2309 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002310 Candidate.Conversions[ArgIdx]
2311 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002312 SuppressUserConversions, ForceRValue,
2313 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002314 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002315 == ImplicitConversionSequence::BadConversion) {
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002316 // 13.3.3.1-p10 If several different sequences of conversions exist that
2317 // each convert the argument to the parameter type, the implicit conversion
2318 // sequence associated with the parameter is defined to be the unique conversion
2319 // sequence designated the ambiguous conversion sequence. For the purpose of
2320 // ranking implicit conversion sequences as described in 13.3.3.2, the ambiguous
2321 // conversion sequence is treated as a user-defined sequence that is
2322 // indistinguishable from any other user-defined conversion sequence
Fariborz Jahanian91ae9fd2009-09-29 17:31:54 +00002323 if (!Candidate.Conversions[ArgIdx].ConversionFunctionSet.empty()) {
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002324 Candidate.Conversions[ArgIdx].ConversionKind =
2325 ImplicitConversionSequence::UserDefinedConversion;
Fariborz Jahanian91ae9fd2009-09-29 17:31:54 +00002326 // Set the conversion function to one of them. As due to ambiguity,
2327 // they carry the same weight and is needed for overload resolution
2328 // later.
2329 Candidate.Conversions[ArgIdx].UserDefined.ConversionFunction =
2330 Candidate.Conversions[ArgIdx].ConversionFunctionSet[0];
2331 }
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002332 else {
2333 Candidate.Viable = false;
2334 break;
2335 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002336 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002337 } else {
2338 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2339 // argument for which there is no corresponding parameter is
2340 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002341 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002342 = ImplicitConversionSequence::EllipsisConversion;
2343 }
2344 }
2345}
2346
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002347/// \brief Add all of the function declarations in the given function set to
2348/// the overload canddiate set.
2349void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2350 Expr **Args, unsigned NumArgs,
2351 OverloadCandidateSet& CandidateSet,
2352 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002353 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002354 FEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00002355 F != FEnd; ++F) {
John McCall6e9f8f62009-12-03 04:06:58 +00002356 // FIXME: using declarations
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002357 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2358 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2359 AddMethodCandidate(cast<CXXMethodDecl>(FD),
John McCall6e9f8f62009-12-03 04:06:58 +00002360 cast<CXXMethodDecl>(FD)->getParent(),
2361 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002362 CandidateSet, SuppressUserConversions);
2363 else
2364 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2365 SuppressUserConversions);
2366 } else {
2367 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2368 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2369 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2370 AddMethodTemplateCandidate(FunTmpl,
John McCall6e9f8f62009-12-03 04:06:58 +00002371 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00002372 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00002373 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002374 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002375 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002376 else
2377 AddTemplateOverloadCandidate(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00002378 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002379 Args, NumArgs, CandidateSet,
2380 SuppressUserConversions);
2381 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002382 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002383}
2384
John McCallf0f1cf02009-11-17 07:50:12 +00002385/// AddMethodCandidate - Adds a named decl (which is some kind of
2386/// method) as a method candidate to the given overload set.
John McCall6e9f8f62009-12-03 04:06:58 +00002387void Sema::AddMethodCandidate(NamedDecl *Decl,
2388 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00002389 Expr **Args, unsigned NumArgs,
2390 OverloadCandidateSet& CandidateSet,
2391 bool SuppressUserConversions, bool ForceRValue) {
2392
2393 // FIXME: use this
John McCall6e9f8f62009-12-03 04:06:58 +00002394 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00002395
2396 if (isa<UsingShadowDecl>(Decl))
2397 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2398
2399 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2400 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2401 "Expected a member function template");
John McCall6e9f8f62009-12-03 04:06:58 +00002402 AddMethodTemplateCandidate(TD, ActingContext, /*ExplicitArgs*/ 0,
2403 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002404 CandidateSet,
2405 SuppressUserConversions,
2406 ForceRValue);
2407 } else {
John McCall6e9f8f62009-12-03 04:06:58 +00002408 AddMethodCandidate(cast<CXXMethodDecl>(Decl), ActingContext,
2409 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00002410 CandidateSet, SuppressUserConversions, ForceRValue);
2411 }
2412}
2413
Douglas Gregor436424c2008-11-18 23:14:02 +00002414/// AddMethodCandidate - Adds the given C++ member function to the set
2415/// of candidate functions, using the given function call arguments
2416/// and the object argument (@c Object). For example, in a call
2417/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2418/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2419/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002420/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2421/// a slightly hacky way to implement the overloading rules for elidable copy
2422/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002423void
John McCall6e9f8f62009-12-03 04:06:58 +00002424Sema::AddMethodCandidate(CXXMethodDecl *Method, CXXRecordDecl *ActingContext,
2425 QualType ObjectType, Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00002426 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002427 bool SuppressUserConversions, bool ForceRValue) {
2428 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002429 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002430 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002431 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor436424c2008-11-18 23:14:02 +00002432 "Use AddConversionCandidate for conversion functions");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002433 assert(!isa<CXXConstructorDecl>(Method) &&
2434 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002435
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002436 if (!CandidateSet.isNewCandidate(Method))
2437 return;
2438
Douglas Gregor27381f32009-11-23 12:27:39 +00002439 // Overload resolution is always an unevaluated context.
2440 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2441
Douglas Gregor436424c2008-11-18 23:14:02 +00002442 // Add this candidate
2443 CandidateSet.push_back(OverloadCandidate());
2444 OverloadCandidate& Candidate = CandidateSet.back();
2445 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002446 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002447 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002448
2449 unsigned NumArgsInProto = Proto->getNumArgs();
2450
2451 // (C++ 13.3.2p2): A candidate function having fewer than m
2452 // parameters is viable only if it has an ellipsis in its parameter
2453 // list (8.3.5).
2454 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2455 Candidate.Viable = false;
2456 return;
2457 }
2458
2459 // (C++ 13.3.2p2): A candidate function having more than m parameters
2460 // is viable only if the (m+1)st parameter has a default argument
2461 // (8.3.6). For the purposes of overload resolution, the
2462 // parameter list is truncated on the right, so that there are
2463 // exactly m parameters.
2464 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2465 if (NumArgs < MinRequiredArgs) {
2466 // Not enough arguments.
2467 Candidate.Viable = false;
2468 return;
2469 }
2470
2471 Candidate.Viable = true;
2472 Candidate.Conversions.resize(NumArgs + 1);
2473
John McCall6e9f8f62009-12-03 04:06:58 +00002474 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002475 // The implicit object argument is ignored.
2476 Candidate.IgnoreObjectArgument = true;
2477 else {
2478 // Determine the implicit conversion sequence for the object
2479 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00002480 Candidate.Conversions[0]
2481 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
Mike Stump11289f42009-09-09 15:08:12 +00002482 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002483 == ImplicitConversionSequence::BadConversion) {
2484 Candidate.Viable = false;
2485 return;
2486 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002487 }
2488
2489 // Determine the implicit conversion sequences for each of the
2490 // arguments.
2491 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2492 if (ArgIdx < NumArgsInProto) {
2493 // (C++ 13.3.2p3): for F to be a viable function, there shall
2494 // exist for each argument an implicit conversion sequence
2495 // (13.3.3.1) that converts that argument to the corresponding
2496 // parameter of F.
2497 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002498 Candidate.Conversions[ArgIdx + 1]
2499 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002500 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002501 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002502 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002503 == ImplicitConversionSequence::BadConversion) {
2504 Candidate.Viable = false;
2505 break;
2506 }
2507 } else {
2508 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2509 // argument for which there is no corresponding parameter is
2510 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002511 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002512 = ImplicitConversionSequence::EllipsisConversion;
2513 }
2514 }
2515}
2516
Douglas Gregor97628d62009-08-21 00:16:32 +00002517/// \brief Add a C++ member function template as a candidate to the candidate
2518/// set, using template argument deduction to produce an appropriate member
2519/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002520void
Douglas Gregor97628d62009-08-21 00:16:32 +00002521Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall6e9f8f62009-12-03 04:06:58 +00002522 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00002523 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00002524 QualType ObjectType,
2525 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002526 OverloadCandidateSet& CandidateSet,
2527 bool SuppressUserConversions,
2528 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002529 if (!CandidateSet.isNewCandidate(MethodTmpl))
2530 return;
2531
Douglas Gregor97628d62009-08-21 00:16:32 +00002532 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002533 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002534 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002535 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002536 // candidate functions in the usual way.113) A given name can refer to one
2537 // or more function templates and also to a set of overloaded non-template
2538 // functions. In such a case, the candidate functions generated from each
2539 // function template are combined with the set of non-template candidate
2540 // functions.
2541 TemplateDeductionInfo Info(Context);
2542 FunctionDecl *Specialization = 0;
2543 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002544 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002545 Args, NumArgs, Specialization, Info)) {
2546 // FIXME: Record what happened with template argument deduction, so
2547 // that we can give the user a beautiful diagnostic.
2548 (void)Result;
2549 return;
2550 }
Mike Stump11289f42009-09-09 15:08:12 +00002551
Douglas Gregor97628d62009-08-21 00:16:32 +00002552 // Add the function template specialization produced by template argument
2553 // deduction as a candidate.
2554 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002555 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002556 "Specialization is not a member function?");
John McCall6e9f8f62009-12-03 04:06:58 +00002557 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), ActingContext,
2558 ObjectType, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002559 CandidateSet, SuppressUserConversions, ForceRValue);
2560}
2561
Douglas Gregor05155d82009-08-21 23:19:43 +00002562/// \brief Add a C++ function template specialization as a candidate
2563/// in the candidate set, using template argument deduction to produce
2564/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002565void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002566Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00002567 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002568 Expr **Args, unsigned NumArgs,
2569 OverloadCandidateSet& CandidateSet,
2570 bool SuppressUserConversions,
2571 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002572 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2573 return;
2574
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002575 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002576 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002577 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002578 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002579 // candidate functions in the usual way.113) A given name can refer to one
2580 // or more function templates and also to a set of overloaded non-template
2581 // functions. In such a case, the candidate functions generated from each
2582 // function template are combined with the set of non-template candidate
2583 // functions.
2584 TemplateDeductionInfo Info(Context);
2585 FunctionDecl *Specialization = 0;
2586 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00002587 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00002588 Args, NumArgs, Specialization, Info)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002589 // FIXME: Record what happened with template argument deduction, so
2590 // that we can give the user a beautiful diagnostic.
2591 (void)Result;
2592 return;
2593 }
Mike Stump11289f42009-09-09 15:08:12 +00002594
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002595 // Add the function template specialization produced by template argument
2596 // deduction as a candidate.
2597 assert(Specialization && "Missing function template specialization?");
2598 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2599 SuppressUserConversions, ForceRValue);
2600}
Mike Stump11289f42009-09-09 15:08:12 +00002601
Douglas Gregora1f013e2008-11-07 22:36:19 +00002602/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002603/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002604/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002605/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002606/// (which may or may not be the same type as the type that the
2607/// conversion function produces).
2608void
2609Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall6e9f8f62009-12-03 04:06:58 +00002610 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002611 Expr *From, QualType ToType,
2612 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002613 assert(!Conversion->getDescribedFunctionTemplate() &&
2614 "Conversion function templates use AddTemplateConversionCandidate");
2615
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002616 if (!CandidateSet.isNewCandidate(Conversion))
2617 return;
2618
Douglas Gregor27381f32009-11-23 12:27:39 +00002619 // Overload resolution is always an unevaluated context.
2620 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2621
Douglas Gregora1f013e2008-11-07 22:36:19 +00002622 // Add this candidate
2623 CandidateSet.push_back(OverloadCandidate());
2624 OverloadCandidate& Candidate = CandidateSet.back();
2625 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002626 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002627 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002628 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00002629 Candidate.FinalConversion.FromTypePtr
Douglas Gregora1f013e2008-11-07 22:36:19 +00002630 = Conversion->getConversionType().getAsOpaquePtr();
2631 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2632
Douglas Gregor436424c2008-11-18 23:14:02 +00002633 // Determine the implicit conversion sequence for the implicit
2634 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002635 Candidate.Viable = true;
2636 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00002637 Candidate.Conversions[0]
2638 = TryObjectArgumentInitialization(From->getType(), Conversion,
2639 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002640 // Conversion functions to a different type in the base class is visible in
2641 // the derived class. So, a derived to base conversion should not participate
2642 // in overload resolution.
2643 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2644 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump11289f42009-09-09 15:08:12 +00002645 if (Candidate.Conversions[0].ConversionKind
Douglas Gregora1f013e2008-11-07 22:36:19 +00002646 == ImplicitConversionSequence::BadConversion) {
2647 Candidate.Viable = false;
2648 return;
2649 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002650
2651 // We won't go through a user-define type conversion function to convert a
2652 // derived to base as such conversions are given Conversion Rank. They only
2653 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2654 QualType FromCanon
2655 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2656 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2657 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2658 Candidate.Viable = false;
2659 return;
2660 }
2661
Douglas Gregora1f013e2008-11-07 22:36:19 +00002662
2663 // To determine what the conversion from the result of calling the
2664 // conversion function to the type we're eventually trying to
2665 // convert to (ToType), we need to synthesize a call to the
2666 // conversion function and attempt copy initialization from it. This
2667 // makes sure that we get the right semantics with respect to
2668 // lvalues/rvalues and the type. Fortunately, we can allocate this
2669 // call on the stack and we don't need its arguments to be
2670 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002671 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002672 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00002673 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00002674 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00002675 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002676
2677 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002678 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2679 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002680 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002681 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00002682 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00002683 ImplicitConversionSequence ICS =
2684 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002685 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002686 /*ForceRValue=*/false,
2687 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002688
Douglas Gregora1f013e2008-11-07 22:36:19 +00002689 switch (ICS.ConversionKind) {
2690 case ImplicitConversionSequence::StandardConversion:
2691 Candidate.FinalConversion = ICS.Standard;
2692 break;
2693
2694 case ImplicitConversionSequence::BadConversion:
2695 Candidate.Viable = false;
2696 break;
2697
2698 default:
Mike Stump11289f42009-09-09 15:08:12 +00002699 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002700 "Can only end up with a standard conversion sequence or failure");
2701 }
2702}
2703
Douglas Gregor05155d82009-08-21 23:19:43 +00002704/// \brief Adds a conversion function template specialization
2705/// candidate to the overload set, using template argument deduction
2706/// to deduce the template arguments of the conversion function
2707/// template from the type that we are converting to (C++
2708/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002709void
Douglas Gregor05155d82009-08-21 23:19:43 +00002710Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall6e9f8f62009-12-03 04:06:58 +00002711 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00002712 Expr *From, QualType ToType,
2713 OverloadCandidateSet &CandidateSet) {
2714 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2715 "Only conversion function templates permitted here");
2716
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002717 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2718 return;
2719
Douglas Gregor05155d82009-08-21 23:19:43 +00002720 TemplateDeductionInfo Info(Context);
2721 CXXConversionDecl *Specialization = 0;
2722 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002723 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002724 Specialization, Info)) {
2725 // FIXME: Record what happened with template argument deduction, so
2726 // that we can give the user a beautiful diagnostic.
2727 (void)Result;
2728 return;
2729 }
Mike Stump11289f42009-09-09 15:08:12 +00002730
Douglas Gregor05155d82009-08-21 23:19:43 +00002731 // Add the conversion function template specialization produced by
2732 // template argument deduction as a candidate.
2733 assert(Specialization && "Missing function template specialization?");
John McCall6e9f8f62009-12-03 04:06:58 +00002734 AddConversionCandidate(Specialization, ActingDC, From, ToType, CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00002735}
2736
Douglas Gregorab7897a2008-11-19 22:57:39 +00002737/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2738/// converts the given @c Object to a function pointer via the
2739/// conversion function @c Conversion, and then attempts to call it
2740/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2741/// the type of function that we'll eventually be calling.
2742void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall6e9f8f62009-12-03 04:06:58 +00002743 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002744 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00002745 QualType ObjectType,
2746 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002747 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002748 if (!CandidateSet.isNewCandidate(Conversion))
2749 return;
2750
Douglas Gregor27381f32009-11-23 12:27:39 +00002751 // Overload resolution is always an unevaluated context.
2752 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2753
Douglas Gregorab7897a2008-11-19 22:57:39 +00002754 CandidateSet.push_back(OverloadCandidate());
2755 OverloadCandidate& Candidate = CandidateSet.back();
2756 Candidate.Function = 0;
2757 Candidate.Surrogate = Conversion;
2758 Candidate.Viable = true;
2759 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002760 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002761 Candidate.Conversions.resize(NumArgs + 1);
2762
2763 // Determine the implicit conversion sequence for the implicit
2764 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002765 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00002766 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
Douglas Gregorab7897a2008-11-19 22:57:39 +00002767 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2768 Candidate.Viable = false;
2769 return;
2770 }
2771
2772 // The first conversion is actually a user-defined conversion whose
2773 // first conversion is ObjectInit's standard conversion (which is
2774 // effectively a reference binding). Record it as such.
Mike Stump11289f42009-09-09 15:08:12 +00002775 Candidate.Conversions[0].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002776 = ImplicitConversionSequence::UserDefinedConversion;
2777 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002778 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002779 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002780 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002781 = Candidate.Conversions[0].UserDefined.Before;
2782 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2783
Mike Stump11289f42009-09-09 15:08:12 +00002784 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002785 unsigned NumArgsInProto = Proto->getNumArgs();
2786
2787 // (C++ 13.3.2p2): A candidate function having fewer than m
2788 // parameters is viable only if it has an ellipsis in its parameter
2789 // list (8.3.5).
2790 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2791 Candidate.Viable = false;
2792 return;
2793 }
2794
2795 // Function types don't have any default arguments, so just check if
2796 // we have enough arguments.
2797 if (NumArgs < NumArgsInProto) {
2798 // Not enough arguments.
2799 Candidate.Viable = false;
2800 return;
2801 }
2802
2803 // Determine the implicit conversion sequences for each of the
2804 // arguments.
2805 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2806 if (ArgIdx < NumArgsInProto) {
2807 // (C++ 13.3.2p3): for F to be a viable function, there shall
2808 // exist for each argument an implicit conversion sequence
2809 // (13.3.3.1) that converts that argument to the corresponding
2810 // parameter of F.
2811 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002812 Candidate.Conversions[ArgIdx + 1]
2813 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002814 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002815 /*ForceRValue=*/false,
2816 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002817 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002818 == ImplicitConversionSequence::BadConversion) {
2819 Candidate.Viable = false;
2820 break;
2821 }
2822 } else {
2823 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2824 // argument for which there is no corresponding parameter is
2825 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002826 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002827 = ImplicitConversionSequence::EllipsisConversion;
2828 }
2829 }
2830}
2831
Mike Stump87c57ac2009-05-16 07:39:55 +00002832// FIXME: This will eventually be removed, once we've migrated all of the
2833// operator overloading logic over to the scheme used by binary operators, which
2834// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002835void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002836 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00002837 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002838 OverloadCandidateSet& CandidateSet,
2839 SourceRange OpRange) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002840 FunctionSet Functions;
2841
2842 QualType T1 = Args[0]->getType();
2843 QualType T2;
2844 if (NumArgs > 1)
2845 T2 = Args[1]->getType();
2846
2847 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002848 if (S)
2849 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Sebastian Redlc057f422009-10-23 19:23:15 +00002850 ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002851 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2852 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002853 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002854}
2855
2856/// \brief Add overload candidates for overloaded operators that are
2857/// member functions.
2858///
2859/// Add the overloaded operator candidates that are member functions
2860/// for the operator Op that was used in an operator expression such
2861/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2862/// CandidateSet will store the added overload candidates. (C++
2863/// [over.match.oper]).
2864void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2865 SourceLocation OpLoc,
2866 Expr **Args, unsigned NumArgs,
2867 OverloadCandidateSet& CandidateSet,
2868 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002869 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2870
2871 // C++ [over.match.oper]p3:
2872 // For a unary operator @ with an operand of a type whose
2873 // cv-unqualified version is T1, and for a binary operator @ with
2874 // a left operand of a type whose cv-unqualified version is T1 and
2875 // a right operand of a type whose cv-unqualified version is T2,
2876 // three sets of candidate functions, designated member
2877 // candidates, non-member candidates and built-in candidates, are
2878 // constructed as follows:
2879 QualType T1 = Args[0]->getType();
2880 QualType T2;
2881 if (NumArgs > 1)
2882 T2 = Args[1]->getType();
2883
2884 // -- If T1 is a class type, the set of member candidates is the
2885 // result of the qualified lookup of T1::operator@
2886 // (13.3.1.1.1); otherwise, the set of member candidates is
2887 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002888 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002889 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00002890 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002891 return;
Mike Stump11289f42009-09-09 15:08:12 +00002892
John McCall27b18f82009-11-17 02:14:36 +00002893 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
2894 LookupQualifiedName(Operators, T1Rec->getDecl());
2895 Operators.suppressDiagnostics();
2896
Mike Stump11289f42009-09-09 15:08:12 +00002897 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002898 OperEnd = Operators.end();
2899 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00002900 ++Oper)
John McCall6e9f8f62009-12-03 04:06:58 +00002901 AddMethodCandidate(*Oper, Args[0]->getType(),
2902 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00002903 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00002904 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002905}
2906
Douglas Gregora11693b2008-11-12 17:17:38 +00002907/// AddBuiltinCandidate - Add a candidate for a built-in
2908/// operator. ResultTy and ParamTys are the result and parameter types
2909/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00002910/// arguments being passed to the candidate. IsAssignmentOperator
2911/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00002912/// operator. NumContextualBoolArguments is the number of arguments
2913/// (at the beginning of the argument list) that will be contextually
2914/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00002915void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00002916 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00002917 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002918 bool IsAssignmentOperator,
2919 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00002920 // Overload resolution is always an unevaluated context.
2921 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2922
Douglas Gregora11693b2008-11-12 17:17:38 +00002923 // Add this candidate
2924 CandidateSet.push_back(OverloadCandidate());
2925 OverloadCandidate& Candidate = CandidateSet.back();
2926 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00002927 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002928 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00002929 Candidate.BuiltinTypes.ResultTy = ResultTy;
2930 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2931 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2932
2933 // Determine the implicit conversion sequences for each of the
2934 // arguments.
2935 Candidate.Viable = true;
2936 Candidate.Conversions.resize(NumArgs);
2937 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00002938 // C++ [over.match.oper]p4:
2939 // For the built-in assignment operators, conversions of the
2940 // left operand are restricted as follows:
2941 // -- no temporaries are introduced to hold the left operand, and
2942 // -- no user-defined conversions are applied to the left
2943 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00002944 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00002945 //
2946 // We block these conversions by turning off user-defined
2947 // conversions, since that is the only way that initialization of
2948 // a reference to a non-class type can occur from something that
2949 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002950 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00002951 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00002952 "Contextual conversion to bool requires bool type");
2953 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2954 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002955 Candidate.Conversions[ArgIdx]
2956 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00002957 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00002958 /*ForceRValue=*/false,
2959 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002960 }
Mike Stump11289f42009-09-09 15:08:12 +00002961 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002962 == ImplicitConversionSequence::BadConversion) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002963 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002964 break;
2965 }
Douglas Gregora11693b2008-11-12 17:17:38 +00002966 }
2967}
2968
2969/// BuiltinCandidateTypeSet - A set of types that will be used for the
2970/// candidate operator functions for built-in operators (C++
2971/// [over.built]). The types are separated into pointer types and
2972/// enumeration types.
2973class BuiltinCandidateTypeSet {
2974 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002975 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00002976
2977 /// PointerTypes - The set of pointer types that will be used in the
2978 /// built-in candidates.
2979 TypeSet PointerTypes;
2980
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002981 /// MemberPointerTypes - The set of member pointer types that will be
2982 /// used in the built-in candidates.
2983 TypeSet MemberPointerTypes;
2984
Douglas Gregora11693b2008-11-12 17:17:38 +00002985 /// EnumerationTypes - The set of enumeration types that will be
2986 /// used in the built-in candidates.
2987 TypeSet EnumerationTypes;
2988
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002989 /// Sema - The semantic analysis instance where we are building the
2990 /// candidate type set.
2991 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00002992
Douglas Gregora11693b2008-11-12 17:17:38 +00002993 /// Context - The AST context in which we will build the type sets.
2994 ASTContext &Context;
2995
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00002996 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
2997 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002998 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00002999
3000public:
3001 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003002 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003003
Mike Stump11289f42009-09-09 15:08:12 +00003004 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003005 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003006
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003007 void AddTypesConvertedFrom(QualType Ty,
3008 SourceLocation Loc,
3009 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003010 bool AllowExplicitConversions,
3011 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003012
3013 /// pointer_begin - First pointer type found;
3014 iterator pointer_begin() { return PointerTypes.begin(); }
3015
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003016 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003017 iterator pointer_end() { return PointerTypes.end(); }
3018
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003019 /// member_pointer_begin - First member pointer type found;
3020 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3021
3022 /// member_pointer_end - Past the last member pointer type found;
3023 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3024
Douglas Gregora11693b2008-11-12 17:17:38 +00003025 /// enumeration_begin - First enumeration type found;
3026 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3027
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003028 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003029 iterator enumeration_end() { return EnumerationTypes.end(); }
3030};
3031
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003032/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003033/// the set of pointer types along with any more-qualified variants of
3034/// that type. For example, if @p Ty is "int const *", this routine
3035/// will add "int const *", "int const volatile *", "int const
3036/// restrict *", and "int const volatile restrict *" to the set of
3037/// pointer types. Returns true if the add of @p Ty itself succeeded,
3038/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003039///
3040/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003041bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003042BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3043 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003044
Douglas Gregora11693b2008-11-12 17:17:38 +00003045 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003046 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003047 return false;
3048
John McCall8ccfcb52009-09-24 19:53:00 +00003049 const PointerType *PointerTy = Ty->getAs<PointerType>();
3050 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003051
John McCall8ccfcb52009-09-24 19:53:00 +00003052 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003053 // Don't add qualified variants of arrays. For one, they're not allowed
3054 // (the qualifier would sink to the element type), and for another, the
3055 // only overload situation where it matters is subscript or pointer +- int,
3056 // and those shouldn't have qualifier variants anyway.
3057 if (PointeeTy->isArrayType())
3058 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003059 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003060 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003061 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003062 bool hasVolatile = VisibleQuals.hasVolatile();
3063 bool hasRestrict = VisibleQuals.hasRestrict();
3064
John McCall8ccfcb52009-09-24 19:53:00 +00003065 // Iterate through all strict supersets of BaseCVR.
3066 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3067 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003068 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3069 // in the types.
3070 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3071 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003072 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3073 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003074 }
3075
3076 return true;
3077}
3078
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003079/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3080/// to the set of pointer types along with any more-qualified variants of
3081/// that type. For example, if @p Ty is "int const *", this routine
3082/// will add "int const *", "int const volatile *", "int const
3083/// restrict *", and "int const volatile restrict *" to the set of
3084/// pointer types. Returns true if the add of @p Ty itself succeeded,
3085/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003086///
3087/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003088bool
3089BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3090 QualType Ty) {
3091 // Insert this type.
3092 if (!MemberPointerTypes.insert(Ty))
3093 return false;
3094
John McCall8ccfcb52009-09-24 19:53:00 +00003095 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3096 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003097
John McCall8ccfcb52009-09-24 19:53:00 +00003098 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003099 // Don't add qualified variants of arrays. For one, they're not allowed
3100 // (the qualifier would sink to the element type), and for another, the
3101 // only overload situation where it matters is subscript or pointer +- int,
3102 // and those shouldn't have qualifier variants anyway.
3103 if (PointeeTy->isArrayType())
3104 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003105 const Type *ClassTy = PointerTy->getClass();
3106
3107 // Iterate through all strict supersets of the pointee type's CVR
3108 // qualifiers.
3109 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3110 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3111 if ((CVR | BaseCVR) != CVR) continue;
3112
3113 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3114 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003115 }
3116
3117 return true;
3118}
3119
Douglas Gregora11693b2008-11-12 17:17:38 +00003120/// AddTypesConvertedFrom - Add each of the types to which the type @p
3121/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003122/// primarily interested in pointer types and enumeration types. We also
3123/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003124/// AllowUserConversions is true if we should look at the conversion
3125/// functions of a class type, and AllowExplicitConversions if we
3126/// should also include the explicit conversion functions of a class
3127/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003128void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003129BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003130 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003131 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003132 bool AllowExplicitConversions,
3133 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003134 // Only deal with canonical types.
3135 Ty = Context.getCanonicalType(Ty);
3136
3137 // Look through reference types; they aren't part of the type of an
3138 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003139 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003140 Ty = RefTy->getPointeeType();
3141
3142 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003143 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003144
Sebastian Redl65ae2002009-11-05 16:36:20 +00003145 // If we're dealing with an array type, decay to the pointer.
3146 if (Ty->isArrayType())
3147 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3148
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003149 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003150 QualType PointeeTy = PointerTy->getPointeeType();
3151
3152 // Insert our type, and its more-qualified variants, into the set
3153 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003154 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003155 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003156 } else if (Ty->isMemberPointerType()) {
3157 // Member pointers are far easier, since the pointee can't be converted.
3158 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3159 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003160 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003161 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003162 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003163 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003164 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003165 // No conversion functions in incomplete types.
3166 return;
3167 }
Mike Stump11289f42009-09-09 15:08:12 +00003168
Douglas Gregora11693b2008-11-12 17:17:38 +00003169 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalld14a8642009-11-21 08:51:07 +00003170 const UnresolvedSet *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003171 = ClassDecl->getVisibleConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00003172 for (UnresolvedSet::iterator I = Conversions->begin(),
3173 E = Conversions->end(); I != E; ++I) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003174
Mike Stump11289f42009-09-09 15:08:12 +00003175 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003176 // about which builtin types we can convert to.
John McCalld14a8642009-11-21 08:51:07 +00003177 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor05155d82009-08-21 23:19:43 +00003178 continue;
3179
John McCalld14a8642009-11-21 08:51:07 +00003180 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003181 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003182 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003183 VisibleQuals);
3184 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003185 }
3186 }
3187 }
3188}
3189
Douglas Gregor84605ae2009-08-24 13:43:27 +00003190/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3191/// the volatile- and non-volatile-qualified assignment operators for the
3192/// given type to the candidate set.
3193static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3194 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003195 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003196 unsigned NumArgs,
3197 OverloadCandidateSet &CandidateSet) {
3198 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003199
Douglas Gregor84605ae2009-08-24 13:43:27 +00003200 // T& operator=(T&, T)
3201 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3202 ParamTypes[1] = T;
3203 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3204 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003205
Douglas Gregor84605ae2009-08-24 13:43:27 +00003206 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3207 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003208 ParamTypes[0]
3209 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003210 ParamTypes[1] = T;
3211 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003212 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003213 }
3214}
Mike Stump11289f42009-09-09 15:08:12 +00003215
Sebastian Redl1054fae2009-10-25 17:03:50 +00003216/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3217/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003218static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3219 Qualifiers VRQuals;
3220 const RecordType *TyRec;
3221 if (const MemberPointerType *RHSMPType =
3222 ArgExpr->getType()->getAs<MemberPointerType>())
3223 TyRec = cast<RecordType>(RHSMPType->getClass());
3224 else
3225 TyRec = ArgExpr->getType()->getAs<RecordType>();
3226 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003227 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003228 VRQuals.addVolatile();
3229 VRQuals.addRestrict();
3230 return VRQuals;
3231 }
3232
3233 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalld14a8642009-11-21 08:51:07 +00003234 const UnresolvedSet *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003235 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003236
John McCalld14a8642009-11-21 08:51:07 +00003237 for (UnresolvedSet::iterator I = Conversions->begin(),
3238 E = Conversions->end(); I != E; ++I) {
3239 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003240 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3241 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3242 CanTy = ResTypeRef->getPointeeType();
3243 // Need to go down the pointer/mempointer chain and add qualifiers
3244 // as see them.
3245 bool done = false;
3246 while (!done) {
3247 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3248 CanTy = ResTypePtr->getPointeeType();
3249 else if (const MemberPointerType *ResTypeMPtr =
3250 CanTy->getAs<MemberPointerType>())
3251 CanTy = ResTypeMPtr->getPointeeType();
3252 else
3253 done = true;
3254 if (CanTy.isVolatileQualified())
3255 VRQuals.addVolatile();
3256 if (CanTy.isRestrictQualified())
3257 VRQuals.addRestrict();
3258 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3259 return VRQuals;
3260 }
3261 }
3262 }
3263 return VRQuals;
3264}
3265
Douglas Gregord08452f2008-11-19 15:42:04 +00003266/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3267/// operator overloads to the candidate set (C++ [over.built]), based
3268/// on the operator @p Op and the arguments given. For example, if the
3269/// operator is a binary '+', this routine might add "int
3270/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003271void
Mike Stump11289f42009-09-09 15:08:12 +00003272Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003273 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003274 Expr **Args, unsigned NumArgs,
3275 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003276 // The set of "promoted arithmetic types", which are the arithmetic
3277 // types are that preserved by promotion (C++ [over.built]p2). Note
3278 // that the first few of these types are the promoted integral
3279 // types; these types need to be first.
3280 // FIXME: What about complex?
3281 const unsigned FirstIntegralType = 0;
3282 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003283 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003284 LastPromotedIntegralType = 13;
3285 const unsigned FirstPromotedArithmeticType = 7,
3286 LastPromotedArithmeticType = 16;
3287 const unsigned NumArithmeticTypes = 16;
3288 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003289 Context.BoolTy, Context.CharTy, Context.WCharTy,
3290// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003291 Context.SignedCharTy, Context.ShortTy,
3292 Context.UnsignedCharTy, Context.UnsignedShortTy,
3293 Context.IntTy, Context.LongTy, Context.LongLongTy,
3294 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3295 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3296 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003297 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3298 "Invalid first promoted integral type");
3299 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3300 == Context.UnsignedLongLongTy &&
3301 "Invalid last promoted integral type");
3302 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3303 "Invalid first promoted arithmetic type");
3304 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3305 == Context.LongDoubleTy &&
3306 "Invalid last promoted arithmetic type");
3307
Douglas Gregora11693b2008-11-12 17:17:38 +00003308 // Find all of the types that the arguments can convert to, but only
3309 // if the operator we're looking at has built-in operator candidates
3310 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003311 Qualifiers VisibleTypeConversionsQuals;
3312 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003313 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3314 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3315
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003316 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003317 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3318 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003319 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003320 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003321 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003322 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003323 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003324 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003325 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003326 true,
3327 (Op == OO_Exclaim ||
3328 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003329 Op == OO_PipePipe),
3330 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003331 }
3332
3333 bool isComparison = false;
3334 switch (Op) {
3335 case OO_None:
3336 case NUM_OVERLOADED_OPERATORS:
3337 assert(false && "Expected an overloaded operator");
3338 break;
3339
Douglas Gregord08452f2008-11-19 15:42:04 +00003340 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003341 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003342 goto UnaryStar;
3343 else
3344 goto BinaryStar;
3345 break;
3346
3347 case OO_Plus: // '+' is either unary or binary
3348 if (NumArgs == 1)
3349 goto UnaryPlus;
3350 else
3351 goto BinaryPlus;
3352 break;
3353
3354 case OO_Minus: // '-' is either unary or binary
3355 if (NumArgs == 1)
3356 goto UnaryMinus;
3357 else
3358 goto BinaryMinus;
3359 break;
3360
3361 case OO_Amp: // '&' is either unary or binary
3362 if (NumArgs == 1)
3363 goto UnaryAmp;
3364 else
3365 goto BinaryAmp;
3366
3367 case OO_PlusPlus:
3368 case OO_MinusMinus:
3369 // C++ [over.built]p3:
3370 //
3371 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3372 // is either volatile or empty, there exist candidate operator
3373 // functions of the form
3374 //
3375 // VQ T& operator++(VQ T&);
3376 // T operator++(VQ T&, int);
3377 //
3378 // C++ [over.built]p4:
3379 //
3380 // For every pair (T, VQ), where T is an arithmetic type other
3381 // than bool, and VQ is either volatile or empty, there exist
3382 // candidate operator functions of the form
3383 //
3384 // VQ T& operator--(VQ T&);
3385 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003386 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003387 Arith < NumArithmeticTypes; ++Arith) {
3388 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003389 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003390 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003391
3392 // Non-volatile version.
3393 if (NumArgs == 1)
3394 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3395 else
3396 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003397 // heuristic to reduce number of builtin candidates in the set.
3398 // Add volatile version only if there are conversions to a volatile type.
3399 if (VisibleTypeConversionsQuals.hasVolatile()) {
3400 // Volatile version
3401 ParamTypes[0]
3402 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3403 if (NumArgs == 1)
3404 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3405 else
3406 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3407 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003408 }
3409
3410 // C++ [over.built]p5:
3411 //
3412 // For every pair (T, VQ), where T is a cv-qualified or
3413 // cv-unqualified object type, and VQ is either volatile or
3414 // empty, there exist candidate operator functions of the form
3415 //
3416 // T*VQ& operator++(T*VQ&);
3417 // T*VQ& operator--(T*VQ&);
3418 // T* operator++(T*VQ&, int);
3419 // T* operator--(T*VQ&, int);
3420 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3421 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3422 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003423 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003424 continue;
3425
Mike Stump11289f42009-09-09 15:08:12 +00003426 QualType ParamTypes[2] = {
3427 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003428 };
Mike Stump11289f42009-09-09 15:08:12 +00003429
Douglas Gregord08452f2008-11-19 15:42:04 +00003430 // Without volatile
3431 if (NumArgs == 1)
3432 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3433 else
3434 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3435
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003436 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3437 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003438 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003439 ParamTypes[0]
3440 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003441 if (NumArgs == 1)
3442 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3443 else
3444 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3445 }
3446 }
3447 break;
3448
3449 UnaryStar:
3450 // C++ [over.built]p6:
3451 // For every cv-qualified or cv-unqualified object type T, there
3452 // exist candidate operator functions of the form
3453 //
3454 // T& operator*(T*);
3455 //
3456 // C++ [over.built]p7:
3457 // For every function type T, there exist candidate operator
3458 // functions of the form
3459 // T& operator*(T*);
3460 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3461 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3462 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003463 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003464 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003465 &ParamTy, Args, 1, CandidateSet);
3466 }
3467 break;
3468
3469 UnaryPlus:
3470 // C++ [over.built]p8:
3471 // For every type T, there exist candidate operator functions of
3472 // the form
3473 //
3474 // T* operator+(T*);
3475 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3476 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3477 QualType ParamTy = *Ptr;
3478 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3479 }
Mike Stump11289f42009-09-09 15:08:12 +00003480
Douglas Gregord08452f2008-11-19 15:42:04 +00003481 // Fall through
3482
3483 UnaryMinus:
3484 // C++ [over.built]p9:
3485 // For every promoted arithmetic type T, there exist candidate
3486 // operator functions of the form
3487 //
3488 // T operator+(T);
3489 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003490 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003491 Arith < LastPromotedArithmeticType; ++Arith) {
3492 QualType ArithTy = ArithmeticTypes[Arith];
3493 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3494 }
3495 break;
3496
3497 case OO_Tilde:
3498 // C++ [over.built]p10:
3499 // For every promoted integral type T, there exist candidate
3500 // operator functions of the form
3501 //
3502 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003503 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003504 Int < LastPromotedIntegralType; ++Int) {
3505 QualType IntTy = ArithmeticTypes[Int];
3506 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3507 }
3508 break;
3509
Douglas Gregora11693b2008-11-12 17:17:38 +00003510 case OO_New:
3511 case OO_Delete:
3512 case OO_Array_New:
3513 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003514 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003515 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003516 break;
3517
3518 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003519 UnaryAmp:
3520 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003521 // C++ [over.match.oper]p3:
3522 // -- For the operator ',', the unary operator '&', or the
3523 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003524 break;
3525
Douglas Gregor84605ae2009-08-24 13:43:27 +00003526 case OO_EqualEqual:
3527 case OO_ExclaimEqual:
3528 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003529 // For every pointer to member type T, there exist candidate operator
3530 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003531 //
3532 // bool operator==(T,T);
3533 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003534 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003535 MemPtr = CandidateTypes.member_pointer_begin(),
3536 MemPtrEnd = CandidateTypes.member_pointer_end();
3537 MemPtr != MemPtrEnd;
3538 ++MemPtr) {
3539 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3540 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3541 }
Mike Stump11289f42009-09-09 15:08:12 +00003542
Douglas Gregor84605ae2009-08-24 13:43:27 +00003543 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003544
Douglas Gregora11693b2008-11-12 17:17:38 +00003545 case OO_Less:
3546 case OO_Greater:
3547 case OO_LessEqual:
3548 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003549 // C++ [over.built]p15:
3550 //
3551 // For every pointer or enumeration type T, there exist
3552 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003553 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003554 // bool operator<(T, T);
3555 // bool operator>(T, T);
3556 // bool operator<=(T, T);
3557 // bool operator>=(T, T);
3558 // bool operator==(T, T);
3559 // bool operator!=(T, T);
3560 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3561 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3562 QualType ParamTypes[2] = { *Ptr, *Ptr };
3563 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3564 }
Mike Stump11289f42009-09-09 15:08:12 +00003565 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003566 = CandidateTypes.enumeration_begin();
3567 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3568 QualType ParamTypes[2] = { *Enum, *Enum };
3569 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3570 }
3571
3572 // Fall through.
3573 isComparison = true;
3574
Douglas Gregord08452f2008-11-19 15:42:04 +00003575 BinaryPlus:
3576 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003577 if (!isComparison) {
3578 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3579
3580 // C++ [over.built]p13:
3581 //
3582 // For every cv-qualified or cv-unqualified object type T
3583 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003584 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003585 // T* operator+(T*, ptrdiff_t);
3586 // T& operator[](T*, ptrdiff_t); [BELOW]
3587 // T* operator-(T*, ptrdiff_t);
3588 // T* operator+(ptrdiff_t, T*);
3589 // T& operator[](ptrdiff_t, T*); [BELOW]
3590 //
3591 // C++ [over.built]p14:
3592 //
3593 // For every T, where T is a pointer to object type, there
3594 // exist candidate operator functions of the form
3595 //
3596 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003597 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003598 = CandidateTypes.pointer_begin();
3599 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3600 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3601
3602 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3603 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3604
3605 if (Op == OO_Plus) {
3606 // T* operator+(ptrdiff_t, T*);
3607 ParamTypes[0] = ParamTypes[1];
3608 ParamTypes[1] = *Ptr;
3609 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3610 } else {
3611 // ptrdiff_t operator-(T, T);
3612 ParamTypes[1] = *Ptr;
3613 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3614 Args, 2, CandidateSet);
3615 }
3616 }
3617 }
3618 // Fall through
3619
Douglas Gregora11693b2008-11-12 17:17:38 +00003620 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003621 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003622 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003623 // C++ [over.built]p12:
3624 //
3625 // For every pair of promoted arithmetic types L and R, there
3626 // exist candidate operator functions of the form
3627 //
3628 // LR operator*(L, R);
3629 // LR operator/(L, R);
3630 // LR operator+(L, R);
3631 // LR operator-(L, R);
3632 // bool operator<(L, R);
3633 // bool operator>(L, R);
3634 // bool operator<=(L, R);
3635 // bool operator>=(L, R);
3636 // bool operator==(L, R);
3637 // bool operator!=(L, R);
3638 //
3639 // where LR is the result of the usual arithmetic conversions
3640 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003641 //
3642 // C++ [over.built]p24:
3643 //
3644 // For every pair of promoted arithmetic types L and R, there exist
3645 // candidate operator functions of the form
3646 //
3647 // LR operator?(bool, L, R);
3648 //
3649 // where LR is the result of the usual arithmetic conversions
3650 // between types L and R.
3651 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003652 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003653 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003654 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003655 Right < LastPromotedArithmeticType; ++Right) {
3656 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003657 QualType Result
3658 = isComparison
3659 ? Context.BoolTy
3660 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003661 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3662 }
3663 }
3664 break;
3665
3666 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003667 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003668 case OO_Caret:
3669 case OO_Pipe:
3670 case OO_LessLess:
3671 case OO_GreaterGreater:
3672 // C++ [over.built]p17:
3673 //
3674 // For every pair of promoted integral types L and R, there
3675 // exist candidate operator functions of the form
3676 //
3677 // LR operator%(L, R);
3678 // LR operator&(L, R);
3679 // LR operator^(L, R);
3680 // LR operator|(L, R);
3681 // L operator<<(L, R);
3682 // L operator>>(L, R);
3683 //
3684 // where LR is the result of the usual arithmetic conversions
3685 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003686 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003687 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003688 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003689 Right < LastPromotedIntegralType; ++Right) {
3690 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3691 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3692 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003693 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003694 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3695 }
3696 }
3697 break;
3698
3699 case OO_Equal:
3700 // C++ [over.built]p20:
3701 //
3702 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003703 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003704 // empty, there exist candidate operator functions of the form
3705 //
3706 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003707 for (BuiltinCandidateTypeSet::iterator
3708 Enum = CandidateTypes.enumeration_begin(),
3709 EnumEnd = CandidateTypes.enumeration_end();
3710 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003711 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003712 CandidateSet);
3713 for (BuiltinCandidateTypeSet::iterator
3714 MemPtr = CandidateTypes.member_pointer_begin(),
3715 MemPtrEnd = CandidateTypes.member_pointer_end();
3716 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003717 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003718 CandidateSet);
3719 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003720
3721 case OO_PlusEqual:
3722 case OO_MinusEqual:
3723 // C++ [over.built]p19:
3724 //
3725 // For every pair (T, VQ), where T is any type and VQ is either
3726 // volatile or empty, there exist candidate operator functions
3727 // of the form
3728 //
3729 // T*VQ& operator=(T*VQ&, T*);
3730 //
3731 // C++ [over.built]p21:
3732 //
3733 // For every pair (T, VQ), where T is a cv-qualified or
3734 // cv-unqualified object type and VQ is either volatile or
3735 // empty, there exist candidate operator functions of the form
3736 //
3737 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3738 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3739 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3740 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3741 QualType ParamTypes[2];
3742 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3743
3744 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003745 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003746 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3747 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003748
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003749 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3750 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003751 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003752 ParamTypes[0]
3753 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00003754 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3755 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003756 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003757 }
3758 // Fall through.
3759
3760 case OO_StarEqual:
3761 case OO_SlashEqual:
3762 // C++ [over.built]p18:
3763 //
3764 // For every triple (L, VQ, R), where L is an arithmetic type,
3765 // VQ is either volatile or empty, and R is a promoted
3766 // arithmetic type, there exist candidate operator functions of
3767 // the form
3768 //
3769 // VQ L& operator=(VQ L&, R);
3770 // VQ L& operator*=(VQ L&, R);
3771 // VQ L& operator/=(VQ L&, R);
3772 // VQ L& operator+=(VQ L&, R);
3773 // VQ L& operator-=(VQ L&, R);
3774 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003775 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003776 Right < LastPromotedArithmeticType; ++Right) {
3777 QualType ParamTypes[2];
3778 ParamTypes[1] = ArithmeticTypes[Right];
3779
3780 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003781 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003782 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3783 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003784
3785 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003786 if (VisibleTypeConversionsQuals.hasVolatile()) {
3787 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3788 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3789 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3790 /*IsAssigmentOperator=*/Op == OO_Equal);
3791 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003792 }
3793 }
3794 break;
3795
3796 case OO_PercentEqual:
3797 case OO_LessLessEqual:
3798 case OO_GreaterGreaterEqual:
3799 case OO_AmpEqual:
3800 case OO_CaretEqual:
3801 case OO_PipeEqual:
3802 // C++ [over.built]p22:
3803 //
3804 // For every triple (L, VQ, R), where L is an integral type, VQ
3805 // is either volatile or empty, and R is a promoted integral
3806 // type, there exist candidate operator functions of the form
3807 //
3808 // VQ L& operator%=(VQ L&, R);
3809 // VQ L& operator<<=(VQ L&, R);
3810 // VQ L& operator>>=(VQ L&, R);
3811 // VQ L& operator&=(VQ L&, R);
3812 // VQ L& operator^=(VQ L&, R);
3813 // VQ L& operator|=(VQ L&, R);
3814 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003815 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003816 Right < LastPromotedIntegralType; ++Right) {
3817 QualType ParamTypes[2];
3818 ParamTypes[1] = ArithmeticTypes[Right];
3819
3820 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003821 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003822 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00003823 if (VisibleTypeConversionsQuals.hasVolatile()) {
3824 // Add this built-in operator as a candidate (VQ is 'volatile').
3825 ParamTypes[0] = ArithmeticTypes[Left];
3826 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3827 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3828 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3829 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003830 }
3831 }
3832 break;
3833
Douglas Gregord08452f2008-11-19 15:42:04 +00003834 case OO_Exclaim: {
3835 // C++ [over.operator]p23:
3836 //
3837 // There also exist candidate operator functions of the form
3838 //
Mike Stump11289f42009-09-09 15:08:12 +00003839 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00003840 // bool operator&&(bool, bool); [BELOW]
3841 // bool operator||(bool, bool); [BELOW]
3842 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003843 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3844 /*IsAssignmentOperator=*/false,
3845 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003846 break;
3847 }
3848
Douglas Gregora11693b2008-11-12 17:17:38 +00003849 case OO_AmpAmp:
3850 case OO_PipePipe: {
3851 // C++ [over.operator]p23:
3852 //
3853 // There also exist candidate operator functions of the form
3854 //
Douglas Gregord08452f2008-11-19 15:42:04 +00003855 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00003856 // bool operator&&(bool, bool);
3857 // bool operator||(bool, bool);
3858 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00003859 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3860 /*IsAssignmentOperator=*/false,
3861 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00003862 break;
3863 }
3864
3865 case OO_Subscript:
3866 // C++ [over.built]p13:
3867 //
3868 // For every cv-qualified or cv-unqualified object type T there
3869 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003870 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003871 // T* operator+(T*, ptrdiff_t); [ABOVE]
3872 // T& operator[](T*, ptrdiff_t);
3873 // T* operator-(T*, ptrdiff_t); [ABOVE]
3874 // T* operator+(ptrdiff_t, T*); [ABOVE]
3875 // T& operator[](ptrdiff_t, T*);
3876 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3877 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3878 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003879 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003880 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00003881
3882 // T& operator[](T*, ptrdiff_t)
3883 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3884
3885 // T& operator[](ptrdiff_t, T*);
3886 ParamTypes[0] = ParamTypes[1];
3887 ParamTypes[1] = *Ptr;
3888 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3889 }
3890 break;
3891
3892 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003893 // C++ [over.built]p11:
3894 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
3895 // C1 is the same type as C2 or is a derived class of C2, T is an object
3896 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
3897 // there exist candidate operator functions of the form
3898 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
3899 // where CV12 is the union of CV1 and CV2.
3900 {
3901 for (BuiltinCandidateTypeSet::iterator Ptr =
3902 CandidateTypes.pointer_begin();
3903 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3904 QualType C1Ty = (*Ptr);
3905 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003906 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003907 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003908 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003909 if (!isa<RecordType>(C1))
3910 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003911 // heuristic to reduce number of builtin candidates in the set.
3912 // Add volatile/restrict version only if there are conversions to a
3913 // volatile/restrict type.
3914 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
3915 continue;
3916 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
3917 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003918 }
3919 for (BuiltinCandidateTypeSet::iterator
3920 MemPtr = CandidateTypes.member_pointer_begin(),
3921 MemPtrEnd = CandidateTypes.member_pointer_end();
3922 MemPtr != MemPtrEnd; ++MemPtr) {
3923 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
3924 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00003925 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003926 if (C1 != C2 && !IsDerivedFrom(C1, C2))
3927 break;
3928 QualType ParamTypes[2] = { *Ptr, *MemPtr };
3929 // build CV12 T&
3930 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003931 if (!VisibleTypeConversionsQuals.hasVolatile() &&
3932 T.isVolatileQualified())
3933 continue;
3934 if (!VisibleTypeConversionsQuals.hasRestrict() &&
3935 T.isRestrictQualified())
3936 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003937 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003938 QualType ResultTy = Context.getLValueReferenceType(T);
3939 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3940 }
3941 }
3942 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003943 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003944
3945 case OO_Conditional:
3946 // Note that we don't consider the first argument, since it has been
3947 // contextually converted to bool long ago. The candidates below are
3948 // therefore added as binary.
3949 //
3950 // C++ [over.built]p24:
3951 // For every type T, where T is a pointer or pointer-to-member type,
3952 // there exist candidate operator functions of the form
3953 //
3954 // T operator?(bool, T, T);
3955 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00003956 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3957 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3958 QualType ParamTypes[2] = { *Ptr, *Ptr };
3959 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3960 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003961 for (BuiltinCandidateTypeSet::iterator Ptr =
3962 CandidateTypes.member_pointer_begin(),
3963 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3964 QualType ParamTypes[2] = { *Ptr, *Ptr };
3965 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3966 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003967 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00003968 }
3969}
3970
Douglas Gregore254f902009-02-04 00:32:51 +00003971/// \brief Add function candidates found via argument-dependent lookup
3972/// to the set of overloading candidates.
3973///
3974/// This routine performs argument-dependent name lookup based on the
3975/// given function name (which may also be an operator name) and adds
3976/// all of the overload candidates found by ADL to the overload
3977/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00003978void
Douglas Gregore254f902009-02-04 00:32:51 +00003979Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3980 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00003981 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00003982 OverloadCandidateSet& CandidateSet,
3983 bool PartialOverloading) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003984 FunctionSet Functions;
Douglas Gregore254f902009-02-04 00:32:51 +00003985
Douglas Gregorcabea402009-09-22 15:41:20 +00003986 // FIXME: Should we be trafficking in canonical function decls throughout?
3987
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003988 // Record all of the function candidates that we've already
3989 // added to the overload set, so that we don't add those same
3990 // candidates a second time.
3991 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3992 CandEnd = CandidateSet.end();
3993 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003994 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003995 Functions.insert(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003996 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3997 Functions.insert(FunTmpl);
3998 }
Douglas Gregore254f902009-02-04 00:32:51 +00003999
Douglas Gregorcabea402009-09-22 15:41:20 +00004000 // FIXME: Pass in the explicit template arguments?
Sebastian Redlc057f422009-10-23 19:23:15 +00004001 ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
Douglas Gregore254f902009-02-04 00:32:51 +00004002
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004003 // Erase all of the candidates we already knew about.
4004 // FIXME: This is suboptimal. Is there a better way?
4005 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4006 CandEnd = CandidateSet.end();
4007 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004008 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004009 Functions.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004010 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4011 Functions.erase(FunTmpl);
4012 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004013
4014 // For each of the ADL candidates we found, add it to the overload
4015 // set.
4016 for (FunctionSet::iterator Func = Functions.begin(),
4017 FuncEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00004018 Func != FuncEnd; ++Func) {
Douglas Gregorcabea402009-09-22 15:41:20 +00004019 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
John McCall6b51f282009-11-23 01:53:49 +00004020 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004021 continue;
4022
4023 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
4024 false, false, PartialOverloading);
4025 } else
Mike Stump11289f42009-09-09 15:08:12 +00004026 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregorcabea402009-09-22 15:41:20 +00004027 ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004028 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004029 }
Douglas Gregore254f902009-02-04 00:32:51 +00004030}
4031
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004032/// isBetterOverloadCandidate - Determines whether the first overload
4033/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004034bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004035Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump11289f42009-09-09 15:08:12 +00004036 const OverloadCandidate& Cand2) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004037 // Define viable functions to be better candidates than non-viable
4038 // functions.
4039 if (!Cand2.Viable)
4040 return Cand1.Viable;
4041 else if (!Cand1.Viable)
4042 return false;
4043
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004044 // C++ [over.match.best]p1:
4045 //
4046 // -- if F is a static member function, ICS1(F) is defined such
4047 // that ICS1(F) is neither better nor worse than ICS1(G) for
4048 // any function G, and, symmetrically, ICS1(G) is neither
4049 // better nor worse than ICS1(F).
4050 unsigned StartArg = 0;
4051 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4052 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004053
Douglas Gregord3cb3562009-07-07 23:38:56 +00004054 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004055 // A viable function F1 is defined to be a better function than another
4056 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004057 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004058 unsigned NumArgs = Cand1.Conversions.size();
4059 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4060 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004061 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004062 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4063 Cand2.Conversions[ArgIdx])) {
4064 case ImplicitConversionSequence::Better:
4065 // Cand1 has a better conversion sequence.
4066 HasBetterConversion = true;
4067 break;
4068
4069 case ImplicitConversionSequence::Worse:
4070 // Cand1 can't be better than Cand2.
4071 return false;
4072
4073 case ImplicitConversionSequence::Indistinguishable:
4074 // Do nothing.
4075 break;
4076 }
4077 }
4078
Mike Stump11289f42009-09-09 15:08:12 +00004079 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004080 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004081 if (HasBetterConversion)
4082 return true;
4083
Mike Stump11289f42009-09-09 15:08:12 +00004084 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004085 // specialization, or, if not that,
4086 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4087 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4088 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004089
4090 // -- F1 and F2 are function template specializations, and the function
4091 // template for F1 is more specialized than the template for F2
4092 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004093 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004094 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4095 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004096 if (FunctionTemplateDecl *BetterTemplate
4097 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4098 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor6010da02009-09-14 23:02:14 +00004099 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4100 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004101 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004102
Douglas Gregora1f013e2008-11-07 22:36:19 +00004103 // -- the context is an initialization by user-defined conversion
4104 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4105 // from the return type of F1 to the destination type (i.e.,
4106 // the type of the entity being initialized) is a better
4107 // conversion sequence than the standard conversion sequence
4108 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004109 if (Cand1.Function && Cand2.Function &&
4110 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004111 isa<CXXConversionDecl>(Cand2.Function)) {
4112 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4113 Cand2.FinalConversion)) {
4114 case ImplicitConversionSequence::Better:
4115 // Cand1 has a better conversion sequence.
4116 return true;
4117
4118 case ImplicitConversionSequence::Worse:
4119 // Cand1 can't be better than Cand2.
4120 return false;
4121
4122 case ImplicitConversionSequence::Indistinguishable:
4123 // Do nothing
4124 break;
4125 }
4126 }
4127
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004128 return false;
4129}
4130
Mike Stump11289f42009-09-09 15:08:12 +00004131/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004132/// within an overload candidate set.
4133///
4134/// \param CandidateSet the set of candidate functions.
4135///
4136/// \param Loc the location of the function name (or operator symbol) for
4137/// which overload resolution occurs.
4138///
Mike Stump11289f42009-09-09 15:08:12 +00004139/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004140/// function, Best points to the candidate function found.
4141///
4142/// \returns The result of overload resolution.
Mike Stump11289f42009-09-09 15:08:12 +00004143Sema::OverloadingResult
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004144Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004145 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004146 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004147 // Find the best viable function.
4148 Best = CandidateSet.end();
4149 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4150 Cand != CandidateSet.end(); ++Cand) {
4151 if (Cand->Viable) {
4152 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4153 Best = Cand;
4154 }
4155 }
4156
4157 // If we didn't find any viable functions, abort.
4158 if (Best == CandidateSet.end())
4159 return OR_No_Viable_Function;
4160
4161 // Make sure that this function is better than every other viable
4162 // function. If not, we have an ambiguity.
4163 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4164 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004165 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004166 Cand != Best &&
Douglas Gregorab7897a2008-11-19 22:57:39 +00004167 !isBetterOverloadCandidate(*Best, *Cand)) {
4168 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004169 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004170 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004171 }
Mike Stump11289f42009-09-09 15:08:12 +00004172
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004173 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004174 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004175 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004176 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004177 return OR_Deleted;
4178
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004179 // C++ [basic.def.odr]p2:
4180 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004181 // when referred to from a potentially-evaluated expression. [Note: this
4182 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004183 // (clause 13), user-defined conversions (12.3.2), allocation function for
4184 // placement new (5.3.4), as well as non-default initialization (8.5).
4185 if (Best->Function)
4186 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004187 return OR_Success;
4188}
4189
4190/// PrintOverloadCandidates - When overload resolution fails, prints
4191/// diagnostic messages containing the candidates in the candidate
4192/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump11289f42009-09-09 15:08:12 +00004193void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004194Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004195 bool OnlyViable,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004196 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004197 SourceLocation OpLoc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004198 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4199 LastCand = CandidateSet.end();
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004200 bool Reported = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004201 for (; Cand != LastCand; ++Cand) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004202 if (Cand->Viable || !OnlyViable) {
4203 if (Cand->Function) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00004204 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004205 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00004206 // Deleted or "unavailable" function.
4207 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
4208 << Cand->Function->isDeleted();
Douglas Gregor4fb9cde8e2009-09-15 20:11:42 +00004209 } else if (FunctionTemplateDecl *FunTmpl
4210 = Cand->Function->getPrimaryTemplate()) {
4211 // Function template specialization
4212 // FIXME: Give a better reason!
4213 Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
4214 << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
4215 *Cand->Function->getTemplateSpecializationArgs());
Douglas Gregor171c45a2009-02-18 21:56:37 +00004216 } else {
4217 // Normal function
Fariborz Jahanian21ccf062009-09-23 00:58:07 +00004218 bool errReported = false;
4219 if (!Cand->Viable && Cand->Conversions.size() > 0) {
4220 for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
4221 const ImplicitConversionSequence &Conversion =
4222 Cand->Conversions[i];
4223 if ((Conversion.ConversionKind !=
4224 ImplicitConversionSequence::BadConversion) ||
4225 Conversion.ConversionFunctionSet.size() == 0)
4226 continue;
4227 Diag(Cand->Function->getLocation(),
4228 diag::err_ovl_candidate_not_viable) << (i+1);
4229 errReported = true;
4230 for (int j = Conversion.ConversionFunctionSet.size()-1;
4231 j >= 0; j--) {
4232 FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
4233 Diag(Func->getLocation(), diag::err_ovl_candidate);
4234 }
4235 }
4236 }
4237 if (!errReported)
4238 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor171c45a2009-02-18 21:56:37 +00004239 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00004240 } else if (Cand->IsSurrogate) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004241 // Desugar the type of the surrogate down to a function type,
4242 // retaining as many typedefs as possible while still showing
4243 // the function type (and, therefore, its parameter types).
4244 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004245 bool isLValueReference = false;
4246 bool isRValueReference = false;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004247 bool isPointer = false;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004248 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004249 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004250 FnType = FnTypeRef->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004251 isLValueReference = true;
4252 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004253 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004254 FnType = FnTypeRef->getPointeeType();
4255 isRValueReference = true;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004256 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004257 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004258 FnType = FnTypePtr->getPointeeType();
4259 isPointer = true;
4260 }
4261 // Desugar down to a function type.
John McCall9dd450b2009-09-21 23:43:11 +00004262 FnType = QualType(FnType->getAs<FunctionType>(), 0);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004263 // Reconstruct the pointer/reference as appropriate.
4264 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004265 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
4266 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004267
Douglas Gregorab7897a2008-11-19 22:57:39 +00004268 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004269 << FnType;
Douglas Gregor66950a32009-09-30 21:46:01 +00004270 } else if (OnlyViable) {
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004271 assert(Cand->Conversions.size() <= 2 &&
Fariborz Jahanian0fe5e032009-10-09 17:09:58 +00004272 "builtin-binary-operator-not-binary");
Fariborz Jahanian956127d2009-10-16 23:25:02 +00004273 std::string TypeStr("operator");
4274 TypeStr += Opc;
4275 TypeStr += "(";
4276 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4277 if (Cand->Conversions.size() == 1) {
4278 TypeStr += ")";
4279 Diag(OpLoc, diag::err_ovl_builtin_unary_candidate) << TypeStr;
4280 }
4281 else {
4282 TypeStr += ", ";
4283 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4284 TypeStr += ")";
4285 Diag(OpLoc, diag::err_ovl_builtin_binary_candidate) << TypeStr;
4286 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004287 }
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004288 else if (!Cand->Viable && !Reported) {
4289 // Non-viability might be due to ambiguous user-defined conversions,
4290 // needed for built-in operators. Report them as well, but only once
4291 // as we have typically many built-in candidates.
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004292 unsigned NoOperands = Cand->Conversions.size();
4293 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004294 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
4295 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion ||
4296 ICS.ConversionFunctionSet.empty())
4297 continue;
4298 if (CXXConversionDecl *Func = dyn_cast<CXXConversionDecl>(
4299 Cand->Conversions[ArgIdx].ConversionFunctionSet[0])) {
4300 QualType FromTy =
4301 QualType(
4302 static_cast<Type*>(ICS.UserDefined.Before.FromTypePtr),0);
4303 Diag(OpLoc,diag::note_ambiguous_type_conversion)
4304 << FromTy << Func->getConversionType();
4305 }
4306 for (unsigned j = 0; j < ICS.ConversionFunctionSet.size(); j++) {
4307 FunctionDecl *Func =
4308 Cand->Conversions[ArgIdx].ConversionFunctionSet[j];
4309 Diag(Func->getLocation(),diag::err_ovl_candidate);
4310 }
4311 }
4312 Reported = true;
4313 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004314 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004315 }
4316}
4317
Douglas Gregorcd695e52008-11-10 20:40:00 +00004318/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4319/// an overloaded function (C++ [over.over]), where @p From is an
4320/// expression with overloaded function type and @p ToType is the type
4321/// we're trying to resolve to. For example:
4322///
4323/// @code
4324/// int f(double);
4325/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00004326///
Douglas Gregorcd695e52008-11-10 20:40:00 +00004327/// int (*pfd)(double) = f; // selects f(double)
4328/// @endcode
4329///
4330/// This routine returns the resulting FunctionDecl if it could be
4331/// resolved, and NULL otherwise. When @p Complain is true, this
4332/// routine will emit diagnostics if there is an error.
4333FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004334Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004335 bool Complain) {
4336 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004337 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004338 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004339 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004340 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00004341 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004342 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004343 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004344 FunctionType = MemTypePtr->getPointeeType();
4345 IsMember = true;
4346 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004347
4348 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00004349 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00004350 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004351 return 0;
4352
4353 // Find the actual overloaded function declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004354
Douglas Gregorcd695e52008-11-10 20:40:00 +00004355 // C++ [over.over]p1:
4356 // [...] [Note: any redundant set of parentheses surrounding the
4357 // overloaded function name is ignored (5.1). ]
4358 Expr *OvlExpr = From->IgnoreParens();
4359
4360 // C++ [over.over]p1:
4361 // [...] The overloaded function name can be preceded by the &
4362 // operator.
4363 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4364 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4365 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4366 }
4367
Anders Carlssonb68b0282009-10-20 22:53:47 +00004368 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00004369 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCalld14a8642009-11-21 08:51:07 +00004370
4371 llvm::SmallVector<NamedDecl*,8> Fns;
Anders Carlssonb68b0282009-10-20 22:53:47 +00004372
John McCall10eae182009-11-30 22:42:35 +00004373 // Look into the overloaded expression.
John McCalle66edc12009-11-24 19:00:30 +00004374 if (UnresolvedLookupExpr *UL
John McCalld14a8642009-11-21 08:51:07 +00004375 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4376 Fns.append(UL->decls_begin(), UL->decls_end());
John McCalle66edc12009-11-24 19:00:30 +00004377 if (UL->hasExplicitTemplateArgs()) {
4378 HasExplicitTemplateArgs = true;
4379 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4380 }
John McCall10eae182009-11-30 22:42:35 +00004381 } else if (UnresolvedMemberExpr *ME
4382 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4383 Fns.append(ME->decls_begin(), ME->decls_end());
4384 if (ME->hasExplicitTemplateArgs()) {
4385 HasExplicitTemplateArgs = true;
John McCall6b51f282009-11-23 01:53:49 +00004386 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00004387 }
Douglas Gregor9b146582009-07-08 20:55:45 +00004388 }
Mike Stump11289f42009-09-09 15:08:12 +00004389
John McCalld14a8642009-11-21 08:51:07 +00004390 // If we didn't actually find anything, we're done.
4391 if (Fns.empty())
4392 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004393
Douglas Gregorcd695e52008-11-10 20:40:00 +00004394 // Look through all of the overloaded functions, searching for one
4395 // whose type matches exactly.
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004396 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004397 bool FoundNonTemplateFunction = false;
John McCalld14a8642009-11-21 08:51:07 +00004398 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4399 E = Fns.end(); I != E; ++I) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00004400 // C++ [over.over]p3:
4401 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00004402 // targets of type "pointer-to-function" or "reference-to-function."
4403 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004404 // type "pointer-to-member-function."
4405 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00004406
Mike Stump11289f42009-09-09 15:08:12 +00004407 if (FunctionTemplateDecl *FunctionTemplate
John McCalld14a8642009-11-21 08:51:07 +00004408 = dyn_cast<FunctionTemplateDecl>(*I)) {
Mike Stump11289f42009-09-09 15:08:12 +00004409 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004410 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00004411 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004412 // static when converting to member pointer.
4413 if (Method->isStatic() == IsMember)
4414 continue;
4415 } else if (IsMember)
4416 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004417
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004418 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004419 // If the name is a function template, template argument deduction is
4420 // done (14.8.2.2), and if the argument deduction succeeds, the
4421 // resulting template argument list is used to generate a single
4422 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004423 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004424 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00004425 FunctionDecl *Specialization = 0;
4426 TemplateDeductionInfo Info(Context);
4427 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004428 = DeduceTemplateArguments(FunctionTemplate,
4429 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
Douglas Gregor9b146582009-07-08 20:55:45 +00004430 FunctionType, Specialization, Info)) {
4431 // FIXME: make a note of the failed deduction for diagnostics.
4432 (void)Result;
4433 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004434 // FIXME: If the match isn't exact, shouldn't we just drop this as
4435 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00004436 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00004437 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004438 Matches.insert(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004439 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor9b146582009-07-08 20:55:45 +00004440 }
John McCalld14a8642009-11-21 08:51:07 +00004441
4442 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00004443 }
Mike Stump11289f42009-09-09 15:08:12 +00004444
John McCalld14a8642009-11-21 08:51:07 +00004445 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004446 // Skip non-static functions when converting to pointer, and static
4447 // when converting to member pointer.
4448 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004449 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00004450
4451 // If we have explicit template arguments, skip non-templates.
4452 if (HasExplicitTemplateArgs)
4453 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004454 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004455 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00004456
John McCalld14a8642009-11-21 08:51:07 +00004457 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*I)) {
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004458 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
John McCalld14a8642009-11-21 08:51:07 +00004459 Matches.insert(cast<FunctionDecl>(FunDecl->getCanonicalDecl()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004460 FoundNonTemplateFunction = true;
4461 }
Mike Stump11289f42009-09-09 15:08:12 +00004462 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004463 }
4464
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004465 // If there were 0 or 1 matches, we're done.
4466 if (Matches.empty())
4467 return 0;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004468 else if (Matches.size() == 1) {
4469 FunctionDecl *Result = *Matches.begin();
4470 MarkDeclarationReferenced(From->getLocStart(), Result);
4471 return Result;
4472 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004473
4474 // C++ [over.over]p4:
4475 // If more than one function is selected, [...]
Douglas Gregor05155d82009-08-21 23:19:43 +00004476 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregorfae1d712009-09-26 03:56:17 +00004477 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004478 // [...] and any given function template specialization F1 is
4479 // eliminated if the set contains a second function template
4480 // specialization whose function template is more specialized
4481 // than the function template of F1 according to the partial
4482 // ordering rules of 14.5.5.2.
4483
4484 // The algorithm specified above is quadratic. We instead use a
4485 // two-pass algorithm (similar to the one used to identify the
4486 // best viable function in an overload set) that identifies the
4487 // best function template (if it exists).
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004488 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
Douglas Gregorfae1d712009-09-26 03:56:17 +00004489 Matches.end());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004490 FunctionDecl *Result =
4491 getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4492 TPOC_Other, From->getLocStart(),
4493 PDiag(),
4494 PDiag(diag::err_addr_ovl_ambiguous)
4495 << TemplateMatches[0]->getDeclName(),
4496 PDiag(diag::err_ovl_template_candidate));
4497 MarkDeclarationReferenced(From->getLocStart(), Result);
4498 return Result;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004499 }
Mike Stump11289f42009-09-09 15:08:12 +00004500
Douglas Gregorfae1d712009-09-26 03:56:17 +00004501 // [...] any function template specializations in the set are
4502 // eliminated if the set also contains a non-template function, [...]
4503 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4504 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4505 if ((*M)->getPrimaryTemplate() == 0)
4506 RemainingMatches.push_back(*M);
4507
Mike Stump11289f42009-09-09 15:08:12 +00004508 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004509 // selected function.
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004510 if (RemainingMatches.size() == 1) {
4511 FunctionDecl *Result = RemainingMatches.front();
4512 MarkDeclarationReferenced(From->getLocStart(), Result);
4513 return Result;
4514 }
Mike Stump11289f42009-09-09 15:08:12 +00004515
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004516 // FIXME: We should probably return the same thing that BestViableFunction
4517 // returns (even if we issue the diagnostics here).
4518 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4519 << RemainingMatches[0]->getDeclName();
4520 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4521 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregorcd695e52008-11-10 20:40:00 +00004522 return 0;
4523}
4524
Douglas Gregorcabea402009-09-22 15:41:20 +00004525/// \brief Add a single candidate to the overload set.
4526static void AddOverloadedCallCandidate(Sema &S,
John McCalld14a8642009-11-21 08:51:07 +00004527 NamedDecl *Callee,
John McCall6b51f282009-11-23 01:53:49 +00004528 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004529 Expr **Args, unsigned NumArgs,
4530 OverloadCandidateSet &CandidateSet,
4531 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00004532 if (isa<UsingShadowDecl>(Callee))
4533 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
4534
Douglas Gregorcabea402009-09-22 15:41:20 +00004535 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00004536 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregorcabea402009-09-22 15:41:20 +00004537 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4538 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00004539 return;
John McCalld14a8642009-11-21 08:51:07 +00004540 }
4541
4542 if (FunctionTemplateDecl *FuncTemplate
4543 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00004544 S.AddTemplateOverloadCandidate(FuncTemplate, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00004545 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00004546 return;
4547 }
4548
4549 assert(false && "unhandled case in overloaded call candidate");
4550
4551 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00004552}
4553
4554/// \brief Add the overload candidates named by callee and/or found by argument
4555/// dependent lookup to the given overload set.
John McCalld14a8642009-11-21 08:51:07 +00004556void Sema::AddOverloadedCallCandidates(llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregorcabea402009-09-22 15:41:20 +00004557 DeclarationName &UnqualifiedName,
John McCall4b1f16e2009-11-21 09:38:42 +00004558 bool ArgumentDependentLookup,
John McCall6b51f282009-11-23 01:53:49 +00004559 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004560 Expr **Args, unsigned NumArgs,
4561 OverloadCandidateSet &CandidateSet,
4562 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00004563
4564#ifndef NDEBUG
4565 // Verify that ArgumentDependentLookup is consistent with the rules
4566 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00004567 //
Douglas Gregorcabea402009-09-22 15:41:20 +00004568 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4569 // and let Y be the lookup set produced by argument dependent
4570 // lookup (defined as follows). If X contains
4571 //
4572 // -- a declaration of a class member, or
4573 //
4574 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00004575 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00004576 //
4577 // -- a declaration that is neither a function or a function
4578 // template
4579 //
4580 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00004581
4582 if (ArgumentDependentLookup) {
4583 for (unsigned I = 0; I < Fns.size(); ++I) {
4584 assert(!Fns[I]->getDeclContext()->isRecord());
4585 assert(isa<UsingShadowDecl>(Fns[I]) ||
4586 !Fns[I]->getDeclContext()->isFunctionOrMethod());
4587 assert(Fns[I]->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
4588 }
4589 }
4590#endif
4591
4592 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4593 E = Fns.end(); I != E; ++I)
John McCall6b51f282009-11-23 01:53:49 +00004594 AddOverloadedCallCandidate(*this, *I, ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00004595 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00004596 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00004597
Douglas Gregorcabea402009-09-22 15:41:20 +00004598 if (ArgumentDependentLookup)
4599 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004600 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004601 CandidateSet,
4602 PartialOverloading);
4603}
4604
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004605/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00004606/// (which eventually refers to the declaration Func) and the call
4607/// arguments Args/NumArgs, attempt to resolve the function call down
4608/// to a specific function. If overload resolution succeeds, returns
4609/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00004610/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004611/// arguments and Fn, and returns NULL.
John McCalld14a8642009-11-21 08:51:07 +00004612FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn,
4613 llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004614 DeclarationName UnqualifiedName,
John McCall6b51f282009-11-23 01:53:49 +00004615 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregora60a6912008-11-26 06:01:48 +00004616 SourceLocation LParenLoc,
4617 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004618 SourceLocation *CommaLocs,
Douglas Gregore254f902009-02-04 00:32:51 +00004619 SourceLocation RParenLoc,
John McCall4b1f16e2009-11-21 09:38:42 +00004620 bool ArgumentDependentLookup) {
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004621 OverloadCandidateSet CandidateSet;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004622
4623 // Add the functions denoted by Callee to the set of candidate
Douglas Gregorcabea402009-09-22 15:41:20 +00004624 // functions.
John McCalld14a8642009-11-21 08:51:07 +00004625 AddOverloadedCallCandidates(Fns, UnqualifiedName, ArgumentDependentLookup,
John McCall6b51f282009-11-23 01:53:49 +00004626 ExplicitTemplateArgs, Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004627 CandidateSet);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004628 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004629 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregora60a6912008-11-26 06:01:48 +00004630 case OR_Success:
4631 return Best->Function;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004632
4633 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00004634 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004635 diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00004636 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004637 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4638 break;
4639
4640 case OR_Ambiguous:
4641 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004642 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004643 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4644 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004645
4646 case OR_Deleted:
4647 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4648 << Best->Function->isDeleted()
4649 << UnqualifiedName
4650 << Fn->getSourceRange();
4651 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4652 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004653 }
4654
4655 // Overload resolution failed. Destroy all of the subexpressions and
4656 // return NULL.
4657 Fn->Destroy(Context);
4658 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4659 Args[Arg]->Destroy(Context);
4660 return 0;
4661}
4662
John McCall283b9012009-11-22 00:44:51 +00004663static bool IsOverloaded(const Sema::FunctionSet &Functions) {
4664 return Functions.size() > 1 ||
4665 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
4666}
4667
Douglas Gregor084d8552009-03-13 23:49:33 +00004668/// \brief Create a unary operation that may resolve to an overloaded
4669/// operator.
4670///
4671/// \param OpLoc The location of the operator itself (e.g., '*').
4672///
4673/// \param OpcIn The UnaryOperator::Opcode that describes this
4674/// operator.
4675///
4676/// \param Functions The set of non-member functions that will be
4677/// considered by overload resolution. The caller needs to build this
4678/// set based on the context using, e.g.,
4679/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4680/// set should not contain any member functions; those will be added
4681/// by CreateOverloadedUnaryOp().
4682///
4683/// \param input The input argument.
4684Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4685 unsigned OpcIn,
4686 FunctionSet &Functions,
Mike Stump11289f42009-09-09 15:08:12 +00004687 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004688 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4689 Expr *Input = (Expr *)input.get();
4690
4691 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4692 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4693 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4694
4695 Expr *Args[2] = { Input, 0 };
4696 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004697
Douglas Gregor084d8552009-03-13 23:49:33 +00004698 // For post-increment and post-decrement, add the implicit '0' as
4699 // the second argument, so that we know this is a post-increment or
4700 // post-decrement.
4701 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4702 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00004703 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00004704 SourceLocation());
4705 NumArgs = 2;
4706 }
4707
4708 if (Input->isTypeDependent()) {
John McCalld14a8642009-11-21 08:51:07 +00004709 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00004710 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
4711 0, SourceRange(), OpName, OpLoc,
John McCall283b9012009-11-22 00:44:51 +00004712 /*ADL*/ true, IsOverloaded(Functions));
Mike Stump11289f42009-09-09 15:08:12 +00004713 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor084d8552009-03-13 23:49:33 +00004714 FuncEnd = Functions.end();
4715 Func != FuncEnd; ++Func)
John McCalld14a8642009-11-21 08:51:07 +00004716 Fn->addDecl(*Func);
Mike Stump11289f42009-09-09 15:08:12 +00004717
Douglas Gregor084d8552009-03-13 23:49:33 +00004718 input.release();
4719 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4720 &Args[0], NumArgs,
4721 Context.DependentTy,
4722 OpLoc));
4723 }
4724
4725 // Build an empty overload set.
4726 OverloadCandidateSet CandidateSet;
4727
4728 // Add the candidates from the given function set.
4729 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4730
4731 // Add operator candidates that are member functions.
4732 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4733
4734 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004735 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00004736
4737 // Perform overload resolution.
4738 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004739 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004740 case OR_Success: {
4741 // We found a built-in operator or an overloaded operator.
4742 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00004743
Douglas Gregor084d8552009-03-13 23:49:33 +00004744 if (FnDecl) {
4745 // We matched an overloaded operator. Build a call to that
4746 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00004747
Douglas Gregor084d8552009-03-13 23:49:33 +00004748 // Convert the arguments.
4749 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4750 if (PerformObjectArgumentInitialization(Input, Method))
4751 return ExprError();
4752 } else {
4753 // Convert the arguments.
4754 if (PerformCopyInitialization(Input,
4755 FnDecl->getParamDecl(0)->getType(),
4756 "passing"))
4757 return ExprError();
4758 }
4759
4760 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004761 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00004762
Douglas Gregor084d8552009-03-13 23:49:33 +00004763 // Build the actual expression node.
4764 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4765 SourceLocation());
4766 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004767
Douglas Gregor084d8552009-03-13 23:49:33 +00004768 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00004769 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004770 ExprOwningPtr<CallExpr> TheCall(this,
4771 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00004772 Args, NumArgs, ResultTy, OpLoc));
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004773
4774 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4775 FnDecl))
4776 return ExprError();
4777
4778 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00004779 } else {
4780 // We matched a built-in operator. Convert the arguments, then
4781 // break out so that we will build the appropriate built-in
4782 // operator node.
4783 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4784 Best->Conversions[0], "passing"))
4785 return ExprError();
4786
4787 break;
4788 }
4789 }
4790
4791 case OR_No_Viable_Function:
4792 // No viable function; fall through to handling this as a
4793 // built-in operator, which will produce an error message for us.
4794 break;
4795
4796 case OR_Ambiguous:
4797 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4798 << UnaryOperator::getOpcodeStr(Opc)
4799 << Input->getSourceRange();
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004800 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4801 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00004802 return ExprError();
4803
4804 case OR_Deleted:
4805 Diag(OpLoc, diag::err_ovl_deleted_oper)
4806 << Best->Function->isDeleted()
4807 << UnaryOperator::getOpcodeStr(Opc)
4808 << Input->getSourceRange();
4809 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4810 return ExprError();
4811 }
4812
4813 // Either we found no viable overloaded operator or we matched a
4814 // built-in operator. In either case, fall through to trying to
4815 // build a built-in operation.
4816 input.release();
4817 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4818}
4819
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004820/// \brief Create a binary operation that may resolve to an overloaded
4821/// operator.
4822///
4823/// \param OpLoc The location of the operator itself (e.g., '+').
4824///
4825/// \param OpcIn The BinaryOperator::Opcode that describes this
4826/// operator.
4827///
4828/// \param Functions The set of non-member functions that will be
4829/// considered by overload resolution. The caller needs to build this
4830/// set based on the context using, e.g.,
4831/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4832/// set should not contain any member functions; those will be added
4833/// by CreateOverloadedBinOp().
4834///
4835/// \param LHS Left-hand argument.
4836/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00004837Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004838Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004839 unsigned OpcIn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004840 FunctionSet &Functions,
4841 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004842 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00004843 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004844
4845 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4846 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4847 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4848
4849 // If either side is type-dependent, create an appropriate dependent
4850 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00004851 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00004852 if (Functions.empty()) {
4853 // If there are no functions to store, just build a dependent
4854 // BinaryOperator or CompoundAssignment.
4855 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
4856 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
4857 Context.DependentTy, OpLoc));
4858
4859 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
4860 Context.DependentTy,
4861 Context.DependentTy,
4862 Context.DependentTy,
4863 OpLoc));
4864 }
4865
John McCalld14a8642009-11-21 08:51:07 +00004866 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00004867 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
4868 0, SourceRange(), OpName, OpLoc,
John McCall283b9012009-11-22 00:44:51 +00004869 /* ADL */ true, IsOverloaded(Functions));
John McCalld14a8642009-11-21 08:51:07 +00004870
Mike Stump11289f42009-09-09 15:08:12 +00004871 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004872 FuncEnd = Functions.end();
4873 Func != FuncEnd; ++Func)
John McCalld14a8642009-11-21 08:51:07 +00004874 Fn->addDecl(*Func);
Mike Stump11289f42009-09-09 15:08:12 +00004875
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004876 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00004877 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004878 Context.DependentTy,
4879 OpLoc));
4880 }
4881
4882 // If this is the .* operator, which is not overloadable, just
4883 // create a built-in binary operator.
4884 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00004885 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004886
Sebastian Redl6a96bf72009-11-18 23:10:33 +00004887 // If this is the assignment operator, we only perform overload resolution
4888 // if the left-hand side is a class or enumeration type. This is actually
4889 // a hack. The standard requires that we do overload resolution between the
4890 // various built-in candidates, but as DR507 points out, this can lead to
4891 // problems. So we do it this way, which pretty much follows what GCC does.
4892 // Note that we go the traditional code path for compound assignment forms.
4893 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00004894 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004895
Douglas Gregor084d8552009-03-13 23:49:33 +00004896 // Build an empty overload set.
4897 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004898
4899 // Add the candidates from the given function set.
4900 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4901
4902 // Add operator candidates that are member functions.
4903 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4904
4905 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004906 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004907
4908 // Perform overload resolution.
4909 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004910 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004911 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004912 // We found a built-in operator or an overloaded operator.
4913 FunctionDecl *FnDecl = Best->Function;
4914
4915 if (FnDecl) {
4916 // We matched an overloaded operator. Build a call to that
4917 // operator.
4918
4919 // Convert the arguments.
4920 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregore9899d92009-08-26 17:08:25 +00004921 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4922 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004923 "passing"))
4924 return ExprError();
4925 } else {
4926 // Convert the arguments.
Douglas Gregore9899d92009-08-26 17:08:25 +00004927 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004928 "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004929 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004930 "passing"))
4931 return ExprError();
4932 }
4933
4934 // Determine the result type
4935 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00004936 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004937 ResultTy = ResultTy.getNonReferenceType();
4938
4939 // Build the actual expression node.
4940 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00004941 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004942 UsualUnaryConversions(FnExpr);
4943
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00004944 ExprOwningPtr<CXXOperatorCallExpr>
4945 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4946 Args, 2, ResultTy,
4947 OpLoc));
4948
4949 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4950 FnDecl))
4951 return ExprError();
4952
4953 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004954 } else {
4955 // We matched a built-in operator. Convert the arguments, then
4956 // break out so that we will build the appropriate built-in
4957 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00004958 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004959 Best->Conversions[0], "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004960 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004961 Best->Conversions[1], "passing"))
4962 return ExprError();
4963
4964 break;
4965 }
4966 }
4967
Douglas Gregor66950a32009-09-30 21:46:01 +00004968 case OR_No_Viable_Function: {
4969 // C++ [over.match.oper]p9:
4970 // If the operator is the operator , [...] and there are no
4971 // viable functions, then the operator is assumed to be the
4972 // built-in operator and interpreted according to clause 5.
4973 if (Opc == BinaryOperator::Comma)
4974 break;
4975
Sebastian Redl027de2a2009-05-21 11:50:50 +00004976 // For class as left operand for assignment or compound assigment operator
4977 // do not fall through to handling in built-in, but report that no overloaded
4978 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00004979 OwningExprResult Result = ExprError();
4980 if (Args[0]->getType()->isRecordType() &&
4981 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00004982 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4983 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004984 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00004985 } else {
4986 // No viable function; try to create a built-in operation, which will
4987 // produce an error. Then, show the non-viable candidates.
4988 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00004989 }
Douglas Gregor66950a32009-09-30 21:46:01 +00004990 assert(Result.isInvalid() &&
4991 "C++ binary operator overloading is missing candidates!");
4992 if (Result.isInvalid())
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004993 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
4994 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00004995 return move(Result);
4996 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004997
4998 case OR_Ambiguous:
4999 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5000 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005001 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005002 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5003 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005004 return ExprError();
5005
5006 case OR_Deleted:
5007 Diag(OpLoc, diag::err_ovl_deleted_oper)
5008 << Best->Function->isDeleted()
5009 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00005010 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005011 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5012 return ExprError();
5013 }
5014
Douglas Gregor66950a32009-09-30 21:46:01 +00005015 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00005016 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005017}
5018
Sebastian Redladba46e2009-10-29 20:17:01 +00005019Action::OwningExprResult
5020Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5021 SourceLocation RLoc,
5022 ExprArg Base, ExprArg Idx) {
5023 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5024 static_cast<Expr*>(Idx.get()) };
5025 DeclarationName OpName =
5026 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5027
5028 // If either side is type-dependent, create an appropriate dependent
5029 // expression.
5030 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5031
John McCalld14a8642009-11-21 08:51:07 +00005032 UnresolvedLookupExpr *Fn
John McCalle66edc12009-11-24 19:00:30 +00005033 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5034 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00005035 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00005036 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00005037
5038 Base.release();
5039 Idx.release();
5040 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5041 Args, 2,
5042 Context.DependentTy,
5043 RLoc));
5044 }
5045
5046 // Build an empty overload set.
5047 OverloadCandidateSet CandidateSet;
5048
5049 // Subscript can only be overloaded as a member function.
5050
5051 // Add operator candidates that are member functions.
5052 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5053
5054 // Add builtin operator candidates.
5055 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5056
5057 // Perform overload resolution.
5058 OverloadCandidateSet::iterator Best;
5059 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5060 case OR_Success: {
5061 // We found a built-in operator or an overloaded operator.
5062 FunctionDecl *FnDecl = Best->Function;
5063
5064 if (FnDecl) {
5065 // We matched an overloaded operator. Build a call to that
5066 // operator.
5067
5068 // Convert the arguments.
5069 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5070 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5071 PerformCopyInitialization(Args[1],
5072 FnDecl->getParamDecl(0)->getType(),
5073 "passing"))
5074 return ExprError();
5075
5076 // Determine the result type
5077 QualType ResultTy
5078 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5079 ResultTy = ResultTy.getNonReferenceType();
5080
5081 // Build the actual expression node.
5082 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5083 LLoc);
5084 UsualUnaryConversions(FnExpr);
5085
5086 Base.release();
5087 Idx.release();
5088 ExprOwningPtr<CXXOperatorCallExpr>
5089 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5090 FnExpr, Args, 2,
5091 ResultTy, RLoc));
5092
5093 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5094 FnDecl))
5095 return ExprError();
5096
5097 return MaybeBindToTemporary(TheCall.release());
5098 } else {
5099 // We matched a built-in operator. Convert the arguments, then
5100 // break out so that we will build the appropriate built-in
5101 // operator node.
5102 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
5103 Best->Conversions[0], "passing") ||
5104 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
5105 Best->Conversions[1], "passing"))
5106 return ExprError();
5107
5108 break;
5109 }
5110 }
5111
5112 case OR_No_Viable_Function: {
5113 // No viable function; try to create a built-in operation, which will
5114 // produce an error. Then, show the non-viable candidates.
5115 OwningExprResult Result =
5116 CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
5117 assert(Result.isInvalid() &&
5118 "C++ subscript operator overloading is missing candidates!");
5119 if (Result.isInvalid())
5120 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5121 "[]", LLoc);
5122 return move(Result);
5123 }
5124
5125 case OR_Ambiguous:
5126 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5127 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5128 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5129 "[]", LLoc);
5130 return ExprError();
5131
5132 case OR_Deleted:
5133 Diag(LLoc, diag::err_ovl_deleted_oper)
5134 << Best->Function->isDeleted() << "[]"
5135 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5136 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5137 return ExprError();
5138 }
5139
5140 // We matched a built-in operator; build it.
5141 Base.release();
5142 Idx.release();
5143 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5144 Owned(Args[1]), RLoc);
5145}
5146
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005147/// BuildCallToMemberFunction - Build a call to a member
5148/// function. MemExpr is the expression that refers to the member
5149/// function (and includes the object parameter), Args/NumArgs are the
5150/// arguments to the function call (not including the object
5151/// parameter). The caller needs to validate that the member
5152/// expression refers to a member function or an overloaded member
5153/// function.
John McCall2d74de92009-12-01 22:10:20 +00005154Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00005155Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5156 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005157 unsigned NumArgs, SourceLocation *CommaLocs,
5158 SourceLocation RParenLoc) {
5159 // Dig out the member expression. This holds both the object
5160 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00005161 Expr *NakedMemExpr = MemExprE->IgnoreParens();
5162
John McCall10eae182009-11-30 22:42:35 +00005163 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005164 CXXMethodDecl *Method = 0;
John McCall10eae182009-11-30 22:42:35 +00005165 if (isa<MemberExpr>(NakedMemExpr)) {
5166 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00005167 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5168 } else {
5169 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
John McCall2d74de92009-12-01 22:10:20 +00005170
John McCall6e9f8f62009-12-03 04:06:58 +00005171 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00005172
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005173 // Add overload candidates
5174 OverloadCandidateSet CandidateSet;
Mike Stump11289f42009-09-09 15:08:12 +00005175
John McCall2d74de92009-12-01 22:10:20 +00005176 // FIXME: avoid copy.
5177 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5178 if (UnresExpr->hasExplicitTemplateArgs()) {
5179 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5180 TemplateArgs = &TemplateArgsBuffer;
5181 }
5182
John McCall10eae182009-11-30 22:42:35 +00005183 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
5184 E = UnresExpr->decls_end(); I != E; ++I) {
5185
John McCall6e9f8f62009-12-03 04:06:58 +00005186 NamedDecl *Func = *I;
5187 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
5188 if (isa<UsingShadowDecl>(Func))
5189 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
5190
John McCall10eae182009-11-30 22:42:35 +00005191 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00005192 // If explicit template arguments were provided, we can't call a
5193 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00005194 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00005195 continue;
5196
John McCall6e9f8f62009-12-03 04:06:58 +00005197 AddMethodCandidate(Method, ActingDC, ObjectType, Args, NumArgs,
5198 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00005199 } else {
John McCall10eae182009-11-30 22:42:35 +00005200 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall6e9f8f62009-12-03 04:06:58 +00005201 ActingDC, TemplateArgs,
5202 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005203 CandidateSet,
5204 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00005205 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005206 }
Mike Stump11289f42009-09-09 15:08:12 +00005207
John McCall10eae182009-11-30 22:42:35 +00005208 DeclarationName DeclName = UnresExpr->getMemberName();
5209
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005210 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00005211 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005212 case OR_Success:
5213 Method = cast<CXXMethodDecl>(Best->Function);
5214 break;
5215
5216 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00005217 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005218 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005219 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005220 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5221 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005222 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005223
5224 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00005225 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005226 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005227 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5228 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005229 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005230
5231 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00005232 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00005233 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00005234 << DeclName << MemExprE->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005235 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5236 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00005237 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005238 }
5239
Douglas Gregor51c538b2009-11-20 19:42:02 +00005240 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
John McCall2d74de92009-12-01 22:10:20 +00005241
John McCall2d74de92009-12-01 22:10:20 +00005242 // If overload resolution picked a static member, build a
5243 // non-member call based on that function.
5244 if (Method->isStatic()) {
5245 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
5246 Args, NumArgs, RParenLoc);
5247 }
5248
John McCall10eae182009-11-30 22:42:35 +00005249 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005250 }
5251
5252 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00005253 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00005254 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00005255 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005256 Method->getResultType().getNonReferenceType(),
5257 RParenLoc));
5258
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005259 // Check for a valid return type.
5260 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5261 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00005262 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005263
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005264 // Convert the object argument (for a non-static member function call).
John McCall2d74de92009-12-01 22:10:20 +00005265 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00005266 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005267 PerformObjectArgumentInitialization(ObjectArg, Method))
John McCall2d74de92009-12-01 22:10:20 +00005268 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005269 MemExpr->setBase(ObjectArg);
5270
5271 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005272 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00005273 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005274 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00005275 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005276
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005277 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00005278 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00005279
John McCall2d74de92009-12-01 22:10:20 +00005280 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005281}
5282
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005283/// BuildCallToObjectOfClassType - Build a call to an object of class
5284/// type (C++ [over.call.object]), which can end up invoking an
5285/// overloaded function call operator (@c operator()) or performing a
5286/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00005287Sema::ExprResult
5288Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00005289 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005290 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00005291 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005292 SourceLocation RParenLoc) {
5293 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005294 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00005295
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005296 // C++ [over.call.object]p1:
5297 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00005298 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005299 // candidate functions includes at least the function call
5300 // operators of T. The function call operators of T are obtained by
5301 // ordinary lookup of the name operator() in the context of
5302 // (E).operator().
5303 OverloadCandidateSet CandidateSet;
Douglas Gregor91f84212008-12-11 16:49:14 +00005304 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005305
5306 if (RequireCompleteType(LParenLoc, Object->getType(),
5307 PartialDiagnostic(diag::err_incomplete_object_call)
5308 << Object->getSourceRange()))
5309 return true;
5310
John McCall27b18f82009-11-17 02:14:36 +00005311 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
5312 LookupQualifiedName(R, Record->getDecl());
5313 R.suppressDiagnostics();
5314
Douglas Gregorc473cbb2009-11-15 07:48:03 +00005315 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00005316 Oper != OperEnd; ++Oper) {
John McCall6e9f8f62009-12-03 04:06:58 +00005317 AddMethodCandidate(*Oper, Object->getType(), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005318 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00005319 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005320
Douglas Gregorab7897a2008-11-19 22:57:39 +00005321 // C++ [over.call.object]p2:
5322 // In addition, for each conversion function declared in T of the
5323 // form
5324 //
5325 // operator conversion-type-id () cv-qualifier;
5326 //
5327 // where cv-qualifier is the same cv-qualification as, or a
5328 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00005329 // denotes the type "pointer to function of (P1,...,Pn) returning
5330 // R", or the type "reference to pointer to function of
5331 // (P1,...,Pn) returning R", or the type "reference to function
5332 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00005333 // is also considered as a candidate function. Similarly,
5334 // surrogate call functions are added to the set of candidate
5335 // functions for each conversion function declared in an
5336 // accessible base class provided the function is not hidden
5337 // within T by another intervening declaration.
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005338 // FIXME: Look in base classes for more conversion operators!
John McCalld14a8642009-11-21 08:51:07 +00005339 const UnresolvedSet *Conversions
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005340 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
John McCalld14a8642009-11-21 08:51:07 +00005341 for (UnresolvedSet::iterator I = Conversions->begin(),
5342 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00005343 NamedDecl *D = *I;
5344 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5345 if (isa<UsingShadowDecl>(D))
5346 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5347
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005348 // Skip over templated conversion functions; they aren't
5349 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00005350 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005351 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005352
John McCall6e9f8f62009-12-03 04:06:58 +00005353 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00005354
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005355 // Strip the reference type (if any) and then the pointer type (if
5356 // any) to get down to what might be a function type.
5357 QualType ConvType = Conv->getConversionType().getNonReferenceType();
5358 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5359 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005360
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005361 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall6e9f8f62009-12-03 04:06:58 +00005362 AddSurrogateCandidate(Conv, ActingContext, Proto,
5363 Object->getType(), Args, NumArgs,
5364 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00005365 }
Mike Stump11289f42009-09-09 15:08:12 +00005366
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005367 // Perform overload resolution.
5368 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005369 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005370 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00005371 // Overload resolution succeeded; we'll build the appropriate call
5372 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005373 break;
5374
5375 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00005376 Diag(Object->getSourceRange().getBegin(),
Sebastian Redl15b02d22008-11-22 13:44:36 +00005377 diag::err_ovl_no_viable_object_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00005378 << Object->getType() << Object->getSourceRange();
Sebastian Redl15b02d22008-11-22 13:44:36 +00005379 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005380 break;
5381
5382 case OR_Ambiguous:
5383 Diag(Object->getSourceRange().getBegin(),
5384 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005385 << Object->getType() << Object->getSourceRange();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005386 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5387 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005388
5389 case OR_Deleted:
5390 Diag(Object->getSourceRange().getBegin(),
5391 diag::err_ovl_deleted_object_call)
5392 << Best->Function->isDeleted()
5393 << Object->getType() << Object->getSourceRange();
5394 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5395 break;
Mike Stump11289f42009-09-09 15:08:12 +00005396 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005397
Douglas Gregorab7897a2008-11-19 22:57:39 +00005398 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005399 // We had an error; delete all of the subexpressions and return
5400 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00005401 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005402 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00005403 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005404 return true;
5405 }
5406
Douglas Gregorab7897a2008-11-19 22:57:39 +00005407 if (Best->Function == 0) {
5408 // Since there is no function declaration, this is one of the
5409 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00005410 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00005411 = cast<CXXConversionDecl>(
5412 Best->Conversions[0].UserDefined.ConversionFunction);
5413
5414 // We selected one of the surrogate functions that converts the
5415 // object parameter to a function pointer. Perform the conversion
5416 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005417
5418 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005419 // and then call it.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005420 CXXMemberCallExpr *CE =
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005421 BuildCXXMemberCallExpr(Object, Conv);
5422
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005423 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005424 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
5425 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005426 }
5427
5428 // We found an overloaded operator(). Build a CXXOperatorCallExpr
5429 // that calls this method, using Object for the implicit object
5430 // parameter and passing along the remaining arguments.
5431 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00005432 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005433
5434 unsigned NumArgsInProto = Proto->getNumArgs();
5435 unsigned NumArgsToCheck = NumArgs;
5436
5437 // Build the full argument list for the method call (the
5438 // implicit object parameter is placed at the beginning of the
5439 // list).
5440 Expr **MethodArgs;
5441 if (NumArgs < NumArgsInProto) {
5442 NumArgsToCheck = NumArgsInProto;
5443 MethodArgs = new Expr*[NumArgsInProto + 1];
5444 } else {
5445 MethodArgs = new Expr*[NumArgs + 1];
5446 }
5447 MethodArgs[0] = Object;
5448 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5449 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00005450
5451 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00005452 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005453 UsualUnaryConversions(NewFn);
5454
5455 // Once we've built TheCall, all of the expressions are properly
5456 // owned.
5457 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005458 ExprOwningPtr<CXXOperatorCallExpr>
5459 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005460 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00005461 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005462 delete [] MethodArgs;
5463
Anders Carlsson3d5829c2009-10-13 21:49:31 +00005464 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
5465 Method))
5466 return true;
5467
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005468 // We may have default arguments. If so, we need to allocate more
5469 // slots in the call for them.
5470 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00005471 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005472 else if (NumArgs > NumArgsInProto)
5473 NumArgsToCheck = NumArgsInProto;
5474
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005475 bool IsError = false;
5476
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005477 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005478 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005479 TheCall->setArg(0, Object);
5480
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005481
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005482 // Check the argument types.
5483 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005484 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005485 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005486 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00005487
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005488 // Pass the argument.
5489 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005490 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005491 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00005492 OwningExprResult DefArg
5493 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
5494 if (DefArg.isInvalid()) {
5495 IsError = true;
5496 break;
5497 }
5498
5499 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005500 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005501
5502 TheCall->setArg(i + 1, Arg);
5503 }
5504
5505 // If this is a variadic call, handle args passed through "...".
5506 if (Proto->isVariadic()) {
5507 // Promote the arguments (C99 6.5.2.2p7).
5508 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
5509 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005510 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005511 TheCall->setArg(i + 1, Arg);
5512 }
5513 }
5514
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005515 if (IsError) return true;
5516
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005517 if (CheckFunctionCall(Method, TheCall.get()))
5518 return true;
5519
Anders Carlsson1c83deb2009-08-16 03:53:54 +00005520 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005521}
5522
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005523/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00005524/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005525/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00005526Sema::OwningExprResult
5527Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
5528 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005529 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00005530
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005531 // C++ [over.ref]p1:
5532 //
5533 // [...] An expression x->m is interpreted as (x.operator->())->m
5534 // for a class object x of type T if T::operator->() exists and if
5535 // the operator is selected as the best match function by the
5536 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005537 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
5538 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005539 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00005540
Eli Friedman132e70b2009-11-18 01:28:03 +00005541 if (RequireCompleteType(Base->getLocStart(), Base->getType(),
5542 PDiag(diag::err_typecheck_incomplete_tag)
5543 << Base->getSourceRange()))
5544 return ExprError();
5545
John McCall27b18f82009-11-17 02:14:36 +00005546 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
5547 LookupQualifiedName(R, BaseRecord->getDecl());
5548 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00005549
5550 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00005551 Oper != OperEnd; ++Oper) {
5552 NamedDecl *D = *Oper;
5553 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5554 if (isa<UsingShadowDecl>(D))
5555 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5556
5557 AddMethodCandidate(cast<CXXMethodDecl>(D), ActingContext,
5558 Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005559 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00005560 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005561
5562 // Perform overload resolution.
5563 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005564 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005565 case OR_Success:
5566 // Overload resolution succeeded; we'll build the call below.
5567 break;
5568
5569 case OR_No_Viable_Function:
5570 if (CandidateSet.empty())
5571 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00005572 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005573 else
5574 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00005575 << "operator->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005576 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregord8061562009-08-06 03:17:00 +00005577 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005578
5579 case OR_Ambiguous:
5580 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00005581 << "->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005582 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005583 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005584
5585 case OR_Deleted:
5586 Diag(OpLoc, diag::err_ovl_deleted_oper)
5587 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00005588 << "->" << Base->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005589 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005590 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005591 }
5592
5593 // Convert the object parameter.
5594 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00005595 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00005596 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00005597
5598 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00005599 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005600
5601 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00005602 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5603 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005604 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00005605
5606 QualType ResultTy = Method->getResultType().getNonReferenceType();
5607 ExprOwningPtr<CXXOperatorCallExpr>
5608 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
5609 &Base, 1, ResultTy, OpLoc));
5610
5611 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
5612 Method))
5613 return ExprError();
5614 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005615}
5616
Douglas Gregorcd695e52008-11-10 20:40:00 +00005617/// FixOverloadedFunctionReference - E is an expression that refers to
5618/// a C++ overloaded function (possibly with some parentheses and
5619/// perhaps a '&' around it). We have resolved the overloaded function
5620/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005621/// refer (possibly indirectly) to Fn. Returns the new expr.
5622Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005623 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor51c538b2009-11-20 19:42:02 +00005624 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
5625 if (SubExpr == PE->getSubExpr())
5626 return PE->Retain();
5627
5628 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
5629 }
5630
5631 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5632 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00005633 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00005634 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00005635 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00005636 if (SubExpr == ICE->getSubExpr())
5637 return ICE->Retain();
5638
5639 return new (Context) ImplicitCastExpr(ICE->getType(),
5640 ICE->getCastKind(),
5641 SubExpr,
5642 ICE->isLvalueCast());
5643 }
5644
5645 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00005646 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00005647 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005648 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5649 if (Method->isStatic()) {
5650 // Do nothing: static member functions aren't any different
5651 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00005652 } else {
John McCalle66edc12009-11-24 19:00:30 +00005653 // Fix the sub expression, which really has to be an
5654 // UnresolvedLookupExpr holding an overloaded member function
5655 // or template.
John McCalld14a8642009-11-21 08:51:07 +00005656 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5657 if (SubExpr == UnOp->getSubExpr())
5658 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00005659
John McCalld14a8642009-11-21 08:51:07 +00005660 assert(isa<DeclRefExpr>(SubExpr)
5661 && "fixed to something other than a decl ref");
5662 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
5663 && "fixed to a member ref with no nested name qualifier");
5664
5665 // We have taken the address of a pointer to member
5666 // function. Perform the computation here so that we get the
5667 // appropriate pointer to member type.
5668 QualType ClassType
5669 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
5670 QualType MemPtrType
5671 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
5672
5673 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
5674 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005675 }
5676 }
Douglas Gregor51c538b2009-11-20 19:42:02 +00005677 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5678 if (SubExpr == UnOp->getSubExpr())
5679 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005680
Douglas Gregor51c538b2009-11-20 19:42:02 +00005681 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
5682 Context.getPointerType(SubExpr->getType()),
5683 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00005684 }
John McCalld14a8642009-11-21 08:51:07 +00005685
5686 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00005687 // FIXME: avoid copy.
5688 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00005689 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00005690 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
5691 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00005692 }
5693
John McCalld14a8642009-11-21 08:51:07 +00005694 return DeclRefExpr::Create(Context,
5695 ULE->getQualifier(),
5696 ULE->getQualifierRange(),
5697 Fn,
5698 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00005699 Fn->getType(),
5700 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00005701 }
5702
John McCall10eae182009-11-30 22:42:35 +00005703 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00005704 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00005705 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5706 if (MemExpr->hasExplicitTemplateArgs()) {
5707 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5708 TemplateArgs = &TemplateArgsBuffer;
5709 }
John McCall6b51f282009-11-23 01:53:49 +00005710
John McCall2d74de92009-12-01 22:10:20 +00005711 Expr *Base;
5712
5713 // If we're filling in
5714 if (MemExpr->isImplicitAccess()) {
5715 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
5716 return DeclRefExpr::Create(Context,
5717 MemExpr->getQualifier(),
5718 MemExpr->getQualifierRange(),
5719 Fn,
5720 MemExpr->getMemberLoc(),
5721 Fn->getType(),
5722 TemplateArgs);
5723 } else
5724 Base = new (Context) CXXThisExpr(SourceLocation(),
5725 MemExpr->getBaseType());
5726 } else
5727 Base = MemExpr->getBase()->Retain();
5728
5729 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00005730 MemExpr->isArrow(),
5731 MemExpr->getQualifier(),
5732 MemExpr->getQualifierRange(),
5733 Fn,
John McCall6b51f282009-11-23 01:53:49 +00005734 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00005735 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00005736 Fn->getType());
5737 }
5738
Douglas Gregor51c538b2009-11-20 19:42:02 +00005739 assert(false && "Invalid reference to overloaded function");
5740 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00005741}
5742
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005743} // end namespace clang