blob: 150f4ae78edbaf8a15ea478140478293cb98f62d [file] [log] [blame]
Douglas Gregor8e9bebd2008-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"
15#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000016#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000017#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000019#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000020#include "clang/AST/ExprCXX.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000022#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000023#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000025#include "llvm/Support/Compiler.h"
26#include <algorithm>
Torok Edwinf42e4a62009-08-24 13:25:12 +000027#include <cstdio>
Douglas Gregor8e9bebd2008-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 Stump1eb44332009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor8e9bebd2008-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 Gregor5cdf8212009-02-12 00:15:05 +000044 ICC_Promotion,
45 ICC_Conversion,
46 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000047 ICC_Conversion,
48 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000052 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000053 ICC_Conversion,
Douglas Gregor8e9bebd2008-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 Gregor5cdf8212009-02-12 00:15:05 +000071 ICR_Promotion,
72 ICR_Conversion,
73 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000074 ICR_Conversion,
75 ICR_Conversion,
76 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000079 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000080 ICR_Conversion,
Douglas Gregor8e9bebd2008-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 Gregor5cdf8212009-02-12 00:15:05 +000097 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000098 "Integral conversion",
99 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000100 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000101 "Floating-integral conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000102 "Complex-real conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000103 "Pointer conversion",
104 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000105 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000106 "Compatible-types conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000107 "Derived-to-base conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000108 };
109 return Name[Kind];
110}
111
Douglas Gregor60d62c22008-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 Redl85002392009-03-29 22:46:24 +0000121 RRefBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000122 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000123}
124
Douglas Gregor8e9bebd2008-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 Stump1eb44332009-09-09 15:08:12 +0000141/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000142/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000143bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-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 Gregor2a7e58d2008-12-23 00:53:59 +0000152 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregor8e9bebd2008-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 Gregorbc0805a2008-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 Stump1eb44332009-09-09 15:08:12 +0000163bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000164StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000165isPointerConversionToVoidPointer(ASTContext& Context) const {
Douglas Gregorbc0805a2008-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 Kremenek6217b802009-07-29 21:53:49 +0000176 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregor8e9bebd2008-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 Gregor225c41e2008-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 Gregor8e9bebd2008-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 Lattnerd9d22dd2008-11-24 05:29:24 +0000227 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000228 if (After.First || After.Second || After.Third) {
229 fprintf(stderr, " -> ");
230 After.DebugPrint();
231 }
232}
233
234/// DebugPrint - Print this implicit conversion sequence to standard
235/// error. Useful for debugging overloading issues.
236void ImplicitConversionSequence::DebugPrint() const {
237 switch (ConversionKind) {
238 case StandardConversion:
239 fprintf(stderr, "Standard conversion: ");
240 Standard.DebugPrint();
241 break;
242 case UserDefinedConversion:
243 fprintf(stderr, "User-defined conversion: ");
244 UserDefined.DebugPrint();
245 break;
246 case EllipsisConversion:
247 fprintf(stderr, "Ellipsis conversion");
248 break;
249 case BadConversion:
250 fprintf(stderr, "Bad conversion");
251 break;
252 }
253
254 fprintf(stderr, "\n");
255}
256
257// IsOverload - Determine whether the given New declaration is an
258// overload of the Old declaration. This routine returns false if New
259// and Old cannot be overloaded, e.g., if they are functions with the
260// same signature (C++ 1.3.10) or if the Old declaration isn't a
261// function (or overload set). When it does return false and Old is an
262// OverloadedFunctionDecl, MatchedDecl will be set to point to the
Mike Stump1eb44332009-09-09 15:08:12 +0000263// FunctionDecl that New cannot be overloaded with.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000264//
265// Example: Given the following input:
266//
267// void f(int, float); // #1
268// void f(int, int); // #2
269// int f(int, int); // #3
270//
271// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000272// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000273//
274// When we process #2, Old is a FunctionDecl for #1. By comparing the
275// parameter types, we see that #1 and #2 are overloaded (since they
276// have different signatures), so this routine returns false;
277// MatchedDecl is unchanged.
278//
279// When we process #3, Old is an OverloadedFunctionDecl containing #1
280// and #2. We compare the signatures of #3 to #1 (they're overloaded,
281// so we do nothing) and then #3 to #2. Since the signatures of #3 and
282// #2 are identical (return types of functions are not part of the
283// signature), IsOverload returns false and MatchedDecl will be set to
284// point to the FunctionDecl for #2.
285bool
Mike Stump1eb44332009-09-09 15:08:12 +0000286Sema::IsOverload(FunctionDecl *New, Decl* OldD,
287 OverloadedFunctionDecl::function_iterator& MatchedDecl) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000288 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
289 // Is this new function an overload of every function in the
290 // overload set?
291 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
292 FuncEnd = Ovl->function_end();
293 for (; Func != FuncEnd; ++Func) {
294 if (!IsOverload(New, *Func, MatchedDecl)) {
295 MatchedDecl = Func;
296 return false;
297 }
298 }
299
300 // This function overloads every function in the overload set.
301 return true;
Douglas Gregore53060f2009-06-25 22:08:12 +0000302 } else if (FunctionTemplateDecl *Old = dyn_cast<FunctionTemplateDecl>(OldD))
303 return IsOverload(New, Old->getTemplatedDecl(), MatchedDecl);
304 else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000305 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +0000306 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
307
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000308 // C++ [temp.fct]p2:
309 // A function template can be overloaded with other function templates
310 // and with normal (non-template) functions.
311 if ((OldTemplate == 0) != (NewTemplate == 0))
312 return true;
313
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000314 // Is the function New an overload of the function Old?
315 QualType OldQType = Context.getCanonicalType(Old->getType());
316 QualType NewQType = Context.getCanonicalType(New->getType());
317
318 // Compare the signatures (C++ 1.3.10) of the two functions to
319 // determine whether they are overloads. If we find any mismatch
320 // in the signature, they are overloads.
321
322 // If either of these functions is a K&R-style function (no
323 // prototype), then we consider them to have matching signatures.
Douglas Gregor72564e72009-02-26 23:50:07 +0000324 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
325 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000326 return false;
327
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000328 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
329 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000330
331 // The signature of a function includes the types of its
332 // parameters (C++ 1.3.10), which includes the presence or absence
333 // of the ellipsis; see C++ DR 357).
334 if (OldQType != NewQType &&
335 (OldType->getNumArgs() != NewType->getNumArgs() ||
336 OldType->isVariadic() != NewType->isVariadic() ||
337 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
338 NewType->arg_type_begin())))
339 return true;
340
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000341 // C++ [temp.over.link]p4:
Mike Stump1eb44332009-09-09 15:08:12 +0000342 // The signature of a function template consists of its function
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000343 // signature, its return type and its template parameter list. The names
344 // of the template parameters are significant only for establishing the
Mike Stump1eb44332009-09-09 15:08:12 +0000345 // relationship between the template parameters and the rest of the
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000346 // signature.
347 //
348 // We check the return type and template parameter lists for function
349 // templates first; the remaining checks follow.
350 if (NewTemplate &&
Mike Stump1eb44332009-09-09 15:08:12 +0000351 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
352 OldTemplate->getTemplateParameters(),
Douglas Gregor34d1dc92009-06-24 16:50:40 +0000353 false, false, SourceLocation()) ||
354 OldType->getResultType() != NewType->getResultType()))
355 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000357 // If the function is a class member, its signature includes the
358 // cv-qualifiers (if any) on the function itself.
359 //
360 // As part of this, also check whether one of the member functions
361 // is static, in which case they are not overloads (C++
362 // 13.1p2). While not part of the definition of the signature,
363 // this check is important to determine whether these functions
364 // can be overloaded.
365 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
366 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
Mike Stump1eb44332009-09-09 15:08:12 +0000367 if (OldMethod && NewMethod &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000368 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor1ca50c32008-11-21 15:36:28 +0000369 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000370 return true;
371
372 // The signatures match; this is not an overload.
373 return false;
374 } else {
375 // (C++ 13p1):
376 // Only function declarations can be overloaded; object and type
377 // declarations cannot be overloaded.
378 return false;
379 }
380}
381
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000382/// TryImplicitConversion - Attempt to perform an implicit conversion
383/// from the given expression (Expr) to the given type (ToType). This
384/// function returns an implicit conversion sequence that can be used
385/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000386///
387/// void f(float f);
388/// void g(int i) { f(i); }
389///
390/// this routine would produce an implicit conversion sequence to
391/// describe the initialization of f from i, which will be a standard
392/// conversion sequence containing an lvalue-to-rvalue conversion (C++
393/// 4.1) followed by a floating-integral conversion (C++ 4.9).
394//
395/// Note that this routine only determines how the conversion can be
396/// performed; it does not actually perform the conversion. As such,
397/// it will not produce any diagnostics if no conversion is available,
398/// but will instead return an implicit conversion sequence of kind
399/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000400///
401/// If @p SuppressUserConversions, then user-defined conversions are
402/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000403/// If @p AllowExplicit, then explicit user-defined conversions are
404/// permitted.
Sebastian Redle2b68332009-04-12 17:16:29 +0000405/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
406/// no matter its actual lvalueness.
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000407/// If @p UserCast, the implicit conversion is being done for a user-specified
408/// cast.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000409ImplicitConversionSequence
Anders Carlsson2974b5c2009-08-27 17:14:02 +0000410Sema::TryImplicitConversion(Expr* From, QualType ToType,
411 bool SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +0000412 bool AllowExplicit, bool ForceRValue,
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000413 bool InOverloadResolution,
414 bool UserCast) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000415 ImplicitConversionSequence ICS;
Fariborz Jahanian78cf9a22009-09-15 00:10:11 +0000416 OverloadCandidateSet Conversions;
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000417 OverloadingResult UserDefResult = OR_Success;
Anders Carlsson08972922009-08-28 15:33:32 +0000418 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
Douglas Gregor60d62c22008-10-31 16:23:19 +0000419 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000420 else if (getLangOptions().CPlusPlus &&
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000421 (UserDefResult = IsUserDefinedConversion(From, ToType,
422 ICS.UserDefined,
Fariborz Jahanian78cf9a22009-09-15 00:10:11 +0000423 Conversions,
Sebastian Redle2b68332009-04-12 17:16:29 +0000424 !SuppressUserConversions, AllowExplicit,
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000425 ForceRValue, UserCast)) == OR_Success) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000426 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000427 // C++ [over.ics.user]p4:
428 // A conversion of an expression of class type to the same class
429 // type is given Exact Match rank, and a conversion of an
430 // expression of class type to a base class of that type is
431 // given Conversion rank, in spite of the fact that a copy
432 // constructor (i.e., a user-defined conversion function) is
433 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000434 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000435 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000436 QualType FromCanon
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000437 = Context.getCanonicalType(From->getType().getUnqualifiedType());
438 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
439 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000440 // Turn this into a "standard" conversion sequence, so that it
441 // gets ranked with standard conversion sequences.
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000442 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
443 ICS.Standard.setAsIdentityConversion();
444 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
445 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000446 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000447 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000448 ICS.Standard.Second = ICK_Derived_To_Base;
449 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000450 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000451
452 // C++ [over.best.ics]p4:
453 // However, when considering the argument of a user-defined
454 // conversion function that is a candidate by 13.3.1.3 when
455 // invoked for the copying of the temporary in the second step
456 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
457 // 13.3.1.6 in all cases, only standard conversion sequences and
458 // ellipsis conversion sequences are allowed.
459 if (SuppressUserConversions &&
460 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
461 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000462 } else {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000463 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000464 if (UserDefResult == OR_Ambiguous) {
465 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
466 Cand != Conversions.end(); ++Cand)
Fariborz Jahanian27687cf2009-10-12 17:51:19 +0000467 if (Cand->Viable)
468 ICS.ConversionFunctionSet.push_back(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000469 }
470 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000471
472 return ICS;
473}
474
475/// IsStandardConversion - Determines whether there is a standard
476/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
477/// expression From to the type ToType. Standard conversion sequences
478/// only consider non-class types; for conversions that involve class
479/// types, use TryImplicitConversion. If a conversion exists, SCS will
480/// contain the standard conversion sequence required to perform this
481/// conversion and this routine will return true. Otherwise, this
482/// routine will return false and the value of SCS is unspecified.
Mike Stump1eb44332009-09-09 15:08:12 +0000483bool
484Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000485 bool InOverloadResolution,
Mike Stump1eb44332009-09-09 15:08:12 +0000486 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000487 QualType FromType = From->getType();
488
Douglas Gregor60d62c22008-10-31 16:23:19 +0000489 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000490 SCS.setAsIdentityConversion();
Douglas Gregor60d62c22008-10-31 16:23:19 +0000491 SCS.Deprecated = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000492 SCS.IncompatibleObjC = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000493 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000494 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000495
Douglas Gregorf9201e02009-02-11 23:02:49 +0000496 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000497 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000498 if (FromType->isRecordType() || ToType->isRecordType()) {
499 if (getLangOptions().CPlusPlus)
500 return false;
501
Mike Stump1eb44332009-09-09 15:08:12 +0000502 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000503 }
504
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000505 // The first conversion can be an lvalue-to-rvalue conversion,
506 // array-to-pointer conversion, or function-to-pointer conversion
507 // (C++ 4p1).
508
Mike Stump1eb44332009-09-09 15:08:12 +0000509 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000510 // An lvalue (3.10) of a non-function, non-array type T can be
511 // converted to an rvalue.
512 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000513 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000514 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor063daf62009-03-13 18:40:31 +0000515 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000516 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000517
518 // If T is a non-class type, the type of the rvalue is the
519 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +0000520 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
521 // just strip the qualifiers because they don't matter.
522
523 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregor60d62c22008-10-31 16:23:19 +0000524 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000525 } else if (FromType->isArrayType()) {
526 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000527 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000528
529 // An lvalue or rvalue of type "array of N T" or "array of unknown
530 // bound of T" can be converted to an rvalue of type "pointer to
531 // T" (C++ 4.2p1).
532 FromType = Context.getArrayDecayedType(FromType);
533
534 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
535 // This conversion is deprecated. (C++ D.4).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000536 SCS.Deprecated = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000537
538 // For the purpose of ranking in overload resolution
539 // (13.3.3.1.1), this conversion is considered an
540 // array-to-pointer conversion followed by a qualification
541 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000542 SCS.Second = ICK_Identity;
543 SCS.Third = ICK_Qualification;
544 SCS.ToTypePtr = ToType.getAsOpaquePtr();
545 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000546 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000547 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
548 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000549 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000550
551 // An lvalue of function type T can be converted to an rvalue of
552 // type "pointer to T." The result is a pointer to the
553 // function. (C++ 4.3p1).
554 FromType = Context.getPointerType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000555 } else if (FunctionDecl *Fn
Douglas Gregor904eed32008-11-10 20:40:00 +0000556 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000557 // Address of overloaded function (C++ [over.over]).
Douglas Gregor904eed32008-11-10 20:40:00 +0000558 SCS.First = ICK_Function_To_Pointer;
559
560 // We were able to resolve the address of the overloaded function,
561 // so we can convert to the type of that function.
562 FromType = Fn->getType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000563 if (ToType->isLValueReferenceType())
564 FromType = Context.getLValueReferenceType(FromType);
565 else if (ToType->isRValueReferenceType())
566 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl33b399a2009-02-04 21:23:32 +0000567 else if (ToType->isMemberPointerType()) {
568 // Resolve address only succeeds if both sides are member pointers,
569 // but it doesn't have to be the same class. See DR 247.
570 // Note that this means that the type of &Derived::fn can be
571 // Ret (Base::*)(Args) if the fn overload actually found is from the
572 // base class, even if it was brought into the derived class via a
573 // using declaration. The standard isn't clear on this issue at all.
574 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
575 FromType = Context.getMemberPointerType(FromType,
576 Context.getTypeDeclType(M->getParent()).getTypePtr());
577 } else
Douglas Gregor904eed32008-11-10 20:40:00 +0000578 FromType = Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000579 } else {
580 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000581 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000582 }
583
584 // The second conversion can be an integral promotion, floating
585 // point promotion, integral conversion, floating point conversion,
586 // floating-integral conversion, pointer conversion,
587 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +0000588 // For overloading in C, this can also be a "compatible-type"
589 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +0000590 bool IncompatibleObjC = false;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000591 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000592 // The unqualified versions of the types are the same: there's no
593 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000594 SCS.Second = ICK_Identity;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000595 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000596 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000597 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000598 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000599 } else if (IsFloatingPointPromotion(FromType, ToType)) {
600 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000601 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000602 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000603 } else if (IsComplexPromotion(FromType, ToType)) {
604 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000605 SCS.Second = ICK_Complex_Promotion;
606 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000607 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000608 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000609 // Integral conversions (C++ 4.7).
610 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000611 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000612 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000613 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
614 // Floating point conversions (C++ 4.8).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000615 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000616 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000617 } else if (FromType->isComplexType() && ToType->isComplexType()) {
618 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000619 SCS.Second = ICK_Complex_Conversion;
620 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000621 } else if ((FromType->isFloatingType() &&
622 ToType->isIntegralType() && (!ToType->isBooleanType() &&
623 !ToType->isEnumeralType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000624 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000625 ToType->isFloatingType())) {
626 // Floating-integral conversions (C++ 4.9).
627 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000628 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000629 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000630 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
631 (ToType->isComplexType() && FromType->isArithmeticType())) {
632 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000633 SCS.Second = ICK_Complex_Real;
634 FromType = ToType.getUnqualifiedType();
Anders Carlsson08972922009-08-28 15:33:32 +0000635 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
636 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000637 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000638 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000639 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregorce940492009-09-25 04:25:58 +0000640 } else if (IsMemberPointerConversion(From, FromType, ToType,
641 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000642 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000643 SCS.Second = ICK_Pointer_Member;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000644 } else if (ToType->isBooleanType() &&
645 (FromType->isArithmeticType() ||
646 FromType->isEnumeralType() ||
647 FromType->isPointerType() ||
648 FromType->isBlockPointerType() ||
649 FromType->isMemberPointerType() ||
650 FromType->isNullPtrType())) {
651 // Boolean conversions (C++ 4.12).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000652 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000653 FromType = Context.BoolTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000654 } else if (!getLangOptions().CPlusPlus &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000655 Context.typesAreCompatible(ToType, FromType)) {
656 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000657 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000658 } else {
659 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000660 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000661 }
662
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000663 QualType CanonFrom;
664 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000665 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000666 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000667 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000668 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000669 CanonFrom = Context.getCanonicalType(FromType);
670 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000671 } else {
672 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000673 SCS.Third = ICK_Identity;
674
Mike Stump1eb44332009-09-09 15:08:12 +0000675 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +0000676 // [...] Any difference in top-level cv-qualification is
677 // subsumed by the initialization itself and does not constitute
678 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000679 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000680 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000681 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000682 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
683 FromType = ToType;
684 CanonFrom = CanonTo;
685 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000686 }
687
688 // If we have not converted the argument type to the parameter type,
689 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000690 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000691 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000692
Douglas Gregor60d62c22008-10-31 16:23:19 +0000693 SCS.ToTypePtr = FromType.getAsOpaquePtr();
694 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000695}
696
697/// IsIntegralPromotion - Determines whether the conversion from the
698/// expression From (whose potentially-adjusted type is FromType) to
699/// ToType is an integral promotion (C++ 4.5). If so, returns true and
700/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000701bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +0000702 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000703 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000704 if (!To) {
705 return false;
706 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000707
708 // An rvalue of type char, signed char, unsigned char, short int, or
709 // unsigned short int can be converted to an rvalue of type int if
710 // int can represent all the values of the source type; otherwise,
711 // the source rvalue can be converted to an rvalue of type unsigned
712 // int (C++ 4.5p1).
Sebastian Redl07779722008-10-31 14:43:28 +0000713 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000714 if (// We can promote any signed, promotable integer type to an int
715 (FromType->isSignedIntegerType() ||
716 // We can promote any unsigned integer type whose size is
717 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +0000718 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000719 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000720 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000721 }
722
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000723 return To->getKind() == BuiltinType::UInt;
724 }
725
726 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
727 // can be converted to an rvalue of the first of the following types
728 // that can represent all the values of its underlying type: int,
729 // unsigned int, long, or unsigned long (C++ 4.5p2).
730 if ((FromType->isEnumeralType() || FromType->isWideCharType())
731 && ToType->isIntegerType()) {
732 // Determine whether the type we're converting from is signed or
733 // unsigned.
734 bool FromIsSigned;
735 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall183700f2009-09-21 23:43:11 +0000736 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000737 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
738 FromIsSigned = UnderlyingType->isSignedIntegerType();
739 } else {
740 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
741 FromIsSigned = true;
742 }
743
744 // The types we'll try to promote to, in the appropriate
745 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +0000746 QualType PromoteTypes[6] = {
747 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000748 Context.LongTy, Context.UnsignedLongTy ,
749 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000750 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000751 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000752 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
753 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +0000754 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000755 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
756 // We found the type that we can promote to. If this is the
757 // type we wanted, we have a promotion. Otherwise, no
758 // promotion.
Sebastian Redl07779722008-10-31 14:43:28 +0000759 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000760 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
761 }
762 }
763 }
764
765 // An rvalue for an integral bit-field (9.6) can be converted to an
766 // rvalue of type int if int can represent all the values of the
767 // bit-field; otherwise, it can be converted to unsigned int if
768 // unsigned int can represent all the values of the bit-field. If
769 // the bit-field is larger yet, no integral promotion applies to
770 // it. If the bit-field has an enumerated type, it is treated as any
771 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +0000772 // FIXME: We should delay checking of bit-fields until we actually perform the
773 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000774 using llvm::APSInt;
775 if (From)
776 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +0000777 APSInt BitWidth;
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000778 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
779 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
780 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
781 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +0000782
Douglas Gregor86f19402008-12-20 23:49:58 +0000783 // Are we promoting to an int from a bitfield that fits in an int?
784 if (BitWidth < ToSize ||
785 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
786 return To->getKind() == BuiltinType::Int;
787 }
Mike Stump1eb44332009-09-09 15:08:12 +0000788
Douglas Gregor86f19402008-12-20 23:49:58 +0000789 // Are we promoting to an unsigned int from an unsigned bitfield
790 // that fits into an unsigned int?
791 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
792 return To->getKind() == BuiltinType::UInt;
793 }
Mike Stump1eb44332009-09-09 15:08:12 +0000794
Douglas Gregor86f19402008-12-20 23:49:58 +0000795 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000796 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000797 }
Mike Stump1eb44332009-09-09 15:08:12 +0000798
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000799 // An rvalue of type bool can be converted to an rvalue of type int,
800 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000801 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000802 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000803 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000804
805 return false;
806}
807
808/// IsFloatingPointPromotion - Determines whether the conversion from
809/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
810/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000811bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000812 /// An rvalue of type float can be converted to an rvalue of type
813 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +0000814 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
815 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000816 if (FromBuiltin->getKind() == BuiltinType::Float &&
817 ToBuiltin->getKind() == BuiltinType::Double)
818 return true;
819
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000820 // C99 6.3.1.5p1:
821 // When a float is promoted to double or long double, or a
822 // double is promoted to long double [...].
823 if (!getLangOptions().CPlusPlus &&
824 (FromBuiltin->getKind() == BuiltinType::Float ||
825 FromBuiltin->getKind() == BuiltinType::Double) &&
826 (ToBuiltin->getKind() == BuiltinType::LongDouble))
827 return true;
828 }
829
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000830 return false;
831}
832
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000833/// \brief Determine if a conversion is a complex promotion.
834///
835/// A complex promotion is defined as a complex -> complex conversion
836/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000837/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000838bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +0000839 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000840 if (!FromComplex)
841 return false;
842
John McCall183700f2009-09-21 23:43:11 +0000843 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000844 if (!ToComplex)
845 return false;
846
847 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000848 ToComplex->getElementType()) ||
849 IsIntegralPromotion(0, FromComplex->getElementType(),
850 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000851}
852
Douglas Gregorcb7de522008-11-26 23:31:11 +0000853/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
854/// the pointer type FromPtr to a pointer to type ToPointee, with the
855/// same type qualifiers as FromPtr has on its pointee type. ToType,
856/// if non-empty, will be a pointer to ToType that may or may not have
857/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +0000858static QualType
859BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000860 QualType ToPointee, QualType ToType,
861 ASTContext &Context) {
862 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
863 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +0000864 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +0000865
866 // Exact qualifier match -> return the pointer type we're converting to.
John McCall0953e762009-09-24 19:53:00 +0000867 if (CanonToPointee.getQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +0000868 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +0000869 if (!ToType.isNull())
Douglas Gregorcb7de522008-11-26 23:31:11 +0000870 return ToType;
871
872 // Build a pointer to ToPointee. It has the right qualifiers
873 // already.
874 return Context.getPointerType(ToPointee);
875 }
876
877 // Just build a canonical type that has the right qualifiers.
John McCall0953e762009-09-24 19:53:00 +0000878 return Context.getPointerType(
879 Context.getQualifiedType(CanonToPointee.getUnqualifiedType(), Quals));
Douglas Gregorcb7de522008-11-26 23:31:11 +0000880}
881
Mike Stump1eb44332009-09-09 15:08:12 +0000882static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000883 bool InOverloadResolution,
884 ASTContext &Context) {
885 // Handle value-dependent integral null pointer constants correctly.
886 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
887 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
888 Expr->getType()->isIntegralType())
889 return !InOverloadResolution;
890
Douglas Gregorce940492009-09-25 04:25:58 +0000891 return Expr->isNullPointerConstant(Context,
892 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
893 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000894}
Mike Stump1eb44332009-09-09 15:08:12 +0000895
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000896/// IsPointerConversion - Determines whether the conversion of the
897/// expression From, which has the (possibly adjusted) type FromType,
898/// can be converted to the type ToType via a pointer conversion (C++
899/// 4.10). If so, returns true and places the converted type (that
900/// might differ from ToType in its cv-qualifiers at some level) into
901/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000902///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000903/// This routine also supports conversions to and from block pointers
904/// and conversions with Objective-C's 'id', 'id<protocols...>', and
905/// pointers to interfaces. FIXME: Once we've determined the
906/// appropriate overloading rules for Objective-C, we may want to
907/// split the Objective-C checks into a different routine; however,
908/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000909/// conversions, so for now they live here. IncompatibleObjC will be
910/// set if the conversion is an allowed Objective-C conversion that
911/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000912bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000913 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +0000914 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +0000915 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +0000916 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +0000917 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
918 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +0000919
Mike Stump1eb44332009-09-09 15:08:12 +0000920 // Conversion from a null pointer constant to any Objective-C pointer type.
921 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000922 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +0000923 ConvertedType = ToType;
924 return true;
925 }
926
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000927 // Blocks: Block pointers can be converted to void*.
928 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000929 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000930 ConvertedType = ToType;
931 return true;
932 }
933 // Blocks: A null pointer constant can be converted to a block
934 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +0000935 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000936 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000937 ConvertedType = ToType;
938 return true;
939 }
940
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000941 // If the left-hand-side is nullptr_t, the right side can be a null
942 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +0000943 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000944 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000945 ConvertedType = ToType;
946 return true;
947 }
948
Ted Kremenek6217b802009-07-29 21:53:49 +0000949 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000950 if (!ToTypePtr)
951 return false;
952
953 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000954 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000955 ConvertedType = ToType;
956 return true;
957 }
Sebastian Redl07779722008-10-31 14:43:28 +0000958
Douglas Gregorcb7de522008-11-26 23:31:11 +0000959 // Beyond this point, both types need to be pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +0000960 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +0000961 if (!FromTypePtr)
962 return false;
963
964 QualType FromPointeeType = FromTypePtr->getPointeeType();
965 QualType ToPointeeType = ToTypePtr->getPointeeType();
966
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000967 // An rvalue of type "pointer to cv T," where T is an object type,
968 // can be converted to an rvalue of type "pointer to cv void" (C++
969 // 4.10p2).
Douglas Gregorbad0e652009-03-24 20:32:41 +0000970 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000971 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +0000972 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000973 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000974 return true;
975 }
976
Douglas Gregorf9201e02009-02-11 23:02:49 +0000977 // When we're overloading in C, we allow a special kind of pointer
978 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +0000979 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +0000980 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000981 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000982 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +0000983 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +0000984 return true;
985 }
986
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000987 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +0000988 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000989 // An rvalue of type "pointer to cv D," where D is a class type,
990 // can be converted to an rvalue of type "pointer to cv B," where
991 // B is a base class (clause 10) of D. If B is an inaccessible
992 // (clause 11) or ambiguous (10.2) base class of D, a program that
993 // necessitates this conversion is ill-formed. The result of the
994 // conversion is a pointer to the base class sub-object of the
995 // derived class object. The null pointer value is converted to
996 // the null pointer value of the destination type.
997 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +0000998 // Note that we do not check for ambiguity or inaccessibility
999 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001000 if (getLangOptions().CPlusPlus &&
1001 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001002 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001003 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001004 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001005 ToType, Context);
1006 return true;
1007 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001008
Douglas Gregorc7887512008-12-19 19:13:09 +00001009 return false;
1010}
1011
1012/// isObjCPointerConversion - Determines whether this is an
1013/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1014/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001015bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001016 QualType& ConvertedType,
1017 bool &IncompatibleObjC) {
1018 if (!getLangOptions().ObjC1)
1019 return false;
1020
Steve Naroff14108da2009-07-10 23:34:53 +00001021 // First, we handle all conversions on ObjC object pointer types.
John McCall183700f2009-09-21 23:43:11 +00001022 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001023 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001024 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001025
Steve Naroff14108da2009-07-10 23:34:53 +00001026 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001027 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001028 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001029 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001030 ConvertedType = ToType;
1031 return true;
1032 }
1033 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001034 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001035 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001036 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001037 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001038 ConvertedType = ToType;
1039 return true;
1040 }
1041 // Objective C++: We're able to convert from a pointer to an
1042 // interface to a pointer to a different interface.
1043 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1044 ConvertedType = ToType;
1045 return true;
1046 }
1047
1048 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1049 // Okay: this is some kind of implicit downcast of Objective-C
1050 // interfaces, which is permitted. However, we're going to
1051 // complain about it.
1052 IncompatibleObjC = true;
1053 ConvertedType = FromType;
1054 return true;
1055 }
Mike Stump1eb44332009-09-09 15:08:12 +00001056 }
Steve Naroff14108da2009-07-10 23:34:53 +00001057 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001058 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001059 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001060 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001061 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001062 ToPointeeType = ToBlockPtr->getPointeeType();
1063 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001064 return false;
1065
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001066 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001067 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001068 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001069 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001070 FromPointeeType = FromBlockPtr->getPointeeType();
1071 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001072 return false;
1073
Douglas Gregorc7887512008-12-19 19:13:09 +00001074 // If we have pointers to pointers, recursively check whether this
1075 // is an Objective-C conversion.
1076 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1077 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1078 IncompatibleObjC)) {
1079 // We always complain about this conversion.
1080 IncompatibleObjC = true;
1081 ConvertedType = ToType;
1082 return true;
1083 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001084 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001085 // differences in the argument and result types are in Objective-C
1086 // pointer conversions. If so, we permit the conversion (but
1087 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001088 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001089 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001090 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001091 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001092 if (FromFunctionType && ToFunctionType) {
1093 // If the function types are exactly the same, this isn't an
1094 // Objective-C pointer conversion.
1095 if (Context.getCanonicalType(FromPointeeType)
1096 == Context.getCanonicalType(ToPointeeType))
1097 return false;
1098
1099 // Perform the quick checks that will tell us whether these
1100 // function types are obviously different.
1101 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1102 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1103 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1104 return false;
1105
1106 bool HasObjCConversion = false;
1107 if (Context.getCanonicalType(FromFunctionType->getResultType())
1108 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1109 // Okay, the types match exactly. Nothing to do.
1110 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1111 ToFunctionType->getResultType(),
1112 ConvertedType, IncompatibleObjC)) {
1113 // Okay, we have an Objective-C pointer conversion.
1114 HasObjCConversion = true;
1115 } else {
1116 // Function types are too different. Abort.
1117 return false;
1118 }
Mike Stump1eb44332009-09-09 15:08:12 +00001119
Douglas Gregorc7887512008-12-19 19:13:09 +00001120 // Check argument types.
1121 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1122 ArgIdx != NumArgs; ++ArgIdx) {
1123 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1124 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1125 if (Context.getCanonicalType(FromArgType)
1126 == Context.getCanonicalType(ToArgType)) {
1127 // Okay, the types match exactly. Nothing to do.
1128 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1129 ConvertedType, IncompatibleObjC)) {
1130 // Okay, we have an Objective-C pointer conversion.
1131 HasObjCConversion = true;
1132 } else {
1133 // Argument types are too different. Abort.
1134 return false;
1135 }
1136 }
1137
1138 if (HasObjCConversion) {
1139 // We had an Objective-C conversion. Allow this pointer
1140 // conversion, but complain about it.
1141 ConvertedType = ToType;
1142 IncompatibleObjC = true;
1143 return true;
1144 }
1145 }
1146
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001147 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001148}
1149
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001150/// CheckPointerConversion - Check the pointer conversion from the
1151/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001152/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001153/// conversions for which IsPointerConversion has already returned
1154/// true. It returns true and produces a diagnostic if there was an
1155/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001156bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
1157 CastExpr::CastKind &Kind) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001158 QualType FromType = From->getType();
1159
Ted Kremenek6217b802009-07-29 21:53:49 +00001160 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1161 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001162 QualType FromPointeeType = FromPtrType->getPointeeType(),
1163 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001164
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001165 if (FromPointeeType->isRecordType() &&
1166 ToPointeeType->isRecordType()) {
1167 // We must have a derived-to-base conversion. Check an
1168 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001169 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1170 From->getExprLoc(),
1171 From->getSourceRange()))
1172 return true;
1173
1174 // The conversion was successful.
1175 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001176 }
1177 }
Mike Stump1eb44332009-09-09 15:08:12 +00001178 if (const ObjCObjectPointerType *FromPtrType =
John McCall183700f2009-09-21 23:43:11 +00001179 FromType->getAs<ObjCObjectPointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001180 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001181 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001182 // Objective-C++ conversions are always okay.
1183 // FIXME: We should have a different class of conversions for the
1184 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001185 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001186 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001187
Steve Naroff14108da2009-07-10 23:34:53 +00001188 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001189 return false;
1190}
1191
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001192/// IsMemberPointerConversion - Determines whether the conversion of the
1193/// expression From, which has the (possibly adjusted) type FromType, can be
1194/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1195/// If so, returns true and places the converted type (that might differ from
1196/// ToType in its cv-qualifiers at some level) into ConvertedType.
1197bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001198 QualType ToType,
1199 bool InOverloadResolution,
1200 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001201 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001202 if (!ToTypePtr)
1203 return false;
1204
1205 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001206 if (From->isNullPointerConstant(Context,
1207 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1208 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001209 ConvertedType = ToType;
1210 return true;
1211 }
1212
1213 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001214 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001215 if (!FromTypePtr)
1216 return false;
1217
1218 // A pointer to member of B can be converted to a pointer to member of D,
1219 // where D is derived from B (C++ 4.11p2).
1220 QualType FromClass(FromTypePtr->getClass(), 0);
1221 QualType ToClass(ToTypePtr->getClass(), 0);
1222 // FIXME: What happens when these are dependent? Is this function even called?
1223
1224 if (IsDerivedFrom(ToClass, FromClass)) {
1225 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1226 ToClass.getTypePtr());
1227 return true;
1228 }
1229
1230 return false;
1231}
1232
1233/// CheckMemberPointerConversion - Check the member pointer conversion from the
1234/// expression From to the type ToType. This routine checks for ambiguous or
1235/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1236/// for which IsMemberPointerConversion has already returned true. It returns
1237/// true and produces a diagnostic if there was an error, or returns false
1238/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001239bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001240 CastExpr::CastKind &Kind) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001241 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001242 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001243 if (!FromPtrType) {
1244 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001245 assert(From->isNullPointerConstant(Context,
1246 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001247 "Expr must be null pointer constant!");
1248 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001249 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001250 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001251
Ted Kremenek6217b802009-07-29 21:53:49 +00001252 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001253 assert(ToPtrType && "No member pointer cast has a target type "
1254 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001255
Sebastian Redl21593ac2009-01-28 18:33:18 +00001256 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1257 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001258
Sebastian Redl21593ac2009-01-28 18:33:18 +00001259 // FIXME: What about dependent types?
1260 assert(FromClass->isRecordType() && "Pointer into non-class.");
1261 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001262
Douglas Gregora8f32e02009-10-06 17:59:45 +00001263 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1264 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001265 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1266 assert(DerivationOkay &&
1267 "Should not have been called if derivation isn't OK.");
1268 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001269
Sebastian Redl21593ac2009-01-28 18:33:18 +00001270 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1271 getUnqualifiedType())) {
1272 // Derivation is ambiguous. Redo the check to find the exact paths.
1273 Paths.clear();
1274 Paths.setRecordingPaths(true);
1275 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1276 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1277 (void)StillOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001278
Sebastian Redl21593ac2009-01-28 18:33:18 +00001279 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1280 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1281 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1282 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001283 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001284
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001285 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001286 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1287 << FromClass << ToClass << QualType(VBase, 0)
1288 << From->getSourceRange();
1289 return true;
1290 }
1291
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001292 // Must be a base to derived member conversion.
1293 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001294 return false;
1295}
1296
Douglas Gregor98cd5992008-10-21 23:43:52 +00001297/// IsQualificationConversion - Determines whether the conversion from
1298/// an rvalue of type FromType to ToType is a qualification conversion
1299/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001300bool
1301Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001302 FromType = Context.getCanonicalType(FromType);
1303 ToType = Context.getCanonicalType(ToType);
1304
1305 // If FromType and ToType are the same type, this is not a
1306 // qualification conversion.
1307 if (FromType == ToType)
1308 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001309
Douglas Gregor98cd5992008-10-21 23:43:52 +00001310 // (C++ 4.4p4):
1311 // A conversion can add cv-qualifiers at levels other than the first
1312 // in multi-level pointers, subject to the following rules: [...]
1313 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001314 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001315 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001316 // Within each iteration of the loop, we check the qualifiers to
1317 // determine if this still looks like a qualification
1318 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001319 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001320 // until there are no more pointers or pointers-to-members left to
1321 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001322 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001323
1324 // -- for every j > 0, if const is in cv 1,j then const is in cv
1325 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001326 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001327 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001328
Douglas Gregor98cd5992008-10-21 23:43:52 +00001329 // -- if the cv 1,j and cv 2,j are different, then const is in
1330 // every cv for 0 < k < j.
1331 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001332 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001333 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001334
Douglas Gregor98cd5992008-10-21 23:43:52 +00001335 // Keep track of whether all prior cv-qualifiers in the "to" type
1336 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001337 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001338 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001339 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001340
1341 // We are left with FromType and ToType being the pointee types
1342 // after unwrapping the original FromType and ToType the same number
1343 // of types. If we unwrapped any pointers, and if FromType and
1344 // ToType have the same unqualified type (since we checked
1345 // qualifiers above), then this is a qualification conversion.
1346 return UnwrappedAnyPointer &&
1347 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1348}
1349
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001350/// \brief Given a function template or function, extract the function template
1351/// declaration (if any) and the underlying function declaration.
1352template<typename T>
1353static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1354 FunctionTemplateDecl *&FunctionTemplate) {
1355 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1356 if (FunctionTemplate)
1357 Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1358 else
1359 Function = cast<T>(Orig);
1360}
1361
Douglas Gregor734d9862009-01-30 23:27:23 +00001362/// Determines whether there is a user-defined conversion sequence
1363/// (C++ [over.ics.user]) that converts expression From to the type
1364/// ToType. If such a conversion exists, User will contain the
1365/// user-defined conversion sequence that performs such a conversion
1366/// and this routine will return true. Otherwise, this routine returns
1367/// false and User is unspecified.
1368///
1369/// \param AllowConversionFunctions true if the conversion should
1370/// consider conversion functions at all. If false, only constructors
1371/// will be considered.
1372///
1373/// \param AllowExplicit true if the conversion should consider C++0x
1374/// "explicit" conversion functions as well as non-explicit conversion
1375/// functions (C++0x [class.conv.fct]p2).
Sebastian Redle2b68332009-04-12 17:16:29 +00001376///
1377/// \param ForceRValue true if the expression should be treated as an rvalue
1378/// for overload resolution.
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001379/// \param UserCast true if looking for user defined conversion for a static
1380/// cast.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001381Sema::OverloadingResult Sema::IsUserDefinedConversion(
1382 Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001383 UserDefinedConversionSequence& User,
Fariborz Jahanian78cf9a22009-09-15 00:10:11 +00001384 OverloadCandidateSet& CandidateSet,
Douglas Gregor734d9862009-01-30 23:27:23 +00001385 bool AllowConversionFunctions,
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001386 bool AllowExplicit, bool ForceRValue,
1387 bool UserCast) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001388 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001389 if (CXXRecordDecl *ToRecordDecl
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001390 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1391 // C++ [over.match.ctor]p1:
1392 // When objects of class type are direct-initialized (8.5), or
1393 // copy-initialized from an expression of the same or a
1394 // derived class type (8.5), overload resolution selects the
1395 // constructor. [...] For copy-initialization, the candidate
1396 // functions are all the converting constructors (12.3.1) of
1397 // that class. The argument list is the expression-list within
1398 // the parentheses of the initializer.
Mike Stump1eb44332009-09-09 15:08:12 +00001399 DeclarationName ConstructorName
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001400 = Context.DeclarationNames.getCXXConstructorName(
1401 Context.getCanonicalType(ToType).getUnqualifiedType());
1402 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump1eb44332009-09-09 15:08:12 +00001403 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001404 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001405 Con != ConEnd; ++Con) {
Douglas Gregordec06662009-08-21 18:42:58 +00001406 // Find the constructor (which may be a template).
1407 CXXConstructorDecl *Constructor = 0;
1408 FunctionTemplateDecl *ConstructorTmpl
1409 = dyn_cast<FunctionTemplateDecl>(*Con);
1410 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001411 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00001412 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1413 else
1414 Constructor = cast<CXXConstructorDecl>(*Con);
Mike Stump1eb44332009-09-09 15:08:12 +00001415
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00001416 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00001417 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001418 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001419 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
Douglas Gregordec06662009-08-21 18:42:58 +00001420 1, CandidateSet,
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001421 /*SuppressUserConversions=*/!UserCast,
Douglas Gregordec06662009-08-21 18:42:58 +00001422 ForceRValue);
1423 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001424 // Allow one user-defined conversion when user specifies a
1425 // From->ToType conversion via an static cast (c-style, etc).
Douglas Gregordec06662009-08-21 18:42:58 +00001426 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001427 /*SuppressUserConversions=*/!UserCast,
1428 ForceRValue);
Douglas Gregordec06662009-08-21 18:42:58 +00001429 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001430 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001431 }
1432 }
1433
Douglas Gregor734d9862009-01-30 23:27:23 +00001434 if (!AllowConversionFunctions) {
1435 // Don't allow any conversion functions to enter the overload set.
Mike Stump1eb44332009-09-09 15:08:12 +00001436 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1437 PDiag(0)
Anders Carlssonb7906612009-08-26 23:45:07 +00001438 << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00001439 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00001440 } else if (const RecordType *FromRecordType
Ted Kremenek6217b802009-07-29 21:53:49 +00001441 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001442 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001443 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1444 // Add all of the conversion functions as candidates.
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001445 OverloadedFunctionDecl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00001446 = FromRecordDecl->getVisibleConversionFunctions();
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001447 for (OverloadedFunctionDecl::function_iterator Func
1448 = Conversions->function_begin();
1449 Func != Conversions->function_end(); ++Func) {
1450 CXXConversionDecl *Conv;
1451 FunctionTemplateDecl *ConvTemplate;
1452 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1453 if (ConvTemplate)
1454 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1455 else
1456 Conv = dyn_cast<CXXConversionDecl>(*Func);
1457
1458 if (AllowExplicit || !Conv->isExplicit()) {
1459 if (ConvTemplate)
1460 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1461 CandidateSet);
1462 else
1463 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1464 }
1465 }
1466 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001467 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001468
1469 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001470 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001471 case OR_Success:
1472 // Record the standard conversion we used and the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00001473 if (CXXConstructorDecl *Constructor
Douglas Gregor60d62c22008-10-31 16:23:19 +00001474 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1475 // C++ [over.ics.user]p1:
1476 // If the user-defined conversion is specified by a
1477 // constructor (12.3.1), the initial standard conversion
1478 // sequence converts the source type to the type required by
1479 // the argument of the constructor.
1480 //
1481 // FIXME: What about ellipsis conversions?
1482 QualType ThisType = Constructor->getThisType(Context);
1483 User.Before = Best->Conversions[0].Standard;
1484 User.ConversionFunction = Constructor;
1485 User.After.setAsIdentityConversion();
Mike Stump1eb44332009-09-09 15:08:12 +00001486 User.After.FromTypePtr
Ted Kremenek6217b802009-07-29 21:53:49 +00001487 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor60d62c22008-10-31 16:23:19 +00001488 User.After.ToTypePtr = ToType.getAsOpaquePtr();
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001489 return OR_Success;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001490 } else if (CXXConversionDecl *Conversion
1491 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1492 // C++ [over.ics.user]p1:
1493 //
1494 // [...] If the user-defined conversion is specified by a
1495 // conversion function (12.3.2), the initial standard
1496 // conversion sequence converts the source type to the
1497 // implicit object parameter of the conversion function.
1498 User.Before = Best->Conversions[0].Standard;
1499 User.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00001500
1501 // C++ [over.ics.user]p2:
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001502 // The second standard conversion sequence converts the
1503 // result of the user-defined conversion to the target type
1504 // for the sequence. Since an implicit conversion sequence
1505 // is an initialization, the special rules for
1506 // initialization by user-defined conversion apply when
1507 // selecting the best user-defined conversion for a
1508 // user-defined conversion sequence (see 13.3.3 and
1509 // 13.3.3.1).
1510 User.After = Best->FinalConversion;
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001511 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001512 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001513 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001514 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001515 }
Mike Stump1eb44332009-09-09 15:08:12 +00001516
Douglas Gregor60d62c22008-10-31 16:23:19 +00001517 case OR_No_Viable_Function:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001518 return OR_No_Viable_Function;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001519 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001520 // No conversion here! We're done.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001521 return OR_Deleted;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001522
1523 case OR_Ambiguous:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001524 return OR_Ambiguous;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001525 }
1526
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001527 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001528}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001529
1530bool
1531Sema::DiagnoseAmbiguousUserDefinedConversion(Expr *From, QualType ToType) {
1532 ImplicitConversionSequence ICS;
1533 OverloadCandidateSet CandidateSet;
1534 OverloadingResult OvResult =
1535 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1536 CandidateSet, true, false, false);
1537 if (OvResult != OR_Ambiguous)
1538 return false;
1539 Diag(From->getSourceRange().getBegin(),
1540 diag::err_typecheck_ambiguous_condition)
1541 << From->getType() << ToType << From->getSourceRange();
1542 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1543 return true;
1544}
Douglas Gregor60d62c22008-10-31 16:23:19 +00001545
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001546/// CompareImplicitConversionSequences - Compare two implicit
1547/// conversion sequences to determine whether one is better than the
1548/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump1eb44332009-09-09 15:08:12 +00001549ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001550Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1551 const ImplicitConversionSequence& ICS2)
1552{
1553 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1554 // conversion sequences (as defined in 13.3.3.1)
1555 // -- a standard conversion sequence (13.3.3.1.1) is a better
1556 // conversion sequence than a user-defined conversion sequence or
1557 // an ellipsis conversion sequence, and
1558 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1559 // conversion sequence than an ellipsis conversion sequence
1560 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00001561 //
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001562 if (ICS1.ConversionKind < ICS2.ConversionKind)
1563 return ImplicitConversionSequence::Better;
1564 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1565 return ImplicitConversionSequence::Worse;
1566
1567 // Two implicit conversion sequences of the same form are
1568 // indistinguishable conversion sequences unless one of the
1569 // following rules apply: (C++ 13.3.3.2p3):
1570 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1571 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump1eb44332009-09-09 15:08:12 +00001572 else if (ICS1.ConversionKind ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001573 ImplicitConversionSequence::UserDefinedConversion) {
1574 // User-defined conversion sequence U1 is a better conversion
1575 // sequence than another user-defined conversion sequence U2 if
1576 // they contain the same user-defined conversion function or
1577 // constructor and if the second standard conversion sequence of
1578 // U1 is better than the second standard conversion sequence of
1579 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001580 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001581 ICS2.UserDefined.ConversionFunction)
1582 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1583 ICS2.UserDefined.After);
1584 }
1585
1586 return ImplicitConversionSequence::Indistinguishable;
1587}
1588
1589/// CompareStandardConversionSequences - Compare two standard
1590/// conversion sequences to determine whether one is better than the
1591/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001592ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001593Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1594 const StandardConversionSequence& SCS2)
1595{
1596 // Standard conversion sequence S1 is a better conversion sequence
1597 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1598
1599 // -- S1 is a proper subsequence of S2 (comparing the conversion
1600 // sequences in the canonical form defined by 13.3.3.1.1,
1601 // excluding any Lvalue Transformation; the identity conversion
1602 // sequence is considered to be a subsequence of any
1603 // non-identity conversion sequence) or, if not that,
1604 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1605 // Neither is a proper subsequence of the other. Do nothing.
1606 ;
1607 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1608 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001609 (SCS1.Second == ICK_Identity &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001610 SCS1.Third == ICK_Identity))
1611 // SCS1 is a proper subsequence of SCS2.
1612 return ImplicitConversionSequence::Better;
1613 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1614 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001615 (SCS2.Second == ICK_Identity &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001616 SCS2.Third == ICK_Identity))
1617 // SCS2 is a proper subsequence of SCS1.
1618 return ImplicitConversionSequence::Worse;
1619
1620 // -- the rank of S1 is better than the rank of S2 (by the rules
1621 // defined below), or, if not that,
1622 ImplicitConversionRank Rank1 = SCS1.getRank();
1623 ImplicitConversionRank Rank2 = SCS2.getRank();
1624 if (Rank1 < Rank2)
1625 return ImplicitConversionSequence::Better;
1626 else if (Rank2 < Rank1)
1627 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001628
Douglas Gregor57373262008-10-22 14:17:15 +00001629 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1630 // are indistinguishable unless one of the following rules
1631 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00001632
Douglas Gregor57373262008-10-22 14:17:15 +00001633 // A conversion that is not a conversion of a pointer, or
1634 // pointer to member, to bool is better than another conversion
1635 // that is such a conversion.
1636 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1637 return SCS2.isPointerConversionToBool()
1638 ? ImplicitConversionSequence::Better
1639 : ImplicitConversionSequence::Worse;
1640
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001641 // C++ [over.ics.rank]p4b2:
1642 //
1643 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001644 // conversion of B* to A* is better than conversion of B* to
1645 // void*, and conversion of A* to void* is better than conversion
1646 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00001647 bool SCS1ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001648 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001649 bool SCS2ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001650 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001651 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1652 // Exactly one of the conversion sequences is a conversion to
1653 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001654 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1655 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001656 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1657 // Neither conversion sequence converts to a void pointer; compare
1658 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001659 if (ImplicitConversionSequence::CompareKind DerivedCK
1660 = CompareDerivedToBaseConversions(SCS1, SCS2))
1661 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001662 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1663 // Both conversion sequences are conversions to void
1664 // pointers. Compare the source types to determine if there's an
1665 // inheritance relationship in their sources.
1666 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1667 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1668
1669 // Adjust the types we're converting from via the array-to-pointer
1670 // conversion, if we need to.
1671 if (SCS1.First == ICK_Array_To_Pointer)
1672 FromType1 = Context.getArrayDecayedType(FromType1);
1673 if (SCS2.First == ICK_Array_To_Pointer)
1674 FromType2 = Context.getArrayDecayedType(FromType2);
1675
Mike Stump1eb44332009-09-09 15:08:12 +00001676 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00001677 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001678 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00001679 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001680
1681 if (IsDerivedFrom(FromPointee2, FromPointee1))
1682 return ImplicitConversionSequence::Better;
1683 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1684 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001685
1686 // Objective-C++: If one interface is more specific than the
1687 // other, it is the better one.
John McCall183700f2009-09-21 23:43:11 +00001688 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1689 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001690 if (FromIface1 && FromIface1) {
1691 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1692 return ImplicitConversionSequence::Better;
1693 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1694 return ImplicitConversionSequence::Worse;
1695 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001696 }
Douglas Gregor57373262008-10-22 14:17:15 +00001697
1698 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1699 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00001700 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001701 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001702 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001703
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001704 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001705 // C++0x [over.ics.rank]p3b4:
1706 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1707 // implicit object parameter of a non-static member function declared
1708 // without a ref-qualifier, and S1 binds an rvalue reference to an
1709 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00001710 // FIXME: We don't know if we're dealing with the implicit object parameter,
1711 // or if the member function in this case has a ref qualifier.
1712 // (Of course, we don't have ref qualifiers yet.)
1713 if (SCS1.RRefBinding != SCS2.RRefBinding)
1714 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1715 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001716
1717 // C++ [over.ics.rank]p3b4:
1718 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1719 // which the references refer are the same type except for
1720 // top-level cv-qualifiers, and the type to which the reference
1721 // initialized by S2 refers is more cv-qualified than the type
1722 // to which the reference initialized by S1 refers.
Sebastian Redla9845802009-03-29 15:27:50 +00001723 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1724 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001725 T1 = Context.getCanonicalType(T1);
1726 T2 = Context.getCanonicalType(T2);
1727 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1728 if (T2.isMoreQualifiedThan(T1))
1729 return ImplicitConversionSequence::Better;
1730 else if (T1.isMoreQualifiedThan(T2))
1731 return ImplicitConversionSequence::Worse;
1732 }
1733 }
Douglas Gregor57373262008-10-22 14:17:15 +00001734
1735 return ImplicitConversionSequence::Indistinguishable;
1736}
1737
1738/// CompareQualificationConversions - Compares two standard conversion
1739/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00001740/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1741ImplicitConversionSequence::CompareKind
Douglas Gregor57373262008-10-22 14:17:15 +00001742Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump1eb44332009-09-09 15:08:12 +00001743 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00001744 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001745 // -- S1 and S2 differ only in their qualification conversion and
1746 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1747 // cv-qualification signature of type T1 is a proper subset of
1748 // the cv-qualification signature of type T2, and S1 is not the
1749 // deprecated string literal array-to-pointer conversion (4.2).
1750 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1751 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1752 return ImplicitConversionSequence::Indistinguishable;
1753
1754 // FIXME: the example in the standard doesn't use a qualification
1755 // conversion (!)
1756 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1757 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1758 T1 = Context.getCanonicalType(T1);
1759 T2 = Context.getCanonicalType(T2);
1760
1761 // If the types are the same, we won't learn anything by unwrapped
1762 // them.
1763 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1764 return ImplicitConversionSequence::Indistinguishable;
1765
Mike Stump1eb44332009-09-09 15:08:12 +00001766 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00001767 = ImplicitConversionSequence::Indistinguishable;
1768 while (UnwrapSimilarPointerTypes(T1, T2)) {
1769 // Within each iteration of the loop, we check the qualifiers to
1770 // determine if this still looks like a qualification
1771 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001772 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001773 // until there are no more pointers or pointers-to-members left
1774 // to unwrap. This essentially mimics what
1775 // IsQualificationConversion does, but here we're checking for a
1776 // strict subset of qualifiers.
1777 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1778 // The qualifiers are the same, so this doesn't tell us anything
1779 // about how the sequences rank.
1780 ;
1781 else if (T2.isMoreQualifiedThan(T1)) {
1782 // T1 has fewer qualifiers, so it could be the better sequence.
1783 if (Result == ImplicitConversionSequence::Worse)
1784 // Neither has qualifiers that are a subset of the other's
1785 // qualifiers.
1786 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001787
Douglas Gregor57373262008-10-22 14:17:15 +00001788 Result = ImplicitConversionSequence::Better;
1789 } else if (T1.isMoreQualifiedThan(T2)) {
1790 // T2 has fewer qualifiers, so it could be the better sequence.
1791 if (Result == ImplicitConversionSequence::Better)
1792 // Neither has qualifiers that are a subset of the other's
1793 // qualifiers.
1794 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001795
Douglas Gregor57373262008-10-22 14:17:15 +00001796 Result = ImplicitConversionSequence::Worse;
1797 } else {
1798 // Qualifiers are disjoint.
1799 return ImplicitConversionSequence::Indistinguishable;
1800 }
1801
1802 // If the types after this point are equivalent, we're done.
1803 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1804 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001805 }
1806
Douglas Gregor57373262008-10-22 14:17:15 +00001807 // Check that the winning standard conversion sequence isn't using
1808 // the deprecated string literal array to pointer conversion.
1809 switch (Result) {
1810 case ImplicitConversionSequence::Better:
1811 if (SCS1.Deprecated)
1812 Result = ImplicitConversionSequence::Indistinguishable;
1813 break;
1814
1815 case ImplicitConversionSequence::Indistinguishable:
1816 break;
1817
1818 case ImplicitConversionSequence::Worse:
1819 if (SCS2.Deprecated)
1820 Result = ImplicitConversionSequence::Indistinguishable;
1821 break;
1822 }
1823
1824 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001825}
1826
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001827/// CompareDerivedToBaseConversions - Compares two standard conversion
1828/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00001829/// various kinds of derived-to-base conversions (C++
1830/// [over.ics.rank]p4b3). As part of these checks, we also look at
1831/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001832ImplicitConversionSequence::CompareKind
1833Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1834 const StandardConversionSequence& SCS2) {
1835 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1836 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1837 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1838 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1839
1840 // Adjust the types we're converting from via the array-to-pointer
1841 // conversion, if we need to.
1842 if (SCS1.First == ICK_Array_To_Pointer)
1843 FromType1 = Context.getArrayDecayedType(FromType1);
1844 if (SCS2.First == ICK_Array_To_Pointer)
1845 FromType2 = Context.getArrayDecayedType(FromType2);
1846
1847 // Canonicalize all of the types.
1848 FromType1 = Context.getCanonicalType(FromType1);
1849 ToType1 = Context.getCanonicalType(ToType1);
1850 FromType2 = Context.getCanonicalType(FromType2);
1851 ToType2 = Context.getCanonicalType(ToType2);
1852
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001853 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001854 //
1855 // If class B is derived directly or indirectly from class A and
1856 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001857 //
1858 // For Objective-C, we let A, B, and C also be Objective-C
1859 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001860
1861 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00001862 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00001863 SCS2.Second == ICK_Pointer_Conversion &&
1864 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1865 FromType1->isPointerType() && FromType2->isPointerType() &&
1866 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001867 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00001868 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00001869 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00001870 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001871 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00001872 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001873 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00001874 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001875
John McCall183700f2009-09-21 23:43:11 +00001876 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1877 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1878 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1879 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001880
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001881 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001882 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1883 if (IsDerivedFrom(ToPointee1, ToPointee2))
1884 return ImplicitConversionSequence::Better;
1885 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1886 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001887
1888 if (ToIface1 && ToIface2) {
1889 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1890 return ImplicitConversionSequence::Better;
1891 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1892 return ImplicitConversionSequence::Worse;
1893 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001894 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001895
1896 // -- conversion of B* to A* is better than conversion of C* to A*,
1897 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1898 if (IsDerivedFrom(FromPointee2, FromPointee1))
1899 return ImplicitConversionSequence::Better;
1900 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1901 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00001902
Douglas Gregorcb7de522008-11-26 23:31:11 +00001903 if (FromIface1 && FromIface2) {
1904 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1905 return ImplicitConversionSequence::Better;
1906 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1907 return ImplicitConversionSequence::Worse;
1908 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001909 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001910 }
1911
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001912 // Compare based on reference bindings.
1913 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1914 SCS1.Second == ICK_Derived_To_Base) {
1915 // -- binding of an expression of type C to a reference of type
1916 // B& is better than binding an expression of type C to a
1917 // reference of type A&,
1918 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1919 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1920 if (IsDerivedFrom(ToType1, ToType2))
1921 return ImplicitConversionSequence::Better;
1922 else if (IsDerivedFrom(ToType2, ToType1))
1923 return ImplicitConversionSequence::Worse;
1924 }
1925
Douglas Gregor225c41e2008-11-03 19:09:14 +00001926 // -- binding of an expression of type B to a reference of type
1927 // A& is better than binding an expression of type C to a
1928 // reference of type A&,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001929 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1930 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1931 if (IsDerivedFrom(FromType2, FromType1))
1932 return ImplicitConversionSequence::Better;
1933 else if (IsDerivedFrom(FromType1, FromType2))
1934 return ImplicitConversionSequence::Worse;
1935 }
1936 }
Fariborz Jahanian2357da02009-10-20 20:07:35 +00001937
1938 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00001939 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
1940 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
1941 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
1942 const MemberPointerType * FromMemPointer1 =
1943 FromType1->getAs<MemberPointerType>();
1944 const MemberPointerType * ToMemPointer1 =
1945 ToType1->getAs<MemberPointerType>();
1946 const MemberPointerType * FromMemPointer2 =
1947 FromType2->getAs<MemberPointerType>();
1948 const MemberPointerType * ToMemPointer2 =
1949 ToType2->getAs<MemberPointerType>();
1950 const Type *FromPointeeType1 = FromMemPointer1->getClass();
1951 const Type *ToPointeeType1 = ToMemPointer1->getClass();
1952 const Type *FromPointeeType2 = FromMemPointer2->getClass();
1953 const Type *ToPointeeType2 = ToMemPointer2->getClass();
1954 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
1955 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
1956 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
1957 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00001958 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00001959 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1960 if (IsDerivedFrom(ToPointee1, ToPointee2))
1961 return ImplicitConversionSequence::Worse;
1962 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1963 return ImplicitConversionSequence::Better;
1964 }
1965 // conversion of B::* to C::* is better than conversion of A::* to C::*
1966 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
1967 if (IsDerivedFrom(FromPointee1, FromPointee2))
1968 return ImplicitConversionSequence::Better;
1969 else if (IsDerivedFrom(FromPointee2, FromPointee1))
1970 return ImplicitConversionSequence::Worse;
1971 }
1972 }
1973
Douglas Gregor225c41e2008-11-03 19:09:14 +00001974 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1975 SCS1.Second == ICK_Derived_To_Base) {
1976 // -- conversion of C to B is better than conversion of C to A,
1977 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1978 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1979 if (IsDerivedFrom(ToType1, ToType2))
1980 return ImplicitConversionSequence::Better;
1981 else if (IsDerivedFrom(ToType2, ToType1))
1982 return ImplicitConversionSequence::Worse;
1983 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001984
Douglas Gregor225c41e2008-11-03 19:09:14 +00001985 // -- conversion of B to A is better than conversion of C to A.
1986 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1987 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1988 if (IsDerivedFrom(FromType2, FromType1))
1989 return ImplicitConversionSequence::Better;
1990 else if (IsDerivedFrom(FromType1, FromType2))
1991 return ImplicitConversionSequence::Worse;
1992 }
1993 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001994
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001995 return ImplicitConversionSequence::Indistinguishable;
1996}
1997
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001998/// TryCopyInitialization - Try to copy-initialize a value of type
1999/// ToType from the expression From. Return the implicit conversion
2000/// sequence required to pass this argument, which may be a bad
2001/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00002002/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redle2b68332009-04-12 17:16:29 +00002003/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2004/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump1eb44332009-09-09 15:08:12 +00002005ImplicitConversionSequence
2006Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002007 bool SuppressUserConversions, bool ForceRValue,
2008 bool InOverloadResolution) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00002009 if (ToType->isReferenceType()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002010 ImplicitConversionSequence ICS;
Mike Stump1eb44332009-09-09 15:08:12 +00002011 CheckReferenceInit(From, ToType,
Douglas Gregor739d8282009-09-23 23:04:10 +00002012 /*FIXME:*/From->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002013 SuppressUserConversions,
2014 /*AllowExplicit=*/false,
2015 ForceRValue,
2016 &ICS);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002017 return ICS;
2018 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002019 return TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002020 SuppressUserConversions,
2021 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002022 ForceRValue,
2023 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002024 }
2025}
2026
Sebastian Redle2b68332009-04-12 17:16:29 +00002027/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2028/// the expression @p From. Returns true (and emits a diagnostic) if there was
2029/// an error, returns false if the initialization succeeded. Elidable should
2030/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2031/// differently in C++0x for this case.
Mike Stump1eb44332009-09-09 15:08:12 +00002032bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +00002033 const char* Flavor, bool Elidable) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002034 if (!getLangOptions().CPlusPlus) {
2035 // In C, argument passing is the same as performing an assignment.
2036 QualType FromType = From->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002037
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002038 AssignConvertType ConvTy =
2039 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00002040 if (ConvTy != Compatible &&
2041 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2042 ConvTy = Compatible;
Mike Stump1eb44332009-09-09 15:08:12 +00002043
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002044 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
2045 FromType, From, Flavor);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002046 }
Sebastian Redle2b68332009-04-12 17:16:29 +00002047
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002048 if (ToType->isReferenceType())
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002049 return CheckReferenceInit(From, ToType,
Douglas Gregor739d8282009-09-23 23:04:10 +00002050 /*FIXME:*/From->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002051 /*SuppressUserConversions=*/false,
2052 /*AllowExplicit=*/false,
2053 /*ForceRValue=*/false);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002054
Sebastian Redle2b68332009-04-12 17:16:29 +00002055 if (!PerformImplicitConversion(From, ToType, Flavor,
2056 /*AllowExplicit=*/false, Elidable))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002057 return false;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002058 if (!DiagnoseAmbiguousUserDefinedConversion(From, ToType))
Fariborz Jahanian455acd92009-09-22 19:53:15 +00002059 return Diag(From->getSourceRange().getBegin(),
2060 diag::err_typecheck_convert_incompatible)
2061 << ToType << From->getType() << Flavor << From->getSourceRange();
Fariborz Jahanian455acd92009-09-22 19:53:15 +00002062 return true;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002063}
2064
Douglas Gregor96176b32008-11-18 23:14:02 +00002065/// TryObjectArgumentInitialization - Try to initialize the object
2066/// parameter of the given member function (@c Method) from the
2067/// expression @p From.
2068ImplicitConversionSequence
2069Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
2070 QualType ClassType = Context.getTypeDeclType(Method->getParent());
John McCall0953e762009-09-24 19:53:00 +00002071 QualType ImplicitParamType
2072 = Context.getCVRQualifiedType(ClassType, Method->getTypeQualifiers());
Douglas Gregor96176b32008-11-18 23:14:02 +00002073
2074 // Set up the conversion sequence as a "bad" conversion, to allow us
2075 // to exit early.
2076 ImplicitConversionSequence ICS;
2077 ICS.Standard.setAsIdentityConversion();
2078 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2079
2080 // We need to have an object of class type.
2081 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002082 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00002083 FromType = PT->getPointeeType();
2084
2085 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002086
2087 // The implicit object parmeter is has the type "reference to cv X",
2088 // where X is the class of which the function is a member
2089 // (C++ [over.match.funcs]p4). However, when finding an implicit
2090 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00002091 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00002092 // (C++ [over.match.funcs]p5). We perform a simplified version of
2093 // reference binding here, that allows class rvalues to bind to
2094 // non-constant references.
2095
2096 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2097 // with the implicit object parameter (C++ [over.match.funcs]p5).
2098 QualType FromTypeCanon = Context.getCanonicalType(FromType);
2099 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
2100 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
2101 return ICS;
2102
2103 // Check that we have either the same type or a derived type. It
2104 // affects the conversion rank.
2105 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2106 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2107 ICS.Standard.Second = ICK_Identity;
2108 else if (IsDerivedFrom(FromType, ClassType))
2109 ICS.Standard.Second = ICK_Derived_To_Base;
2110 else
2111 return ICS;
2112
2113 // Success. Mark this as a reference binding.
2114 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2115 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2116 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2117 ICS.Standard.ReferenceBinding = true;
2118 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00002119 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002120 return ICS;
2121}
2122
2123/// PerformObjectArgumentInitialization - Perform initialization of
2124/// the implicit object parameter for the given Method with the given
2125/// expression.
2126bool
2127Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002128 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00002129 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00002130 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002131
Ted Kremenek6217b802009-07-29 21:53:49 +00002132 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002133 FromRecordType = PT->getPointeeType();
2134 DestType = Method->getThisType(Context);
2135 } else {
2136 FromRecordType = From->getType();
2137 DestType = ImplicitParamRecordType;
2138 }
2139
Mike Stump1eb44332009-09-09 15:08:12 +00002140 ImplicitConversionSequence ICS
Douglas Gregor96176b32008-11-18 23:14:02 +00002141 = TryObjectArgumentInitialization(From, Method);
2142 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2143 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002144 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00002145 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002146
Douglas Gregor96176b32008-11-18 23:14:02 +00002147 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssona552f7c2009-05-01 18:34:30 +00002148 CheckDerivedToBaseConversion(FromRecordType,
2149 ImplicitParamRecordType,
Douglas Gregor96176b32008-11-18 23:14:02 +00002150 From->getSourceRange().getBegin(),
2151 From->getSourceRange()))
2152 return true;
2153
Mike Stump1eb44332009-09-09 15:08:12 +00002154 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson116b7d92009-08-07 18:45:49 +00002155 /*isLvalue=*/true);
Douglas Gregor96176b32008-11-18 23:14:02 +00002156 return false;
2157}
2158
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002159/// TryContextuallyConvertToBool - Attempt to contextually convert the
2160/// expression From to bool (C++0x [conv]p3).
2161ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump1eb44332009-09-09 15:08:12 +00002162 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002163 // FIXME: Are these flags correct?
2164 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00002165 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00002166 /*ForceRValue=*/false,
2167 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002168}
2169
2170/// PerformContextuallyConvertToBool - Perform a contextual conversion
2171/// of the expression From to bool (C++0x [conv]p3).
2172bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2173 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2174 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2175 return false;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002176
2177 if (!DiagnoseAmbiguousUserDefinedConversion(From, Context.BoolTy))
2178 return Diag(From->getSourceRange().getBegin(),
2179 diag::err_typecheck_bool_condition)
2180 << From->getType() << From->getSourceRange();
2181 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002182}
2183
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002184/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00002185/// candidate functions, using the given function call arguments. If
2186/// @p SuppressUserConversions, then don't allow user-defined
2187/// conversions via constructors or conversion operators.
Sebastian Redle2b68332009-04-12 17:16:29 +00002188/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2189/// hacky way to implement the overloading rules for elidable copy
2190/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002191///
2192/// \para PartialOverloading true if we are performing "partial" overloading
2193/// based on an incomplete set of function arguments. This feature is used by
2194/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00002195void
2196Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002197 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002198 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00002199 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002200 bool ForceRValue,
2201 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00002202 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002203 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002204 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00002205 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002206 "Use AddConversionCandidate for conversion functions");
Mike Stump1eb44332009-09-09 15:08:12 +00002207 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00002208 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00002209
Douglas Gregor88a35142008-12-22 05:46:06 +00002210 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002211 if (!isa<CXXConstructorDecl>(Method)) {
2212 // If we get here, it's because we're calling a member function
2213 // that is named without a member access expression (e.g.,
2214 // "this->f") that was either written explicitly or created
2215 // implicitly. This can happen with a qualified call to a member
2216 // function, e.g., X::f(). We use a NULL object as the implied
2217 // object argument (C++ [over.call.func]p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002218 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002219 SuppressUserConversions, ForceRValue);
2220 return;
2221 }
2222 // We treat a constructor like a non-member function, since its object
2223 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00002224 }
2225
Douglas Gregor3f396022009-09-28 04:47:19 +00002226 if (!CandidateSet.isNewCandidate(Function))
2227 return;
2228
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002229 // Add this candidate
2230 CandidateSet.push_back(OverloadCandidate());
2231 OverloadCandidate& Candidate = CandidateSet.back();
2232 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00002233 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002234 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002235 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002236
2237 unsigned NumArgsInProto = Proto->getNumArgs();
2238
2239 // (C++ 13.3.2p2): A candidate function having fewer than m
2240 // parameters is viable only if it has an ellipsis in its parameter
2241 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00002242 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2243 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002244 Candidate.Viable = false;
2245 return;
2246 }
2247
2248 // (C++ 13.3.2p2): A candidate function having more than m parameters
2249 // is viable only if the (m+1)st parameter has a default argument
2250 // (8.3.6). For the purposes of overload resolution, the
2251 // parameter list is truncated on the right, so that there are
2252 // exactly m parameters.
2253 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002254 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002255 // Not enough arguments.
2256 Candidate.Viable = false;
2257 return;
2258 }
2259
2260 // Determine the implicit conversion sequences for each of the
2261 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002262 Candidate.Conversions.resize(NumArgs);
2263 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2264 if (ArgIdx < NumArgsInProto) {
2265 // (C++ 13.3.2p3): for F to be a viable function, there shall
2266 // exist for each argument an implicit conversion sequence
2267 // (13.3.3.1) that converts that argument to the corresponding
2268 // parameter of F.
2269 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002270 Candidate.Conversions[ArgIdx]
2271 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002272 SuppressUserConversions, ForceRValue,
2273 /*InOverloadResolution=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00002274 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002275 == ImplicitConversionSequence::BadConversion) {
Fariborz Jahanian99d6c442009-09-28 19:06:58 +00002276 // 13.3.3.1-p10 If several different sequences of conversions exist that
2277 // each convert the argument to the parameter type, the implicit conversion
2278 // sequence associated with the parameter is defined to be the unique conversion
2279 // sequence designated the ambiguous conversion sequence. For the purpose of
2280 // ranking implicit conversion sequences as described in 13.3.3.2, the ambiguous
2281 // conversion sequence is treated as a user-defined sequence that is
2282 // indistinguishable from any other user-defined conversion sequence
Fariborz Jahanian4a6a2b82009-09-29 17:31:54 +00002283 if (!Candidate.Conversions[ArgIdx].ConversionFunctionSet.empty()) {
Fariborz Jahanian99d6c442009-09-28 19:06:58 +00002284 Candidate.Conversions[ArgIdx].ConversionKind =
2285 ImplicitConversionSequence::UserDefinedConversion;
Fariborz Jahanian4a6a2b82009-09-29 17:31:54 +00002286 // Set the conversion function to one of them. As due to ambiguity,
2287 // they carry the same weight and is needed for overload resolution
2288 // later.
2289 Candidate.Conversions[ArgIdx].UserDefined.ConversionFunction =
2290 Candidate.Conversions[ArgIdx].ConversionFunctionSet[0];
2291 }
Fariborz Jahanian99d6c442009-09-28 19:06:58 +00002292 else {
2293 Candidate.Viable = false;
2294 break;
2295 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002296 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002297 } else {
2298 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2299 // argument for which there is no corresponding parameter is
2300 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002301 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002302 = ImplicitConversionSequence::EllipsisConversion;
2303 }
2304 }
2305}
2306
Douglas Gregor063daf62009-03-13 18:40:31 +00002307/// \brief Add all of the function declarations in the given function set to
2308/// the overload canddiate set.
2309void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2310 Expr **Args, unsigned NumArgs,
2311 OverloadCandidateSet& CandidateSet,
2312 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00002313 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor063daf62009-03-13 18:40:31 +00002314 FEnd = Functions.end();
Douglas Gregor364e0212009-06-27 21:05:07 +00002315 F != FEnd; ++F) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002316 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2317 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2318 AddMethodCandidate(cast<CXXMethodDecl>(FD),
2319 Args[0], Args + 1, NumArgs - 1,
2320 CandidateSet, SuppressUserConversions);
2321 else
2322 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2323 SuppressUserConversions);
2324 } else {
2325 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2326 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2327 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2328 AddMethodTemplateCandidate(FunTmpl,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002329 /*FIXME: explicit args */false, 0, 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00002330 Args[0], Args + 1, NumArgs - 1,
2331 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00002332 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00002333 else
2334 AddTemplateOverloadCandidate(FunTmpl,
2335 /*FIXME: explicit args */false, 0, 0,
2336 Args, NumArgs, CandidateSet,
2337 SuppressUserConversions);
2338 }
Douglas Gregor364e0212009-06-27 21:05:07 +00002339 }
Douglas Gregor063daf62009-03-13 18:40:31 +00002340}
2341
Douglas Gregor96176b32008-11-18 23:14:02 +00002342/// AddMethodCandidate - Adds the given C++ member function to the set
2343/// of candidate functions, using the given function call arguments
2344/// and the object argument (@c Object). For example, in a call
2345/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2346/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2347/// allow user-defined conversions via constructors or conversion
Sebastian Redle2b68332009-04-12 17:16:29 +00002348/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2349/// a slightly hacky way to implement the overloading rules for elidable copy
2350/// initialization in C++0x (C++0x 12.8p15).
Mike Stump1eb44332009-09-09 15:08:12 +00002351void
Douglas Gregor96176b32008-11-18 23:14:02 +00002352Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2353 Expr **Args, unsigned NumArgs,
2354 OverloadCandidateSet& CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00002355 bool SuppressUserConversions, bool ForceRValue) {
2356 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002357 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00002358 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002359 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor96176b32008-11-18 23:14:02 +00002360 "Use AddConversionCandidate for conversion functions");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002361 assert(!isa<CXXConstructorDecl>(Method) &&
2362 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00002363
Douglas Gregor3f396022009-09-28 04:47:19 +00002364 if (!CandidateSet.isNewCandidate(Method))
2365 return;
2366
Douglas Gregor96176b32008-11-18 23:14:02 +00002367 // Add this candidate
2368 CandidateSet.push_back(OverloadCandidate());
2369 OverloadCandidate& Candidate = CandidateSet.back();
2370 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002371 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002372 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002373
2374 unsigned NumArgsInProto = Proto->getNumArgs();
2375
2376 // (C++ 13.3.2p2): A candidate function having fewer than m
2377 // parameters is viable only if it has an ellipsis in its parameter
2378 // list (8.3.5).
2379 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2380 Candidate.Viable = false;
2381 return;
2382 }
2383
2384 // (C++ 13.3.2p2): A candidate function having more than m parameters
2385 // is viable only if the (m+1)st parameter has a default argument
2386 // (8.3.6). For the purposes of overload resolution, the
2387 // parameter list is truncated on the right, so that there are
2388 // exactly m parameters.
2389 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2390 if (NumArgs < MinRequiredArgs) {
2391 // Not enough arguments.
2392 Candidate.Viable = false;
2393 return;
2394 }
2395
2396 Candidate.Viable = true;
2397 Candidate.Conversions.resize(NumArgs + 1);
2398
Douglas Gregor88a35142008-12-22 05:46:06 +00002399 if (Method->isStatic() || !Object)
2400 // The implicit object argument is ignored.
2401 Candidate.IgnoreObjectArgument = true;
2402 else {
2403 // Determine the implicit conversion sequence for the object
2404 // parameter.
2405 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
Mike Stump1eb44332009-09-09 15:08:12 +00002406 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor88a35142008-12-22 05:46:06 +00002407 == ImplicitConversionSequence::BadConversion) {
2408 Candidate.Viable = false;
2409 return;
2410 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002411 }
2412
2413 // Determine the implicit conversion sequences for each of the
2414 // arguments.
2415 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2416 if (ArgIdx < NumArgsInProto) {
2417 // (C++ 13.3.2p3): for F to be a viable function, there shall
2418 // exist for each argument an implicit conversion sequence
2419 // (13.3.3.1) that converts that argument to the corresponding
2420 // parameter of F.
2421 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002422 Candidate.Conversions[ArgIdx + 1]
2423 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002424 SuppressUserConversions, ForceRValue,
Anders Carlsson08972922009-08-28 15:33:32 +00002425 /*InOverloadResolution=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00002426 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002427 == ImplicitConversionSequence::BadConversion) {
2428 Candidate.Viable = false;
2429 break;
2430 }
2431 } else {
2432 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2433 // argument for which there is no corresponding parameter is
2434 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002435 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002436 = ImplicitConversionSequence::EllipsisConversion;
2437 }
2438 }
2439}
2440
Douglas Gregor6b906862009-08-21 00:16:32 +00002441/// \brief Add a C++ member function template as a candidate to the candidate
2442/// set, using template argument deduction to produce an appropriate member
2443/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002444void
Douglas Gregor6b906862009-08-21 00:16:32 +00002445Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2446 bool HasExplicitTemplateArgs,
John McCall833ca992009-10-29 08:12:44 +00002447 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002448 unsigned NumExplicitTemplateArgs,
2449 Expr *Object, Expr **Args, unsigned NumArgs,
2450 OverloadCandidateSet& CandidateSet,
2451 bool SuppressUserConversions,
2452 bool ForceRValue) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002453 if (!CandidateSet.isNewCandidate(MethodTmpl))
2454 return;
2455
Douglas Gregor6b906862009-08-21 00:16:32 +00002456 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002457 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00002458 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002459 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00002460 // candidate functions in the usual way.113) A given name can refer to one
2461 // or more function templates and also to a set of overloaded non-template
2462 // functions. In such a case, the candidate functions generated from each
2463 // function template are combined with the set of non-template candidate
2464 // functions.
2465 TemplateDeductionInfo Info(Context);
2466 FunctionDecl *Specialization = 0;
2467 if (TemplateDeductionResult Result
2468 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2469 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2470 Args, NumArgs, Specialization, Info)) {
2471 // FIXME: Record what happened with template argument deduction, so
2472 // that we can give the user a beautiful diagnostic.
2473 (void)Result;
2474 return;
2475 }
Mike Stump1eb44332009-09-09 15:08:12 +00002476
Douglas Gregor6b906862009-08-21 00:16:32 +00002477 // Add the function template specialization produced by template argument
2478 // deduction as a candidate.
2479 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00002480 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00002481 "Specialization is not a member function?");
Mike Stump1eb44332009-09-09 15:08:12 +00002482 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002483 CandidateSet, SuppressUserConversions, ForceRValue);
2484}
2485
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002486/// \brief Add a C++ function template specialization as a candidate
2487/// in the candidate set, using template argument deduction to produce
2488/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002489void
Douglas Gregore53060f2009-06-25 22:08:12 +00002490Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002491 bool HasExplicitTemplateArgs,
John McCall833ca992009-10-29 08:12:44 +00002492 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002493 unsigned NumExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002494 Expr **Args, unsigned NumArgs,
2495 OverloadCandidateSet& CandidateSet,
2496 bool SuppressUserConversions,
2497 bool ForceRValue) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002498 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2499 return;
2500
Douglas Gregore53060f2009-06-25 22:08:12 +00002501 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002502 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00002503 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002504 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00002505 // candidate functions in the usual way.113) A given name can refer to one
2506 // or more function templates and also to a set of overloaded non-template
2507 // functions. In such a case, the candidate functions generated from each
2508 // function template are combined with the set of non-template candidate
2509 // functions.
2510 TemplateDeductionInfo Info(Context);
2511 FunctionDecl *Specialization = 0;
2512 if (TemplateDeductionResult Result
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002513 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2514 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2515 Args, NumArgs, Specialization, Info)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002516 // FIXME: Record what happened with template argument deduction, so
2517 // that we can give the user a beautiful diagnostic.
2518 (void)Result;
2519 return;
2520 }
Mike Stump1eb44332009-09-09 15:08:12 +00002521
Douglas Gregore53060f2009-06-25 22:08:12 +00002522 // Add the function template specialization produced by template argument
2523 // deduction as a candidate.
2524 assert(Specialization && "Missing function template specialization?");
2525 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2526 SuppressUserConversions, ForceRValue);
2527}
Mike Stump1eb44332009-09-09 15:08:12 +00002528
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002529/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00002530/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002531/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00002532/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002533/// (which may or may not be the same type as the type that the
2534/// conversion function produces).
2535void
2536Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2537 Expr *From, QualType ToType,
2538 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002539 assert(!Conversion->getDescribedFunctionTemplate() &&
2540 "Conversion function templates use AddTemplateConversionCandidate");
2541
Douglas Gregor3f396022009-09-28 04:47:19 +00002542 if (!CandidateSet.isNewCandidate(Conversion))
2543 return;
2544
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002545 // Add this candidate
2546 CandidateSet.push_back(OverloadCandidate());
2547 OverloadCandidate& Candidate = CandidateSet.back();
2548 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002549 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002550 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002551 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump1eb44332009-09-09 15:08:12 +00002552 Candidate.FinalConversion.FromTypePtr
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002553 = Conversion->getConversionType().getAsOpaquePtr();
2554 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2555
Douglas Gregor96176b32008-11-18 23:14:02 +00002556 // Determine the implicit conversion sequence for the implicit
2557 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002558 Candidate.Viable = true;
2559 Candidate.Conversions.resize(1);
Douglas Gregor96176b32008-11-18 23:14:02 +00002560 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002561 // Conversion functions to a different type in the base class is visible in
2562 // the derived class. So, a derived to base conversion should not participate
2563 // in overload resolution.
2564 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2565 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump1eb44332009-09-09 15:08:12 +00002566 if (Candidate.Conversions[0].ConversionKind
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002567 == ImplicitConversionSequence::BadConversion) {
2568 Candidate.Viable = false;
2569 return;
2570 }
Fariborz Jahanian3759a032009-10-19 19:18:20 +00002571
2572 // We won't go through a user-define type conversion function to convert a
2573 // derived to base as such conversions are given Conversion Rank. They only
2574 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2575 QualType FromCanon
2576 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2577 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2578 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2579 Candidate.Viable = false;
2580 return;
2581 }
2582
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002583
2584 // To determine what the conversion from the result of calling the
2585 // conversion function to the type we're eventually trying to
2586 // convert to (ToType), we need to synthesize a call to the
2587 // conversion function and attempt copy initialization from it. This
2588 // makes sure that we get the right semantics with respect to
2589 // lvalues/rvalues and the type. Fortunately, we can allocate this
2590 // call on the stack and we don't need its arguments to be
2591 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00002592 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002593 SourceLocation());
2594 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman73c39ab2009-10-20 08:27:19 +00002595 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002596 &ConversionRef, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002597
2598 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00002599 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2600 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00002601 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002602 Conversion->getConversionType().getNonReferenceType(),
2603 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002604 ImplicitConversionSequence ICS =
2605 TryCopyInitialization(&Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002606 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002607 /*ForceRValue=*/false,
2608 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002609
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002610 switch (ICS.ConversionKind) {
2611 case ImplicitConversionSequence::StandardConversion:
2612 Candidate.FinalConversion = ICS.Standard;
2613 break;
2614
2615 case ImplicitConversionSequence::BadConversion:
2616 Candidate.Viable = false;
2617 break;
2618
2619 default:
Mike Stump1eb44332009-09-09 15:08:12 +00002620 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002621 "Can only end up with a standard conversion sequence or failure");
2622 }
2623}
2624
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002625/// \brief Adds a conversion function template specialization
2626/// candidate to the overload set, using template argument deduction
2627/// to deduce the template arguments of the conversion function
2628/// template from the type that we are converting to (C++
2629/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00002630void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002631Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2632 Expr *From, QualType ToType,
2633 OverloadCandidateSet &CandidateSet) {
2634 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2635 "Only conversion function templates permitted here");
2636
Douglas Gregor3f396022009-09-28 04:47:19 +00002637 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2638 return;
2639
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002640 TemplateDeductionInfo Info(Context);
2641 CXXConversionDecl *Specialization = 0;
2642 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00002643 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002644 Specialization, Info)) {
2645 // FIXME: Record what happened with template argument deduction, so
2646 // that we can give the user a beautiful diagnostic.
2647 (void)Result;
2648 return;
2649 }
Mike Stump1eb44332009-09-09 15:08:12 +00002650
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002651 // Add the conversion function template specialization produced by
2652 // template argument deduction as a candidate.
2653 assert(Specialization && "Missing function template specialization?");
2654 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2655}
2656
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002657/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2658/// converts the given @c Object to a function pointer via the
2659/// conversion function @c Conversion, and then attempts to call it
2660/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2661/// the type of function that we'll eventually be calling.
2662void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregor72564e72009-02-26 23:50:07 +00002663 const FunctionProtoType *Proto,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002664 Expr *Object, Expr **Args, unsigned NumArgs,
2665 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002666 if (!CandidateSet.isNewCandidate(Conversion))
2667 return;
2668
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002669 CandidateSet.push_back(OverloadCandidate());
2670 OverloadCandidate& Candidate = CandidateSet.back();
2671 Candidate.Function = 0;
2672 Candidate.Surrogate = Conversion;
2673 Candidate.Viable = true;
2674 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002675 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002676 Candidate.Conversions.resize(NumArgs + 1);
2677
2678 // Determine the implicit conversion sequence for the implicit
2679 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00002680 ImplicitConversionSequence ObjectInit
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002681 = TryObjectArgumentInitialization(Object, Conversion);
2682 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2683 Candidate.Viable = false;
2684 return;
2685 }
2686
2687 // The first conversion is actually a user-defined conversion whose
2688 // first conversion is ObjectInit's standard conversion (which is
2689 // effectively a reference binding). Record it as such.
Mike Stump1eb44332009-09-09 15:08:12 +00002690 Candidate.Conversions[0].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002691 = ImplicitConversionSequence::UserDefinedConversion;
2692 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2693 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00002694 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002695 = Candidate.Conversions[0].UserDefined.Before;
2696 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2697
Mike Stump1eb44332009-09-09 15:08:12 +00002698 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002699 unsigned NumArgsInProto = Proto->getNumArgs();
2700
2701 // (C++ 13.3.2p2): A candidate function having fewer than m
2702 // parameters is viable only if it has an ellipsis in its parameter
2703 // list (8.3.5).
2704 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2705 Candidate.Viable = false;
2706 return;
2707 }
2708
2709 // Function types don't have any default arguments, so just check if
2710 // we have enough arguments.
2711 if (NumArgs < NumArgsInProto) {
2712 // Not enough arguments.
2713 Candidate.Viable = false;
2714 return;
2715 }
2716
2717 // Determine the implicit conversion sequences for each of the
2718 // arguments.
2719 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2720 if (ArgIdx < NumArgsInProto) {
2721 // (C++ 13.3.2p3): for F to be a viable function, there shall
2722 // exist for each argument an implicit conversion sequence
2723 // (13.3.3.1) that converts that argument to the corresponding
2724 // parameter of F.
2725 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002726 Candidate.Conversions[ArgIdx + 1]
2727 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002728 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002729 /*ForceRValue=*/false,
2730 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002731 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002732 == ImplicitConversionSequence::BadConversion) {
2733 Candidate.Viable = false;
2734 break;
2735 }
2736 } else {
2737 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2738 // argument for which there is no corresponding parameter is
2739 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002740 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002741 = ImplicitConversionSequence::EllipsisConversion;
2742 }
2743 }
2744}
2745
Mike Stump390b4cc2009-05-16 07:39:55 +00002746// FIXME: This will eventually be removed, once we've migrated all of the
2747// operator overloading logic over to the scheme used by binary operators, which
2748// works for template instantiation.
Douglas Gregor063daf62009-03-13 18:40:31 +00002749void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002750 SourceLocation OpLoc,
Douglas Gregor96176b32008-11-18 23:14:02 +00002751 Expr **Args, unsigned NumArgs,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002752 OverloadCandidateSet& CandidateSet,
2753 SourceRange OpRange) {
Douglas Gregor063daf62009-03-13 18:40:31 +00002754 FunctionSet Functions;
2755
2756 QualType T1 = Args[0]->getType();
2757 QualType T2;
2758 if (NumArgs > 1)
2759 T2 = Args[1]->getType();
2760
2761 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002762 if (S)
2763 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Sebastian Redl644be852009-10-23 19:23:15 +00002764 ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00002765 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2766 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002767 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00002768}
2769
2770/// \brief Add overload candidates for overloaded operators that are
2771/// member functions.
2772///
2773/// Add the overloaded operator candidates that are member functions
2774/// for the operator Op that was used in an operator expression such
2775/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2776/// CandidateSet will store the added overload candidates. (C++
2777/// [over.match.oper]).
2778void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2779 SourceLocation OpLoc,
2780 Expr **Args, unsigned NumArgs,
2781 OverloadCandidateSet& CandidateSet,
2782 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002783 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2784
2785 // C++ [over.match.oper]p3:
2786 // For a unary operator @ with an operand of a type whose
2787 // cv-unqualified version is T1, and for a binary operator @ with
2788 // a left operand of a type whose cv-unqualified version is T1 and
2789 // a right operand of a type whose cv-unqualified version is T2,
2790 // three sets of candidate functions, designated member
2791 // candidates, non-member candidates and built-in candidates, are
2792 // constructed as follows:
2793 QualType T1 = Args[0]->getType();
2794 QualType T2;
2795 if (NumArgs > 1)
2796 T2 = Args[1]->getType();
2797
2798 // -- If T1 is a class type, the set of member candidates is the
2799 // result of the qualified lookup of T1::operator@
2800 // (13.3.1.1.1); otherwise, the set of member candidates is
2801 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00002802 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002803 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00002804 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002805 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002806
John McCallf36e02d2009-10-09 21:13:30 +00002807 LookupResult Operators;
2808 LookupQualifiedName(Operators, T1Rec->getDecl(), OpName,
2809 LookupOrdinaryName, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002810 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002811 OperEnd = Operators.end();
2812 Oper != OperEnd;
Douglas Gregord9842d02009-10-14 16:50:13 +00002813 ++Oper) {
2814 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Oper)) {
2815 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet,
2816 /*SuppressUserConversions=*/false);
2817 continue;
2818 }
2819
2820 assert(isa<FunctionTemplateDecl>(*Oper) &&
2821 isa<CXXMethodDecl>(cast<FunctionTemplateDecl>(*Oper)
2822 ->getTemplatedDecl()) &&
2823 "Expected a member function template");
2824 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Oper), false, 0, 0,
2825 Args[0], Args+1, NumArgs - 1, CandidateSet,
2826 /*SuppressUserConversions=*/false);
2827 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002828 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002829}
2830
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002831/// AddBuiltinCandidate - Add a candidate for a built-in
2832/// operator. ResultTy and ParamTys are the result and parameter types
2833/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002834/// arguments being passed to the candidate. IsAssignmentOperator
2835/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002836/// operator. NumContextualBoolArguments is the number of arguments
2837/// (at the beginning of the argument list) that will be contextually
2838/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00002839void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002840 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002841 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002842 bool IsAssignmentOperator,
2843 unsigned NumContextualBoolArguments) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002844 // Add this candidate
2845 CandidateSet.push_back(OverloadCandidate());
2846 OverloadCandidate& Candidate = CandidateSet.back();
2847 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00002848 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002849 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002850 Candidate.BuiltinTypes.ResultTy = ResultTy;
2851 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2852 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2853
2854 // Determine the implicit conversion sequences for each of the
2855 // arguments.
2856 Candidate.Viable = true;
2857 Candidate.Conversions.resize(NumArgs);
2858 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002859 // C++ [over.match.oper]p4:
2860 // For the built-in assignment operators, conversions of the
2861 // left operand are restricted as follows:
2862 // -- no temporaries are introduced to hold the left operand, and
2863 // -- no user-defined conversions are applied to the left
2864 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00002865 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002866 //
2867 // We block these conversions by turning off user-defined
2868 // conversions, since that is the only way that initialization of
2869 // a reference to a non-class type can occur from something that
2870 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002871 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00002872 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002873 "Contextual conversion to bool requires bool type");
2874 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2875 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002876 Candidate.Conversions[ArgIdx]
2877 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00002878 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002879 /*ForceRValue=*/false,
2880 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002881 }
Mike Stump1eb44332009-09-09 15:08:12 +00002882 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002883 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002884 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002885 break;
2886 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002887 }
2888}
2889
2890/// BuiltinCandidateTypeSet - A set of types that will be used for the
2891/// candidate operator functions for built-in operators (C++
2892/// [over.built]). The types are separated into pointer types and
2893/// enumeration types.
2894class BuiltinCandidateTypeSet {
2895 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002896 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002897
2898 /// PointerTypes - The set of pointer types that will be used in the
2899 /// built-in candidates.
2900 TypeSet PointerTypes;
2901
Sebastian Redl78eb8742009-04-19 21:53:20 +00002902 /// MemberPointerTypes - The set of member pointer types that will be
2903 /// used in the built-in candidates.
2904 TypeSet MemberPointerTypes;
2905
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002906 /// EnumerationTypes - The set of enumeration types that will be
2907 /// used in the built-in candidates.
2908 TypeSet EnumerationTypes;
2909
Douglas Gregor5842ba92009-08-24 15:23:48 +00002910 /// Sema - The semantic analysis instance where we are building the
2911 /// candidate type set.
2912 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00002913
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002914 /// Context - The AST context in which we will build the type sets.
2915 ASTContext &Context;
2916
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00002917 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
2918 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00002919 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002920
2921public:
2922 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002923 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002924
Mike Stump1eb44332009-09-09 15:08:12 +00002925 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00002926 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002927
Douglas Gregor573d9c32009-10-21 23:19:44 +00002928 void AddTypesConvertedFrom(QualType Ty,
2929 SourceLocation Loc,
2930 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00002931 bool AllowExplicitConversions,
2932 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002933
2934 /// pointer_begin - First pointer type found;
2935 iterator pointer_begin() { return PointerTypes.begin(); }
2936
Sebastian Redl78eb8742009-04-19 21:53:20 +00002937 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002938 iterator pointer_end() { return PointerTypes.end(); }
2939
Sebastian Redl78eb8742009-04-19 21:53:20 +00002940 /// member_pointer_begin - First member pointer type found;
2941 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2942
2943 /// member_pointer_end - Past the last member pointer type found;
2944 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2945
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002946 /// enumeration_begin - First enumeration type found;
2947 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2948
Sebastian Redl78eb8742009-04-19 21:53:20 +00002949 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002950 iterator enumeration_end() { return EnumerationTypes.end(); }
2951};
2952
Sebastian Redl78eb8742009-04-19 21:53:20 +00002953/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002954/// the set of pointer types along with any more-qualified variants of
2955/// that type. For example, if @p Ty is "int const *", this routine
2956/// will add "int const *", "int const volatile *", "int const
2957/// restrict *", and "int const volatile restrict *" to the set of
2958/// pointer types. Returns true if the add of @p Ty itself succeeded,
2959/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00002960///
2961/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00002962bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00002963BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
2964 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00002965
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002966 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00002967 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002968 return false;
2969
John McCall0953e762009-09-24 19:53:00 +00002970 const PointerType *PointerTy = Ty->getAs<PointerType>();
2971 assert(PointerTy && "type was not a pointer type!");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002972
John McCall0953e762009-09-24 19:53:00 +00002973 QualType PointeeTy = PointerTy->getPointeeType();
2974 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00002975 bool hasVolatile = VisibleQuals.hasVolatile();
2976 bool hasRestrict = VisibleQuals.hasRestrict();
2977
John McCall0953e762009-09-24 19:53:00 +00002978 // Iterate through all strict supersets of BaseCVR.
2979 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
2980 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00002981 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
2982 // in the types.
2983 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
2984 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00002985 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
2986 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002987 }
2988
2989 return true;
2990}
2991
Sebastian Redl78eb8742009-04-19 21:53:20 +00002992/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2993/// to the set of pointer types along with any more-qualified variants of
2994/// that type. For example, if @p Ty is "int const *", this routine
2995/// will add "int const *", "int const volatile *", "int const
2996/// restrict *", and "int const volatile restrict *" to the set of
2997/// pointer types. Returns true if the add of @p Ty itself succeeded,
2998/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00002999///
3000/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003001bool
3002BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3003 QualType Ty) {
3004 // Insert this type.
3005 if (!MemberPointerTypes.insert(Ty))
3006 return false;
3007
John McCall0953e762009-09-24 19:53:00 +00003008 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3009 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00003010
John McCall0953e762009-09-24 19:53:00 +00003011 QualType PointeeTy = PointerTy->getPointeeType();
3012 const Type *ClassTy = PointerTy->getClass();
3013
3014 // Iterate through all strict supersets of the pointee type's CVR
3015 // qualifiers.
3016 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3017 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3018 if ((CVR | BaseCVR) != CVR) continue;
3019
3020 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3021 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00003022 }
3023
3024 return true;
3025}
3026
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003027/// AddTypesConvertedFrom - Add each of the types to which the type @p
3028/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00003029/// primarily interested in pointer types and enumeration types. We also
3030/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003031/// AllowUserConversions is true if we should look at the conversion
3032/// functions of a class type, and AllowExplicitConversions if we
3033/// should also include the explicit conversion functions of a class
3034/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003035void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003036BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003037 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003038 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003039 bool AllowExplicitConversions,
3040 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003041 // Only deal with canonical types.
3042 Ty = Context.getCanonicalType(Ty);
3043
3044 // Look through reference types; they aren't part of the type of an
3045 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00003046 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003047 Ty = RefTy->getPointeeType();
3048
3049 // We don't care about qualifiers on the type.
3050 Ty = Ty.getUnqualifiedType();
3051
Ted Kremenek6217b802009-07-29 21:53:49 +00003052 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003053 QualType PointeeTy = PointerTy->getPointeeType();
3054
3055 // Insert our type, and its more-qualified variants, into the set
3056 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003057 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003058 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00003059 } else if (Ty->isMemberPointerType()) {
3060 // Member pointers are far easier, since the pointee can't be converted.
3061 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3062 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003063 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00003064 EnumerationTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003065 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003066 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003067 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003068 // No conversion functions in incomplete types.
3069 return;
3070 }
Mike Stump1eb44332009-09-09 15:08:12 +00003071
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003072 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003073 OverloadedFunctionDecl *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00003074 = ClassDecl->getVisibleConversionFunctions();
Mike Stump1eb44332009-09-09 15:08:12 +00003075 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003076 = Conversions->function_begin();
3077 Func != Conversions->function_end(); ++Func) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003078 CXXConversionDecl *Conv;
3079 FunctionTemplateDecl *ConvTemplate;
3080 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
3081
Mike Stump1eb44332009-09-09 15:08:12 +00003082 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003083 // about which builtin types we can convert to.
3084 if (ConvTemplate)
3085 continue;
3086
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003087 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003088 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003089 VisibleQuals);
3090 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003091 }
3092 }
3093 }
3094}
3095
Douglas Gregor19b7b152009-08-24 13:43:27 +00003096/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3097/// the volatile- and non-volatile-qualified assignment operators for the
3098/// given type to the candidate set.
3099static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3100 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00003101 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003102 unsigned NumArgs,
3103 OverloadCandidateSet &CandidateSet) {
3104 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00003105
Douglas Gregor19b7b152009-08-24 13:43:27 +00003106 // T& operator=(T&, T)
3107 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3108 ParamTypes[1] = T;
3109 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3110 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003111
Douglas Gregor19b7b152009-08-24 13:43:27 +00003112 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3113 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00003114 ParamTypes[0]
3115 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00003116 ParamTypes[1] = T;
3117 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00003118 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003119 }
3120}
Mike Stump1eb44332009-09-09 15:08:12 +00003121
Sebastian Redl9994a342009-10-25 17:03:50 +00003122/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3123/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003124static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3125 Qualifiers VRQuals;
3126 const RecordType *TyRec;
3127 if (const MemberPointerType *RHSMPType =
3128 ArgExpr->getType()->getAs<MemberPointerType>())
3129 TyRec = cast<RecordType>(RHSMPType->getClass());
3130 else
3131 TyRec = ArgExpr->getType()->getAs<RecordType>();
3132 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003133 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003134 VRQuals.addVolatile();
3135 VRQuals.addRestrict();
3136 return VRQuals;
3137 }
3138
3139 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
3140 OverloadedFunctionDecl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00003141 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003142
3143 for (OverloadedFunctionDecl::function_iterator Func
3144 = Conversions->function_begin();
3145 Func != Conversions->function_end(); ++Func) {
3146 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*Func)) {
3147 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3148 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3149 CanTy = ResTypeRef->getPointeeType();
3150 // Need to go down the pointer/mempointer chain and add qualifiers
3151 // as see them.
3152 bool done = false;
3153 while (!done) {
3154 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3155 CanTy = ResTypePtr->getPointeeType();
3156 else if (const MemberPointerType *ResTypeMPtr =
3157 CanTy->getAs<MemberPointerType>())
3158 CanTy = ResTypeMPtr->getPointeeType();
3159 else
3160 done = true;
3161 if (CanTy.isVolatileQualified())
3162 VRQuals.addVolatile();
3163 if (CanTy.isRestrictQualified())
3164 VRQuals.addRestrict();
3165 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3166 return VRQuals;
3167 }
3168 }
3169 }
3170 return VRQuals;
3171}
3172
Douglas Gregor74253732008-11-19 15:42:04 +00003173/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3174/// operator overloads to the candidate set (C++ [over.built]), based
3175/// on the operator @p Op and the arguments given. For example, if the
3176/// operator is a binary '+', this routine might add "int
3177/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003178void
Mike Stump1eb44332009-09-09 15:08:12 +00003179Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003180 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00003181 Expr **Args, unsigned NumArgs,
3182 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003183 // The set of "promoted arithmetic types", which are the arithmetic
3184 // types are that preserved by promotion (C++ [over.built]p2). Note
3185 // that the first few of these types are the promoted integral
3186 // types; these types need to be first.
3187 // FIXME: What about complex?
3188 const unsigned FirstIntegralType = 0;
3189 const unsigned LastIntegralType = 13;
Mike Stump1eb44332009-09-09 15:08:12 +00003190 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003191 LastPromotedIntegralType = 13;
3192 const unsigned FirstPromotedArithmeticType = 7,
3193 LastPromotedArithmeticType = 16;
3194 const unsigned NumArithmeticTypes = 16;
3195 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00003196 Context.BoolTy, Context.CharTy, Context.WCharTy,
3197// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003198 Context.SignedCharTy, Context.ShortTy,
3199 Context.UnsignedCharTy, Context.UnsignedShortTy,
3200 Context.IntTy, Context.LongTy, Context.LongLongTy,
3201 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3202 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3203 };
Douglas Gregor652371a2009-10-21 22:01:30 +00003204 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3205 "Invalid first promoted integral type");
3206 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3207 == Context.UnsignedLongLongTy &&
3208 "Invalid last promoted integral type");
3209 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3210 "Invalid first promoted arithmetic type");
3211 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3212 == Context.LongDoubleTy &&
3213 "Invalid last promoted arithmetic type");
3214
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003215 // Find all of the types that the arguments can convert to, but only
3216 // if the operator we're looking at has built-in operator candidates
3217 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003218 Qualifiers VisibleTypeConversionsQuals;
3219 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003220 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3221 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3222
Douglas Gregor5842ba92009-08-24 15:23:48 +00003223 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003224 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3225 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00003226 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003227 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00003228 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003229 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor74253732008-11-19 15:42:04 +00003230 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003231 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregor573d9c32009-10-21 23:19:44 +00003232 OpLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003233 true,
3234 (Op == OO_Exclaim ||
3235 Op == OO_AmpAmp ||
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003236 Op == OO_PipePipe),
3237 VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003238 }
3239
3240 bool isComparison = false;
3241 switch (Op) {
3242 case OO_None:
3243 case NUM_OVERLOADED_OPERATORS:
3244 assert(false && "Expected an overloaded operator");
3245 break;
3246
Douglas Gregor74253732008-11-19 15:42:04 +00003247 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00003248 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00003249 goto UnaryStar;
3250 else
3251 goto BinaryStar;
3252 break;
3253
3254 case OO_Plus: // '+' is either unary or binary
3255 if (NumArgs == 1)
3256 goto UnaryPlus;
3257 else
3258 goto BinaryPlus;
3259 break;
3260
3261 case OO_Minus: // '-' is either unary or binary
3262 if (NumArgs == 1)
3263 goto UnaryMinus;
3264 else
3265 goto BinaryMinus;
3266 break;
3267
3268 case OO_Amp: // '&' is either unary or binary
3269 if (NumArgs == 1)
3270 goto UnaryAmp;
3271 else
3272 goto BinaryAmp;
3273
3274 case OO_PlusPlus:
3275 case OO_MinusMinus:
3276 // C++ [over.built]p3:
3277 //
3278 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3279 // is either volatile or empty, there exist candidate operator
3280 // functions of the form
3281 //
3282 // VQ T& operator++(VQ T&);
3283 // T operator++(VQ T&, int);
3284 //
3285 // C++ [over.built]p4:
3286 //
3287 // For every pair (T, VQ), where T is an arithmetic type other
3288 // than bool, and VQ is either volatile or empty, there exist
3289 // candidate operator functions of the form
3290 //
3291 // VQ T& operator--(VQ T&);
3292 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00003293 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00003294 Arith < NumArithmeticTypes; ++Arith) {
3295 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00003296 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003297 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00003298
3299 // Non-volatile version.
3300 if (NumArgs == 1)
3301 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3302 else
3303 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003304 // heuristic to reduce number of builtin candidates in the set.
3305 // Add volatile version only if there are conversions to a volatile type.
3306 if (VisibleTypeConversionsQuals.hasVolatile()) {
3307 // Volatile version
3308 ParamTypes[0]
3309 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3310 if (NumArgs == 1)
3311 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3312 else
3313 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3314 }
Douglas Gregor74253732008-11-19 15:42:04 +00003315 }
3316
3317 // C++ [over.built]p5:
3318 //
3319 // For every pair (T, VQ), where T is a cv-qualified or
3320 // cv-unqualified object type, and VQ is either volatile or
3321 // empty, there exist candidate operator functions of the form
3322 //
3323 // T*VQ& operator++(T*VQ&);
3324 // T*VQ& operator--(T*VQ&);
3325 // T* operator++(T*VQ&, int);
3326 // T* operator--(T*VQ&, int);
3327 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3328 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3329 // Skip pointer types that aren't pointers to object types.
Ted Kremenek6217b802009-07-29 21:53:49 +00003330 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00003331 continue;
3332
Mike Stump1eb44332009-09-09 15:08:12 +00003333 QualType ParamTypes[2] = {
3334 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00003335 };
Mike Stump1eb44332009-09-09 15:08:12 +00003336
Douglas Gregor74253732008-11-19 15:42:04 +00003337 // Without volatile
3338 if (NumArgs == 1)
3339 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3340 else
3341 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3342
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003343 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3344 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00003345 // With volatile
John McCall0953e762009-09-24 19:53:00 +00003346 ParamTypes[0]
3347 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00003348 if (NumArgs == 1)
3349 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3350 else
3351 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3352 }
3353 }
3354 break;
3355
3356 UnaryStar:
3357 // C++ [over.built]p6:
3358 // For every cv-qualified or cv-unqualified object type T, there
3359 // exist candidate operator functions of the form
3360 //
3361 // T& operator*(T*);
3362 //
3363 // C++ [over.built]p7:
3364 // For every function type T, there exist candidate operator
3365 // functions of the form
3366 // T& operator*(T*);
3367 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3368 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3369 QualType ParamTy = *Ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00003370 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003371 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00003372 &ParamTy, Args, 1, CandidateSet);
3373 }
3374 break;
3375
3376 UnaryPlus:
3377 // C++ [over.built]p8:
3378 // For every type T, there exist candidate operator functions of
3379 // the form
3380 //
3381 // T* operator+(T*);
3382 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3383 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3384 QualType ParamTy = *Ptr;
3385 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3386 }
Mike Stump1eb44332009-09-09 15:08:12 +00003387
Douglas Gregor74253732008-11-19 15:42:04 +00003388 // Fall through
3389
3390 UnaryMinus:
3391 // C++ [over.built]p9:
3392 // For every promoted arithmetic type T, there exist candidate
3393 // operator functions of the form
3394 //
3395 // T operator+(T);
3396 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003397 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00003398 Arith < LastPromotedArithmeticType; ++Arith) {
3399 QualType ArithTy = ArithmeticTypes[Arith];
3400 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3401 }
3402 break;
3403
3404 case OO_Tilde:
3405 // C++ [over.built]p10:
3406 // For every promoted integral type T, there exist candidate
3407 // operator functions of the form
3408 //
3409 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003410 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00003411 Int < LastPromotedIntegralType; ++Int) {
3412 QualType IntTy = ArithmeticTypes[Int];
3413 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3414 }
3415 break;
3416
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003417 case OO_New:
3418 case OO_Delete:
3419 case OO_Array_New:
3420 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003421 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00003422 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003423 break;
3424
3425 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00003426 UnaryAmp:
3427 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003428 // C++ [over.match.oper]p3:
3429 // -- For the operator ',', the unary operator '&', or the
3430 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003431 break;
3432
Douglas Gregor19b7b152009-08-24 13:43:27 +00003433 case OO_EqualEqual:
3434 case OO_ExclaimEqual:
3435 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00003436 // For every pointer to member type T, there exist candidate operator
3437 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00003438 //
3439 // bool operator==(T,T);
3440 // bool operator!=(T,T);
Mike Stump1eb44332009-09-09 15:08:12 +00003441 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor19b7b152009-08-24 13:43:27 +00003442 MemPtr = CandidateTypes.member_pointer_begin(),
3443 MemPtrEnd = CandidateTypes.member_pointer_end();
3444 MemPtr != MemPtrEnd;
3445 ++MemPtr) {
3446 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3447 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3448 }
Mike Stump1eb44332009-09-09 15:08:12 +00003449
Douglas Gregor19b7b152009-08-24 13:43:27 +00003450 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00003451
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003452 case OO_Less:
3453 case OO_Greater:
3454 case OO_LessEqual:
3455 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003456 // C++ [over.built]p15:
3457 //
3458 // For every pointer or enumeration type T, there exist
3459 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003460 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003461 // bool operator<(T, T);
3462 // bool operator>(T, T);
3463 // bool operator<=(T, T);
3464 // bool operator>=(T, T);
3465 // bool operator==(T, T);
3466 // bool operator!=(T, T);
3467 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3468 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3469 QualType ParamTypes[2] = { *Ptr, *Ptr };
3470 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3471 }
Mike Stump1eb44332009-09-09 15:08:12 +00003472 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003473 = CandidateTypes.enumeration_begin();
3474 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3475 QualType ParamTypes[2] = { *Enum, *Enum };
3476 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3477 }
3478
3479 // Fall through.
3480 isComparison = true;
3481
Douglas Gregor74253732008-11-19 15:42:04 +00003482 BinaryPlus:
3483 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003484 if (!isComparison) {
3485 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3486
3487 // C++ [over.built]p13:
3488 //
3489 // For every cv-qualified or cv-unqualified object type T
3490 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003491 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003492 // T* operator+(T*, ptrdiff_t);
3493 // T& operator[](T*, ptrdiff_t); [BELOW]
3494 // T* operator-(T*, ptrdiff_t);
3495 // T* operator+(ptrdiff_t, T*);
3496 // T& operator[](ptrdiff_t, T*); [BELOW]
3497 //
3498 // C++ [over.built]p14:
3499 //
3500 // For every T, where T is a pointer to object type, there
3501 // exist candidate operator functions of the form
3502 //
3503 // ptrdiff_t operator-(T, T);
Mike Stump1eb44332009-09-09 15:08:12 +00003504 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003505 = CandidateTypes.pointer_begin();
3506 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3507 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3508
3509 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3510 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3511
3512 if (Op == OO_Plus) {
3513 // T* operator+(ptrdiff_t, T*);
3514 ParamTypes[0] = ParamTypes[1];
3515 ParamTypes[1] = *Ptr;
3516 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3517 } else {
3518 // ptrdiff_t operator-(T, T);
3519 ParamTypes[1] = *Ptr;
3520 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3521 Args, 2, CandidateSet);
3522 }
3523 }
3524 }
3525 // Fall through
3526
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003527 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00003528 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003529 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003530 // C++ [over.built]p12:
3531 //
3532 // For every pair of promoted arithmetic types L and R, there
3533 // exist candidate operator functions of the form
3534 //
3535 // LR operator*(L, R);
3536 // LR operator/(L, R);
3537 // LR operator+(L, R);
3538 // LR operator-(L, R);
3539 // bool operator<(L, R);
3540 // bool operator>(L, R);
3541 // bool operator<=(L, R);
3542 // bool operator>=(L, R);
3543 // bool operator==(L, R);
3544 // bool operator!=(L, R);
3545 //
3546 // where LR is the result of the usual arithmetic conversions
3547 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003548 //
3549 // C++ [over.built]p24:
3550 //
3551 // For every pair of promoted arithmetic types L and R, there exist
3552 // candidate operator functions of the form
3553 //
3554 // LR operator?(bool, L, R);
3555 //
3556 // where LR is the result of the usual arithmetic conversions
3557 // between types L and R.
3558 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003559 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003560 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003561 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003562 Right < LastPromotedArithmeticType; ++Right) {
3563 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00003564 QualType Result
3565 = isComparison
3566 ? Context.BoolTy
3567 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003568 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3569 }
3570 }
3571 break;
3572
3573 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00003574 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003575 case OO_Caret:
3576 case OO_Pipe:
3577 case OO_LessLess:
3578 case OO_GreaterGreater:
3579 // C++ [over.built]p17:
3580 //
3581 // For every pair of promoted integral types L and R, there
3582 // exist candidate operator functions of the form
3583 //
3584 // LR operator%(L, R);
3585 // LR operator&(L, R);
3586 // LR operator^(L, R);
3587 // LR operator|(L, R);
3588 // L operator<<(L, R);
3589 // L operator>>(L, R);
3590 //
3591 // where LR is the result of the usual arithmetic conversions
3592 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00003593 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003594 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003595 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003596 Right < LastPromotedIntegralType; ++Right) {
3597 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3598 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3599 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00003600 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003601 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3602 }
3603 }
3604 break;
3605
3606 case OO_Equal:
3607 // C++ [over.built]p20:
3608 //
3609 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00003610 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003611 // empty, there exist candidate operator functions of the form
3612 //
3613 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003614 for (BuiltinCandidateTypeSet::iterator
3615 Enum = CandidateTypes.enumeration_begin(),
3616 EnumEnd = CandidateTypes.enumeration_end();
3617 Enum != EnumEnd; ++Enum)
Mike Stump1eb44332009-09-09 15:08:12 +00003618 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003619 CandidateSet);
3620 for (BuiltinCandidateTypeSet::iterator
3621 MemPtr = CandidateTypes.member_pointer_begin(),
3622 MemPtrEnd = CandidateTypes.member_pointer_end();
3623 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump1eb44332009-09-09 15:08:12 +00003624 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003625 CandidateSet);
3626 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003627
3628 case OO_PlusEqual:
3629 case OO_MinusEqual:
3630 // C++ [over.built]p19:
3631 //
3632 // For every pair (T, VQ), where T is any type and VQ is either
3633 // volatile or empty, there exist candidate operator functions
3634 // of the form
3635 //
3636 // T*VQ& operator=(T*VQ&, T*);
3637 //
3638 // C++ [over.built]p21:
3639 //
3640 // For every pair (T, VQ), where T is a cv-qualified or
3641 // cv-unqualified object type and VQ is either volatile or
3642 // empty, there exist candidate operator functions of the form
3643 //
3644 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3645 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3646 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3647 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3648 QualType ParamTypes[2];
3649 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3650
3651 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003652 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003653 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3654 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003655
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003656 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3657 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00003658 // volatile version
John McCall0953e762009-09-24 19:53:00 +00003659 ParamTypes[0]
3660 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003661 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3662 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00003663 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003664 }
3665 // Fall through.
3666
3667 case OO_StarEqual:
3668 case OO_SlashEqual:
3669 // C++ [over.built]p18:
3670 //
3671 // For every triple (L, VQ, R), where L is an arithmetic type,
3672 // VQ is either volatile or empty, and R is a promoted
3673 // arithmetic type, there exist candidate operator functions of
3674 // the form
3675 //
3676 // VQ L& operator=(VQ L&, R);
3677 // VQ L& operator*=(VQ L&, R);
3678 // VQ L& operator/=(VQ L&, R);
3679 // VQ L& operator+=(VQ L&, R);
3680 // VQ L& operator-=(VQ L&, R);
3681 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003682 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003683 Right < LastPromotedArithmeticType; ++Right) {
3684 QualType ParamTypes[2];
3685 ParamTypes[1] = ArithmeticTypes[Right];
3686
3687 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003688 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003689 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3690 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003691
3692 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003693 if (VisibleTypeConversionsQuals.hasVolatile()) {
3694 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3695 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3696 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3697 /*IsAssigmentOperator=*/Op == OO_Equal);
3698 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003699 }
3700 }
3701 break;
3702
3703 case OO_PercentEqual:
3704 case OO_LessLessEqual:
3705 case OO_GreaterGreaterEqual:
3706 case OO_AmpEqual:
3707 case OO_CaretEqual:
3708 case OO_PipeEqual:
3709 // C++ [over.built]p22:
3710 //
3711 // For every triple (L, VQ, R), where L is an integral type, VQ
3712 // is either volatile or empty, and R is a promoted integral
3713 // type, there exist candidate operator functions of the form
3714 //
3715 // VQ L& operator%=(VQ L&, R);
3716 // VQ L& operator<<=(VQ L&, R);
3717 // VQ L& operator>>=(VQ L&, R);
3718 // VQ L& operator&=(VQ L&, R);
3719 // VQ L& operator^=(VQ L&, R);
3720 // VQ L& operator|=(VQ L&, R);
3721 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003722 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003723 Right < LastPromotedIntegralType; ++Right) {
3724 QualType ParamTypes[2];
3725 ParamTypes[1] = ArithmeticTypes[Right];
3726
3727 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003728 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003729 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00003730 if (VisibleTypeConversionsQuals.hasVolatile()) {
3731 // Add this built-in operator as a candidate (VQ is 'volatile').
3732 ParamTypes[0] = ArithmeticTypes[Left];
3733 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3734 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3735 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3736 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003737 }
3738 }
3739 break;
3740
Douglas Gregor74253732008-11-19 15:42:04 +00003741 case OO_Exclaim: {
3742 // C++ [over.operator]p23:
3743 //
3744 // There also exist candidate operator functions of the form
3745 //
Mike Stump1eb44332009-09-09 15:08:12 +00003746 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00003747 // bool operator&&(bool, bool); [BELOW]
3748 // bool operator||(bool, bool); [BELOW]
3749 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003750 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3751 /*IsAssignmentOperator=*/false,
3752 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00003753 break;
3754 }
3755
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003756 case OO_AmpAmp:
3757 case OO_PipePipe: {
3758 // C++ [over.operator]p23:
3759 //
3760 // There also exist candidate operator functions of the form
3761 //
Douglas Gregor74253732008-11-19 15:42:04 +00003762 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003763 // bool operator&&(bool, bool);
3764 // bool operator||(bool, bool);
3765 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003766 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3767 /*IsAssignmentOperator=*/false,
3768 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003769 break;
3770 }
3771
3772 case OO_Subscript:
3773 // C++ [over.built]p13:
3774 //
3775 // For every cv-qualified or cv-unqualified object type T there
3776 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003777 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003778 // T* operator+(T*, ptrdiff_t); [ABOVE]
3779 // T& operator[](T*, ptrdiff_t);
3780 // T* operator-(T*, ptrdiff_t); [ABOVE]
3781 // T* operator+(ptrdiff_t, T*); [ABOVE]
3782 // T& operator[](ptrdiff_t, T*);
3783 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3784 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3785 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenek6217b802009-07-29 21:53:49 +00003786 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003787 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003788
3789 // T& operator[](T*, ptrdiff_t)
3790 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3791
3792 // T& operator[](ptrdiff_t, T*);
3793 ParamTypes[0] = ParamTypes[1];
3794 ParamTypes[1] = *Ptr;
3795 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3796 }
3797 break;
3798
3799 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003800 // C++ [over.built]p11:
3801 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
3802 // C1 is the same type as C2 or is a derived class of C2, T is an object
3803 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
3804 // there exist candidate operator functions of the form
3805 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
3806 // where CV12 is the union of CV1 and CV2.
3807 {
3808 for (BuiltinCandidateTypeSet::iterator Ptr =
3809 CandidateTypes.pointer_begin();
3810 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3811 QualType C1Ty = (*Ptr);
3812 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00003813 QualifierCollector Q1;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003814 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00003815 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003816 if (!isa<RecordType>(C1))
3817 continue;
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003818 // heuristic to reduce number of builtin candidates in the set.
3819 // Add volatile/restrict version only if there are conversions to a
3820 // volatile/restrict type.
3821 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
3822 continue;
3823 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
3824 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003825 }
3826 for (BuiltinCandidateTypeSet::iterator
3827 MemPtr = CandidateTypes.member_pointer_begin(),
3828 MemPtrEnd = CandidateTypes.member_pointer_end();
3829 MemPtr != MemPtrEnd; ++MemPtr) {
3830 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
3831 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00003832 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003833 if (C1 != C2 && !IsDerivedFrom(C1, C2))
3834 break;
3835 QualType ParamTypes[2] = { *Ptr, *MemPtr };
3836 // build CV12 T&
3837 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003838 if (!VisibleTypeConversionsQuals.hasVolatile() &&
3839 T.isVolatileQualified())
3840 continue;
3841 if (!VisibleTypeConversionsQuals.hasRestrict() &&
3842 T.isRestrictQualified())
3843 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00003844 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003845 QualType ResultTy = Context.getLValueReferenceType(T);
3846 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3847 }
3848 }
3849 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003850 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003851
3852 case OO_Conditional:
3853 // Note that we don't consider the first argument, since it has been
3854 // contextually converted to bool long ago. The candidates below are
3855 // therefore added as binary.
3856 //
3857 // C++ [over.built]p24:
3858 // For every type T, where T is a pointer or pointer-to-member type,
3859 // there exist candidate operator functions of the form
3860 //
3861 // T operator?(bool, T, T);
3862 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003863 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3864 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3865 QualType ParamTypes[2] = { *Ptr, *Ptr };
3866 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3867 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00003868 for (BuiltinCandidateTypeSet::iterator Ptr =
3869 CandidateTypes.member_pointer_begin(),
3870 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3871 QualType ParamTypes[2] = { *Ptr, *Ptr };
3872 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3873 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003874 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003875 }
3876}
3877
Douglas Gregorfa047642009-02-04 00:32:51 +00003878/// \brief Add function candidates found via argument-dependent lookup
3879/// to the set of overloading candidates.
3880///
3881/// This routine performs argument-dependent name lookup based on the
3882/// given function name (which may also be an operator name) and adds
3883/// all of the overload candidates found by ADL to the overload
3884/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00003885void
Douglas Gregorfa047642009-02-04 00:32:51 +00003886Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3887 Expr **Args, unsigned NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003888 bool HasExplicitTemplateArgs,
John McCall833ca992009-10-29 08:12:44 +00003889 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003890 unsigned NumExplicitTemplateArgs,
3891 OverloadCandidateSet& CandidateSet,
3892 bool PartialOverloading) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003893 FunctionSet Functions;
Douglas Gregorfa047642009-02-04 00:32:51 +00003894
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003895 // FIXME: Should we be trafficking in canonical function decls throughout?
3896
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003897 // Record all of the function candidates that we've already
3898 // added to the overload set, so that we don't add those same
3899 // candidates a second time.
3900 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3901 CandEnd = CandidateSet.end();
3902 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00003903 if (Cand->Function) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003904 Functions.insert(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00003905 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3906 Functions.insert(FunTmpl);
3907 }
Douglas Gregorfa047642009-02-04 00:32:51 +00003908
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003909 // FIXME: Pass in the explicit template arguments?
Sebastian Redl644be852009-10-23 19:23:15 +00003910 ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
Douglas Gregorfa047642009-02-04 00:32:51 +00003911
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003912 // Erase all of the candidates we already knew about.
3913 // FIXME: This is suboptimal. Is there a better way?
3914 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3915 CandEnd = CandidateSet.end();
3916 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00003917 if (Cand->Function) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003918 Functions.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00003919 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3920 Functions.erase(FunTmpl);
3921 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00003922
3923 // For each of the ADL candidates we found, add it to the overload
3924 // set.
3925 for (FunctionSet::iterator Func = Functions.begin(),
3926 FuncEnd = Functions.end();
Douglas Gregor364e0212009-06-27 21:05:07 +00003927 Func != FuncEnd; ++Func) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003928 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
3929 if (HasExplicitTemplateArgs)
3930 continue;
3931
3932 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
3933 false, false, PartialOverloading);
3934 } else
Mike Stump1eb44332009-09-09 15:08:12 +00003935 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003936 HasExplicitTemplateArgs,
3937 ExplicitTemplateArgs,
3938 NumExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003939 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00003940 }
Douglas Gregorfa047642009-02-04 00:32:51 +00003941}
3942
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003943/// isBetterOverloadCandidate - Determines whether the first overload
3944/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00003945bool
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003946Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump1eb44332009-09-09 15:08:12 +00003947 const OverloadCandidate& Cand2) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003948 // Define viable functions to be better candidates than non-viable
3949 // functions.
3950 if (!Cand2.Viable)
3951 return Cand1.Viable;
3952 else if (!Cand1.Viable)
3953 return false;
3954
Douglas Gregor88a35142008-12-22 05:46:06 +00003955 // C++ [over.match.best]p1:
3956 //
3957 // -- if F is a static member function, ICS1(F) is defined such
3958 // that ICS1(F) is neither better nor worse than ICS1(G) for
3959 // any function G, and, symmetrically, ICS1(G) is neither
3960 // better nor worse than ICS1(F).
3961 unsigned StartArg = 0;
3962 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3963 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003964
Douglas Gregor3e15cc32009-07-07 23:38:56 +00003965 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00003966 // A viable function F1 is defined to be a better function than another
3967 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00003968 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003969 unsigned NumArgs = Cand1.Conversions.size();
3970 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3971 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003972 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003973 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3974 Cand2.Conversions[ArgIdx])) {
3975 case ImplicitConversionSequence::Better:
3976 // Cand1 has a better conversion sequence.
3977 HasBetterConversion = true;
3978 break;
3979
3980 case ImplicitConversionSequence::Worse:
3981 // Cand1 can't be better than Cand2.
3982 return false;
3983
3984 case ImplicitConversionSequence::Indistinguishable:
3985 // Do nothing.
3986 break;
3987 }
3988 }
3989
Mike Stump1eb44332009-09-09 15:08:12 +00003990 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00003991 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003992 if (HasBetterConversion)
3993 return true;
3994
Mike Stump1eb44332009-09-09 15:08:12 +00003995 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00003996 // specialization, or, if not that,
3997 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3998 Cand2.Function && Cand2.Function->getPrimaryTemplate())
3999 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004000
4001 // -- F1 and F2 are function template specializations, and the function
4002 // template for F1 is more specialized than the template for F2
4003 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004004 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00004005 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4006 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004007 if (FunctionTemplateDecl *BetterTemplate
4008 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4009 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor5d7d3752009-09-14 23:02:14 +00004010 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4011 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004012 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004013
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004014 // -- the context is an initialization by user-defined conversion
4015 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4016 // from the return type of F1 to the destination type (i.e.,
4017 // the type of the entity being initialized) is a better
4018 // conversion sequence than the standard conversion sequence
4019 // from the return type of F2 to the destination type.
Mike Stump1eb44332009-09-09 15:08:12 +00004020 if (Cand1.Function && Cand2.Function &&
4021 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004022 isa<CXXConversionDecl>(Cand2.Function)) {
4023 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4024 Cand2.FinalConversion)) {
4025 case ImplicitConversionSequence::Better:
4026 // Cand1 has a better conversion sequence.
4027 return true;
4028
4029 case ImplicitConversionSequence::Worse:
4030 // Cand1 can't be better than Cand2.
4031 return false;
4032
4033 case ImplicitConversionSequence::Indistinguishable:
4034 // Do nothing
4035 break;
4036 }
4037 }
4038
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004039 return false;
4040}
4041
Mike Stump1eb44332009-09-09 15:08:12 +00004042/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00004043/// within an overload candidate set.
4044///
4045/// \param CandidateSet the set of candidate functions.
4046///
4047/// \param Loc the location of the function name (or operator symbol) for
4048/// which overload resolution occurs.
4049///
Mike Stump1eb44332009-09-09 15:08:12 +00004050/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00004051/// function, Best points to the candidate function found.
4052///
4053/// \returns The result of overload resolution.
Mike Stump1eb44332009-09-09 15:08:12 +00004054Sema::OverloadingResult
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004055Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregore0762c92009-06-19 23:52:42 +00004056 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00004057 OverloadCandidateSet::iterator& Best) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004058 // Find the best viable function.
4059 Best = CandidateSet.end();
4060 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4061 Cand != CandidateSet.end(); ++Cand) {
4062 if (Cand->Viable) {
4063 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4064 Best = Cand;
4065 }
4066 }
4067
4068 // If we didn't find any viable functions, abort.
4069 if (Best == CandidateSet.end())
4070 return OR_No_Viable_Function;
4071
4072 // Make sure that this function is better than every other viable
4073 // function. If not, we have an ambiguity.
4074 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4075 Cand != CandidateSet.end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00004076 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004077 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004078 !isBetterOverloadCandidate(*Best, *Cand)) {
4079 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004080 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004081 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004082 }
Mike Stump1eb44332009-09-09 15:08:12 +00004083
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004084 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004085 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00004086 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004087 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004088 return OR_Deleted;
4089
Douglas Gregore0762c92009-06-19 23:52:42 +00004090 // C++ [basic.def.odr]p2:
4091 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00004092 // when referred to from a potentially-evaluated expression. [Note: this
4093 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00004094 // (clause 13), user-defined conversions (12.3.2), allocation function for
4095 // placement new (5.3.4), as well as non-default initialization (8.5).
4096 if (Best->Function)
4097 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004098 return OR_Success;
4099}
4100
4101/// PrintOverloadCandidates - When overload resolution fails, prints
4102/// diagnostic messages containing the candidates in the candidate
4103/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump1eb44332009-09-09 15:08:12 +00004104void
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004105Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Fariborz Jahanian16a5eac2009-10-09 00:13:15 +00004106 bool OnlyViable,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004107 const char *Opc,
Fariborz Jahanian16a5eac2009-10-09 00:13:15 +00004108 SourceLocation OpLoc) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004109 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4110 LastCand = CandidateSet.end();
Fariborz Jahanian27687cf2009-10-12 17:51:19 +00004111 bool Reported = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004112 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004113 if (Cand->Viable || !OnlyViable) {
4114 if (Cand->Function) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004115 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004116 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004117 // Deleted or "unavailable" function.
4118 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
4119 << Cand->Function->isDeleted();
Douglas Gregor1fdd89b2009-09-15 20:11:42 +00004120 } else if (FunctionTemplateDecl *FunTmpl
4121 = Cand->Function->getPrimaryTemplate()) {
4122 // Function template specialization
4123 // FIXME: Give a better reason!
4124 Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
4125 << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
4126 *Cand->Function->getTemplateSpecializationArgs());
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004127 } else {
4128 // Normal function
Fariborz Jahanianb1663d02009-09-23 00:58:07 +00004129 bool errReported = false;
4130 if (!Cand->Viable && Cand->Conversions.size() > 0) {
4131 for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
4132 const ImplicitConversionSequence &Conversion =
4133 Cand->Conversions[i];
4134 if ((Conversion.ConversionKind !=
4135 ImplicitConversionSequence::BadConversion) ||
4136 Conversion.ConversionFunctionSet.size() == 0)
4137 continue;
4138 Diag(Cand->Function->getLocation(),
4139 diag::err_ovl_candidate_not_viable) << (i+1);
4140 errReported = true;
4141 for (int j = Conversion.ConversionFunctionSet.size()-1;
4142 j >= 0; j--) {
4143 FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
4144 Diag(Func->getLocation(), diag::err_ovl_candidate);
4145 }
4146 }
4147 }
4148 if (!errReported)
4149 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004150 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004151 } else if (Cand->IsSurrogate) {
Douglas Gregor621b3932008-11-21 02:54:28 +00004152 // Desugar the type of the surrogate down to a function type,
4153 // retaining as many typedefs as possible while still showing
4154 // the function type (and, therefore, its parameter types).
4155 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004156 bool isLValueReference = false;
4157 bool isRValueReference = false;
Douglas Gregor621b3932008-11-21 02:54:28 +00004158 bool isPointer = false;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004159 if (const LValueReferenceType *FnTypeRef =
Ted Kremenek6217b802009-07-29 21:53:49 +00004160 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor621b3932008-11-21 02:54:28 +00004161 FnType = FnTypeRef->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004162 isLValueReference = true;
4163 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenek6217b802009-07-29 21:53:49 +00004164 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004165 FnType = FnTypeRef->getPointeeType();
4166 isRValueReference = true;
Douglas Gregor621b3932008-11-21 02:54:28 +00004167 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004168 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor621b3932008-11-21 02:54:28 +00004169 FnType = FnTypePtr->getPointeeType();
4170 isPointer = true;
4171 }
4172 // Desugar down to a function type.
John McCall183700f2009-09-21 23:43:11 +00004173 FnType = QualType(FnType->getAs<FunctionType>(), 0);
Douglas Gregor621b3932008-11-21 02:54:28 +00004174 // Reconstruct the pointer/reference as appropriate.
4175 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004176 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
4177 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor621b3932008-11-21 02:54:28 +00004178
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004179 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattnerd1625842008-11-24 06:25:27 +00004180 << FnType;
Douglas Gregor33074752009-09-30 21:46:01 +00004181 } else if (OnlyViable) {
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004182 assert(Cand->Conversions.size() <= 2 &&
Fariborz Jahanianad3607d2009-10-09 17:09:58 +00004183 "builtin-binary-operator-not-binary");
Fariborz Jahanian866b2742009-10-16 23:25:02 +00004184 std::string TypeStr("operator");
4185 TypeStr += Opc;
4186 TypeStr += "(";
4187 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4188 if (Cand->Conversions.size() == 1) {
4189 TypeStr += ")";
4190 Diag(OpLoc, diag::err_ovl_builtin_unary_candidate) << TypeStr;
4191 }
4192 else {
4193 TypeStr += ", ";
4194 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4195 TypeStr += ")";
4196 Diag(OpLoc, diag::err_ovl_builtin_binary_candidate) << TypeStr;
4197 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004198 }
Fariborz Jahanian27687cf2009-10-12 17:51:19 +00004199 else if (!Cand->Viable && !Reported) {
4200 // Non-viability might be due to ambiguous user-defined conversions,
4201 // needed for built-in operators. Report them as well, but only once
4202 // as we have typically many built-in candidates.
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004203 unsigned NoOperands = Cand->Conversions.size();
4204 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
Fariborz Jahanian27687cf2009-10-12 17:51:19 +00004205 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
4206 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion ||
4207 ICS.ConversionFunctionSet.empty())
4208 continue;
4209 if (CXXConversionDecl *Func = dyn_cast<CXXConversionDecl>(
4210 Cand->Conversions[ArgIdx].ConversionFunctionSet[0])) {
4211 QualType FromTy =
4212 QualType(
4213 static_cast<Type*>(ICS.UserDefined.Before.FromTypePtr),0);
4214 Diag(OpLoc,diag::note_ambiguous_type_conversion)
4215 << FromTy << Func->getConversionType();
4216 }
4217 for (unsigned j = 0; j < ICS.ConversionFunctionSet.size(); j++) {
4218 FunctionDecl *Func =
4219 Cand->Conversions[ArgIdx].ConversionFunctionSet[j];
4220 Diag(Func->getLocation(),diag::err_ovl_candidate);
4221 }
4222 }
4223 Reported = true;
4224 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004225 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004226 }
4227}
4228
Douglas Gregor904eed32008-11-10 20:40:00 +00004229/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4230/// an overloaded function (C++ [over.over]), where @p From is an
4231/// expression with overloaded function type and @p ToType is the type
4232/// we're trying to resolve to. For example:
4233///
4234/// @code
4235/// int f(double);
4236/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00004237///
Douglas Gregor904eed32008-11-10 20:40:00 +00004238/// int (*pfd)(double) = f; // selects f(double)
4239/// @endcode
4240///
4241/// This routine returns the resulting FunctionDecl if it could be
4242/// resolved, and NULL otherwise. When @p Complain is true, this
4243/// routine will emit diagnostics if there is an error.
4244FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00004245Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor904eed32008-11-10 20:40:00 +00004246 bool Complain) {
4247 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00004248 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00004249 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00004250 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004251 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00004252 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00004253 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00004254 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00004255 FunctionType = MemTypePtr->getPointeeType();
4256 IsMember = true;
4257 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004258
4259 // We only look at pointers or references to functions.
Douglas Gregor72e771f2009-07-09 17:16:51 +00004260 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor83314aa2009-07-08 20:55:45 +00004261 if (!FunctionType->isFunctionType())
Douglas Gregor904eed32008-11-10 20:40:00 +00004262 return 0;
4263
4264 // Find the actual overloaded function declaration.
4265 OverloadedFunctionDecl *Ovl = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004266
Douglas Gregor904eed32008-11-10 20:40:00 +00004267 // C++ [over.over]p1:
4268 // [...] [Note: any redundant set of parentheses surrounding the
4269 // overloaded function name is ignored (5.1). ]
4270 Expr *OvlExpr = From->IgnoreParens();
4271
4272 // C++ [over.over]p1:
4273 // [...] The overloaded function name can be preceded by the &
4274 // operator.
4275 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4276 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4277 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4278 }
4279
Anders Carlsson70534852009-10-20 22:53:47 +00004280 bool HasExplicitTemplateArgs = false;
John McCall833ca992009-10-29 08:12:44 +00004281 const TemplateArgumentLoc *ExplicitTemplateArgs = 0;
Anders Carlsson70534852009-10-20 22:53:47 +00004282 unsigned NumExplicitTemplateArgs = 0;
4283
Douglas Gregor904eed32008-11-10 20:40:00 +00004284 // Try to dig out the overloaded function.
Douglas Gregor83314aa2009-07-08 20:55:45 +00004285 FunctionTemplateDecl *FunctionTemplate = 0;
4286 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00004287 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor83314aa2009-07-08 20:55:45 +00004288 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00004289 HasExplicitTemplateArgs = DR->hasExplicitTemplateArgumentList();
4290 ExplicitTemplateArgs = DR->getTemplateArgs();
4291 NumExplicitTemplateArgs = DR->getNumTemplateArgs();
Anders Carlsson6e8f5502009-10-07 22:26:29 +00004292 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(OvlExpr)) {
4293 Ovl = dyn_cast<OverloadedFunctionDecl>(ME->getMemberDecl());
4294 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(ME->getMemberDecl());
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00004295 HasExplicitTemplateArgs = ME->hasExplicitTemplateArgumentList();
4296 ExplicitTemplateArgs = ME->getTemplateArgs();
4297 NumExplicitTemplateArgs = ME->getNumTemplateArgs();
Anders Carlsson70534852009-10-20 22:53:47 +00004298 } else if (TemplateIdRefExpr *TIRE = dyn_cast<TemplateIdRefExpr>(OvlExpr)) {
4299 TemplateName Name = TIRE->getTemplateName();
4300 Ovl = Name.getAsOverloadedFunctionDecl();
4301 FunctionTemplate =
4302 dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4303
4304 HasExplicitTemplateArgs = true;
4305 ExplicitTemplateArgs = TIRE->getTemplateArgs();
4306 NumExplicitTemplateArgs = TIRE->getNumTemplateArgs();
Douglas Gregor83314aa2009-07-08 20:55:45 +00004307 }
Anders Carlsson70534852009-10-20 22:53:47 +00004308
Mike Stump1eb44332009-09-09 15:08:12 +00004309 // If there's no overloaded function declaration or function template,
Douglas Gregor83314aa2009-07-08 20:55:45 +00004310 // we're done.
4311 if (!Ovl && !FunctionTemplate)
Douglas Gregor904eed32008-11-10 20:40:00 +00004312 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004313
Douglas Gregor83314aa2009-07-08 20:55:45 +00004314 OverloadIterator Fun;
4315 if (Ovl)
4316 Fun = Ovl;
4317 else
4318 Fun = FunctionTemplate;
Mike Stump1eb44332009-09-09 15:08:12 +00004319
Douglas Gregor904eed32008-11-10 20:40:00 +00004320 // Look through all of the overloaded functions, searching for one
4321 // whose type matches exactly.
Douglas Gregor00aeb522009-07-08 23:33:52 +00004322 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004323 bool FoundNonTemplateFunction = false;
Douglas Gregor83314aa2009-07-08 20:55:45 +00004324 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregor904eed32008-11-10 20:40:00 +00004325 // C++ [over.over]p3:
4326 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00004327 // targets of type "pointer-to-function" or "reference-to-function."
4328 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00004329 // type "pointer-to-member-function."
4330 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00004331
Mike Stump1eb44332009-09-09 15:08:12 +00004332 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregor83314aa2009-07-08 20:55:45 +00004333 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004334 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00004335 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004336 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00004337 // static when converting to member pointer.
4338 if (Method->isStatic() == IsMember)
4339 continue;
4340 } else if (IsMember)
4341 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00004342
Douglas Gregor00aeb522009-07-08 23:33:52 +00004343 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004344 // If the name is a function template, template argument deduction is
4345 // done (14.8.2.2), and if the argument deduction succeeds, the
4346 // resulting template argument list is used to generate a single
4347 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00004348 // overloaded functions considered.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004349 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor83314aa2009-07-08 20:55:45 +00004350 FunctionDecl *Specialization = 0;
4351 TemplateDeductionInfo Info(Context);
4352 if (TemplateDeductionResult Result
Anders Carlsson70534852009-10-20 22:53:47 +00004353 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
4354 ExplicitTemplateArgs,
4355 NumExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00004356 FunctionType, Specialization, Info)) {
4357 // FIXME: make a note of the failed deduction for diagnostics.
4358 (void)Result;
4359 } else {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004360 // FIXME: If the match isn't exact, shouldn't we just drop this as
4361 // a candidate? Find a testcase before changing the code.
Mike Stump1eb44332009-09-09 15:08:12 +00004362 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00004363 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor00aeb522009-07-08 23:33:52 +00004364 Matches.insert(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00004365 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor83314aa2009-07-08 20:55:45 +00004366 }
4367 }
Mike Stump1eb44332009-09-09 15:08:12 +00004368
Sebastian Redl33b399a2009-02-04 21:23:32 +00004369 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
4370 // Skip non-static functions when converting to pointer, and static
4371 // when converting to member pointer.
4372 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00004373 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00004374
4375 // If we have explicit template arguments, skip non-templates.
4376 if (HasExplicitTemplateArgs)
4377 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004378 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00004379 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00004380
Douglas Gregore53060f2009-06-25 22:08:12 +00004381 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregor00aeb522009-07-08 23:33:52 +00004382 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00004383 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregor00aeb522009-07-08 23:33:52 +00004384 FoundNonTemplateFunction = true;
4385 }
Mike Stump1eb44332009-09-09 15:08:12 +00004386 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004387 }
4388
Douglas Gregor00aeb522009-07-08 23:33:52 +00004389 // If there were 0 or 1 matches, we're done.
4390 if (Matches.empty())
4391 return 0;
Sebastian Redl07ab2022009-10-17 21:12:09 +00004392 else if (Matches.size() == 1) {
4393 FunctionDecl *Result = *Matches.begin();
4394 MarkDeclarationReferenced(From->getLocStart(), Result);
4395 return Result;
4396 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00004397
4398 // C++ [over.over]p4:
4399 // If more than one function is selected, [...]
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004400 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregor312a2022009-09-26 03:56:17 +00004401 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004402 // [...] and any given function template specialization F1 is
4403 // eliminated if the set contains a second function template
4404 // specialization whose function template is more specialized
4405 // than the function template of F1 according to the partial
4406 // ordering rules of 14.5.5.2.
4407
4408 // The algorithm specified above is quadratic. We instead use a
4409 // two-pass algorithm (similar to the one used to identify the
4410 // best viable function in an overload set) that identifies the
4411 // best function template (if it exists).
Sebastian Redl07ab2022009-10-17 21:12:09 +00004412 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
Douglas Gregor312a2022009-09-26 03:56:17 +00004413 Matches.end());
Sebastian Redl07ab2022009-10-17 21:12:09 +00004414 FunctionDecl *Result =
4415 getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4416 TPOC_Other, From->getLocStart(),
4417 PDiag(),
4418 PDiag(diag::err_addr_ovl_ambiguous)
4419 << TemplateMatches[0]->getDeclName(),
4420 PDiag(diag::err_ovl_template_candidate));
4421 MarkDeclarationReferenced(From->getLocStart(), Result);
4422 return Result;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004423 }
Mike Stump1eb44332009-09-09 15:08:12 +00004424
Douglas Gregor312a2022009-09-26 03:56:17 +00004425 // [...] any function template specializations in the set are
4426 // eliminated if the set also contains a non-template function, [...]
4427 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4428 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4429 if ((*M)->getPrimaryTemplate() == 0)
4430 RemainingMatches.push_back(*M);
4431
Mike Stump1eb44332009-09-09 15:08:12 +00004432 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00004433 // selected function.
Sebastian Redl07ab2022009-10-17 21:12:09 +00004434 if (RemainingMatches.size() == 1) {
4435 FunctionDecl *Result = RemainingMatches.front();
4436 MarkDeclarationReferenced(From->getLocStart(), Result);
4437 return Result;
4438 }
Mike Stump1eb44332009-09-09 15:08:12 +00004439
Douglas Gregor00aeb522009-07-08 23:33:52 +00004440 // FIXME: We should probably return the same thing that BestViableFunction
4441 // returns (even if we issue the diagnostics here).
4442 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4443 << RemainingMatches[0]->getDeclName();
4444 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4445 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregor904eed32008-11-10 20:40:00 +00004446 return 0;
4447}
4448
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004449/// \brief Add a single candidate to the overload set.
4450static void AddOverloadedCallCandidate(Sema &S,
4451 AnyFunctionDecl Callee,
4452 bool &ArgumentDependentLookup,
4453 bool HasExplicitTemplateArgs,
John McCall833ca992009-10-29 08:12:44 +00004454 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004455 unsigned NumExplicitTemplateArgs,
4456 Expr **Args, unsigned NumArgs,
4457 OverloadCandidateSet &CandidateSet,
4458 bool PartialOverloading) {
4459 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
4460 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
4461 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4462 PartialOverloading);
4463
4464 if (Func->getDeclContext()->isRecord() ||
4465 Func->getDeclContext()->isFunctionOrMethod())
4466 ArgumentDependentLookup = false;
4467 return;
4468 }
4469
4470 FunctionTemplateDecl *FuncTemplate = cast<FunctionTemplateDecl>(Callee);
4471 S.AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4472 ExplicitTemplateArgs,
4473 NumExplicitTemplateArgs,
4474 Args, NumArgs, CandidateSet);
4475
4476 if (FuncTemplate->getDeclContext()->isRecord())
4477 ArgumentDependentLookup = false;
4478}
4479
4480/// \brief Add the overload candidates named by callee and/or found by argument
4481/// dependent lookup to the given overload set.
4482void Sema::AddOverloadedCallCandidates(NamedDecl *Callee,
4483 DeclarationName &UnqualifiedName,
4484 bool &ArgumentDependentLookup,
4485 bool HasExplicitTemplateArgs,
John McCall833ca992009-10-29 08:12:44 +00004486 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004487 unsigned NumExplicitTemplateArgs,
4488 Expr **Args, unsigned NumArgs,
4489 OverloadCandidateSet &CandidateSet,
4490 bool PartialOverloading) {
4491 // Add the functions denoted by Callee to the set of candidate
4492 // functions. While we're doing so, track whether argument-dependent
4493 // lookup still applies, per:
4494 //
4495 // C++0x [basic.lookup.argdep]p3:
4496 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4497 // and let Y be the lookup set produced by argument dependent
4498 // lookup (defined as follows). If X contains
4499 //
4500 // -- a declaration of a class member, or
4501 //
4502 // -- a block-scope function declaration that is not a
4503 // using-declaration (FIXME: check for using declaration), or
4504 //
4505 // -- a declaration that is neither a function or a function
4506 // template
4507 //
4508 // then Y is empty.
4509 if (!Callee) {
4510 // Nothing to do.
4511 } else if (OverloadedFunctionDecl *Ovl
4512 = dyn_cast<OverloadedFunctionDecl>(Callee)) {
4513 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4514 FuncEnd = Ovl->function_end();
4515 Func != FuncEnd; ++Func)
4516 AddOverloadedCallCandidate(*this, *Func, ArgumentDependentLookup,
4517 HasExplicitTemplateArgs,
4518 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4519 Args, NumArgs, CandidateSet,
4520 PartialOverloading);
4521 } else if (isa<FunctionDecl>(Callee) || isa<FunctionTemplateDecl>(Callee))
4522 AddOverloadedCallCandidate(*this,
4523 AnyFunctionDecl::getFromNamedDecl(Callee),
4524 ArgumentDependentLookup,
4525 HasExplicitTemplateArgs,
4526 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4527 Args, NumArgs, CandidateSet,
4528 PartialOverloading);
4529 // FIXME: assert isa<FunctionDecl> || isa<FunctionTemplateDecl> rather than
4530 // checking dynamically.
4531
4532 if (Callee)
4533 UnqualifiedName = Callee->getDeclName();
4534
4535 if (ArgumentDependentLookup)
4536 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
4537 HasExplicitTemplateArgs,
4538 ExplicitTemplateArgs,
4539 NumExplicitTemplateArgs,
4540 CandidateSet,
4541 PartialOverloading);
4542}
4543
Douglas Gregorf6b89692008-11-26 05:54:23 +00004544/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00004545/// (which eventually refers to the declaration Func) and the call
4546/// arguments Args/NumArgs, attempt to resolve the function call down
4547/// to a specific function. If overload resolution succeeds, returns
4548/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00004549/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00004550/// arguments and Fn, and returns NULL.
Douglas Gregorfa047642009-02-04 00:32:51 +00004551FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregor17330012009-02-04 15:01:18 +00004552 DeclarationName UnqualifiedName,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004553 bool HasExplicitTemplateArgs,
John McCall833ca992009-10-29 08:12:44 +00004554 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004555 unsigned NumExplicitTemplateArgs,
Douglas Gregor0a396682008-11-26 06:01:48 +00004556 SourceLocation LParenLoc,
4557 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00004558 SourceLocation *CommaLocs,
Douglas Gregorfa047642009-02-04 00:32:51 +00004559 SourceLocation RParenLoc,
Douglas Gregor17330012009-02-04 15:01:18 +00004560 bool &ArgumentDependentLookup) {
Douglas Gregorf6b89692008-11-26 05:54:23 +00004561 OverloadCandidateSet CandidateSet;
Douglas Gregor17330012009-02-04 15:01:18 +00004562
4563 // Add the functions denoted by Callee to the set of candidate
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004564 // functions.
4565 AddOverloadedCallCandidates(Callee, UnqualifiedName, ArgumentDependentLookup,
4566 HasExplicitTemplateArgs, ExplicitTemplateArgs,
4567 NumExplicitTemplateArgs, Args, NumArgs,
4568 CandidateSet);
Douglas Gregorf6b89692008-11-26 05:54:23 +00004569 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004570 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregor0a396682008-11-26 06:01:48 +00004571 case OR_Success:
4572 return Best->Function;
Douglas Gregorf6b89692008-11-26 05:54:23 +00004573
4574 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00004575 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00004576 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00004577 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00004578 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4579 break;
4580
4581 case OR_Ambiguous:
4582 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor17330012009-02-04 15:01:18 +00004583 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00004584 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4585 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004586
4587 case OR_Deleted:
4588 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4589 << Best->Function->isDeleted()
4590 << UnqualifiedName
4591 << Fn->getSourceRange();
4592 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4593 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00004594 }
4595
4596 // Overload resolution failed. Destroy all of the subexpressions and
4597 // return NULL.
4598 Fn->Destroy(Context);
4599 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4600 Args[Arg]->Destroy(Context);
4601 return 0;
4602}
4603
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004604/// \brief Create a unary operation that may resolve to an overloaded
4605/// operator.
4606///
4607/// \param OpLoc The location of the operator itself (e.g., '*').
4608///
4609/// \param OpcIn The UnaryOperator::Opcode that describes this
4610/// operator.
4611///
4612/// \param Functions The set of non-member functions that will be
4613/// considered by overload resolution. The caller needs to build this
4614/// set based on the context using, e.g.,
4615/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4616/// set should not contain any member functions; those will be added
4617/// by CreateOverloadedUnaryOp().
4618///
4619/// \param input The input argument.
4620Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4621 unsigned OpcIn,
4622 FunctionSet &Functions,
Mike Stump1eb44332009-09-09 15:08:12 +00004623 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004624 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4625 Expr *Input = (Expr *)input.get();
4626
4627 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4628 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4629 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4630
4631 Expr *Args[2] = { Input, 0 };
4632 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004633
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004634 // For post-increment and post-decrement, add the implicit '0' as
4635 // the second argument, so that we know this is a post-increment or
4636 // post-decrement.
4637 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4638 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump1eb44332009-09-09 15:08:12 +00004639 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004640 SourceLocation());
4641 NumArgs = 2;
4642 }
4643
4644 if (Input->isTypeDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004645 OverloadedFunctionDecl *Overloads
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004646 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump1eb44332009-09-09 15:08:12 +00004647 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004648 FuncEnd = Functions.end();
4649 Func != FuncEnd; ++Func)
4650 Overloads->addOverload(*Func);
4651
4652 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4653 OpLoc, false, false);
Mike Stump1eb44332009-09-09 15:08:12 +00004654
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004655 input.release();
4656 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4657 &Args[0], NumArgs,
4658 Context.DependentTy,
4659 OpLoc));
4660 }
4661
4662 // Build an empty overload set.
4663 OverloadCandidateSet CandidateSet;
4664
4665 // Add the candidates from the given function set.
4666 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4667
4668 // Add operator candidates that are member functions.
4669 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4670
4671 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00004672 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004673
4674 // Perform overload resolution.
4675 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004676 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004677 case OR_Success: {
4678 // We found a built-in operator or an overloaded operator.
4679 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00004680
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004681 if (FnDecl) {
4682 // We matched an overloaded operator. Build a call to that
4683 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00004684
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004685 // Convert the arguments.
4686 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4687 if (PerformObjectArgumentInitialization(Input, Method))
4688 return ExprError();
4689 } else {
4690 // Convert the arguments.
4691 if (PerformCopyInitialization(Input,
4692 FnDecl->getParamDecl(0)->getType(),
4693 "passing"))
4694 return ExprError();
4695 }
4696
4697 // Determine the result type
Anders Carlsson26a2a072009-10-13 21:19:37 +00004698 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00004699
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004700 // Build the actual expression node.
4701 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4702 SourceLocation());
4703 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004704
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004705 input.release();
Mike Stump1eb44332009-09-09 15:08:12 +00004706
Anders Carlsson26a2a072009-10-13 21:19:37 +00004707 ExprOwningPtr<CallExpr> TheCall(this,
4708 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4709 &Input, 1, ResultTy, OpLoc));
4710
4711 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4712 FnDecl))
4713 return ExprError();
4714
4715 return MaybeBindToTemporary(TheCall.release());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004716 } else {
4717 // We matched a built-in operator. Convert the arguments, then
4718 // break out so that we will build the appropriate built-in
4719 // operator node.
4720 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4721 Best->Conversions[0], "passing"))
4722 return ExprError();
4723
4724 break;
4725 }
4726 }
4727
4728 case OR_No_Viable_Function:
4729 // No viable function; fall through to handling this as a
4730 // built-in operator, which will produce an error message for us.
4731 break;
4732
4733 case OR_Ambiguous:
4734 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4735 << UnaryOperator::getOpcodeStr(Opc)
4736 << Input->getSourceRange();
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004737 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4738 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004739 return ExprError();
4740
4741 case OR_Deleted:
4742 Diag(OpLoc, diag::err_ovl_deleted_oper)
4743 << Best->Function->isDeleted()
4744 << UnaryOperator::getOpcodeStr(Opc)
4745 << Input->getSourceRange();
4746 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4747 return ExprError();
4748 }
4749
4750 // Either we found no viable overloaded operator or we matched a
4751 // built-in operator. In either case, fall through to trying to
4752 // build a built-in operation.
4753 input.release();
4754 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4755}
4756
Douglas Gregor063daf62009-03-13 18:40:31 +00004757/// \brief Create a binary operation that may resolve to an overloaded
4758/// operator.
4759///
4760/// \param OpLoc The location of the operator itself (e.g., '+').
4761///
4762/// \param OpcIn The BinaryOperator::Opcode that describes this
4763/// operator.
4764///
4765/// \param Functions The set of non-member functions that will be
4766/// considered by overload resolution. The caller needs to build this
4767/// set based on the context using, e.g.,
4768/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4769/// set should not contain any member functions; those will be added
4770/// by CreateOverloadedBinOp().
4771///
4772/// \param LHS Left-hand argument.
4773/// \param RHS Right-hand argument.
Mike Stump1eb44332009-09-09 15:08:12 +00004774Sema::OwningExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00004775Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004776 unsigned OpcIn,
Douglas Gregor063daf62009-03-13 18:40:31 +00004777 FunctionSet &Functions,
4778 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00004779 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004780 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00004781
4782 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4783 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4784 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4785
4786 // If either side is type-dependent, create an appropriate dependent
4787 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004788 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor063daf62009-03-13 18:40:31 +00004789 // .* cannot be overloaded.
4790 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004791 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
Douglas Gregor063daf62009-03-13 18:40:31 +00004792 Context.DependentTy, OpLoc));
4793
Mike Stump1eb44332009-09-09 15:08:12 +00004794 OverloadedFunctionDecl *Overloads
Douglas Gregor063daf62009-03-13 18:40:31 +00004795 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump1eb44332009-09-09 15:08:12 +00004796 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004797 FuncEnd = Functions.end();
4798 Func != FuncEnd; ++Func)
4799 Overloads->addOverload(*Func);
4800
4801 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4802 OpLoc, false, false);
Mike Stump1eb44332009-09-09 15:08:12 +00004803
Douglas Gregor063daf62009-03-13 18:40:31 +00004804 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00004805 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00004806 Context.DependentTy,
4807 OpLoc));
4808 }
4809
4810 // If this is the .* operator, which is not overloadable, just
4811 // create a built-in binary operator.
4812 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004813 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00004814
4815 // If this is one of the assignment operators, we only perform
4816 // overload resolution if the left-hand side is a class or
4817 // enumeration type (C++ [expr.ass]p3).
4818 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004819 !Args[0]->getType()->isOverloadableType())
4820 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00004821
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004822 // Build an empty overload set.
4823 OverloadCandidateSet CandidateSet;
Douglas Gregor063daf62009-03-13 18:40:31 +00004824
4825 // Add the candidates from the given function set.
4826 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4827
4828 // Add operator candidates that are member functions.
4829 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4830
4831 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00004832 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00004833
4834 // Perform overload resolution.
4835 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004836 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004837 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00004838 // We found a built-in operator or an overloaded operator.
4839 FunctionDecl *FnDecl = Best->Function;
4840
4841 if (FnDecl) {
4842 // We matched an overloaded operator. Build a call to that
4843 // operator.
4844
4845 // Convert the arguments.
4846 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004847 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4848 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004849 "passing"))
4850 return ExprError();
4851 } else {
4852 // Convert the arguments.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004853 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004854 "passing") ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004855 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004856 "passing"))
4857 return ExprError();
4858 }
4859
4860 // Determine the result type
4861 QualType ResultTy
John McCall183700f2009-09-21 23:43:11 +00004862 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor063daf62009-03-13 18:40:31 +00004863 ResultTy = ResultTy.getNonReferenceType();
4864
4865 // Build the actual expression node.
4866 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00004867 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00004868 UsualUnaryConversions(FnExpr);
4869
Anders Carlsson15ea3782009-10-13 22:43:21 +00004870 ExprOwningPtr<CXXOperatorCallExpr>
4871 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4872 Args, 2, ResultTy,
4873 OpLoc));
4874
4875 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4876 FnDecl))
4877 return ExprError();
4878
4879 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor063daf62009-03-13 18:40:31 +00004880 } else {
4881 // We matched a built-in operator. Convert the arguments, then
4882 // break out so that we will build the appropriate built-in
4883 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004884 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor063daf62009-03-13 18:40:31 +00004885 Best->Conversions[0], "passing") ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004886 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor063daf62009-03-13 18:40:31 +00004887 Best->Conversions[1], "passing"))
4888 return ExprError();
4889
4890 break;
4891 }
4892 }
4893
Douglas Gregor33074752009-09-30 21:46:01 +00004894 case OR_No_Viable_Function: {
4895 // C++ [over.match.oper]p9:
4896 // If the operator is the operator , [...] and there are no
4897 // viable functions, then the operator is assumed to be the
4898 // built-in operator and interpreted according to clause 5.
4899 if (Opc == BinaryOperator::Comma)
4900 break;
4901
Sebastian Redl8593c782009-05-21 11:50:50 +00004902 // For class as left operand for assignment or compound assigment operator
4903 // do not fall through to handling in built-in, but report that no overloaded
4904 // assignment operator found
Douglas Gregor33074752009-09-30 21:46:01 +00004905 OwningExprResult Result = ExprError();
4906 if (Args[0]->getType()->isRecordType() &&
4907 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00004908 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4909 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004910 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00004911 } else {
4912 // No viable function; try to create a built-in operation, which will
4913 // produce an error. Then, show the non-viable candidates.
4914 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00004915 }
Douglas Gregor33074752009-09-30 21:46:01 +00004916 assert(Result.isInvalid() &&
4917 "C++ binary operator overloading is missing candidates!");
4918 if (Result.isInvalid())
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004919 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
4920 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00004921 return move(Result);
4922 }
Douglas Gregor063daf62009-03-13 18:40:31 +00004923
4924 case OR_Ambiguous:
4925 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4926 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004927 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004928 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4929 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00004930 return ExprError();
4931
4932 case OR_Deleted:
4933 Diag(OpLoc, diag::err_ovl_deleted_oper)
4934 << Best->Function->isDeleted()
4935 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004936 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor063daf62009-03-13 18:40:31 +00004937 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4938 return ExprError();
4939 }
4940
Douglas Gregor33074752009-09-30 21:46:01 +00004941 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004942 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00004943}
4944
Douglas Gregor88a35142008-12-22 05:46:06 +00004945/// BuildCallToMemberFunction - Build a call to a member
4946/// function. MemExpr is the expression that refers to the member
4947/// function (and includes the object parameter), Args/NumArgs are the
4948/// arguments to the function call (not including the object
4949/// parameter). The caller needs to validate that the member
4950/// expression refers to a member function or an overloaded member
4951/// function.
4952Sema::ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00004953Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4954 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor88a35142008-12-22 05:46:06 +00004955 unsigned NumArgs, SourceLocation *CommaLocs,
4956 SourceLocation RParenLoc) {
4957 // Dig out the member expression. This holds both the object
4958 // argument and the member function we're referring to.
4959 MemberExpr *MemExpr = 0;
4960 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4961 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4962 else
4963 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4964 assert(MemExpr && "Building member call without member expression");
4965
4966 // Extract the object argument.
4967 Expr *ObjectArg = MemExpr->getBase();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004968
Douglas Gregor88a35142008-12-22 05:46:06 +00004969 CXXMethodDecl *Method = 0;
Douglas Gregor6b906862009-08-21 00:16:32 +00004970 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
4971 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004972 // Add overload candidates
4973 OverloadCandidateSet CandidateSet;
Douglas Gregor6b906862009-08-21 00:16:32 +00004974 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00004975
Douglas Gregordec06662009-08-21 18:42:58 +00004976 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
4977 Func != FuncEnd; ++Func) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00004978 if ((Method = dyn_cast<CXXMethodDecl>(*Func))) {
4979 // If explicit template arguments were provided, we can't call a
4980 // non-template member function.
4981 if (MemExpr->hasExplicitTemplateArgumentList())
4982 continue;
4983
Mike Stump1eb44332009-09-09 15:08:12 +00004984 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +00004985 /*SuppressUserConversions=*/false);
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00004986 } else
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00004987 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
4988 MemExpr->hasExplicitTemplateArgumentList(),
4989 MemExpr->getTemplateArgs(),
4990 MemExpr->getNumTemplateArgs(),
4991 ObjectArg, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00004992 CandidateSet,
4993 /*SuppressUsedConversions=*/false);
4994 }
Mike Stump1eb44332009-09-09 15:08:12 +00004995
Douglas Gregor88a35142008-12-22 05:46:06 +00004996 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004997 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004998 case OR_Success:
4999 Method = cast<CXXMethodDecl>(Best->Function);
5000 break;
5001
5002 case OR_No_Viable_Function:
Mike Stump1eb44332009-09-09 15:08:12 +00005003 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor88a35142008-12-22 05:46:06 +00005004 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00005005 << DeclName << MemExprE->getSourceRange();
Douglas Gregor88a35142008-12-22 05:46:06 +00005006 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5007 // FIXME: Leaking incoming expressions!
5008 return true;
5009
5010 case OR_Ambiguous:
Mike Stump1eb44332009-09-09 15:08:12 +00005011 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor88a35142008-12-22 05:46:06 +00005012 diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00005013 << DeclName << MemExprE->getSourceRange();
Douglas Gregor88a35142008-12-22 05:46:06 +00005014 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5015 // FIXME: Leaking incoming expressions!
5016 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005017
5018 case OR_Deleted:
Mike Stump1eb44332009-09-09 15:08:12 +00005019 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005020 diag::err_ovl_deleted_member_call)
5021 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00005022 << DeclName << MemExprE->getSourceRange();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005023 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5024 // FIXME: Leaking incoming expressions!
5025 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00005026 }
5027
5028 FixOverloadedFunctionReference(MemExpr, Method);
5029 } else {
5030 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5031 }
5032
5033 assert(Method && "Member call to something that isn't a method?");
Mike Stump1eb44332009-09-09 15:08:12 +00005034 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenek668bf912009-02-09 20:51:47 +00005035 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
Mike Stump1eb44332009-09-09 15:08:12 +00005036 NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00005037 Method->getResultType().getNonReferenceType(),
5038 RParenLoc));
5039
Anders Carlssoneed3e692009-10-10 00:06:20 +00005040 // Check for a valid return type.
5041 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5042 TheCall.get(), Method))
5043 return true;
5044
Douglas Gregor88a35142008-12-22 05:46:06 +00005045 // Convert the object argument (for a non-static member function call).
Mike Stump1eb44332009-09-09 15:08:12 +00005046 if (!Method->isStatic() &&
Douglas Gregor88a35142008-12-22 05:46:06 +00005047 PerformObjectArgumentInitialization(ObjectArg, Method))
5048 return true;
5049 MemExpr->setBase(ObjectArg);
5050
5051 // Convert the rest of the arguments
Douglas Gregor72564e72009-02-26 23:50:07 +00005052 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00005053 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00005054 RParenLoc))
5055 return true;
5056
Anders Carlssond406bf02009-08-16 01:56:34 +00005057 if (CheckFunctionCall(Method, TheCall.get()))
5058 return true;
Anders Carlsson6f680272009-08-16 03:42:12 +00005059
5060 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor88a35142008-12-22 05:46:06 +00005061}
5062
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005063/// BuildCallToObjectOfClassType - Build a call to an object of class
5064/// type (C++ [over.call.object]), which can end up invoking an
5065/// overloaded function call operator (@c operator()) or performing a
5066/// user-defined conversion on the object argument.
Mike Stump1eb44332009-09-09 15:08:12 +00005067Sema::ExprResult
5068Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00005069 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005070 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00005071 SourceLocation *CommaLocs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005072 SourceLocation RParenLoc) {
5073 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00005074 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005075
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005076 // C++ [over.call.object]p1:
5077 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00005078 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005079 // candidate functions includes at least the function call
5080 // operators of T. The function call operators of T are obtained by
5081 // ordinary lookup of the name operator() in the context of
5082 // (E).operator().
5083 OverloadCandidateSet CandidateSet;
Douglas Gregor44b43212008-12-11 16:49:14 +00005084 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00005085 DeclContext::lookup_const_iterator Oper, OperEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005086 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00005087 Oper != OperEnd; ++Oper)
Mike Stump1eb44332009-09-09 15:08:12 +00005088 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
Douglas Gregor3fc749d2008-12-23 00:26:44 +00005089 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005090
Douglas Gregor4a27d702009-10-21 06:18:39 +00005091 if (RequireCompleteType(LParenLoc, Object->getType(),
5092 PartialDiagnostic(diag::err_incomplete_object_call)
5093 << Object->getSourceRange()))
5094 return true;
5095
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005096 // C++ [over.call.object]p2:
5097 // In addition, for each conversion function declared in T of the
5098 // form
5099 //
5100 // operator conversion-type-id () cv-qualifier;
5101 //
5102 // where cv-qualifier is the same cv-qualification as, or a
5103 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00005104 // denotes the type "pointer to function of (P1,...,Pn) returning
5105 // R", or the type "reference to pointer to function of
5106 // (P1,...,Pn) returning R", or the type "reference to function
5107 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005108 // is also considered as a candidate function. Similarly,
5109 // surrogate call functions are added to the set of candidate
5110 // functions for each conversion function declared in an
5111 // accessible base class provided the function is not hidden
5112 // within T by another intervening declaration.
Douglas Gregor4a27d702009-10-21 06:18:39 +00005113 // FIXME: Look in base classes for more conversion operators!
5114 OverloadedFunctionDecl *Conversions
5115 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
5116 for (OverloadedFunctionDecl::function_iterator
5117 Func = Conversions->function_begin(),
5118 FuncEnd = Conversions->function_end();
5119 Func != FuncEnd; ++Func) {
5120 CXXConversionDecl *Conv;
5121 FunctionTemplateDecl *ConvTemplate;
5122 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
Mike Stump1eb44332009-09-09 15:08:12 +00005123
Douglas Gregor4a27d702009-10-21 06:18:39 +00005124 // Skip over templated conversion functions; they aren't
5125 // surrogates.
5126 if (ConvTemplate)
5127 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005128
Douglas Gregor4a27d702009-10-21 06:18:39 +00005129 // Strip the reference type (if any) and then the pointer type (if
5130 // any) to get down to what might be a function type.
5131 QualType ConvType = Conv->getConversionType().getNonReferenceType();
5132 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5133 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005134
Douglas Gregor4a27d702009-10-21 06:18:39 +00005135 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
5136 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005137 }
Mike Stump1eb44332009-09-09 15:08:12 +00005138
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005139 // Perform overload resolution.
5140 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005141 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005142 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005143 // Overload resolution succeeded; we'll build the appropriate call
5144 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005145 break;
5146
5147 case OR_No_Viable_Function:
Mike Stump1eb44332009-09-09 15:08:12 +00005148 Diag(Object->getSourceRange().getBegin(),
Sebastian Redle4c452c2008-11-22 13:44:36 +00005149 diag::err_ovl_no_viable_object_call)
Chris Lattner4330d652009-02-17 07:29:20 +00005150 << Object->getType() << Object->getSourceRange();
Sebastian Redle4c452c2008-11-22 13:44:36 +00005151 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005152 break;
5153
5154 case OR_Ambiguous:
5155 Diag(Object->getSourceRange().getBegin(),
5156 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00005157 << Object->getType() << Object->getSourceRange();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005158 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5159 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005160
5161 case OR_Deleted:
5162 Diag(Object->getSourceRange().getBegin(),
5163 diag::err_ovl_deleted_object_call)
5164 << Best->Function->isDeleted()
5165 << Object->getType() << Object->getSourceRange();
5166 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5167 break;
Mike Stump1eb44332009-09-09 15:08:12 +00005168 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005169
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005170 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005171 // We had an error; delete all of the subexpressions and return
5172 // the error.
Ted Kremenek8189cde2009-02-07 01:47:29 +00005173 Object->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005174 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek8189cde2009-02-07 01:47:29 +00005175 Args[ArgIdx]->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005176 return true;
5177 }
5178
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005179 if (Best->Function == 0) {
5180 // Since there is no function declaration, this is one of the
5181 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00005182 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005183 = cast<CXXConversionDecl>(
5184 Best->Conversions[0].UserDefined.ConversionFunction);
5185
5186 // We selected one of the surrogate functions that converts the
5187 // object parameter to a function pointer. Perform the conversion
5188 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00005189
5190 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00005191 // and then call it.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00005192 CXXMemberCallExpr *CE =
Fariborz Jahanianb7400232009-09-28 23:23:40 +00005193 BuildCXXMemberCallExpr(Object, Conv);
5194
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00005195 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00005196 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
5197 CommaLocs, RParenLoc).release();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005198 }
5199
5200 // We found an overloaded operator(). Build a CXXOperatorCallExpr
5201 // that calls this method, using Object for the implicit object
5202 // parameter and passing along the remaining arguments.
5203 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00005204 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005205
5206 unsigned NumArgsInProto = Proto->getNumArgs();
5207 unsigned NumArgsToCheck = NumArgs;
5208
5209 // Build the full argument list for the method call (the
5210 // implicit object parameter is placed at the beginning of the
5211 // list).
5212 Expr **MethodArgs;
5213 if (NumArgs < NumArgsInProto) {
5214 NumArgsToCheck = NumArgsInProto;
5215 MethodArgs = new Expr*[NumArgsInProto + 1];
5216 } else {
5217 MethodArgs = new Expr*[NumArgs + 1];
5218 }
5219 MethodArgs[0] = Object;
5220 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5221 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00005222
5223 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00005224 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005225 UsualUnaryConversions(NewFn);
5226
5227 // Once we've built TheCall, all of the expressions are properly
5228 // owned.
5229 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00005230 ExprOwningPtr<CXXOperatorCallExpr>
5231 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor063daf62009-03-13 18:40:31 +00005232 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00005233 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005234 delete [] MethodArgs;
5235
Anders Carlsson07d68f12009-10-13 21:49:31 +00005236 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
5237 Method))
5238 return true;
5239
Douglas Gregor518fda12009-01-13 05:10:00 +00005240 // We may have default arguments. If so, we need to allocate more
5241 // slots in the call for them.
5242 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00005243 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00005244 else if (NumArgs > NumArgsInProto)
5245 NumArgsToCheck = NumArgsInProto;
5246
Chris Lattner312531a2009-04-12 08:11:20 +00005247 bool IsError = false;
5248
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005249 // Initialize the implicit object parameter.
Chris Lattner312531a2009-04-12 08:11:20 +00005250 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005251 TheCall->setArg(0, Object);
5252
Chris Lattner312531a2009-04-12 08:11:20 +00005253
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005254 // Check the argument types.
5255 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005256 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00005257 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005258 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00005259
Douglas Gregor518fda12009-01-13 05:10:00 +00005260 // Pass the argument.
5261 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner312531a2009-04-12 08:11:20 +00005262 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor518fda12009-01-13 05:10:00 +00005263 } else {
Anders Carlssonf1480ee2009-08-14 18:30:22 +00005264 Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
Douglas Gregor518fda12009-01-13 05:10:00 +00005265 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005266
5267 TheCall->setArg(i + 1, Arg);
5268 }
5269
5270 // If this is a variadic call, handle args passed through "...".
5271 if (Proto->isVariadic()) {
5272 // Promote the arguments (C99 6.5.2.2p7).
5273 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
5274 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00005275 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005276 TheCall->setArg(i + 1, Arg);
5277 }
5278 }
5279
Chris Lattner312531a2009-04-12 08:11:20 +00005280 if (IsError) return true;
5281
Anders Carlssond406bf02009-08-16 01:56:34 +00005282 if (CheckFunctionCall(Method, TheCall.get()))
5283 return true;
5284
Anders Carlssona303f9e2009-08-16 03:53:54 +00005285 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005286}
5287
Douglas Gregor8ba10742008-11-20 16:27:02 +00005288/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00005289/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00005290/// @c Member is the name of the member we're trying to find.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005291Sema::OwningExprResult
5292Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
5293 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor8ba10742008-11-20 16:27:02 +00005294 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00005295
Douglas Gregor8ba10742008-11-20 16:27:02 +00005296 // C++ [over.ref]p1:
5297 //
5298 // [...] An expression x->m is interpreted as (x.operator->())->m
5299 // for a class object x of type T if T::operator->() exists and if
5300 // the operator is selected as the best match function by the
5301 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00005302 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
5303 OverloadCandidateSet CandidateSet;
Ted Kremenek6217b802009-07-29 21:53:49 +00005304 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005305
John McCallf36e02d2009-10-09 21:13:30 +00005306 LookupResult R;
5307 LookupQualifiedName(R, BaseRecord->getDecl(), OpName, LookupOrdinaryName);
Anders Carlssone30572a2009-09-10 23:18:36 +00005308
5309 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
5310 Oper != OperEnd; ++Oper)
Douglas Gregor3fc749d2008-12-23 00:26:44 +00005311 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00005312 /*SuppressUserConversions=*/false);
Douglas Gregor8ba10742008-11-20 16:27:02 +00005313
5314 // Perform overload resolution.
5315 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005316 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00005317 case OR_Success:
5318 // Overload resolution succeeded; we'll build the call below.
5319 break;
5320
5321 case OR_No_Viable_Function:
5322 if (CandidateSet.empty())
5323 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005324 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005325 else
5326 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005327 << "operator->" << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005328 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005329 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005330
5331 case OR_Ambiguous:
5332 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00005333 << "->" << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005334 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005335 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005336
5337 case OR_Deleted:
5338 Diag(OpLoc, diag::err_ovl_deleted_oper)
5339 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00005340 << "->" << Base->getSourceRange();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005341 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005342 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005343 }
5344
5345 // Convert the object parameter.
5346 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00005347 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005348 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00005349
5350 // No concerns about early exits now.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005351 BaseIn.release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005352
5353 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00005354 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5355 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00005356 UsualUnaryConversions(FnExpr);
Anders Carlsson15ea3782009-10-13 22:43:21 +00005357
5358 QualType ResultTy = Method->getResultType().getNonReferenceType();
5359 ExprOwningPtr<CXXOperatorCallExpr>
5360 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
5361 &Base, 1, ResultTy, OpLoc));
5362
5363 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
5364 Method))
5365 return ExprError();
5366 return move(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00005367}
5368
Douglas Gregor904eed32008-11-10 20:40:00 +00005369/// FixOverloadedFunctionReference - E is an expression that refers to
5370/// a C++ overloaded function (possibly with some parentheses and
5371/// perhaps a '&' around it). We have resolved the overloaded function
5372/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00005373/// refer (possibly indirectly) to Fn. Returns the new expr.
5374Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005375 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Anders Carlsson96ad5332009-10-21 17:16:23 +00005376 Expr *NewExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00005377 PE->setSubExpr(NewExpr);
5378 PE->setType(NewExpr->getType());
5379 } else if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5380 Expr *NewExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
5381 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
5382 NewExpr->getType()) &&
5383 "Implicit cast type cannot be determined from overload");
5384 ICE->setSubExpr(NewExpr);
Douglas Gregor904eed32008-11-10 20:40:00 +00005385 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump1eb44332009-09-09 15:08:12 +00005386 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00005387 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00005388 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5389 if (Method->isStatic()) {
5390 // Do nothing: static member functions aren't any different
5391 // from non-member functions.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005392 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr())) {
5393 if (DRE->getQualifier()) {
5394 // We have taken the address of a pointer to member
5395 // function. Perform the computation here so that we get the
5396 // appropriate pointer to member type.
5397 DRE->setDecl(Fn);
5398 DRE->setType(Fn->getType());
5399 QualType ClassType
5400 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
5401 E->setType(Context.getMemberPointerType(Fn->getType(),
5402 ClassType.getTypePtr()));
5403 return E;
5404 }
Douglas Gregorb86b0572009-02-11 01:18:59 +00005405 }
Douglas Gregor423a4e02009-10-22 18:02:20 +00005406 // FIXME: TemplateIdRefExpr referring to a member function template
5407 // specialization!
Douglas Gregorb86b0572009-02-11 01:18:59 +00005408 }
Anders Carlsson96ad5332009-10-21 17:16:23 +00005409 Expr *NewExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5410 UnOp->setSubExpr(NewExpr);
5411 UnOp->setType(Context.getPointerType(NewExpr->getType()));
5412
5413 return UnOp;
Douglas Gregor904eed32008-11-10 20:40:00 +00005414 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00005415 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
Douglas Gregor097bfb12009-10-23 22:18:25 +00005416 isa<FunctionTemplateDecl>(DR->getDecl()) ||
5417 isa<FunctionDecl>(DR->getDecl())) &&
5418 "Expected function or function template");
Douglas Gregor904eed32008-11-10 20:40:00 +00005419 DR->setDecl(Fn);
5420 E->setType(Fn->getType());
Douglas Gregor88a35142008-12-22 05:46:06 +00005421 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
5422 MemExpr->setMemberDecl(Fn);
5423 E->setType(Fn->getType());
Anders Carlsson96ad5332009-10-21 17:16:23 +00005424 } else if (TemplateIdRefExpr *TID = dyn_cast<TemplateIdRefExpr>(E)) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00005425 E = DeclRefExpr::Create(Context,
5426 TID->getQualifier(), TID->getQualifierRange(),
5427 Fn, TID->getTemplateNameLoc(),
5428 true,
5429 TID->getLAngleLoc(),
5430 TID->getTemplateArgs(),
5431 TID->getNumTemplateArgs(),
5432 TID->getRAngleLoc(),
5433 Fn->getType(),
5434 /*FIXME?*/false, /*FIXME?*/false);
Douglas Gregor423a4e02009-10-22 18:02:20 +00005435
Douglas Gregora2813ce2009-10-23 18:54:35 +00005436 // FIXME: Don't destroy TID here, since we need its template arguments
5437 // to survive.
5438 // TID->Destroy(Context);
Douglas Gregor097bfb12009-10-23 22:18:25 +00005439 } else if (isa<UnresolvedFunctionNameExpr>(E)) {
5440 return DeclRefExpr::Create(Context,
5441 /*Qualifier=*/0,
5442 /*QualifierRange=*/SourceRange(),
5443 Fn, E->getLocStart(),
5444 Fn->getType(), false, false);
Douglas Gregor904eed32008-11-10 20:40:00 +00005445 } else {
5446 assert(false && "Invalid reference to overloaded function");
5447 }
Anders Carlsson96ad5332009-10-21 17:16:23 +00005448
5449 return E;
Douglas Gregor904eed32008-11-10 20:40:00 +00005450}
5451
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005452} // end namespace clang