blob: 2555f5bde60af3da80d6a5e03557a8641381afba [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"
John McCall7d384dd2009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000016#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000018#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000020#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000022#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000024#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000025#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000026#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,
Douglas Gregor43c79c22009-12-09 00:47:37 +000041 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000042 ICC_Qualification_Adjustment,
43 ICC_Promotion,
44 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000045 ICC_Promotion,
46 ICC_Conversion,
47 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000048 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000053 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000054 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000055 ICC_Conversion
56 };
57 return Category[(int)Kind];
58}
59
60/// GetConversionRank - Retrieve the implicit conversion rank
61/// corresponding to the given implicit conversion kind.
62ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
63 static const ImplicitConversionRank
64 Rank[(int)ICK_Num_Conversion_Kinds] = {
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +000070 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000071 ICR_Promotion,
72 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000073 ICR_Promotion,
74 ICR_Conversion,
75 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000076 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000081 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000082 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000083 ICR_Conversion
84 };
85 return Rank[(int)Kind];
86}
87
88/// GetImplicitConversionName - Return the name of this kind of
89/// implicit conversion.
90const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
91 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
92 "No conversion",
93 "Lvalue-to-rvalue",
94 "Array-to-pointer",
95 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +000096 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000097 "Qualification",
98 "Integral promotion",
99 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000100 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000101 "Integral conversion",
102 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000103 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000104 "Floating-integral conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000105 "Complex-real conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000106 "Pointer conversion",
107 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000108 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000109 "Compatible-types conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000110 "Derived-to-base conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000111 };
112 return Name[Kind];
113}
114
Douglas Gregor60d62c22008-10-31 16:23:19 +0000115/// StandardConversionSequence - Set the standard conversion
116/// sequence to the identity conversion.
117void StandardConversionSequence::setAsIdentityConversion() {
118 First = ICK_Identity;
119 Second = ICK_Identity;
120 Third = ICK_Identity;
121 Deprecated = false;
122 ReferenceBinding = false;
123 DirectBinding = false;
Sebastian Redl85002392009-03-29 22:46:24 +0000124 RRefBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000125 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000126}
127
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000128/// getRank - Retrieve the rank of this standard conversion sequence
129/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
130/// implicit conversions.
131ImplicitConversionRank StandardConversionSequence::getRank() const {
132 ImplicitConversionRank Rank = ICR_Exact_Match;
133 if (GetConversionRank(First) > Rank)
134 Rank = GetConversionRank(First);
135 if (GetConversionRank(Second) > Rank)
136 Rank = GetConversionRank(Second);
137 if (GetConversionRank(Third) > Rank)
138 Rank = GetConversionRank(Third);
139 return Rank;
140}
141
142/// isPointerConversionToBool - Determines whether this conversion is
143/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000144/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000145/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000146bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000147 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
148 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
149
150 // Note that FromType has not necessarily been transformed by the
151 // array-to-pointer or function-to-pointer implicit conversions, so
152 // check for their presence as well as checking whether FromType is
153 // a pointer.
154 if (ToType->isBooleanType() &&
Douglas Gregor2a7e58d2008-12-23 00:53:59 +0000155 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000156 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
157 return true;
158
159 return false;
160}
161
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000162/// isPointerConversionToVoidPointer - Determines whether this
163/// conversion is a conversion of a pointer to a void pointer. This is
164/// used as part of the ranking of standard conversion sequences (C++
165/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000166bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000167StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000168isPointerConversionToVoidPointer(ASTContext& Context) const {
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000169 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
170 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
171
172 // Note that FromType has not necessarily been transformed by the
173 // array-to-pointer implicit conversion, so check for its presence
174 // and redo the conversion to get a pointer.
175 if (First == ICK_Array_To_Pointer)
176 FromType = Context.getArrayDecayedType(FromType);
177
178 if (Second == ICK_Pointer_Conversion)
Ted Kremenek6217b802009-07-29 21:53:49 +0000179 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000180 return ToPtrType->getPointeeType()->isVoidType();
181
182 return false;
183}
184
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000185/// DebugPrint - Print this standard conversion sequence to standard
186/// error. Useful for debugging overloading issues.
187void StandardConversionSequence::DebugPrint() const {
188 bool PrintedSomething = false;
189 if (First != ICK_Identity) {
190 fprintf(stderr, "%s", GetImplicitConversionName(First));
191 PrintedSomething = true;
192 }
193
194 if (Second != ICK_Identity) {
195 if (PrintedSomething) {
196 fprintf(stderr, " -> ");
197 }
198 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregor225c41e2008-11-03 19:09:14 +0000199
200 if (CopyConstructor) {
201 fprintf(stderr, " (by copy constructor)");
202 } else if (DirectBinding) {
203 fprintf(stderr, " (direct reference binding)");
204 } else if (ReferenceBinding) {
205 fprintf(stderr, " (reference binding)");
206 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000207 PrintedSomething = true;
208 }
209
210 if (Third != ICK_Identity) {
211 if (PrintedSomething) {
212 fprintf(stderr, " -> ");
213 }
214 fprintf(stderr, "%s", GetImplicitConversionName(Third));
215 PrintedSomething = true;
216 }
217
218 if (!PrintedSomething) {
219 fprintf(stderr, "No conversions required");
220 }
221}
222
223/// DebugPrint - Print this user-defined conversion sequence to standard
224/// error. Useful for debugging overloading issues.
225void UserDefinedConversionSequence::DebugPrint() const {
226 if (Before.First || Before.Second || Before.Third) {
227 Before.DebugPrint();
228 fprintf(stderr, " -> ");
229 }
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000230 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000231 if (After.First || After.Second || After.Third) {
232 fprintf(stderr, " -> ");
233 After.DebugPrint();
234 }
235}
236
237/// DebugPrint - Print this implicit conversion sequence to standard
238/// error. Useful for debugging overloading issues.
239void ImplicitConversionSequence::DebugPrint() const {
240 switch (ConversionKind) {
241 case StandardConversion:
242 fprintf(stderr, "Standard conversion: ");
243 Standard.DebugPrint();
244 break;
245 case UserDefinedConversion:
246 fprintf(stderr, "User-defined conversion: ");
247 UserDefined.DebugPrint();
248 break;
249 case EllipsisConversion:
250 fprintf(stderr, "Ellipsis conversion");
251 break;
252 case BadConversion:
253 fprintf(stderr, "Bad conversion");
254 break;
255 }
256
257 fprintf(stderr, "\n");
258}
259
260// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000261// overload of the declarations in Old. This routine returns false if
262// New and Old cannot be overloaded, e.g., if New has the same
263// signature as some function in Old (C++ 1.3.10) or if the Old
264// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000265// it does return false, MatchedDecl will point to the decl that New
266// cannot be overloaded with. This decl may be a UsingShadowDecl on
267// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000268//
269// Example: Given the following input:
270//
271// void f(int, float); // #1
272// void f(int, int); // #2
273// int f(int, int); // #3
274//
275// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000276// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000277//
John McCall51fa86f2009-12-02 08:47:38 +0000278// When we process #2, Old contains only the FunctionDecl for #1. By
279// comparing the parameter types, we see that #1 and #2 are overloaded
280// (since they have different signatures), so this routine returns
281// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000282//
John McCall51fa86f2009-12-02 08:47:38 +0000283// When we process #3, Old is an overload set containing #1 and #2. We
284// compare the signatures of #3 to #1 (they're overloaded, so we do
285// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
286// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000287// signature), IsOverload returns false and MatchedDecl will be set to
288// point to the FunctionDecl for #2.
John McCall871b2e72009-12-09 03:35:25 +0000289Sema::OverloadKind
290Sema::CheckOverload(FunctionDecl *New, LookupResult &Old, NamedDecl *&Match) {
John McCall51fa86f2009-12-02 08:47:38 +0000291 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000292 I != E; ++I) {
John McCall51fa86f2009-12-02 08:47:38 +0000293 NamedDecl *OldD = (*I)->getUnderlyingDecl();
294 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCall68263142009-11-18 22:49:29 +0000295 if (!IsOverload(New, OldT->getTemplatedDecl())) {
John McCall871b2e72009-12-09 03:35:25 +0000296 Match = *I;
297 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000298 }
John McCall51fa86f2009-12-02 08:47:38 +0000299 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCall68263142009-11-18 22:49:29 +0000300 if (!IsOverload(New, OldF)) {
John McCall871b2e72009-12-09 03:35:25 +0000301 Match = *I;
302 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000303 }
John McCall871b2e72009-12-09 03:35:25 +0000304 } else if (!isa<UnresolvedUsingValueDecl>(OldD)) {
John McCall68263142009-11-18 22:49:29 +0000305 // (C++ 13p1):
306 // Only function declarations can be overloaded; object and type
307 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000308 // But we permit unresolved using value decls and diagnose the error
309 // during template instantiation.
310 Match = *I;
311 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000312 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000313 }
John McCall68263142009-11-18 22:49:29 +0000314
John McCall871b2e72009-12-09 03:35:25 +0000315 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000316}
317
318bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
319 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
320 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
321
322 // C++ [temp.fct]p2:
323 // A function template can be overloaded with other function templates
324 // and with normal (non-template) functions.
325 if ((OldTemplate == 0) != (NewTemplate == 0))
326 return true;
327
328 // Is the function New an overload of the function Old?
329 QualType OldQType = Context.getCanonicalType(Old->getType());
330 QualType NewQType = Context.getCanonicalType(New->getType());
331
332 // Compare the signatures (C++ 1.3.10) of the two functions to
333 // determine whether they are overloads. If we find any mismatch
334 // in the signature, they are overloads.
335
336 // If either of these functions is a K&R-style function (no
337 // prototype), then we consider them to have matching signatures.
338 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
339 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
340 return false;
341
342 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
343 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
344
345 // The signature of a function includes the types of its
346 // parameters (C++ 1.3.10), which includes the presence or absence
347 // of the ellipsis; see C++ DR 357).
348 if (OldQType != NewQType &&
349 (OldType->getNumArgs() != NewType->getNumArgs() ||
350 OldType->isVariadic() != NewType->isVariadic() ||
351 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
352 NewType->arg_type_begin())))
353 return true;
354
355 // C++ [temp.over.link]p4:
356 // The signature of a function template consists of its function
357 // signature, its return type and its template parameter list. The names
358 // of the template parameters are significant only for establishing the
359 // relationship between the template parameters and the rest of the
360 // signature.
361 //
362 // We check the return type and template parameter lists for function
363 // templates first; the remaining checks follow.
364 if (NewTemplate &&
365 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
366 OldTemplate->getTemplateParameters(),
367 false, TPL_TemplateMatch) ||
368 OldType->getResultType() != NewType->getResultType()))
369 return true;
370
371 // If the function is a class member, its signature includes the
372 // cv-qualifiers (if any) on the function itself.
373 //
374 // As part of this, also check whether one of the member functions
375 // is static, in which case they are not overloads (C++
376 // 13.1p2). While not part of the definition of the signature,
377 // this check is important to determine whether these functions
378 // can be overloaded.
379 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
380 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
381 if (OldMethod && NewMethod &&
382 !OldMethod->isStatic() && !NewMethod->isStatic() &&
383 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
384 return true;
385
386 // The signatures match; this is not an overload.
387 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000388}
389
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000390/// TryImplicitConversion - Attempt to perform an implicit conversion
391/// from the given expression (Expr) to the given type (ToType). This
392/// function returns an implicit conversion sequence that can be used
393/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000394///
395/// void f(float f);
396/// void g(int i) { f(i); }
397///
398/// this routine would produce an implicit conversion sequence to
399/// describe the initialization of f from i, which will be a standard
400/// conversion sequence containing an lvalue-to-rvalue conversion (C++
401/// 4.1) followed by a floating-integral conversion (C++ 4.9).
402//
403/// Note that this routine only determines how the conversion can be
404/// performed; it does not actually perform the conversion. As such,
405/// it will not produce any diagnostics if no conversion is available,
406/// but will instead return an implicit conversion sequence of kind
407/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000408///
409/// If @p SuppressUserConversions, then user-defined conversions are
410/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000411/// If @p AllowExplicit, then explicit user-defined conversions are
412/// permitted.
Sebastian Redle2b68332009-04-12 17:16:29 +0000413/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
414/// no matter its actual lvalueness.
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000415/// If @p UserCast, the implicit conversion is being done for a user-specified
416/// cast.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000417ImplicitConversionSequence
Anders Carlsson2974b5c2009-08-27 17:14:02 +0000418Sema::TryImplicitConversion(Expr* From, QualType ToType,
419 bool SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +0000420 bool AllowExplicit, bool ForceRValue,
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000421 bool InOverloadResolution,
422 bool UserCast) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000423 ImplicitConversionSequence ICS;
Fariborz Jahanian78cf9a22009-09-15 00:10:11 +0000424 OverloadCandidateSet Conversions;
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000425 OverloadingResult UserDefResult = OR_Success;
Anders Carlsson08972922009-08-28 15:33:32 +0000426 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
Douglas Gregor60d62c22008-10-31 16:23:19 +0000427 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000428 else if (getLangOptions().CPlusPlus &&
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000429 (UserDefResult = IsUserDefinedConversion(From, ToType,
430 ICS.UserDefined,
Fariborz Jahanian78cf9a22009-09-15 00:10:11 +0000431 Conversions,
Sebastian Redle2b68332009-04-12 17:16:29 +0000432 !SuppressUserConversions, AllowExplicit,
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000433 ForceRValue, UserCast)) == OR_Success) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000434 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000435 // C++ [over.ics.user]p4:
436 // A conversion of an expression of class type to the same class
437 // type is given Exact Match rank, and a conversion of an
438 // expression of class type to a base class of that type is
439 // given Conversion rank, in spite of the fact that a copy
440 // constructor (i.e., a user-defined conversion function) is
441 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000442 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000443 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000444 QualType FromCanon
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000445 = Context.getCanonicalType(From->getType().getUnqualifiedType());
446 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
447 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000448 // Turn this into a "standard" conversion sequence, so that it
449 // gets ranked with standard conversion sequences.
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000450 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
451 ICS.Standard.setAsIdentityConversion();
452 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
453 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000454 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000455 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000456 ICS.Standard.Second = ICK_Derived_To_Base;
457 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000458 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000459
460 // C++ [over.best.ics]p4:
461 // However, when considering the argument of a user-defined
462 // conversion function that is a candidate by 13.3.1.3 when
463 // invoked for the copying of the temporary in the second step
464 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
465 // 13.3.1.6 in all cases, only standard conversion sequences and
466 // ellipsis conversion sequences are allowed.
467 if (SuppressUserConversions &&
468 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
469 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000470 } else {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000471 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000472 if (UserDefResult == OR_Ambiguous) {
473 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
474 Cand != Conversions.end(); ++Cand)
Fariborz Jahanian27687cf2009-10-12 17:51:19 +0000475 if (Cand->Viable)
476 ICS.ConversionFunctionSet.push_back(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000477 }
478 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000479
480 return ICS;
481}
482
Douglas Gregor43c79c22009-12-09 00:47:37 +0000483/// \brief Determine whether the conversion from FromType to ToType is a valid
484/// conversion that strips "noreturn" off the nested function type.
485static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
486 QualType ToType, QualType &ResultTy) {
487 if (Context.hasSameUnqualifiedType(FromType, ToType))
488 return false;
489
490 // Strip the noreturn off the type we're converting from; noreturn can
491 // safely be removed.
492 FromType = Context.getNoReturnType(FromType, false);
493 if (!Context.hasSameUnqualifiedType(FromType, ToType))
494 return false;
495
496 ResultTy = FromType;
497 return true;
498}
499
Douglas Gregor60d62c22008-10-31 16:23:19 +0000500/// IsStandardConversion - Determines whether there is a standard
501/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
502/// expression From to the type ToType. Standard conversion sequences
503/// only consider non-class types; for conversions that involve class
504/// types, use TryImplicitConversion. If a conversion exists, SCS will
505/// contain the standard conversion sequence required to perform this
506/// conversion and this routine will return true. Otherwise, this
507/// routine will return false and the value of SCS is unspecified.
Mike Stump1eb44332009-09-09 15:08:12 +0000508bool
509Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000510 bool InOverloadResolution,
Mike Stump1eb44332009-09-09 15:08:12 +0000511 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000512 QualType FromType = From->getType();
513
Douglas Gregor60d62c22008-10-31 16:23:19 +0000514 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000515 SCS.setAsIdentityConversion();
Douglas Gregor60d62c22008-10-31 16:23:19 +0000516 SCS.Deprecated = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000517 SCS.IncompatibleObjC = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000518 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000519 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000520
Douglas Gregorf9201e02009-02-11 23:02:49 +0000521 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000522 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000523 if (FromType->isRecordType() || ToType->isRecordType()) {
524 if (getLangOptions().CPlusPlus)
525 return false;
526
Mike Stump1eb44332009-09-09 15:08:12 +0000527 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000528 }
529
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000530 // The first conversion can be an lvalue-to-rvalue conversion,
531 // array-to-pointer conversion, or function-to-pointer conversion
532 // (C++ 4p1).
533
Mike Stump1eb44332009-09-09 15:08:12 +0000534 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000535 // An lvalue (3.10) of a non-function, non-array type T can be
536 // converted to an rvalue.
537 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000538 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000539 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor063daf62009-03-13 18:40:31 +0000540 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000541 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000542
543 // If T is a non-class type, the type of the rvalue is the
544 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +0000545 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
546 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000547 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000548 } else if (FromType->isArrayType()) {
549 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000550 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000551
552 // An lvalue or rvalue of type "array of N T" or "array of unknown
553 // bound of T" can be converted to an rvalue of type "pointer to
554 // T" (C++ 4.2p1).
555 FromType = Context.getArrayDecayedType(FromType);
556
557 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
558 // This conversion is deprecated. (C++ D.4).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000559 SCS.Deprecated = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000560
561 // For the purpose of ranking in overload resolution
562 // (13.3.3.1.1), this conversion is considered an
563 // array-to-pointer conversion followed by a qualification
564 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000565 SCS.Second = ICK_Identity;
566 SCS.Third = ICK_Qualification;
567 SCS.ToTypePtr = ToType.getAsOpaquePtr();
568 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000569 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000570 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
571 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000572 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000573
574 // An lvalue of function type T can be converted to an rvalue of
575 // type "pointer to T." The result is a pointer to the
576 // function. (C++ 4.3p1).
577 FromType = Context.getPointerType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000578 } else if (FunctionDecl *Fn
Douglas Gregor43c79c22009-12-09 00:47:37 +0000579 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000580 // Address of overloaded function (C++ [over.over]).
Douglas Gregor904eed32008-11-10 20:40:00 +0000581 SCS.First = ICK_Function_To_Pointer;
582
583 // We were able to resolve the address of the overloaded function,
584 // so we can convert to the type of that function.
585 FromType = Fn->getType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000586 if (ToType->isLValueReferenceType())
587 FromType = Context.getLValueReferenceType(FromType);
588 else if (ToType->isRValueReferenceType())
589 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl33b399a2009-02-04 21:23:32 +0000590 else if (ToType->isMemberPointerType()) {
591 // Resolve address only succeeds if both sides are member pointers,
592 // but it doesn't have to be the same class. See DR 247.
593 // Note that this means that the type of &Derived::fn can be
594 // Ret (Base::*)(Args) if the fn overload actually found is from the
595 // base class, even if it was brought into the derived class via a
596 // using declaration. The standard isn't clear on this issue at all.
597 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
598 FromType = Context.getMemberPointerType(FromType,
599 Context.getTypeDeclType(M->getParent()).getTypePtr());
600 } else
Douglas Gregor904eed32008-11-10 20:40:00 +0000601 FromType = Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000602 } else {
603 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000604 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000605 }
606
607 // The second conversion can be an integral promotion, floating
608 // point promotion, integral conversion, floating point conversion,
609 // floating-integral conversion, pointer conversion,
610 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +0000611 // For overloading in C, this can also be a "compatible-type"
612 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +0000613 bool IncompatibleObjC = false;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000614 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000615 // The unqualified versions of the types are the same: there's no
616 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000617 SCS.Second = ICK_Identity;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000618 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000619 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000620 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000621 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000622 } else if (IsFloatingPointPromotion(FromType, ToType)) {
623 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000624 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000625 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000626 } else if (IsComplexPromotion(FromType, ToType)) {
627 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000628 SCS.Second = ICK_Complex_Promotion;
629 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000630 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000631 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000632 // Integral conversions (C++ 4.7).
633 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000634 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000635 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000636 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
637 // Floating point conversions (C++ 4.8).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000638 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000639 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000640 } else if (FromType->isComplexType() && ToType->isComplexType()) {
641 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000642 SCS.Second = ICK_Complex_Conversion;
643 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000644 } else if ((FromType->isFloatingType() &&
645 ToType->isIntegralType() && (!ToType->isBooleanType() &&
646 !ToType->isEnumeralType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000647 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000648 ToType->isFloatingType())) {
649 // Floating-integral conversions (C++ 4.9).
650 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000651 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000652 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000653 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
654 (ToType->isComplexType() && FromType->isArithmeticType())) {
655 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000656 SCS.Second = ICK_Complex_Real;
657 FromType = ToType.getUnqualifiedType();
Anders Carlsson08972922009-08-28 15:33:32 +0000658 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
659 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000660 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000661 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000662 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregorce940492009-09-25 04:25:58 +0000663 } else if (IsMemberPointerConversion(From, FromType, ToType,
664 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000665 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000666 SCS.Second = ICK_Pointer_Member;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000667 } else if (ToType->isBooleanType() &&
668 (FromType->isArithmeticType() ||
669 FromType->isEnumeralType() ||
670 FromType->isPointerType() ||
671 FromType->isBlockPointerType() ||
672 FromType->isMemberPointerType() ||
673 FromType->isNullPtrType())) {
674 // Boolean conversions (C++ 4.12).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000675 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000676 FromType = Context.BoolTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000677 } else if (!getLangOptions().CPlusPlus &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000678 Context.typesAreCompatible(ToType, FromType)) {
679 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000680 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor43c79c22009-12-09 00:47:37 +0000681 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
682 // Treat a conversion that strips "noreturn" as an identity conversion.
683 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000684 } else {
685 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000686 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000687 }
688
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000689 QualType CanonFrom;
690 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000691 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000692 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000693 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000694 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000695 CanonFrom = Context.getCanonicalType(FromType);
696 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000697 } else {
698 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000699 SCS.Third = ICK_Identity;
700
Mike Stump1eb44332009-09-09 15:08:12 +0000701 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +0000702 // [...] Any difference in top-level cv-qualification is
703 // subsumed by the initialization itself and does not constitute
704 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000705 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000706 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregora4923eb2009-11-16 21:35:15 +0000707 if (CanonFrom.getLocalUnqualifiedType()
708 == CanonTo.getLocalUnqualifiedType() &&
709 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000710 FromType = ToType;
711 CanonFrom = CanonTo;
712 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000713 }
714
715 // If we have not converted the argument type to the parameter type,
716 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000717 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000718 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000719
Douglas Gregor60d62c22008-10-31 16:23:19 +0000720 SCS.ToTypePtr = FromType.getAsOpaquePtr();
721 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000722}
723
724/// IsIntegralPromotion - Determines whether the conversion from the
725/// expression From (whose potentially-adjusted type is FromType) to
726/// ToType is an integral promotion (C++ 4.5). If so, returns true and
727/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000728bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +0000729 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000730 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000731 if (!To) {
732 return false;
733 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000734
735 // An rvalue of type char, signed char, unsigned char, short int, or
736 // unsigned short int can be converted to an rvalue of type int if
737 // int can represent all the values of the source type; otherwise,
738 // the source rvalue can be converted to an rvalue of type unsigned
739 // int (C++ 4.5p1).
Sebastian Redl07779722008-10-31 14:43:28 +0000740 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000741 if (// We can promote any signed, promotable integer type to an int
742 (FromType->isSignedIntegerType() ||
743 // We can promote any unsigned integer type whose size is
744 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +0000745 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000746 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000747 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000748 }
749
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000750 return To->getKind() == BuiltinType::UInt;
751 }
752
753 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
754 // can be converted to an rvalue of the first of the following types
755 // that can represent all the values of its underlying type: int,
756 // unsigned int, long, or unsigned long (C++ 4.5p2).
757 if ((FromType->isEnumeralType() || FromType->isWideCharType())
758 && ToType->isIntegerType()) {
759 // Determine whether the type we're converting from is signed or
760 // unsigned.
761 bool FromIsSigned;
762 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall183700f2009-09-21 23:43:11 +0000763 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000764 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
765 FromIsSigned = UnderlyingType->isSignedIntegerType();
766 } else {
767 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
768 FromIsSigned = true;
769 }
770
771 // The types we'll try to promote to, in the appropriate
772 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +0000773 QualType PromoteTypes[6] = {
774 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000775 Context.LongTy, Context.UnsignedLongTy ,
776 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000777 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000778 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000779 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
780 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +0000781 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000782 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
783 // We found the type that we can promote to. If this is the
784 // type we wanted, we have a promotion. Otherwise, no
785 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000786 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000787 }
788 }
789 }
790
791 // An rvalue for an integral bit-field (9.6) can be converted to an
792 // rvalue of type int if int can represent all the values of the
793 // bit-field; otherwise, it can be converted to unsigned int if
794 // unsigned int can represent all the values of the bit-field. If
795 // the bit-field is larger yet, no integral promotion applies to
796 // it. If the bit-field has an enumerated type, it is treated as any
797 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +0000798 // FIXME: We should delay checking of bit-fields until we actually perform the
799 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000800 using llvm::APSInt;
801 if (From)
802 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +0000803 APSInt BitWidth;
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000804 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
805 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
806 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
807 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Douglas Gregor86f19402008-12-20 23:49:58 +0000809 // Are we promoting to an int from a bitfield that fits in an int?
810 if (BitWidth < ToSize ||
811 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
812 return To->getKind() == BuiltinType::Int;
813 }
Mike Stump1eb44332009-09-09 15:08:12 +0000814
Douglas Gregor86f19402008-12-20 23:49:58 +0000815 // Are we promoting to an unsigned int from an unsigned bitfield
816 // that fits into an unsigned int?
817 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
818 return To->getKind() == BuiltinType::UInt;
819 }
Mike Stump1eb44332009-09-09 15:08:12 +0000820
Douglas Gregor86f19402008-12-20 23:49:58 +0000821 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000822 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000823 }
Mike Stump1eb44332009-09-09 15:08:12 +0000824
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000825 // An rvalue of type bool can be converted to an rvalue of type int,
826 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000827 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000828 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000829 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000830
831 return false;
832}
833
834/// IsFloatingPointPromotion - Determines whether the conversion from
835/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
836/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000837bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000838 /// An rvalue of type float can be converted to an rvalue of type
839 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +0000840 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
841 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000842 if (FromBuiltin->getKind() == BuiltinType::Float &&
843 ToBuiltin->getKind() == BuiltinType::Double)
844 return true;
845
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000846 // C99 6.3.1.5p1:
847 // When a float is promoted to double or long double, or a
848 // double is promoted to long double [...].
849 if (!getLangOptions().CPlusPlus &&
850 (FromBuiltin->getKind() == BuiltinType::Float ||
851 FromBuiltin->getKind() == BuiltinType::Double) &&
852 (ToBuiltin->getKind() == BuiltinType::LongDouble))
853 return true;
854 }
855
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000856 return false;
857}
858
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000859/// \brief Determine if a conversion is a complex promotion.
860///
861/// A complex promotion is defined as a complex -> complex conversion
862/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000863/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000864bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +0000865 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000866 if (!FromComplex)
867 return false;
868
John McCall183700f2009-09-21 23:43:11 +0000869 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000870 if (!ToComplex)
871 return false;
872
873 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000874 ToComplex->getElementType()) ||
875 IsIntegralPromotion(0, FromComplex->getElementType(),
876 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000877}
878
Douglas Gregorcb7de522008-11-26 23:31:11 +0000879/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
880/// the pointer type FromPtr to a pointer to type ToPointee, with the
881/// same type qualifiers as FromPtr has on its pointee type. ToType,
882/// if non-empty, will be a pointer to ToType that may or may not have
883/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +0000884static QualType
885BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000886 QualType ToPointee, QualType ToType,
887 ASTContext &Context) {
888 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
889 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +0000890 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +0000891
892 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000893 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +0000894 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +0000895 if (!ToType.isNull())
Douglas Gregorcb7de522008-11-26 23:31:11 +0000896 return ToType;
897
898 // Build a pointer to ToPointee. It has the right qualifiers
899 // already.
900 return Context.getPointerType(ToPointee);
901 }
902
903 // Just build a canonical type that has the right qualifiers.
John McCall0953e762009-09-24 19:53:00 +0000904 return Context.getPointerType(
Douglas Gregora4923eb2009-11-16 21:35:15 +0000905 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
906 Quals));
Douglas Gregorcb7de522008-11-26 23:31:11 +0000907}
908
Mike Stump1eb44332009-09-09 15:08:12 +0000909static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000910 bool InOverloadResolution,
911 ASTContext &Context) {
912 // Handle value-dependent integral null pointer constants correctly.
913 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
914 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
915 Expr->getType()->isIntegralType())
916 return !InOverloadResolution;
917
Douglas Gregorce940492009-09-25 04:25:58 +0000918 return Expr->isNullPointerConstant(Context,
919 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
920 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000921}
Mike Stump1eb44332009-09-09 15:08:12 +0000922
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000923/// IsPointerConversion - Determines whether the conversion of the
924/// expression From, which has the (possibly adjusted) type FromType,
925/// can be converted to the type ToType via a pointer conversion (C++
926/// 4.10). If so, returns true and places the converted type (that
927/// might differ from ToType in its cv-qualifiers at some level) into
928/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000929///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000930/// This routine also supports conversions to and from block pointers
931/// and conversions with Objective-C's 'id', 'id<protocols...>', and
932/// pointers to interfaces. FIXME: Once we've determined the
933/// appropriate overloading rules for Objective-C, we may want to
934/// split the Objective-C checks into a different routine; however,
935/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000936/// conversions, so for now they live here. IncompatibleObjC will be
937/// set if the conversion is an allowed Objective-C conversion that
938/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000939bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000940 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +0000941 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +0000942 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +0000943 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +0000944 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
945 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +0000946
Mike Stump1eb44332009-09-09 15:08:12 +0000947 // Conversion from a null pointer constant to any Objective-C pointer type.
948 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000949 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +0000950 ConvertedType = ToType;
951 return true;
952 }
953
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000954 // Blocks: Block pointers can be converted to void*.
955 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000956 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000957 ConvertedType = ToType;
958 return true;
959 }
960 // Blocks: A null pointer constant can be converted to a block
961 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +0000962 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000963 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000964 ConvertedType = ToType;
965 return true;
966 }
967
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000968 // If the left-hand-side is nullptr_t, the right side can be a null
969 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +0000970 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000971 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000972 ConvertedType = ToType;
973 return true;
974 }
975
Ted Kremenek6217b802009-07-29 21:53:49 +0000976 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000977 if (!ToTypePtr)
978 return false;
979
980 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000981 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000982 ConvertedType = ToType;
983 return true;
984 }
Sebastian Redl07779722008-10-31 14:43:28 +0000985
Douglas Gregorcb7de522008-11-26 23:31:11 +0000986 // Beyond this point, both types need to be pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +0000987 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +0000988 if (!FromTypePtr)
989 return false;
990
991 QualType FromPointeeType = FromTypePtr->getPointeeType();
992 QualType ToPointeeType = ToTypePtr->getPointeeType();
993
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000994 // An rvalue of type "pointer to cv T," where T is an object type,
995 // can be converted to an rvalue of type "pointer to cv void" (C++
996 // 4.10p2).
Douglas Gregorbad0e652009-03-24 20:32:41 +0000997 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000998 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +0000999 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001000 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001001 return true;
1002 }
1003
Douglas Gregorf9201e02009-02-11 23:02:49 +00001004 // When we're overloading in C, we allow a special kind of pointer
1005 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001006 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001007 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001008 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001009 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001010 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001011 return true;
1012 }
1013
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001014 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001015 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001016 // An rvalue of type "pointer to cv D," where D is a class type,
1017 // can be converted to an rvalue of type "pointer to cv B," where
1018 // B is a base class (clause 10) of D. If B is an inaccessible
1019 // (clause 11) or ambiguous (10.2) base class of D, a program that
1020 // necessitates this conversion is ill-formed. The result of the
1021 // conversion is a pointer to the base class sub-object of the
1022 // derived class object. The null pointer value is converted to
1023 // the null pointer value of the destination type.
1024 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001025 // Note that we do not check for ambiguity or inaccessibility
1026 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001027 if (getLangOptions().CPlusPlus &&
1028 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001029 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001030 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001031 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001032 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001033 ToType, Context);
1034 return true;
1035 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001036
Douglas Gregorc7887512008-12-19 19:13:09 +00001037 return false;
1038}
1039
1040/// isObjCPointerConversion - Determines whether this is an
1041/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1042/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001043bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001044 QualType& ConvertedType,
1045 bool &IncompatibleObjC) {
1046 if (!getLangOptions().ObjC1)
1047 return false;
1048
Steve Naroff14108da2009-07-10 23:34:53 +00001049 // First, we handle all conversions on ObjC object pointer types.
John McCall183700f2009-09-21 23:43:11 +00001050 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001051 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001052 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001053
Steve Naroff14108da2009-07-10 23:34:53 +00001054 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001055 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001056 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001057 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001058 ConvertedType = ToType;
1059 return true;
1060 }
1061 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001062 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001063 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001064 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001065 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001066 ConvertedType = ToType;
1067 return true;
1068 }
1069 // Objective C++: We're able to convert from a pointer to an
1070 // interface to a pointer to a different interface.
1071 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1072 ConvertedType = ToType;
1073 return true;
1074 }
1075
1076 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1077 // Okay: this is some kind of implicit downcast of Objective-C
1078 // interfaces, which is permitted. However, we're going to
1079 // complain about it.
1080 IncompatibleObjC = true;
1081 ConvertedType = FromType;
1082 return true;
1083 }
Mike Stump1eb44332009-09-09 15:08:12 +00001084 }
Steve Naroff14108da2009-07-10 23:34:53 +00001085 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001086 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001087 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001088 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001089 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001090 ToPointeeType = ToBlockPtr->getPointeeType();
1091 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001092 return false;
1093
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001094 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001095 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001096 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001097 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001098 FromPointeeType = FromBlockPtr->getPointeeType();
1099 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001100 return false;
1101
Douglas Gregorc7887512008-12-19 19:13:09 +00001102 // If we have pointers to pointers, recursively check whether this
1103 // is an Objective-C conversion.
1104 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1105 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1106 IncompatibleObjC)) {
1107 // We always complain about this conversion.
1108 IncompatibleObjC = true;
1109 ConvertedType = ToType;
1110 return true;
1111 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001112 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001113 // differences in the argument and result types are in Objective-C
1114 // pointer conversions. If so, we permit the conversion (but
1115 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001116 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001117 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001118 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001119 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001120 if (FromFunctionType && ToFunctionType) {
1121 // If the function types are exactly the same, this isn't an
1122 // Objective-C pointer conversion.
1123 if (Context.getCanonicalType(FromPointeeType)
1124 == Context.getCanonicalType(ToPointeeType))
1125 return false;
1126
1127 // Perform the quick checks that will tell us whether these
1128 // function types are obviously different.
1129 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1130 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1131 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1132 return false;
1133
1134 bool HasObjCConversion = false;
1135 if (Context.getCanonicalType(FromFunctionType->getResultType())
1136 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1137 // Okay, the types match exactly. Nothing to do.
1138 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1139 ToFunctionType->getResultType(),
1140 ConvertedType, IncompatibleObjC)) {
1141 // Okay, we have an Objective-C pointer conversion.
1142 HasObjCConversion = true;
1143 } else {
1144 // Function types are too different. Abort.
1145 return false;
1146 }
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Douglas Gregorc7887512008-12-19 19:13:09 +00001148 // Check argument types.
1149 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1150 ArgIdx != NumArgs; ++ArgIdx) {
1151 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1152 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1153 if (Context.getCanonicalType(FromArgType)
1154 == Context.getCanonicalType(ToArgType)) {
1155 // Okay, the types match exactly. Nothing to do.
1156 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1157 ConvertedType, IncompatibleObjC)) {
1158 // Okay, we have an Objective-C pointer conversion.
1159 HasObjCConversion = true;
1160 } else {
1161 // Argument types are too different. Abort.
1162 return false;
1163 }
1164 }
1165
1166 if (HasObjCConversion) {
1167 // We had an Objective-C conversion. Allow this pointer
1168 // conversion, but complain about it.
1169 ConvertedType = ToType;
1170 IncompatibleObjC = true;
1171 return true;
1172 }
1173 }
1174
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001175 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001176}
1177
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001178/// CheckPointerConversion - Check the pointer conversion from the
1179/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001180/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001181/// conversions for which IsPointerConversion has already returned
1182/// true. It returns true and produces a diagnostic if there was an
1183/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001184bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001185 CastExpr::CastKind &Kind,
1186 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001187 QualType FromType = From->getType();
1188
Ted Kremenek6217b802009-07-29 21:53:49 +00001189 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1190 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001191 QualType FromPointeeType = FromPtrType->getPointeeType(),
1192 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001193
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001194 if (FromPointeeType->isRecordType() &&
1195 ToPointeeType->isRecordType()) {
1196 // We must have a derived-to-base conversion. Check an
1197 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001198 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1199 From->getExprLoc(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001200 From->getSourceRange(),
1201 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001202 return true;
1203
1204 // The conversion was successful.
1205 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001206 }
1207 }
Mike Stump1eb44332009-09-09 15:08:12 +00001208 if (const ObjCObjectPointerType *FromPtrType =
John McCall183700f2009-09-21 23:43:11 +00001209 FromType->getAs<ObjCObjectPointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001210 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001211 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001212 // Objective-C++ conversions are always okay.
1213 // FIXME: We should have a different class of conversions for the
1214 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001215 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001216 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001217
Steve Naroff14108da2009-07-10 23:34:53 +00001218 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001219 return false;
1220}
1221
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001222/// IsMemberPointerConversion - Determines whether the conversion of the
1223/// expression From, which has the (possibly adjusted) type FromType, can be
1224/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1225/// If so, returns true and places the converted type (that might differ from
1226/// ToType in its cv-qualifiers at some level) into ConvertedType.
1227bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001228 QualType ToType,
1229 bool InOverloadResolution,
1230 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001231 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001232 if (!ToTypePtr)
1233 return false;
1234
1235 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001236 if (From->isNullPointerConstant(Context,
1237 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1238 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001239 ConvertedType = ToType;
1240 return true;
1241 }
1242
1243 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001244 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001245 if (!FromTypePtr)
1246 return false;
1247
1248 // A pointer to member of B can be converted to a pointer to member of D,
1249 // where D is derived from B (C++ 4.11p2).
1250 QualType FromClass(FromTypePtr->getClass(), 0);
1251 QualType ToClass(ToTypePtr->getClass(), 0);
1252 // FIXME: What happens when these are dependent? Is this function even called?
1253
1254 if (IsDerivedFrom(ToClass, FromClass)) {
1255 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1256 ToClass.getTypePtr());
1257 return true;
1258 }
1259
1260 return false;
1261}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001262
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001263/// CheckMemberPointerConversion - Check the member pointer conversion from the
1264/// expression From to the type ToType. This routine checks for ambiguous or
1265/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1266/// for which IsMemberPointerConversion has already returned true. It returns
1267/// true and produces a diagnostic if there was an error, or returns false
1268/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001269bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001270 CastExpr::CastKind &Kind,
1271 bool IgnoreBaseAccess) {
1272 (void)IgnoreBaseAccess;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001273 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001274 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001275 if (!FromPtrType) {
1276 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001277 assert(From->isNullPointerConstant(Context,
1278 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001279 "Expr must be null pointer constant!");
1280 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001281 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001282 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001283
Ted Kremenek6217b802009-07-29 21:53:49 +00001284 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001285 assert(ToPtrType && "No member pointer cast has a target type "
1286 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001287
Sebastian Redl21593ac2009-01-28 18:33:18 +00001288 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1289 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001290
Sebastian Redl21593ac2009-01-28 18:33:18 +00001291 // FIXME: What about dependent types?
1292 assert(FromClass->isRecordType() && "Pointer into non-class.");
1293 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001294
Douglas Gregora8f32e02009-10-06 17:59:45 +00001295 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1296 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001297 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1298 assert(DerivationOkay &&
1299 "Should not have been called if derivation isn't OK.");
1300 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001301
Sebastian Redl21593ac2009-01-28 18:33:18 +00001302 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1303 getUnqualifiedType())) {
1304 // Derivation is ambiguous. Redo the check to find the exact paths.
1305 Paths.clear();
1306 Paths.setRecordingPaths(true);
1307 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1308 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1309 (void)StillOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001310
Sebastian Redl21593ac2009-01-28 18:33:18 +00001311 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1312 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1313 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1314 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001315 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001316
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001317 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001318 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1319 << FromClass << ToClass << QualType(VBase, 0)
1320 << From->getSourceRange();
1321 return true;
1322 }
1323
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001324 // Must be a base to derived member conversion.
1325 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001326 return false;
1327}
1328
Douglas Gregor98cd5992008-10-21 23:43:52 +00001329/// IsQualificationConversion - Determines whether the conversion from
1330/// an rvalue of type FromType to ToType is a qualification conversion
1331/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001332bool
1333Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001334 FromType = Context.getCanonicalType(FromType);
1335 ToType = Context.getCanonicalType(ToType);
1336
1337 // If FromType and ToType are the same type, this is not a
1338 // qualification conversion.
1339 if (FromType == ToType)
1340 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001341
Douglas Gregor98cd5992008-10-21 23:43:52 +00001342 // (C++ 4.4p4):
1343 // A conversion can add cv-qualifiers at levels other than the first
1344 // in multi-level pointers, subject to the following rules: [...]
1345 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001346 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001347 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001348 // Within each iteration of the loop, we check the qualifiers to
1349 // determine if this still looks like a qualification
1350 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001351 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001352 // until there are no more pointers or pointers-to-members left to
1353 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001354 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001355
1356 // -- for every j > 0, if const is in cv 1,j then const is in cv
1357 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001358 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001359 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001360
Douglas Gregor98cd5992008-10-21 23:43:52 +00001361 // -- if the cv 1,j and cv 2,j are different, then const is in
1362 // every cv for 0 < k < j.
1363 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001364 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001365 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001366
Douglas Gregor98cd5992008-10-21 23:43:52 +00001367 // Keep track of whether all prior cv-qualifiers in the "to" type
1368 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001369 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001370 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001371 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001372
1373 // We are left with FromType and ToType being the pointee types
1374 // after unwrapping the original FromType and ToType the same number
1375 // of types. If we unwrapped any pointers, and if FromType and
1376 // ToType have the same unqualified type (since we checked
1377 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001378 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00001379}
1380
Douglas Gregor734d9862009-01-30 23:27:23 +00001381/// Determines whether there is a user-defined conversion sequence
1382/// (C++ [over.ics.user]) that converts expression From to the type
1383/// ToType. If such a conversion exists, User will contain the
1384/// user-defined conversion sequence that performs such a conversion
1385/// and this routine will return true. Otherwise, this routine returns
1386/// false and User is unspecified.
1387///
1388/// \param AllowConversionFunctions true if the conversion should
1389/// consider conversion functions at all. If false, only constructors
1390/// will be considered.
1391///
1392/// \param AllowExplicit true if the conversion should consider C++0x
1393/// "explicit" conversion functions as well as non-explicit conversion
1394/// functions (C++0x [class.conv.fct]p2).
Sebastian Redle2b68332009-04-12 17:16:29 +00001395///
1396/// \param ForceRValue true if the expression should be treated as an rvalue
1397/// for overload resolution.
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001398/// \param UserCast true if looking for user defined conversion for a static
1399/// cast.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001400Sema::OverloadingResult Sema::IsUserDefinedConversion(
1401 Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001402 UserDefinedConversionSequence& User,
Fariborz Jahanian78cf9a22009-09-15 00:10:11 +00001403 OverloadCandidateSet& CandidateSet,
Douglas Gregor734d9862009-01-30 23:27:23 +00001404 bool AllowConversionFunctions,
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001405 bool AllowExplicit, bool ForceRValue,
1406 bool UserCast) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001407 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00001408 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1409 // We're not going to find any constructors.
1410 } else if (CXXRecordDecl *ToRecordDecl
1411 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001412 // C++ [over.match.ctor]p1:
1413 // When objects of class type are direct-initialized (8.5), or
1414 // copy-initialized from an expression of the same or a
1415 // derived class type (8.5), overload resolution selects the
1416 // constructor. [...] For copy-initialization, the candidate
1417 // functions are all the converting constructors (12.3.1) of
1418 // that class. The argument list is the expression-list within
1419 // the parentheses of the initializer.
Douglas Gregor79b680e2009-11-13 18:44:21 +00001420 bool SuppressUserConversions = !UserCast;
1421 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1422 IsDerivedFrom(From->getType(), ToType)) {
1423 SuppressUserConversions = false;
1424 AllowConversionFunctions = false;
1425 }
1426
Mike Stump1eb44332009-09-09 15:08:12 +00001427 DeclarationName ConstructorName
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001428 = Context.DeclarationNames.getCXXConstructorName(
1429 Context.getCanonicalType(ToType).getUnqualifiedType());
1430 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump1eb44332009-09-09 15:08:12 +00001431 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001432 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001433 Con != ConEnd; ++Con) {
Douglas Gregordec06662009-08-21 18:42:58 +00001434 // Find the constructor (which may be a template).
1435 CXXConstructorDecl *Constructor = 0;
1436 FunctionTemplateDecl *ConstructorTmpl
1437 = dyn_cast<FunctionTemplateDecl>(*Con);
1438 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001439 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00001440 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1441 else
1442 Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001443
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00001444 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00001445 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001446 if (ConstructorTmpl)
John McCalld5532b62009-11-23 01:53:49 +00001447 AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
1448 &From, 1, CandidateSet,
Douglas Gregor79b680e2009-11-13 18:44:21 +00001449 SuppressUserConversions, ForceRValue);
Douglas Gregordec06662009-08-21 18:42:58 +00001450 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001451 // Allow one user-defined conversion when user specifies a
1452 // From->ToType conversion via an static cast (c-style, etc).
Douglas Gregordec06662009-08-21 18:42:58 +00001453 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Douglas Gregor79b680e2009-11-13 18:44:21 +00001454 SuppressUserConversions, ForceRValue);
Douglas Gregordec06662009-08-21 18:42:58 +00001455 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001456 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001457 }
1458 }
1459
Douglas Gregor734d9862009-01-30 23:27:23 +00001460 if (!AllowConversionFunctions) {
1461 // Don't allow any conversion functions to enter the overload set.
Mike Stump1eb44332009-09-09 15:08:12 +00001462 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1463 PDiag(0)
Anders Carlssonb7906612009-08-26 23:45:07 +00001464 << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00001465 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00001466 } else if (const RecordType *FromRecordType
Ted Kremenek6217b802009-07-29 21:53:49 +00001467 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001468 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001469 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1470 // Add all of the conversion functions as candidates.
John McCallba135432009-11-21 08:51:07 +00001471 const UnresolvedSet *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00001472 = FromRecordDecl->getVisibleConversionFunctions();
John McCallba135432009-11-21 08:51:07 +00001473 for (UnresolvedSet::iterator I = Conversions->begin(),
1474 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00001475 NamedDecl *D = *I;
1476 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1477 if (isa<UsingShadowDecl>(D))
1478 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1479
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001480 CXXConversionDecl *Conv;
1481 FunctionTemplateDecl *ConvTemplate;
John McCallba135432009-11-21 08:51:07 +00001482 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001483 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1484 else
John McCallba135432009-11-21 08:51:07 +00001485 Conv = dyn_cast<CXXConversionDecl>(*I);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001486
1487 if (AllowExplicit || !Conv->isExplicit()) {
1488 if (ConvTemplate)
John McCall701c89e2009-12-03 04:06:58 +00001489 AddTemplateConversionCandidate(ConvTemplate, ActingContext,
1490 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001491 else
John McCall701c89e2009-12-03 04:06:58 +00001492 AddConversionCandidate(Conv, ActingContext, From, ToType,
1493 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001494 }
1495 }
1496 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001497 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001498
1499 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001500 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001501 case OR_Success:
1502 // Record the standard conversion we used and the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00001503 if (CXXConstructorDecl *Constructor
Douglas Gregor60d62c22008-10-31 16:23:19 +00001504 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1505 // C++ [over.ics.user]p1:
1506 // If the user-defined conversion is specified by a
1507 // constructor (12.3.1), the initial standard conversion
1508 // sequence converts the source type to the type required by
1509 // the argument of the constructor.
1510 //
Douglas Gregor60d62c22008-10-31 16:23:19 +00001511 QualType ThisType = Constructor->getThisType(Context);
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001512 if (Best->Conversions[0].ConversionKind ==
1513 ImplicitConversionSequence::EllipsisConversion)
1514 User.EllipsisConversion = true;
1515 else {
1516 User.Before = Best->Conversions[0].Standard;
1517 User.EllipsisConversion = false;
1518 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001519 User.ConversionFunction = Constructor;
1520 User.After.setAsIdentityConversion();
Mike Stump1eb44332009-09-09 15:08:12 +00001521 User.After.FromTypePtr
Ted Kremenek6217b802009-07-29 21:53:49 +00001522 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor60d62c22008-10-31 16:23:19 +00001523 User.After.ToTypePtr = ToType.getAsOpaquePtr();
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001524 return OR_Success;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001525 } else if (CXXConversionDecl *Conversion
1526 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1527 // C++ [over.ics.user]p1:
1528 //
1529 // [...] If the user-defined conversion is specified by a
1530 // conversion function (12.3.2), the initial standard
1531 // conversion sequence converts the source type to the
1532 // implicit object parameter of the conversion function.
1533 User.Before = Best->Conversions[0].Standard;
1534 User.ConversionFunction = Conversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001535 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001536
1537 // C++ [over.ics.user]p2:
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001538 // The second standard conversion sequence converts the
1539 // result of the user-defined conversion to the target type
1540 // for the sequence. Since an implicit conversion sequence
1541 // is an initialization, the special rules for
1542 // initialization by user-defined conversion apply when
1543 // selecting the best user-defined conversion for a
1544 // user-defined conversion sequence (see 13.3.3 and
1545 // 13.3.3.1).
1546 User.After = Best->FinalConversion;
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001547 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001548 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001549 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001550 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001551 }
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Douglas Gregor60d62c22008-10-31 16:23:19 +00001553 case OR_No_Viable_Function:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001554 return OR_No_Viable_Function;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001555 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001556 // No conversion here! We're done.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001557 return OR_Deleted;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001558
1559 case OR_Ambiguous:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001560 return OR_Ambiguous;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001561 }
1562
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001563 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001564}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001565
1566bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001567Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001568 ImplicitConversionSequence ICS;
1569 OverloadCandidateSet CandidateSet;
1570 OverloadingResult OvResult =
1571 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1572 CandidateSet, true, false, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001573 if (OvResult == OR_Ambiguous)
1574 Diag(From->getSourceRange().getBegin(),
1575 diag::err_typecheck_ambiguous_condition)
1576 << From->getType() << ToType << From->getSourceRange();
1577 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1578 Diag(From->getSourceRange().getBegin(),
1579 diag::err_typecheck_nonviable_condition)
1580 << From->getType() << ToType << From->getSourceRange();
1581 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001582 return false;
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001583 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001584 return true;
1585}
Douglas Gregor60d62c22008-10-31 16:23:19 +00001586
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001587/// CompareImplicitConversionSequences - Compare two implicit
1588/// conversion sequences to determine whether one is better than the
1589/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump1eb44332009-09-09 15:08:12 +00001590ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001591Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1592 const ImplicitConversionSequence& ICS2)
1593{
1594 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1595 // conversion sequences (as defined in 13.3.3.1)
1596 // -- a standard conversion sequence (13.3.3.1.1) is a better
1597 // conversion sequence than a user-defined conversion sequence or
1598 // an ellipsis conversion sequence, and
1599 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1600 // conversion sequence than an ellipsis conversion sequence
1601 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00001602 //
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001603 if (ICS1.ConversionKind < ICS2.ConversionKind)
1604 return ImplicitConversionSequence::Better;
1605 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1606 return ImplicitConversionSequence::Worse;
1607
1608 // Two implicit conversion sequences of the same form are
1609 // indistinguishable conversion sequences unless one of the
1610 // following rules apply: (C++ 13.3.3.2p3):
1611 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1612 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump1eb44332009-09-09 15:08:12 +00001613 else if (ICS1.ConversionKind ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001614 ImplicitConversionSequence::UserDefinedConversion) {
1615 // User-defined conversion sequence U1 is a better conversion
1616 // sequence than another user-defined conversion sequence U2 if
1617 // they contain the same user-defined conversion function or
1618 // constructor and if the second standard conversion sequence of
1619 // U1 is better than the second standard conversion sequence of
1620 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001621 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001622 ICS2.UserDefined.ConversionFunction)
1623 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1624 ICS2.UserDefined.After);
1625 }
1626
1627 return ImplicitConversionSequence::Indistinguishable;
1628}
1629
1630/// CompareStandardConversionSequences - Compare two standard
1631/// conversion sequences to determine whether one is better than the
1632/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001633ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001634Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1635 const StandardConversionSequence& SCS2)
1636{
1637 // Standard conversion sequence S1 is a better conversion sequence
1638 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1639
1640 // -- S1 is a proper subsequence of S2 (comparing the conversion
1641 // sequences in the canonical form defined by 13.3.3.1.1,
1642 // excluding any Lvalue Transformation; the identity conversion
1643 // sequence is considered to be a subsequence of any
1644 // non-identity conversion sequence) or, if not that,
1645 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1646 // Neither is a proper subsequence of the other. Do nothing.
1647 ;
1648 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1649 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001650 (SCS1.Second == ICK_Identity &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001651 SCS1.Third == ICK_Identity))
1652 // SCS1 is a proper subsequence of SCS2.
1653 return ImplicitConversionSequence::Better;
1654 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1655 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001656 (SCS2.Second == ICK_Identity &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001657 SCS2.Third == ICK_Identity))
1658 // SCS2 is a proper subsequence of SCS1.
1659 return ImplicitConversionSequence::Worse;
1660
1661 // -- the rank of S1 is better than the rank of S2 (by the rules
1662 // defined below), or, if not that,
1663 ImplicitConversionRank Rank1 = SCS1.getRank();
1664 ImplicitConversionRank Rank2 = SCS2.getRank();
1665 if (Rank1 < Rank2)
1666 return ImplicitConversionSequence::Better;
1667 else if (Rank2 < Rank1)
1668 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001669
Douglas Gregor57373262008-10-22 14:17:15 +00001670 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1671 // are indistinguishable unless one of the following rules
1672 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00001673
Douglas Gregor57373262008-10-22 14:17:15 +00001674 // A conversion that is not a conversion of a pointer, or
1675 // pointer to member, to bool is better than another conversion
1676 // that is such a conversion.
1677 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1678 return SCS2.isPointerConversionToBool()
1679 ? ImplicitConversionSequence::Better
1680 : ImplicitConversionSequence::Worse;
1681
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001682 // C++ [over.ics.rank]p4b2:
1683 //
1684 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001685 // conversion of B* to A* is better than conversion of B* to
1686 // void*, and conversion of A* to void* is better than conversion
1687 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00001688 bool SCS1ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001689 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001690 bool SCS2ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001691 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001692 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1693 // Exactly one of the conversion sequences is a conversion to
1694 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001695 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1696 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001697 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1698 // Neither conversion sequence converts to a void pointer; compare
1699 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001700 if (ImplicitConversionSequence::CompareKind DerivedCK
1701 = CompareDerivedToBaseConversions(SCS1, SCS2))
1702 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001703 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1704 // Both conversion sequences are conversions to void
1705 // pointers. Compare the source types to determine if there's an
1706 // inheritance relationship in their sources.
1707 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1708 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1709
1710 // Adjust the types we're converting from via the array-to-pointer
1711 // conversion, if we need to.
1712 if (SCS1.First == ICK_Array_To_Pointer)
1713 FromType1 = Context.getArrayDecayedType(FromType1);
1714 if (SCS2.First == ICK_Array_To_Pointer)
1715 FromType2 = Context.getArrayDecayedType(FromType2);
1716
Mike Stump1eb44332009-09-09 15:08:12 +00001717 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00001718 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001719 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00001720 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001721
1722 if (IsDerivedFrom(FromPointee2, FromPointee1))
1723 return ImplicitConversionSequence::Better;
1724 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1725 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001726
1727 // Objective-C++: If one interface is more specific than the
1728 // other, it is the better one.
John McCall183700f2009-09-21 23:43:11 +00001729 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1730 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001731 if (FromIface1 && FromIface1) {
1732 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1733 return ImplicitConversionSequence::Better;
1734 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1735 return ImplicitConversionSequence::Worse;
1736 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001737 }
Douglas Gregor57373262008-10-22 14:17:15 +00001738
1739 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1740 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00001741 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001742 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001743 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001744
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001745 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001746 // C++0x [over.ics.rank]p3b4:
1747 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1748 // implicit object parameter of a non-static member function declared
1749 // without a ref-qualifier, and S1 binds an rvalue reference to an
1750 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00001751 // FIXME: We don't know if we're dealing with the implicit object parameter,
1752 // or if the member function in this case has a ref qualifier.
1753 // (Of course, we don't have ref qualifiers yet.)
1754 if (SCS1.RRefBinding != SCS2.RRefBinding)
1755 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1756 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001757
1758 // C++ [over.ics.rank]p3b4:
1759 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1760 // which the references refer are the same type except for
1761 // top-level cv-qualifiers, and the type to which the reference
1762 // initialized by S2 refers is more cv-qualified than the type
1763 // to which the reference initialized by S1 refers.
Sebastian Redla9845802009-03-29 15:27:50 +00001764 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1765 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001766 T1 = Context.getCanonicalType(T1);
1767 T2 = Context.getCanonicalType(T2);
Douglas Gregora4923eb2009-11-16 21:35:15 +00001768 if (Context.hasSameUnqualifiedType(T1, T2)) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001769 if (T2.isMoreQualifiedThan(T1))
1770 return ImplicitConversionSequence::Better;
1771 else if (T1.isMoreQualifiedThan(T2))
1772 return ImplicitConversionSequence::Worse;
1773 }
1774 }
Douglas Gregor57373262008-10-22 14:17:15 +00001775
1776 return ImplicitConversionSequence::Indistinguishable;
1777}
1778
1779/// CompareQualificationConversions - Compares two standard conversion
1780/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00001781/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1782ImplicitConversionSequence::CompareKind
Douglas Gregor57373262008-10-22 14:17:15 +00001783Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump1eb44332009-09-09 15:08:12 +00001784 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00001785 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001786 // -- S1 and S2 differ only in their qualification conversion and
1787 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1788 // cv-qualification signature of type T1 is a proper subset of
1789 // the cv-qualification signature of type T2, and S1 is not the
1790 // deprecated string literal array-to-pointer conversion (4.2).
1791 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1792 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1793 return ImplicitConversionSequence::Indistinguishable;
1794
1795 // FIXME: the example in the standard doesn't use a qualification
1796 // conversion (!)
1797 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1798 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1799 T1 = Context.getCanonicalType(T1);
1800 T2 = Context.getCanonicalType(T2);
1801
1802 // If the types are the same, we won't learn anything by unwrapped
1803 // them.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001804 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00001805 return ImplicitConversionSequence::Indistinguishable;
1806
Mike Stump1eb44332009-09-09 15:08:12 +00001807 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00001808 = ImplicitConversionSequence::Indistinguishable;
1809 while (UnwrapSimilarPointerTypes(T1, T2)) {
1810 // Within each iteration of the loop, we check the qualifiers to
1811 // determine if this still looks like a qualification
1812 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001813 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001814 // until there are no more pointers or pointers-to-members left
1815 // to unwrap. This essentially mimics what
1816 // IsQualificationConversion does, but here we're checking for a
1817 // strict subset of qualifiers.
1818 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1819 // The qualifiers are the same, so this doesn't tell us anything
1820 // about how the sequences rank.
1821 ;
1822 else if (T2.isMoreQualifiedThan(T1)) {
1823 // T1 has fewer qualifiers, so it could be the better sequence.
1824 if (Result == ImplicitConversionSequence::Worse)
1825 // Neither has qualifiers that are a subset of the other's
1826 // qualifiers.
1827 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001828
Douglas Gregor57373262008-10-22 14:17:15 +00001829 Result = ImplicitConversionSequence::Better;
1830 } else if (T1.isMoreQualifiedThan(T2)) {
1831 // T2 has fewer qualifiers, so it could be the better sequence.
1832 if (Result == ImplicitConversionSequence::Better)
1833 // Neither has qualifiers that are a subset of the other's
1834 // qualifiers.
1835 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001836
Douglas Gregor57373262008-10-22 14:17:15 +00001837 Result = ImplicitConversionSequence::Worse;
1838 } else {
1839 // Qualifiers are disjoint.
1840 return ImplicitConversionSequence::Indistinguishable;
1841 }
1842
1843 // If the types after this point are equivalent, we're done.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001844 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00001845 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001846 }
1847
Douglas Gregor57373262008-10-22 14:17:15 +00001848 // Check that the winning standard conversion sequence isn't using
1849 // the deprecated string literal array to pointer conversion.
1850 switch (Result) {
1851 case ImplicitConversionSequence::Better:
1852 if (SCS1.Deprecated)
1853 Result = ImplicitConversionSequence::Indistinguishable;
1854 break;
1855
1856 case ImplicitConversionSequence::Indistinguishable:
1857 break;
1858
1859 case ImplicitConversionSequence::Worse:
1860 if (SCS2.Deprecated)
1861 Result = ImplicitConversionSequence::Indistinguishable;
1862 break;
1863 }
1864
1865 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001866}
1867
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001868/// CompareDerivedToBaseConversions - Compares two standard conversion
1869/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00001870/// various kinds of derived-to-base conversions (C++
1871/// [over.ics.rank]p4b3). As part of these checks, we also look at
1872/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001873ImplicitConversionSequence::CompareKind
1874Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1875 const StandardConversionSequence& SCS2) {
1876 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1877 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1878 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1879 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1880
1881 // Adjust the types we're converting from via the array-to-pointer
1882 // conversion, if we need to.
1883 if (SCS1.First == ICK_Array_To_Pointer)
1884 FromType1 = Context.getArrayDecayedType(FromType1);
1885 if (SCS2.First == ICK_Array_To_Pointer)
1886 FromType2 = Context.getArrayDecayedType(FromType2);
1887
1888 // Canonicalize all of the types.
1889 FromType1 = Context.getCanonicalType(FromType1);
1890 ToType1 = Context.getCanonicalType(ToType1);
1891 FromType2 = Context.getCanonicalType(FromType2);
1892 ToType2 = Context.getCanonicalType(ToType2);
1893
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001894 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001895 //
1896 // If class B is derived directly or indirectly from class A and
1897 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001898 //
1899 // For Objective-C, we let A, B, and C also be Objective-C
1900 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001901
1902 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00001903 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00001904 SCS2.Second == ICK_Pointer_Conversion &&
1905 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1906 FromType1->isPointerType() && FromType2->isPointerType() &&
1907 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001908 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00001909 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00001910 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00001911 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001912 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00001913 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001914 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00001915 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001916
John McCall183700f2009-09-21 23:43:11 +00001917 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1918 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1919 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1920 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001921
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001922 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001923 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1924 if (IsDerivedFrom(ToPointee1, ToPointee2))
1925 return ImplicitConversionSequence::Better;
1926 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1927 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001928
1929 if (ToIface1 && ToIface2) {
1930 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1931 return ImplicitConversionSequence::Better;
1932 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1933 return ImplicitConversionSequence::Worse;
1934 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001935 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001936
1937 // -- conversion of B* to A* is better than conversion of C* to A*,
1938 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1939 if (IsDerivedFrom(FromPointee2, FromPointee1))
1940 return ImplicitConversionSequence::Better;
1941 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1942 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00001943
Douglas Gregorcb7de522008-11-26 23:31:11 +00001944 if (FromIface1 && FromIface2) {
1945 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1946 return ImplicitConversionSequence::Better;
1947 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1948 return ImplicitConversionSequence::Worse;
1949 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001950 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001951 }
1952
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001953 // Compare based on reference bindings.
1954 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1955 SCS1.Second == ICK_Derived_To_Base) {
1956 // -- binding of an expression of type C to a reference of type
1957 // B& is better than binding an expression of type C to a
1958 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00001959 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1960 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001961 if (IsDerivedFrom(ToType1, ToType2))
1962 return ImplicitConversionSequence::Better;
1963 else if (IsDerivedFrom(ToType2, ToType1))
1964 return ImplicitConversionSequence::Worse;
1965 }
1966
Douglas Gregor225c41e2008-11-03 19:09:14 +00001967 // -- binding of an expression of type B to a reference of type
1968 // A& is better than binding an expression of type C to a
1969 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00001970 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1971 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001972 if (IsDerivedFrom(FromType2, FromType1))
1973 return ImplicitConversionSequence::Better;
1974 else if (IsDerivedFrom(FromType1, FromType2))
1975 return ImplicitConversionSequence::Worse;
1976 }
1977 }
Fariborz Jahanian2357da02009-10-20 20:07:35 +00001978
1979 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00001980 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
1981 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
1982 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
1983 const MemberPointerType * FromMemPointer1 =
1984 FromType1->getAs<MemberPointerType>();
1985 const MemberPointerType * ToMemPointer1 =
1986 ToType1->getAs<MemberPointerType>();
1987 const MemberPointerType * FromMemPointer2 =
1988 FromType2->getAs<MemberPointerType>();
1989 const MemberPointerType * ToMemPointer2 =
1990 ToType2->getAs<MemberPointerType>();
1991 const Type *FromPointeeType1 = FromMemPointer1->getClass();
1992 const Type *ToPointeeType1 = ToMemPointer1->getClass();
1993 const Type *FromPointeeType2 = FromMemPointer2->getClass();
1994 const Type *ToPointeeType2 = ToMemPointer2->getClass();
1995 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
1996 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
1997 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
1998 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00001999 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002000 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2001 if (IsDerivedFrom(ToPointee1, ToPointee2))
2002 return ImplicitConversionSequence::Worse;
2003 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2004 return ImplicitConversionSequence::Better;
2005 }
2006 // conversion of B::* to C::* is better than conversion of A::* to C::*
2007 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2008 if (IsDerivedFrom(FromPointee1, FromPointee2))
2009 return ImplicitConversionSequence::Better;
2010 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2011 return ImplicitConversionSequence::Worse;
2012 }
2013 }
2014
Douglas Gregor225c41e2008-11-03 19:09:14 +00002015 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
2016 SCS1.Second == ICK_Derived_To_Base) {
2017 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002018 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2019 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002020 if (IsDerivedFrom(ToType1, ToType2))
2021 return ImplicitConversionSequence::Better;
2022 else if (IsDerivedFrom(ToType2, ToType1))
2023 return ImplicitConversionSequence::Worse;
2024 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002025
Douglas Gregor225c41e2008-11-03 19:09:14 +00002026 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002027 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2028 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002029 if (IsDerivedFrom(FromType2, FromType1))
2030 return ImplicitConversionSequence::Better;
2031 else if (IsDerivedFrom(FromType1, FromType2))
2032 return ImplicitConversionSequence::Worse;
2033 }
2034 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002035
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002036 return ImplicitConversionSequence::Indistinguishable;
2037}
2038
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002039/// TryCopyInitialization - Try to copy-initialize a value of type
2040/// ToType from the expression From. Return the implicit conversion
2041/// sequence required to pass this argument, which may be a bad
2042/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00002043/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redle2b68332009-04-12 17:16:29 +00002044/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2045/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump1eb44332009-09-09 15:08:12 +00002046ImplicitConversionSequence
2047Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002048 bool SuppressUserConversions, bool ForceRValue,
2049 bool InOverloadResolution) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00002050 if (ToType->isReferenceType()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002051 ImplicitConversionSequence ICS;
Mike Stump1eb44332009-09-09 15:08:12 +00002052 CheckReferenceInit(From, ToType,
Douglas Gregor739d8282009-09-23 23:04:10 +00002053 /*FIXME:*/From->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002054 SuppressUserConversions,
2055 /*AllowExplicit=*/false,
2056 ForceRValue,
2057 &ICS);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002058 return ICS;
2059 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002060 return TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002061 SuppressUserConversions,
2062 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002063 ForceRValue,
2064 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002065 }
2066}
2067
Sebastian Redle2b68332009-04-12 17:16:29 +00002068/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2069/// the expression @p From. Returns true (and emits a diagnostic) if there was
2070/// an error, returns false if the initialization succeeded. Elidable should
2071/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2072/// differently in C++0x for this case.
Mike Stump1eb44332009-09-09 15:08:12 +00002073bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +00002074 const char* Flavor, bool Elidable) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002075 if (!getLangOptions().CPlusPlus) {
2076 // In C, argument passing is the same as performing an assignment.
2077 QualType FromType = From->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002078
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002079 AssignConvertType ConvTy =
2080 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00002081 if (ConvTy != Compatible &&
2082 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2083 ConvTy = Compatible;
Mike Stump1eb44332009-09-09 15:08:12 +00002084
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002085 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
2086 FromType, From, Flavor);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002087 }
Sebastian Redle2b68332009-04-12 17:16:29 +00002088
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002089 if (ToType->isReferenceType())
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002090 return CheckReferenceInit(From, ToType,
Douglas Gregor739d8282009-09-23 23:04:10 +00002091 /*FIXME:*/From->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002092 /*SuppressUserConversions=*/false,
2093 /*AllowExplicit=*/false,
2094 /*ForceRValue=*/false);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002095
Sebastian Redle2b68332009-04-12 17:16:29 +00002096 if (!PerformImplicitConversion(From, ToType, Flavor,
2097 /*AllowExplicit=*/false, Elidable))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002098 return false;
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002099 if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
Fariborz Jahanian455acd92009-09-22 19:53:15 +00002100 return Diag(From->getSourceRange().getBegin(),
2101 diag::err_typecheck_convert_incompatible)
2102 << ToType << From->getType() << Flavor << From->getSourceRange();
Fariborz Jahanian455acd92009-09-22 19:53:15 +00002103 return true;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002104}
2105
Douglas Gregor96176b32008-11-18 23:14:02 +00002106/// TryObjectArgumentInitialization - Try to initialize the object
2107/// parameter of the given member function (@c Method) from the
2108/// expression @p From.
2109ImplicitConversionSequence
John McCall701c89e2009-12-03 04:06:58 +00002110Sema::TryObjectArgumentInitialization(QualType FromType,
2111 CXXMethodDecl *Method,
2112 CXXRecordDecl *ActingContext) {
2113 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002114 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2115 // const volatile object.
2116 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2117 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2118 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00002119
2120 // Set up the conversion sequence as a "bad" conversion, to allow us
2121 // to exit early.
2122 ImplicitConversionSequence ICS;
2123 ICS.Standard.setAsIdentityConversion();
2124 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2125
2126 // We need to have an object of class type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002127 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00002128 FromType = PT->getPointeeType();
2129
2130 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002131
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002132 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00002133 // where X is the class of which the function is a member
2134 // (C++ [over.match.funcs]p4). However, when finding an implicit
2135 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00002136 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00002137 // (C++ [over.match.funcs]p5). We perform a simplified version of
2138 // reference binding here, that allows class rvalues to bind to
2139 // non-constant references.
2140
2141 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2142 // with the implicit object parameter (C++ [over.match.funcs]p5).
2143 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00002144 if (ImplicitParamType.getCVRQualifiers()
2145 != FromTypeCanon.getLocalCVRQualifiers() &&
Douglas Gregorb1c2ea52009-11-05 00:07:36 +00002146 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon))
Douglas Gregor96176b32008-11-18 23:14:02 +00002147 return ICS;
2148
2149 // Check that we have either the same type or a derived type. It
2150 // affects the conversion rank.
2151 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00002152 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType())
Douglas Gregor96176b32008-11-18 23:14:02 +00002153 ICS.Standard.Second = ICK_Identity;
2154 else if (IsDerivedFrom(FromType, ClassType))
2155 ICS.Standard.Second = ICK_Derived_To_Base;
2156 else
2157 return ICS;
2158
2159 // Success. Mark this as a reference binding.
2160 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2161 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2162 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2163 ICS.Standard.ReferenceBinding = true;
2164 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00002165 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002166 return ICS;
2167}
2168
2169/// PerformObjectArgumentInitialization - Perform initialization of
2170/// the implicit object parameter for the given Method with the given
2171/// expression.
2172bool
2173Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002174 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00002175 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00002176 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002177
Ted Kremenek6217b802009-07-29 21:53:49 +00002178 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002179 FromRecordType = PT->getPointeeType();
2180 DestType = Method->getThisType(Context);
2181 } else {
2182 FromRecordType = From->getType();
2183 DestType = ImplicitParamRecordType;
2184 }
2185
John McCall701c89e2009-12-03 04:06:58 +00002186 // Note that we always use the true parent context when performing
2187 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002188 ImplicitConversionSequence ICS
John McCall701c89e2009-12-03 04:06:58 +00002189 = TryObjectArgumentInitialization(From->getType(), Method,
2190 Method->getParent());
Douglas Gregor96176b32008-11-18 23:14:02 +00002191 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2192 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002193 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00002194 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002195
Douglas Gregor96176b32008-11-18 23:14:02 +00002196 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssona552f7c2009-05-01 18:34:30 +00002197 CheckDerivedToBaseConversion(FromRecordType,
2198 ImplicitParamRecordType,
Douglas Gregor96176b32008-11-18 23:14:02 +00002199 From->getSourceRange().getBegin(),
2200 From->getSourceRange()))
2201 return true;
2202
Mike Stump1eb44332009-09-09 15:08:12 +00002203 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson116b7d92009-08-07 18:45:49 +00002204 /*isLvalue=*/true);
Douglas Gregor96176b32008-11-18 23:14:02 +00002205 return false;
2206}
2207
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002208/// TryContextuallyConvertToBool - Attempt to contextually convert the
2209/// expression From to bool (C++0x [conv]p3).
2210ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump1eb44332009-09-09 15:08:12 +00002211 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002212 // FIXME: Are these flags correct?
2213 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00002214 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00002215 /*ForceRValue=*/false,
2216 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002217}
2218
2219/// PerformContextuallyConvertToBool - Perform a contextual conversion
2220/// of the expression From to bool (C++0x [conv]p3).
2221bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2222 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2223 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2224 return false;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002225
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002226 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002227 return Diag(From->getSourceRange().getBegin(),
2228 diag::err_typecheck_bool_condition)
2229 << From->getType() << From->getSourceRange();
2230 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002231}
2232
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002233/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00002234/// candidate functions, using the given function call arguments. If
2235/// @p SuppressUserConversions, then don't allow user-defined
2236/// conversions via constructors or conversion operators.
Sebastian Redle2b68332009-04-12 17:16:29 +00002237/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2238/// hacky way to implement the overloading rules for elidable copy
2239/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002240///
2241/// \para PartialOverloading true if we are performing "partial" overloading
2242/// based on an incomplete set of function arguments. This feature is used by
2243/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00002244void
2245Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002246 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002247 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00002248 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002249 bool ForceRValue,
2250 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00002251 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002252 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002253 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00002254 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002255 "Use AddConversionCandidate for conversion functions");
Mike Stump1eb44332009-09-09 15:08:12 +00002256 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00002257 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00002258
Douglas Gregor88a35142008-12-22 05:46:06 +00002259 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002260 if (!isa<CXXConstructorDecl>(Method)) {
2261 // If we get here, it's because we're calling a member function
2262 // that is named without a member access expression (e.g.,
2263 // "this->f") that was either written explicitly or created
2264 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00002265 // function, e.g., X::f(). We use an empty type for the implied
2266 // object argument (C++ [over.call.func]p3), and the acting context
2267 // is irrelevant.
2268 AddMethodCandidate(Method, Method->getParent(),
2269 QualType(), Args, NumArgs, CandidateSet,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002270 SuppressUserConversions, ForceRValue);
2271 return;
2272 }
2273 // We treat a constructor like a non-member function, since its object
2274 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00002275 }
2276
Douglas Gregorfd476482009-11-13 23:59:09 +00002277 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00002278 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00002279
Douglas Gregor7edfb692009-11-23 12:27:39 +00002280 // Overload resolution is always an unevaluated context.
2281 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2282
Douglas Gregor66724ea2009-11-14 01:20:54 +00002283 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2284 // C++ [class.copy]p3:
2285 // A member function template is never instantiated to perform the copy
2286 // of a class object to an object of its class type.
2287 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2288 if (NumArgs == 1 &&
2289 Constructor->isCopyConstructorLikeSpecialization() &&
2290 Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2291 return;
2292 }
2293
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002294 // Add this candidate
2295 CandidateSet.push_back(OverloadCandidate());
2296 OverloadCandidate& Candidate = CandidateSet.back();
2297 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00002298 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002299 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002300 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002301
2302 unsigned NumArgsInProto = Proto->getNumArgs();
2303
2304 // (C++ 13.3.2p2): A candidate function having fewer than m
2305 // parameters is viable only if it has an ellipsis in its parameter
2306 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00002307 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2308 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002309 Candidate.Viable = false;
2310 return;
2311 }
2312
2313 // (C++ 13.3.2p2): A candidate function having more than m parameters
2314 // is viable only if the (m+1)st parameter has a default argument
2315 // (8.3.6). For the purposes of overload resolution, the
2316 // parameter list is truncated on the right, so that there are
2317 // exactly m parameters.
2318 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002319 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002320 // Not enough arguments.
2321 Candidate.Viable = false;
2322 return;
2323 }
2324
2325 // Determine the implicit conversion sequences for each of the
2326 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002327 Candidate.Conversions.resize(NumArgs);
2328 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2329 if (ArgIdx < NumArgsInProto) {
2330 // (C++ 13.3.2p3): for F to be a viable function, there shall
2331 // exist for each argument an implicit conversion sequence
2332 // (13.3.3.1) that converts that argument to the corresponding
2333 // parameter of F.
2334 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002335 Candidate.Conversions[ArgIdx]
2336 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002337 SuppressUserConversions, ForceRValue,
2338 /*InOverloadResolution=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00002339 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002340 == ImplicitConversionSequence::BadConversion) {
Fariborz Jahanian99d6c442009-09-28 19:06:58 +00002341 // 13.3.3.1-p10 If several different sequences of conversions exist that
2342 // each convert the argument to the parameter type, the implicit conversion
2343 // sequence associated with the parameter is defined to be the unique conversion
2344 // sequence designated the ambiguous conversion sequence. For the purpose of
2345 // ranking implicit conversion sequences as described in 13.3.3.2, the ambiguous
2346 // conversion sequence is treated as a user-defined sequence that is
2347 // indistinguishable from any other user-defined conversion sequence
Fariborz Jahanian4a6a2b82009-09-29 17:31:54 +00002348 if (!Candidate.Conversions[ArgIdx].ConversionFunctionSet.empty()) {
Fariborz Jahanian99d6c442009-09-28 19:06:58 +00002349 Candidate.Conversions[ArgIdx].ConversionKind =
2350 ImplicitConversionSequence::UserDefinedConversion;
Fariborz Jahanian4a6a2b82009-09-29 17:31:54 +00002351 // Set the conversion function to one of them. As due to ambiguity,
2352 // they carry the same weight and is needed for overload resolution
2353 // later.
2354 Candidate.Conversions[ArgIdx].UserDefined.ConversionFunction =
2355 Candidate.Conversions[ArgIdx].ConversionFunctionSet[0];
2356 }
Fariborz Jahanian99d6c442009-09-28 19:06:58 +00002357 else {
2358 Candidate.Viable = false;
2359 break;
2360 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002361 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002362 } else {
2363 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2364 // argument for which there is no corresponding parameter is
2365 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002366 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002367 = ImplicitConversionSequence::EllipsisConversion;
2368 }
2369 }
2370}
2371
Douglas Gregor063daf62009-03-13 18:40:31 +00002372/// \brief Add all of the function declarations in the given function set to
2373/// the overload canddiate set.
2374void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2375 Expr **Args, unsigned NumArgs,
2376 OverloadCandidateSet& CandidateSet,
2377 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00002378 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor063daf62009-03-13 18:40:31 +00002379 FEnd = Functions.end();
Douglas Gregor364e0212009-06-27 21:05:07 +00002380 F != FEnd; ++F) {
John McCall701c89e2009-12-03 04:06:58 +00002381 // FIXME: using declarations
Douglas Gregor3f396022009-09-28 04:47:19 +00002382 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2383 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2384 AddMethodCandidate(cast<CXXMethodDecl>(FD),
John McCall701c89e2009-12-03 04:06:58 +00002385 cast<CXXMethodDecl>(FD)->getParent(),
2386 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00002387 CandidateSet, SuppressUserConversions);
2388 else
2389 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2390 SuppressUserConversions);
2391 } else {
2392 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2393 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2394 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2395 AddMethodTemplateCandidate(FunTmpl,
John McCall701c89e2009-12-03 04:06:58 +00002396 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00002397 /*FIXME: explicit args */ 0,
John McCall701c89e2009-12-03 04:06:58 +00002398 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00002399 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00002400 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00002401 else
2402 AddTemplateOverloadCandidate(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00002403 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00002404 Args, NumArgs, CandidateSet,
2405 SuppressUserConversions);
2406 }
Douglas Gregor364e0212009-06-27 21:05:07 +00002407 }
Douglas Gregor063daf62009-03-13 18:40:31 +00002408}
2409
John McCall314be4e2009-11-17 07:50:12 +00002410/// AddMethodCandidate - Adds a named decl (which is some kind of
2411/// method) as a method candidate to the given overload set.
John McCall701c89e2009-12-03 04:06:58 +00002412void Sema::AddMethodCandidate(NamedDecl *Decl,
2413 QualType ObjectType,
John McCall314be4e2009-11-17 07:50:12 +00002414 Expr **Args, unsigned NumArgs,
2415 OverloadCandidateSet& CandidateSet,
2416 bool SuppressUserConversions, bool ForceRValue) {
2417
2418 // FIXME: use this
John McCall701c89e2009-12-03 04:06:58 +00002419 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00002420
2421 if (isa<UsingShadowDecl>(Decl))
2422 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2423
2424 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2425 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2426 "Expected a member function template");
John McCall701c89e2009-12-03 04:06:58 +00002427 AddMethodTemplateCandidate(TD, ActingContext, /*ExplicitArgs*/ 0,
2428 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00002429 CandidateSet,
2430 SuppressUserConversions,
2431 ForceRValue);
2432 } else {
John McCall701c89e2009-12-03 04:06:58 +00002433 AddMethodCandidate(cast<CXXMethodDecl>(Decl), ActingContext,
2434 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00002435 CandidateSet, SuppressUserConversions, ForceRValue);
2436 }
2437}
2438
Douglas Gregor96176b32008-11-18 23:14:02 +00002439/// AddMethodCandidate - Adds the given C++ member function to the set
2440/// of candidate functions, using the given function call arguments
2441/// and the object argument (@c Object). For example, in a call
2442/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2443/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2444/// allow user-defined conversions via constructors or conversion
Sebastian Redle2b68332009-04-12 17:16:29 +00002445/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2446/// a slightly hacky way to implement the overloading rules for elidable copy
2447/// initialization in C++0x (C++0x 12.8p15).
Mike Stump1eb44332009-09-09 15:08:12 +00002448void
John McCall701c89e2009-12-03 04:06:58 +00002449Sema::AddMethodCandidate(CXXMethodDecl *Method, CXXRecordDecl *ActingContext,
2450 QualType ObjectType, Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00002451 OverloadCandidateSet& CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00002452 bool SuppressUserConversions, bool ForceRValue) {
2453 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002454 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00002455 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002456 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor96176b32008-11-18 23:14:02 +00002457 "Use AddConversionCandidate for conversion functions");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002458 assert(!isa<CXXConstructorDecl>(Method) &&
2459 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00002460
Douglas Gregor3f396022009-09-28 04:47:19 +00002461 if (!CandidateSet.isNewCandidate(Method))
2462 return;
2463
Douglas Gregor7edfb692009-11-23 12:27:39 +00002464 // Overload resolution is always an unevaluated context.
2465 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2466
Douglas Gregor96176b32008-11-18 23:14:02 +00002467 // Add this candidate
2468 CandidateSet.push_back(OverloadCandidate());
2469 OverloadCandidate& Candidate = CandidateSet.back();
2470 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002471 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002472 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002473
2474 unsigned NumArgsInProto = Proto->getNumArgs();
2475
2476 // (C++ 13.3.2p2): A candidate function having fewer than m
2477 // parameters is viable only if it has an ellipsis in its parameter
2478 // list (8.3.5).
2479 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2480 Candidate.Viable = false;
2481 return;
2482 }
2483
2484 // (C++ 13.3.2p2): A candidate function having more than m parameters
2485 // is viable only if the (m+1)st parameter has a default argument
2486 // (8.3.6). For the purposes of overload resolution, the
2487 // parameter list is truncated on the right, so that there are
2488 // exactly m parameters.
2489 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2490 if (NumArgs < MinRequiredArgs) {
2491 // Not enough arguments.
2492 Candidate.Viable = false;
2493 return;
2494 }
2495
2496 Candidate.Viable = true;
2497 Candidate.Conversions.resize(NumArgs + 1);
2498
John McCall701c89e2009-12-03 04:06:58 +00002499 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00002500 // The implicit object argument is ignored.
2501 Candidate.IgnoreObjectArgument = true;
2502 else {
2503 // Determine the implicit conversion sequence for the object
2504 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00002505 Candidate.Conversions[0]
2506 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
Mike Stump1eb44332009-09-09 15:08:12 +00002507 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor88a35142008-12-22 05:46:06 +00002508 == ImplicitConversionSequence::BadConversion) {
2509 Candidate.Viable = false;
2510 return;
2511 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002512 }
2513
2514 // Determine the implicit conversion sequences for each of the
2515 // arguments.
2516 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2517 if (ArgIdx < NumArgsInProto) {
2518 // (C++ 13.3.2p3): for F to be a viable function, there shall
2519 // exist for each argument an implicit conversion sequence
2520 // (13.3.3.1) that converts that argument to the corresponding
2521 // parameter of F.
2522 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002523 Candidate.Conversions[ArgIdx + 1]
2524 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002525 SuppressUserConversions, ForceRValue,
Anders Carlsson08972922009-08-28 15:33:32 +00002526 /*InOverloadResolution=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00002527 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002528 == ImplicitConversionSequence::BadConversion) {
2529 Candidate.Viable = false;
2530 break;
2531 }
2532 } else {
2533 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2534 // argument for which there is no corresponding parameter is
2535 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002536 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002537 = ImplicitConversionSequence::EllipsisConversion;
2538 }
2539 }
2540}
2541
Douglas Gregor6b906862009-08-21 00:16:32 +00002542/// \brief Add a C++ member function template as a candidate to the candidate
2543/// set, using template argument deduction to produce an appropriate member
2544/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002545void
Douglas Gregor6b906862009-08-21 00:16:32 +00002546Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall701c89e2009-12-03 04:06:58 +00002547 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00002548 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00002549 QualType ObjectType,
2550 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002551 OverloadCandidateSet& CandidateSet,
2552 bool SuppressUserConversions,
2553 bool ForceRValue) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002554 if (!CandidateSet.isNewCandidate(MethodTmpl))
2555 return;
2556
Douglas Gregor6b906862009-08-21 00:16:32 +00002557 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002558 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00002559 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002560 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00002561 // candidate functions in the usual way.113) A given name can refer to one
2562 // or more function templates and also to a set of overloaded non-template
2563 // functions. In such a case, the candidate functions generated from each
2564 // function template are combined with the set of non-template candidate
2565 // functions.
2566 TemplateDeductionInfo Info(Context);
2567 FunctionDecl *Specialization = 0;
2568 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00002569 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002570 Args, NumArgs, Specialization, Info)) {
2571 // FIXME: Record what happened with template argument deduction, so
2572 // that we can give the user a beautiful diagnostic.
2573 (void)Result;
2574 return;
2575 }
Mike Stump1eb44332009-09-09 15:08:12 +00002576
Douglas Gregor6b906862009-08-21 00:16:32 +00002577 // Add the function template specialization produced by template argument
2578 // deduction as a candidate.
2579 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00002580 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00002581 "Specialization is not a member function?");
John McCall701c89e2009-12-03 04:06:58 +00002582 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), ActingContext,
2583 ObjectType, Args, NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002584 CandidateSet, SuppressUserConversions, ForceRValue);
2585}
2586
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002587/// \brief Add a C++ function template specialization as a candidate
2588/// in the candidate set, using template argument deduction to produce
2589/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002590void
Douglas Gregore53060f2009-06-25 22:08:12 +00002591Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002592 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002593 Expr **Args, unsigned NumArgs,
2594 OverloadCandidateSet& CandidateSet,
2595 bool SuppressUserConversions,
2596 bool ForceRValue) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002597 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2598 return;
2599
Douglas Gregore53060f2009-06-25 22:08:12 +00002600 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002601 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00002602 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002603 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00002604 // candidate functions in the usual way.113) A given name can refer to one
2605 // or more function templates and also to a set of overloaded non-template
2606 // functions. In such a case, the candidate functions generated from each
2607 // function template are combined with the set of non-template candidate
2608 // functions.
2609 TemplateDeductionInfo Info(Context);
2610 FunctionDecl *Specialization = 0;
2611 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00002612 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002613 Args, NumArgs, Specialization, Info)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002614 // FIXME: Record what happened with template argument deduction, so
2615 // that we can give the user a beautiful diagnostic.
2616 (void)Result;
2617 return;
2618 }
Mike Stump1eb44332009-09-09 15:08:12 +00002619
Douglas Gregore53060f2009-06-25 22:08:12 +00002620 // Add the function template specialization produced by template argument
2621 // deduction as a candidate.
2622 assert(Specialization && "Missing function template specialization?");
2623 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2624 SuppressUserConversions, ForceRValue);
2625}
Mike Stump1eb44332009-09-09 15:08:12 +00002626
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002627/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00002628/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002629/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00002630/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002631/// (which may or may not be the same type as the type that the
2632/// conversion function produces).
2633void
2634Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall701c89e2009-12-03 04:06:58 +00002635 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002636 Expr *From, QualType ToType,
2637 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002638 assert(!Conversion->getDescribedFunctionTemplate() &&
2639 "Conversion function templates use AddTemplateConversionCandidate");
2640
Douglas Gregor3f396022009-09-28 04:47:19 +00002641 if (!CandidateSet.isNewCandidate(Conversion))
2642 return;
2643
Douglas Gregor7edfb692009-11-23 12:27:39 +00002644 // Overload resolution is always an unevaluated context.
2645 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2646
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002647 // Add this candidate
2648 CandidateSet.push_back(OverloadCandidate());
2649 OverloadCandidate& Candidate = CandidateSet.back();
2650 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002651 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002652 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002653 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump1eb44332009-09-09 15:08:12 +00002654 Candidate.FinalConversion.FromTypePtr
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002655 = Conversion->getConversionType().getAsOpaquePtr();
2656 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2657
Douglas Gregor96176b32008-11-18 23:14:02 +00002658 // Determine the implicit conversion sequence for the implicit
2659 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002660 Candidate.Viable = true;
2661 Candidate.Conversions.resize(1);
John McCall701c89e2009-12-03 04:06:58 +00002662 Candidate.Conversions[0]
2663 = TryObjectArgumentInitialization(From->getType(), Conversion,
2664 ActingContext);
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002665 // Conversion functions to a different type in the base class is visible in
2666 // the derived class. So, a derived to base conversion should not participate
2667 // in overload resolution.
2668 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2669 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump1eb44332009-09-09 15:08:12 +00002670 if (Candidate.Conversions[0].ConversionKind
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002671 == ImplicitConversionSequence::BadConversion) {
2672 Candidate.Viable = false;
2673 return;
2674 }
Fariborz Jahanian3759a032009-10-19 19:18:20 +00002675
2676 // We won't go through a user-define type conversion function to convert a
2677 // derived to base as such conversions are given Conversion Rank. They only
2678 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2679 QualType FromCanon
2680 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2681 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2682 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2683 Candidate.Viable = false;
2684 return;
2685 }
2686
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002687
2688 // To determine what the conversion from the result of calling the
2689 // conversion function to the type we're eventually trying to
2690 // convert to (ToType), we need to synthesize a call to the
2691 // conversion function and attempt copy initialization from it. This
2692 // makes sure that we get the right semantics with respect to
2693 // lvalues/rvalues and the type. Fortunately, we can allocate this
2694 // call on the stack and we don't need its arguments to be
2695 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00002696 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00002697 From->getLocStart());
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002698 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman73c39ab2009-10-20 08:27:19 +00002699 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002700 &ConversionRef, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002701
2702 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00002703 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2704 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00002705 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002706 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00002707 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00002708 ImplicitConversionSequence ICS =
2709 TryCopyInitialization(&Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002710 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002711 /*ForceRValue=*/false,
2712 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002713
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002714 switch (ICS.ConversionKind) {
2715 case ImplicitConversionSequence::StandardConversion:
2716 Candidate.FinalConversion = ICS.Standard;
2717 break;
2718
2719 case ImplicitConversionSequence::BadConversion:
2720 Candidate.Viable = false;
2721 break;
2722
2723 default:
Mike Stump1eb44332009-09-09 15:08:12 +00002724 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002725 "Can only end up with a standard conversion sequence or failure");
2726 }
2727}
2728
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002729/// \brief Adds a conversion function template specialization
2730/// candidate to the overload set, using template argument deduction
2731/// to deduce the template arguments of the conversion function
2732/// template from the type that we are converting to (C++
2733/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00002734void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002735Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall701c89e2009-12-03 04:06:58 +00002736 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002737 Expr *From, QualType ToType,
2738 OverloadCandidateSet &CandidateSet) {
2739 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2740 "Only conversion function templates permitted here");
2741
Douglas Gregor3f396022009-09-28 04:47:19 +00002742 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2743 return;
2744
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002745 TemplateDeductionInfo Info(Context);
2746 CXXConversionDecl *Specialization = 0;
2747 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00002748 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002749 Specialization, Info)) {
2750 // FIXME: Record what happened with template argument deduction, so
2751 // that we can give the user a beautiful diagnostic.
2752 (void)Result;
2753 return;
2754 }
Mike Stump1eb44332009-09-09 15:08:12 +00002755
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002756 // Add the conversion function template specialization produced by
2757 // template argument deduction as a candidate.
2758 assert(Specialization && "Missing function template specialization?");
John McCall701c89e2009-12-03 04:06:58 +00002759 AddConversionCandidate(Specialization, ActingDC, From, ToType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002760}
2761
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002762/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2763/// converts the given @c Object to a function pointer via the
2764/// conversion function @c Conversion, and then attempts to call it
2765/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2766/// the type of function that we'll eventually be calling.
2767void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall701c89e2009-12-03 04:06:58 +00002768 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00002769 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00002770 QualType ObjectType,
2771 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002772 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002773 if (!CandidateSet.isNewCandidate(Conversion))
2774 return;
2775
Douglas Gregor7edfb692009-11-23 12:27:39 +00002776 // Overload resolution is always an unevaluated context.
2777 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2778
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002779 CandidateSet.push_back(OverloadCandidate());
2780 OverloadCandidate& Candidate = CandidateSet.back();
2781 Candidate.Function = 0;
2782 Candidate.Surrogate = Conversion;
2783 Candidate.Viable = true;
2784 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002785 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002786 Candidate.Conversions.resize(NumArgs + 1);
2787
2788 // Determine the implicit conversion sequence for the implicit
2789 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00002790 ImplicitConversionSequence ObjectInit
John McCall701c89e2009-12-03 04:06:58 +00002791 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002792 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2793 Candidate.Viable = false;
2794 return;
2795 }
2796
2797 // The first conversion is actually a user-defined conversion whose
2798 // first conversion is ObjectInit's standard conversion (which is
2799 // effectively a reference binding). Record it as such.
Mike Stump1eb44332009-09-09 15:08:12 +00002800 Candidate.Conversions[0].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002801 = ImplicitConversionSequence::UserDefinedConversion;
2802 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002803 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002804 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00002805 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002806 = Candidate.Conversions[0].UserDefined.Before;
2807 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2808
Mike Stump1eb44332009-09-09 15:08:12 +00002809 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002810 unsigned NumArgsInProto = Proto->getNumArgs();
2811
2812 // (C++ 13.3.2p2): A candidate function having fewer than m
2813 // parameters is viable only if it has an ellipsis in its parameter
2814 // list (8.3.5).
2815 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2816 Candidate.Viable = false;
2817 return;
2818 }
2819
2820 // Function types don't have any default arguments, so just check if
2821 // we have enough arguments.
2822 if (NumArgs < NumArgsInProto) {
2823 // Not enough arguments.
2824 Candidate.Viable = false;
2825 return;
2826 }
2827
2828 // Determine the implicit conversion sequences for each of the
2829 // arguments.
2830 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2831 if (ArgIdx < NumArgsInProto) {
2832 // (C++ 13.3.2p3): for F to be a viable function, there shall
2833 // exist for each argument an implicit conversion sequence
2834 // (13.3.3.1) that converts that argument to the corresponding
2835 // parameter of F.
2836 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002837 Candidate.Conversions[ArgIdx + 1]
2838 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002839 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002840 /*ForceRValue=*/false,
2841 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002842 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002843 == ImplicitConversionSequence::BadConversion) {
2844 Candidate.Viable = false;
2845 break;
2846 }
2847 } else {
2848 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2849 // argument for which there is no corresponding parameter is
2850 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002851 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002852 = ImplicitConversionSequence::EllipsisConversion;
2853 }
2854 }
2855}
2856
Mike Stump390b4cc2009-05-16 07:39:55 +00002857// FIXME: This will eventually be removed, once we've migrated all of the
2858// operator overloading logic over to the scheme used by binary operators, which
2859// works for template instantiation.
Douglas Gregor063daf62009-03-13 18:40:31 +00002860void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002861 SourceLocation OpLoc,
Douglas Gregor96176b32008-11-18 23:14:02 +00002862 Expr **Args, unsigned NumArgs,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002863 OverloadCandidateSet& CandidateSet,
2864 SourceRange OpRange) {
Douglas Gregor063daf62009-03-13 18:40:31 +00002865 FunctionSet Functions;
2866
2867 QualType T1 = Args[0]->getType();
2868 QualType T2;
2869 if (NumArgs > 1)
2870 T2 = Args[1]->getType();
2871
2872 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002873 if (S)
2874 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Sebastian Redl644be852009-10-23 19:23:15 +00002875 ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00002876 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2877 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002878 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00002879}
2880
2881/// \brief Add overload candidates for overloaded operators that are
2882/// member functions.
2883///
2884/// Add the overloaded operator candidates that are member functions
2885/// for the operator Op that was used in an operator expression such
2886/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2887/// CandidateSet will store the added overload candidates. (C++
2888/// [over.match.oper]).
2889void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2890 SourceLocation OpLoc,
2891 Expr **Args, unsigned NumArgs,
2892 OverloadCandidateSet& CandidateSet,
2893 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002894 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2895
2896 // C++ [over.match.oper]p3:
2897 // For a unary operator @ with an operand of a type whose
2898 // cv-unqualified version is T1, and for a binary operator @ with
2899 // a left operand of a type whose cv-unqualified version is T1 and
2900 // a right operand of a type whose cv-unqualified version is T2,
2901 // three sets of candidate functions, designated member
2902 // candidates, non-member candidates and built-in candidates, are
2903 // constructed as follows:
2904 QualType T1 = Args[0]->getType();
2905 QualType T2;
2906 if (NumArgs > 1)
2907 T2 = Args[1]->getType();
2908
2909 // -- If T1 is a class type, the set of member candidates is the
2910 // result of the qualified lookup of T1::operator@
2911 // (13.3.1.1.1); otherwise, the set of member candidates is
2912 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00002913 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002914 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00002915 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002916 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002917
John McCalla24dc2e2009-11-17 02:14:36 +00002918 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
2919 LookupQualifiedName(Operators, T1Rec->getDecl());
2920 Operators.suppressDiagnostics();
2921
Mike Stump1eb44332009-09-09 15:08:12 +00002922 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002923 OperEnd = Operators.end();
2924 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00002925 ++Oper)
John McCall701c89e2009-12-03 04:06:58 +00002926 AddMethodCandidate(*Oper, Args[0]->getType(),
2927 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00002928 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00002929 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002930}
2931
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002932/// AddBuiltinCandidate - Add a candidate for a built-in
2933/// operator. ResultTy and ParamTys are the result and parameter types
2934/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002935/// arguments being passed to the candidate. IsAssignmentOperator
2936/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002937/// operator. NumContextualBoolArguments is the number of arguments
2938/// (at the beginning of the argument list) that will be contextually
2939/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00002940void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002941 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002942 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002943 bool IsAssignmentOperator,
2944 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00002945 // Overload resolution is always an unevaluated context.
2946 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2947
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002948 // Add this candidate
2949 CandidateSet.push_back(OverloadCandidate());
2950 OverloadCandidate& Candidate = CandidateSet.back();
2951 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00002952 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002953 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002954 Candidate.BuiltinTypes.ResultTy = ResultTy;
2955 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2956 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2957
2958 // Determine the implicit conversion sequences for each of the
2959 // arguments.
2960 Candidate.Viable = true;
2961 Candidate.Conversions.resize(NumArgs);
2962 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002963 // C++ [over.match.oper]p4:
2964 // For the built-in assignment operators, conversions of the
2965 // left operand are restricted as follows:
2966 // -- no temporaries are introduced to hold the left operand, and
2967 // -- no user-defined conversions are applied to the left
2968 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00002969 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002970 //
2971 // We block these conversions by turning off user-defined
2972 // conversions, since that is the only way that initialization of
2973 // a reference to a non-class type can occur from something that
2974 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002975 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00002976 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002977 "Contextual conversion to bool requires bool type");
2978 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2979 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002980 Candidate.Conversions[ArgIdx]
2981 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00002982 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002983 /*ForceRValue=*/false,
2984 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002985 }
Mike Stump1eb44332009-09-09 15:08:12 +00002986 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002987 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002988 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002989 break;
2990 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002991 }
2992}
2993
2994/// BuiltinCandidateTypeSet - A set of types that will be used for the
2995/// candidate operator functions for built-in operators (C++
2996/// [over.built]). The types are separated into pointer types and
2997/// enumeration types.
2998class BuiltinCandidateTypeSet {
2999 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003000 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003001
3002 /// PointerTypes - The set of pointer types that will be used in the
3003 /// built-in candidates.
3004 TypeSet PointerTypes;
3005
Sebastian Redl78eb8742009-04-19 21:53:20 +00003006 /// MemberPointerTypes - The set of member pointer types that will be
3007 /// used in the built-in candidates.
3008 TypeSet MemberPointerTypes;
3009
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003010 /// EnumerationTypes - The set of enumeration types that will be
3011 /// used in the built-in candidates.
3012 TypeSet EnumerationTypes;
3013
Douglas Gregor5842ba92009-08-24 15:23:48 +00003014 /// Sema - The semantic analysis instance where we are building the
3015 /// candidate type set.
3016 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00003017
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003018 /// Context - The AST context in which we will build the type sets.
3019 ASTContext &Context;
3020
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003021 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3022 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00003023 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003024
3025public:
3026 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003027 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003028
Mike Stump1eb44332009-09-09 15:08:12 +00003029 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00003030 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003031
Douglas Gregor573d9c32009-10-21 23:19:44 +00003032 void AddTypesConvertedFrom(QualType Ty,
3033 SourceLocation Loc,
3034 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003035 bool AllowExplicitConversions,
3036 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003037
3038 /// pointer_begin - First pointer type found;
3039 iterator pointer_begin() { return PointerTypes.begin(); }
3040
Sebastian Redl78eb8742009-04-19 21:53:20 +00003041 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003042 iterator pointer_end() { return PointerTypes.end(); }
3043
Sebastian Redl78eb8742009-04-19 21:53:20 +00003044 /// member_pointer_begin - First member pointer type found;
3045 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3046
3047 /// member_pointer_end - Past the last member pointer type found;
3048 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3049
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003050 /// enumeration_begin - First enumeration type found;
3051 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3052
Sebastian Redl78eb8742009-04-19 21:53:20 +00003053 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003054 iterator enumeration_end() { return EnumerationTypes.end(); }
3055};
3056
Sebastian Redl78eb8742009-04-19 21:53:20 +00003057/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003058/// the set of pointer types along with any more-qualified variants of
3059/// that type. For example, if @p Ty is "int const *", this routine
3060/// will add "int const *", "int const volatile *", "int const
3061/// restrict *", and "int const volatile restrict *" to the set of
3062/// pointer types. Returns true if the add of @p Ty itself succeeded,
3063/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003064///
3065/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003066bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00003067BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3068 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00003069
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003070 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003071 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003072 return false;
3073
John McCall0953e762009-09-24 19:53:00 +00003074 const PointerType *PointerTy = Ty->getAs<PointerType>();
3075 assert(PointerTy && "type was not a pointer type!");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003076
John McCall0953e762009-09-24 19:53:00 +00003077 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003078 // Don't add qualified variants of arrays. For one, they're not allowed
3079 // (the qualifier would sink to the element type), and for another, the
3080 // only overload situation where it matters is subscript or pointer +- int,
3081 // and those shouldn't have qualifier variants anyway.
3082 if (PointeeTy->isArrayType())
3083 return true;
John McCall0953e762009-09-24 19:53:00 +00003084 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00003085 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00003086 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003087 bool hasVolatile = VisibleQuals.hasVolatile();
3088 bool hasRestrict = VisibleQuals.hasRestrict();
3089
John McCall0953e762009-09-24 19:53:00 +00003090 // Iterate through all strict supersets of BaseCVR.
3091 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3092 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003093 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3094 // in the types.
3095 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3096 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00003097 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3098 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003099 }
3100
3101 return true;
3102}
3103
Sebastian Redl78eb8742009-04-19 21:53:20 +00003104/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3105/// to the set of pointer types along with any more-qualified variants of
3106/// that type. For example, if @p Ty is "int const *", this routine
3107/// will add "int const *", "int const volatile *", "int const
3108/// restrict *", and "int const volatile restrict *" to the set of
3109/// pointer types. Returns true if the add of @p Ty itself succeeded,
3110/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003111///
3112/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003113bool
3114BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3115 QualType Ty) {
3116 // Insert this type.
3117 if (!MemberPointerTypes.insert(Ty))
3118 return false;
3119
John McCall0953e762009-09-24 19:53:00 +00003120 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3121 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00003122
John McCall0953e762009-09-24 19:53:00 +00003123 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003124 // Don't add qualified variants of arrays. For one, they're not allowed
3125 // (the qualifier would sink to the element type), and for another, the
3126 // only overload situation where it matters is subscript or pointer +- int,
3127 // and those shouldn't have qualifier variants anyway.
3128 if (PointeeTy->isArrayType())
3129 return true;
John McCall0953e762009-09-24 19:53:00 +00003130 const Type *ClassTy = PointerTy->getClass();
3131
3132 // Iterate through all strict supersets of the pointee type's CVR
3133 // qualifiers.
3134 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3135 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3136 if ((CVR | BaseCVR) != CVR) continue;
3137
3138 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3139 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00003140 }
3141
3142 return true;
3143}
3144
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003145/// AddTypesConvertedFrom - Add each of the types to which the type @p
3146/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00003147/// primarily interested in pointer types and enumeration types. We also
3148/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003149/// AllowUserConversions is true if we should look at the conversion
3150/// functions of a class type, and AllowExplicitConversions if we
3151/// should also include the explicit conversion functions of a class
3152/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003153void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003154BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003155 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003156 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003157 bool AllowExplicitConversions,
3158 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003159 // Only deal with canonical types.
3160 Ty = Context.getCanonicalType(Ty);
3161
3162 // Look through reference types; they aren't part of the type of an
3163 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00003164 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003165 Ty = RefTy->getPointeeType();
3166
3167 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003168 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003169
Sebastian Redla65b5512009-11-05 16:36:20 +00003170 // If we're dealing with an array type, decay to the pointer.
3171 if (Ty->isArrayType())
3172 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3173
Ted Kremenek6217b802009-07-29 21:53:49 +00003174 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003175 QualType PointeeTy = PointerTy->getPointeeType();
3176
3177 // Insert our type, and its more-qualified variants, into the set
3178 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003179 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003180 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00003181 } else if (Ty->isMemberPointerType()) {
3182 // Member pointers are far easier, since the pointee can't be converted.
3183 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3184 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003185 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00003186 EnumerationTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003187 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003188 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003189 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003190 // No conversion functions in incomplete types.
3191 return;
3192 }
Mike Stump1eb44332009-09-09 15:08:12 +00003193
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003194 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallba135432009-11-21 08:51:07 +00003195 const UnresolvedSet *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00003196 = ClassDecl->getVisibleConversionFunctions();
John McCallba135432009-11-21 08:51:07 +00003197 for (UnresolvedSet::iterator I = Conversions->begin(),
3198 E = Conversions->end(); I != E; ++I) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003199
Mike Stump1eb44332009-09-09 15:08:12 +00003200 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003201 // about which builtin types we can convert to.
John McCallba135432009-11-21 08:51:07 +00003202 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003203 continue;
3204
John McCallba135432009-11-21 08:51:07 +00003205 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003206 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003207 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003208 VisibleQuals);
3209 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003210 }
3211 }
3212 }
3213}
3214
Douglas Gregor19b7b152009-08-24 13:43:27 +00003215/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3216/// the volatile- and non-volatile-qualified assignment operators for the
3217/// given type to the candidate set.
3218static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3219 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00003220 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003221 unsigned NumArgs,
3222 OverloadCandidateSet &CandidateSet) {
3223 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00003224
Douglas Gregor19b7b152009-08-24 13:43:27 +00003225 // T& operator=(T&, T)
3226 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3227 ParamTypes[1] = T;
3228 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3229 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003230
Douglas Gregor19b7b152009-08-24 13:43:27 +00003231 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3232 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00003233 ParamTypes[0]
3234 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00003235 ParamTypes[1] = T;
3236 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00003237 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003238 }
3239}
Mike Stump1eb44332009-09-09 15:08:12 +00003240
Sebastian Redl9994a342009-10-25 17:03:50 +00003241/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3242/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003243static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3244 Qualifiers VRQuals;
3245 const RecordType *TyRec;
3246 if (const MemberPointerType *RHSMPType =
3247 ArgExpr->getType()->getAs<MemberPointerType>())
3248 TyRec = cast<RecordType>(RHSMPType->getClass());
3249 else
3250 TyRec = ArgExpr->getType()->getAs<RecordType>();
3251 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003252 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003253 VRQuals.addVolatile();
3254 VRQuals.addRestrict();
3255 return VRQuals;
3256 }
3257
3258 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallba135432009-11-21 08:51:07 +00003259 const UnresolvedSet *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00003260 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003261
John McCallba135432009-11-21 08:51:07 +00003262 for (UnresolvedSet::iterator I = Conversions->begin(),
3263 E = Conversions->end(); I != E; ++I) {
3264 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003265 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3266 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3267 CanTy = ResTypeRef->getPointeeType();
3268 // Need to go down the pointer/mempointer chain and add qualifiers
3269 // as see them.
3270 bool done = false;
3271 while (!done) {
3272 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3273 CanTy = ResTypePtr->getPointeeType();
3274 else if (const MemberPointerType *ResTypeMPtr =
3275 CanTy->getAs<MemberPointerType>())
3276 CanTy = ResTypeMPtr->getPointeeType();
3277 else
3278 done = true;
3279 if (CanTy.isVolatileQualified())
3280 VRQuals.addVolatile();
3281 if (CanTy.isRestrictQualified())
3282 VRQuals.addRestrict();
3283 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3284 return VRQuals;
3285 }
3286 }
3287 }
3288 return VRQuals;
3289}
3290
Douglas Gregor74253732008-11-19 15:42:04 +00003291/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3292/// operator overloads to the candidate set (C++ [over.built]), based
3293/// on the operator @p Op and the arguments given. For example, if the
3294/// operator is a binary '+', this routine might add "int
3295/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003296void
Mike Stump1eb44332009-09-09 15:08:12 +00003297Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003298 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00003299 Expr **Args, unsigned NumArgs,
3300 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003301 // The set of "promoted arithmetic types", which are the arithmetic
3302 // types are that preserved by promotion (C++ [over.built]p2). Note
3303 // that the first few of these types are the promoted integral
3304 // types; these types need to be first.
3305 // FIXME: What about complex?
3306 const unsigned FirstIntegralType = 0;
3307 const unsigned LastIntegralType = 13;
Mike Stump1eb44332009-09-09 15:08:12 +00003308 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003309 LastPromotedIntegralType = 13;
3310 const unsigned FirstPromotedArithmeticType = 7,
3311 LastPromotedArithmeticType = 16;
3312 const unsigned NumArithmeticTypes = 16;
3313 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00003314 Context.BoolTy, Context.CharTy, Context.WCharTy,
3315// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003316 Context.SignedCharTy, Context.ShortTy,
3317 Context.UnsignedCharTy, Context.UnsignedShortTy,
3318 Context.IntTy, Context.LongTy, Context.LongLongTy,
3319 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3320 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3321 };
Douglas Gregor652371a2009-10-21 22:01:30 +00003322 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3323 "Invalid first promoted integral type");
3324 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3325 == Context.UnsignedLongLongTy &&
3326 "Invalid last promoted integral type");
3327 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3328 "Invalid first promoted arithmetic type");
3329 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3330 == Context.LongDoubleTy &&
3331 "Invalid last promoted arithmetic type");
3332
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003333 // Find all of the types that the arguments can convert to, but only
3334 // if the operator we're looking at has built-in operator candidates
3335 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003336 Qualifiers VisibleTypeConversionsQuals;
3337 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003338 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3339 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3340
Douglas Gregor5842ba92009-08-24 15:23:48 +00003341 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003342 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3343 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00003344 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003345 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00003346 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003347 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor74253732008-11-19 15:42:04 +00003348 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003349 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregor573d9c32009-10-21 23:19:44 +00003350 OpLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003351 true,
3352 (Op == OO_Exclaim ||
3353 Op == OO_AmpAmp ||
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003354 Op == OO_PipePipe),
3355 VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003356 }
3357
3358 bool isComparison = false;
3359 switch (Op) {
3360 case OO_None:
3361 case NUM_OVERLOADED_OPERATORS:
3362 assert(false && "Expected an overloaded operator");
3363 break;
3364
Douglas Gregor74253732008-11-19 15:42:04 +00003365 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00003366 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00003367 goto UnaryStar;
3368 else
3369 goto BinaryStar;
3370 break;
3371
3372 case OO_Plus: // '+' is either unary or binary
3373 if (NumArgs == 1)
3374 goto UnaryPlus;
3375 else
3376 goto BinaryPlus;
3377 break;
3378
3379 case OO_Minus: // '-' is either unary or binary
3380 if (NumArgs == 1)
3381 goto UnaryMinus;
3382 else
3383 goto BinaryMinus;
3384 break;
3385
3386 case OO_Amp: // '&' is either unary or binary
3387 if (NumArgs == 1)
3388 goto UnaryAmp;
3389 else
3390 goto BinaryAmp;
3391
3392 case OO_PlusPlus:
3393 case OO_MinusMinus:
3394 // C++ [over.built]p3:
3395 //
3396 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3397 // is either volatile or empty, there exist candidate operator
3398 // functions of the form
3399 //
3400 // VQ T& operator++(VQ T&);
3401 // T operator++(VQ T&, int);
3402 //
3403 // C++ [over.built]p4:
3404 //
3405 // For every pair (T, VQ), where T is an arithmetic type other
3406 // than bool, and VQ is either volatile or empty, there exist
3407 // candidate operator functions of the form
3408 //
3409 // VQ T& operator--(VQ T&);
3410 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00003411 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00003412 Arith < NumArithmeticTypes; ++Arith) {
3413 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00003414 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003415 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00003416
3417 // Non-volatile version.
3418 if (NumArgs == 1)
3419 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3420 else
3421 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003422 // heuristic to reduce number of builtin candidates in the set.
3423 // Add volatile version only if there are conversions to a volatile type.
3424 if (VisibleTypeConversionsQuals.hasVolatile()) {
3425 // Volatile version
3426 ParamTypes[0]
3427 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3428 if (NumArgs == 1)
3429 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3430 else
3431 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3432 }
Douglas Gregor74253732008-11-19 15:42:04 +00003433 }
3434
3435 // C++ [over.built]p5:
3436 //
3437 // For every pair (T, VQ), where T is a cv-qualified or
3438 // cv-unqualified object type, and VQ is either volatile or
3439 // empty, there exist candidate operator functions of the form
3440 //
3441 // T*VQ& operator++(T*VQ&);
3442 // T*VQ& operator--(T*VQ&);
3443 // T* operator++(T*VQ&, int);
3444 // T* operator--(T*VQ&, int);
3445 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3446 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3447 // Skip pointer types that aren't pointers to object types.
Ted Kremenek6217b802009-07-29 21:53:49 +00003448 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00003449 continue;
3450
Mike Stump1eb44332009-09-09 15:08:12 +00003451 QualType ParamTypes[2] = {
3452 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00003453 };
Mike Stump1eb44332009-09-09 15:08:12 +00003454
Douglas Gregor74253732008-11-19 15:42:04 +00003455 // Without volatile
3456 if (NumArgs == 1)
3457 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3458 else
3459 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3460
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003461 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3462 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00003463 // With volatile
John McCall0953e762009-09-24 19:53:00 +00003464 ParamTypes[0]
3465 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00003466 if (NumArgs == 1)
3467 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3468 else
3469 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3470 }
3471 }
3472 break;
3473
3474 UnaryStar:
3475 // C++ [over.built]p6:
3476 // For every cv-qualified or cv-unqualified object type T, there
3477 // exist candidate operator functions of the form
3478 //
3479 // T& operator*(T*);
3480 //
3481 // C++ [over.built]p7:
3482 // For every function type T, there exist candidate operator
3483 // functions of the form
3484 // T& operator*(T*);
3485 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3486 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3487 QualType ParamTy = *Ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00003488 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003489 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00003490 &ParamTy, Args, 1, CandidateSet);
3491 }
3492 break;
3493
3494 UnaryPlus:
3495 // C++ [over.built]p8:
3496 // For every type T, there exist candidate operator functions of
3497 // the form
3498 //
3499 // T* operator+(T*);
3500 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3501 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3502 QualType ParamTy = *Ptr;
3503 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3504 }
Mike Stump1eb44332009-09-09 15:08:12 +00003505
Douglas Gregor74253732008-11-19 15:42:04 +00003506 // Fall through
3507
3508 UnaryMinus:
3509 // C++ [over.built]p9:
3510 // For every promoted arithmetic type T, there exist candidate
3511 // operator functions of the form
3512 //
3513 // T operator+(T);
3514 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003515 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00003516 Arith < LastPromotedArithmeticType; ++Arith) {
3517 QualType ArithTy = ArithmeticTypes[Arith];
3518 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3519 }
3520 break;
3521
3522 case OO_Tilde:
3523 // C++ [over.built]p10:
3524 // For every promoted integral type T, there exist candidate
3525 // operator functions of the form
3526 //
3527 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003528 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00003529 Int < LastPromotedIntegralType; ++Int) {
3530 QualType IntTy = ArithmeticTypes[Int];
3531 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3532 }
3533 break;
3534
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003535 case OO_New:
3536 case OO_Delete:
3537 case OO_Array_New:
3538 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003539 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00003540 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003541 break;
3542
3543 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00003544 UnaryAmp:
3545 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003546 // C++ [over.match.oper]p3:
3547 // -- For the operator ',', the unary operator '&', or the
3548 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003549 break;
3550
Douglas Gregor19b7b152009-08-24 13:43:27 +00003551 case OO_EqualEqual:
3552 case OO_ExclaimEqual:
3553 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00003554 // For every pointer to member type T, there exist candidate operator
3555 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00003556 //
3557 // bool operator==(T,T);
3558 // bool operator!=(T,T);
Mike Stump1eb44332009-09-09 15:08:12 +00003559 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor19b7b152009-08-24 13:43:27 +00003560 MemPtr = CandidateTypes.member_pointer_begin(),
3561 MemPtrEnd = CandidateTypes.member_pointer_end();
3562 MemPtr != MemPtrEnd;
3563 ++MemPtr) {
3564 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3565 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3566 }
Mike Stump1eb44332009-09-09 15:08:12 +00003567
Douglas Gregor19b7b152009-08-24 13:43:27 +00003568 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00003569
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003570 case OO_Less:
3571 case OO_Greater:
3572 case OO_LessEqual:
3573 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003574 // C++ [over.built]p15:
3575 //
3576 // For every pointer or enumeration type T, there exist
3577 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003578 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003579 // bool operator<(T, T);
3580 // bool operator>(T, T);
3581 // bool operator<=(T, T);
3582 // bool operator>=(T, T);
3583 // bool operator==(T, T);
3584 // bool operator!=(T, T);
3585 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3586 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3587 QualType ParamTypes[2] = { *Ptr, *Ptr };
3588 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3589 }
Mike Stump1eb44332009-09-09 15:08:12 +00003590 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003591 = CandidateTypes.enumeration_begin();
3592 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3593 QualType ParamTypes[2] = { *Enum, *Enum };
3594 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3595 }
3596
3597 // Fall through.
3598 isComparison = true;
3599
Douglas Gregor74253732008-11-19 15:42:04 +00003600 BinaryPlus:
3601 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003602 if (!isComparison) {
3603 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3604
3605 // C++ [over.built]p13:
3606 //
3607 // For every cv-qualified or cv-unqualified object type T
3608 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003609 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003610 // T* operator+(T*, ptrdiff_t);
3611 // T& operator[](T*, ptrdiff_t); [BELOW]
3612 // T* operator-(T*, ptrdiff_t);
3613 // T* operator+(ptrdiff_t, T*);
3614 // T& operator[](ptrdiff_t, T*); [BELOW]
3615 //
3616 // C++ [over.built]p14:
3617 //
3618 // For every T, where T is a pointer to object type, there
3619 // exist candidate operator functions of the form
3620 //
3621 // ptrdiff_t operator-(T, T);
Mike Stump1eb44332009-09-09 15:08:12 +00003622 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003623 = CandidateTypes.pointer_begin();
3624 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3625 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3626
3627 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3628 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3629
3630 if (Op == OO_Plus) {
3631 // T* operator+(ptrdiff_t, T*);
3632 ParamTypes[0] = ParamTypes[1];
3633 ParamTypes[1] = *Ptr;
3634 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3635 } else {
3636 // ptrdiff_t operator-(T, T);
3637 ParamTypes[1] = *Ptr;
3638 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3639 Args, 2, CandidateSet);
3640 }
3641 }
3642 }
3643 // Fall through
3644
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003645 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00003646 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003647 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003648 // C++ [over.built]p12:
3649 //
3650 // For every pair of promoted arithmetic types L and R, there
3651 // exist candidate operator functions of the form
3652 //
3653 // LR operator*(L, R);
3654 // LR operator/(L, R);
3655 // LR operator+(L, R);
3656 // LR operator-(L, R);
3657 // bool operator<(L, R);
3658 // bool operator>(L, R);
3659 // bool operator<=(L, R);
3660 // bool operator>=(L, R);
3661 // bool operator==(L, R);
3662 // bool operator!=(L, R);
3663 //
3664 // where LR is the result of the usual arithmetic conversions
3665 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003666 //
3667 // C++ [over.built]p24:
3668 //
3669 // For every pair of promoted arithmetic types L and R, there exist
3670 // candidate operator functions of the form
3671 //
3672 // LR operator?(bool, L, R);
3673 //
3674 // where LR is the result of the usual arithmetic conversions
3675 // between types L and R.
3676 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003677 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003678 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003679 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003680 Right < LastPromotedArithmeticType; ++Right) {
3681 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00003682 QualType Result
3683 = isComparison
3684 ? Context.BoolTy
3685 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003686 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3687 }
3688 }
3689 break;
3690
3691 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00003692 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003693 case OO_Caret:
3694 case OO_Pipe:
3695 case OO_LessLess:
3696 case OO_GreaterGreater:
3697 // C++ [over.built]p17:
3698 //
3699 // For every pair of promoted integral types L and R, there
3700 // exist candidate operator functions of the form
3701 //
3702 // LR operator%(L, R);
3703 // LR operator&(L, R);
3704 // LR operator^(L, R);
3705 // LR operator|(L, R);
3706 // L operator<<(L, R);
3707 // L operator>>(L, R);
3708 //
3709 // where LR is the result of the usual arithmetic conversions
3710 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00003711 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003712 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003713 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003714 Right < LastPromotedIntegralType; ++Right) {
3715 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3716 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3717 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00003718 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003719 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3720 }
3721 }
3722 break;
3723
3724 case OO_Equal:
3725 // C++ [over.built]p20:
3726 //
3727 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00003728 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003729 // empty, there exist candidate operator functions of the form
3730 //
3731 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003732 for (BuiltinCandidateTypeSet::iterator
3733 Enum = CandidateTypes.enumeration_begin(),
3734 EnumEnd = CandidateTypes.enumeration_end();
3735 Enum != EnumEnd; ++Enum)
Mike Stump1eb44332009-09-09 15:08:12 +00003736 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003737 CandidateSet);
3738 for (BuiltinCandidateTypeSet::iterator
3739 MemPtr = CandidateTypes.member_pointer_begin(),
3740 MemPtrEnd = CandidateTypes.member_pointer_end();
3741 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump1eb44332009-09-09 15:08:12 +00003742 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003743 CandidateSet);
3744 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003745
3746 case OO_PlusEqual:
3747 case OO_MinusEqual:
3748 // C++ [over.built]p19:
3749 //
3750 // For every pair (T, VQ), where T is any type and VQ is either
3751 // volatile or empty, there exist candidate operator functions
3752 // of the form
3753 //
3754 // T*VQ& operator=(T*VQ&, T*);
3755 //
3756 // C++ [over.built]p21:
3757 //
3758 // For every pair (T, VQ), where T is a cv-qualified or
3759 // cv-unqualified object type and VQ is either volatile or
3760 // empty, there exist candidate operator functions of the form
3761 //
3762 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3763 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3764 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3765 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3766 QualType ParamTypes[2];
3767 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3768
3769 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003770 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003771 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3772 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003773
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003774 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3775 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00003776 // volatile version
John McCall0953e762009-09-24 19:53:00 +00003777 ParamTypes[0]
3778 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003779 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3780 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00003781 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003782 }
3783 // Fall through.
3784
3785 case OO_StarEqual:
3786 case OO_SlashEqual:
3787 // C++ [over.built]p18:
3788 //
3789 // For every triple (L, VQ, R), where L is an arithmetic type,
3790 // VQ is either volatile or empty, and R is a promoted
3791 // arithmetic type, there exist candidate operator functions of
3792 // the form
3793 //
3794 // VQ L& operator=(VQ L&, R);
3795 // VQ L& operator*=(VQ L&, R);
3796 // VQ L& operator/=(VQ L&, R);
3797 // VQ L& operator+=(VQ L&, R);
3798 // VQ L& operator-=(VQ L&, R);
3799 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003800 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003801 Right < LastPromotedArithmeticType; ++Right) {
3802 QualType ParamTypes[2];
3803 ParamTypes[1] = ArithmeticTypes[Right];
3804
3805 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003806 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003807 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3808 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003809
3810 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003811 if (VisibleTypeConversionsQuals.hasVolatile()) {
3812 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3813 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3814 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3815 /*IsAssigmentOperator=*/Op == OO_Equal);
3816 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003817 }
3818 }
3819 break;
3820
3821 case OO_PercentEqual:
3822 case OO_LessLessEqual:
3823 case OO_GreaterGreaterEqual:
3824 case OO_AmpEqual:
3825 case OO_CaretEqual:
3826 case OO_PipeEqual:
3827 // C++ [over.built]p22:
3828 //
3829 // For every triple (L, VQ, R), where L is an integral type, VQ
3830 // is either volatile or empty, and R is a promoted integral
3831 // type, there exist candidate operator functions of the form
3832 //
3833 // VQ L& operator%=(VQ L&, R);
3834 // VQ L& operator<<=(VQ L&, R);
3835 // VQ L& operator>>=(VQ L&, R);
3836 // VQ L& operator&=(VQ L&, R);
3837 // VQ L& operator^=(VQ L&, R);
3838 // VQ L& operator|=(VQ L&, R);
3839 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003840 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003841 Right < LastPromotedIntegralType; ++Right) {
3842 QualType ParamTypes[2];
3843 ParamTypes[1] = ArithmeticTypes[Right];
3844
3845 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003846 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003847 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00003848 if (VisibleTypeConversionsQuals.hasVolatile()) {
3849 // Add this built-in operator as a candidate (VQ is 'volatile').
3850 ParamTypes[0] = ArithmeticTypes[Left];
3851 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3852 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3853 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3854 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003855 }
3856 }
3857 break;
3858
Douglas Gregor74253732008-11-19 15:42:04 +00003859 case OO_Exclaim: {
3860 // C++ [over.operator]p23:
3861 //
3862 // There also exist candidate operator functions of the form
3863 //
Mike Stump1eb44332009-09-09 15:08:12 +00003864 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00003865 // bool operator&&(bool, bool); [BELOW]
3866 // bool operator||(bool, bool); [BELOW]
3867 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003868 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3869 /*IsAssignmentOperator=*/false,
3870 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00003871 break;
3872 }
3873
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003874 case OO_AmpAmp:
3875 case OO_PipePipe: {
3876 // C++ [over.operator]p23:
3877 //
3878 // There also exist candidate operator functions of the form
3879 //
Douglas Gregor74253732008-11-19 15:42:04 +00003880 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003881 // bool operator&&(bool, bool);
3882 // bool operator||(bool, bool);
3883 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003884 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3885 /*IsAssignmentOperator=*/false,
3886 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003887 break;
3888 }
3889
3890 case OO_Subscript:
3891 // C++ [over.built]p13:
3892 //
3893 // For every cv-qualified or cv-unqualified object type T there
3894 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003895 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003896 // T* operator+(T*, ptrdiff_t); [ABOVE]
3897 // T& operator[](T*, ptrdiff_t);
3898 // T* operator-(T*, ptrdiff_t); [ABOVE]
3899 // T* operator+(ptrdiff_t, T*); [ABOVE]
3900 // T& operator[](ptrdiff_t, T*);
3901 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3902 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3903 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenek6217b802009-07-29 21:53:49 +00003904 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003905 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003906
3907 // T& operator[](T*, ptrdiff_t)
3908 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3909
3910 // T& operator[](ptrdiff_t, T*);
3911 ParamTypes[0] = ParamTypes[1];
3912 ParamTypes[1] = *Ptr;
3913 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3914 }
3915 break;
3916
3917 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003918 // C++ [over.built]p11:
3919 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
3920 // C1 is the same type as C2 or is a derived class of C2, T is an object
3921 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
3922 // there exist candidate operator functions of the form
3923 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
3924 // where CV12 is the union of CV1 and CV2.
3925 {
3926 for (BuiltinCandidateTypeSet::iterator Ptr =
3927 CandidateTypes.pointer_begin();
3928 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3929 QualType C1Ty = (*Ptr);
3930 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00003931 QualifierCollector Q1;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003932 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00003933 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003934 if (!isa<RecordType>(C1))
3935 continue;
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003936 // heuristic to reduce number of builtin candidates in the set.
3937 // Add volatile/restrict version only if there are conversions to a
3938 // volatile/restrict type.
3939 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
3940 continue;
3941 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
3942 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003943 }
3944 for (BuiltinCandidateTypeSet::iterator
3945 MemPtr = CandidateTypes.member_pointer_begin(),
3946 MemPtrEnd = CandidateTypes.member_pointer_end();
3947 MemPtr != MemPtrEnd; ++MemPtr) {
3948 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
3949 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00003950 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003951 if (C1 != C2 && !IsDerivedFrom(C1, C2))
3952 break;
3953 QualType ParamTypes[2] = { *Ptr, *MemPtr };
3954 // build CV12 T&
3955 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003956 if (!VisibleTypeConversionsQuals.hasVolatile() &&
3957 T.isVolatileQualified())
3958 continue;
3959 if (!VisibleTypeConversionsQuals.hasRestrict() &&
3960 T.isRestrictQualified())
3961 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00003962 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003963 QualType ResultTy = Context.getLValueReferenceType(T);
3964 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3965 }
3966 }
3967 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003968 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003969
3970 case OO_Conditional:
3971 // Note that we don't consider the first argument, since it has been
3972 // contextually converted to bool long ago. The candidates below are
3973 // therefore added as binary.
3974 //
3975 // C++ [over.built]p24:
3976 // For every type T, where T is a pointer or pointer-to-member type,
3977 // there exist candidate operator functions of the form
3978 //
3979 // T operator?(bool, T, T);
3980 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003981 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3982 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3983 QualType ParamTypes[2] = { *Ptr, *Ptr };
3984 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3985 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00003986 for (BuiltinCandidateTypeSet::iterator Ptr =
3987 CandidateTypes.member_pointer_begin(),
3988 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3989 QualType ParamTypes[2] = { *Ptr, *Ptr };
3990 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3991 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003992 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003993 }
3994}
3995
Douglas Gregorfa047642009-02-04 00:32:51 +00003996/// \brief Add function candidates found via argument-dependent lookup
3997/// to the set of overloading candidates.
3998///
3999/// This routine performs argument-dependent name lookup based on the
4000/// given function name (which may also be an operator name) and adds
4001/// all of the overload candidates found by ADL to the overload
4002/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00004003void
Douglas Gregorfa047642009-02-04 00:32:51 +00004004Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
4005 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00004006 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004007 OverloadCandidateSet& CandidateSet,
4008 bool PartialOverloading) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004009 FunctionSet Functions;
Douglas Gregorfa047642009-02-04 00:32:51 +00004010
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004011 // FIXME: Should we be trafficking in canonical function decls throughout?
4012
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004013 // Record all of the function candidates that we've already
4014 // added to the overload set, so that we don't add those same
4015 // candidates a second time.
4016 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4017 CandEnd = CandidateSet.end();
4018 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00004019 if (Cand->Function) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004020 Functions.insert(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00004021 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4022 Functions.insert(FunTmpl);
4023 }
Douglas Gregorfa047642009-02-04 00:32:51 +00004024
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004025 // FIXME: Pass in the explicit template arguments?
Sebastian Redl644be852009-10-23 19:23:15 +00004026 ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
Douglas Gregorfa047642009-02-04 00:32:51 +00004027
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004028 // Erase all of the candidates we already knew about.
4029 // FIXME: This is suboptimal. Is there a better way?
4030 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4031 CandEnd = CandidateSet.end();
4032 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00004033 if (Cand->Function) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004034 Functions.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00004035 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4036 Functions.erase(FunTmpl);
4037 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004038
4039 // For each of the ADL candidates we found, add it to the overload
4040 // set.
4041 for (FunctionSet::iterator Func = Functions.begin(),
4042 FuncEnd = Functions.end();
Douglas Gregor364e0212009-06-27 21:05:07 +00004043 Func != FuncEnd; ++Func) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004044 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
John McCalld5532b62009-11-23 01:53:49 +00004045 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004046 continue;
4047
4048 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
4049 false, false, PartialOverloading);
4050 } else
Mike Stump1eb44332009-09-09 15:08:12 +00004051 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004052 ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004053 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00004054 }
Douglas Gregorfa047642009-02-04 00:32:51 +00004055}
4056
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004057/// isBetterOverloadCandidate - Determines whether the first overload
4058/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00004059bool
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004060Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump1eb44332009-09-09 15:08:12 +00004061 const OverloadCandidate& Cand2) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004062 // Define viable functions to be better candidates than non-viable
4063 // functions.
4064 if (!Cand2.Viable)
4065 return Cand1.Viable;
4066 else if (!Cand1.Viable)
4067 return false;
4068
Douglas Gregor88a35142008-12-22 05:46:06 +00004069 // C++ [over.match.best]p1:
4070 //
4071 // -- if F is a static member function, ICS1(F) is defined such
4072 // that ICS1(F) is neither better nor worse than ICS1(G) for
4073 // any function G, and, symmetrically, ICS1(G) is neither
4074 // better nor worse than ICS1(F).
4075 unsigned StartArg = 0;
4076 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4077 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004078
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004079 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00004080 // A viable function F1 is defined to be a better function than another
4081 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004082 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004083 unsigned NumArgs = Cand1.Conversions.size();
4084 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4085 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004086 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004087 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4088 Cand2.Conversions[ArgIdx])) {
4089 case ImplicitConversionSequence::Better:
4090 // Cand1 has a better conversion sequence.
4091 HasBetterConversion = true;
4092 break;
4093
4094 case ImplicitConversionSequence::Worse:
4095 // Cand1 can't be better than Cand2.
4096 return false;
4097
4098 case ImplicitConversionSequence::Indistinguishable:
4099 // Do nothing.
4100 break;
4101 }
4102 }
4103
Mike Stump1eb44332009-09-09 15:08:12 +00004104 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004105 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004106 if (HasBetterConversion)
4107 return true;
4108
Mike Stump1eb44332009-09-09 15:08:12 +00004109 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004110 // specialization, or, if not that,
4111 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4112 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4113 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004114
4115 // -- F1 and F2 are function template specializations, and the function
4116 // template for F1 is more specialized than the template for F2
4117 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004118 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00004119 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4120 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004121 if (FunctionTemplateDecl *BetterTemplate
4122 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4123 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor5d7d3752009-09-14 23:02:14 +00004124 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4125 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004126 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004127
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004128 // -- the context is an initialization by user-defined conversion
4129 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4130 // from the return type of F1 to the destination type (i.e.,
4131 // the type of the entity being initialized) is a better
4132 // conversion sequence than the standard conversion sequence
4133 // from the return type of F2 to the destination type.
Mike Stump1eb44332009-09-09 15:08:12 +00004134 if (Cand1.Function && Cand2.Function &&
4135 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004136 isa<CXXConversionDecl>(Cand2.Function)) {
4137 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4138 Cand2.FinalConversion)) {
4139 case ImplicitConversionSequence::Better:
4140 // Cand1 has a better conversion sequence.
4141 return true;
4142
4143 case ImplicitConversionSequence::Worse:
4144 // Cand1 can't be better than Cand2.
4145 return false;
4146
4147 case ImplicitConversionSequence::Indistinguishable:
4148 // Do nothing
4149 break;
4150 }
4151 }
4152
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004153 return false;
4154}
4155
Mike Stump1eb44332009-09-09 15:08:12 +00004156/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00004157/// within an overload candidate set.
4158///
4159/// \param CandidateSet the set of candidate functions.
4160///
4161/// \param Loc the location of the function name (or operator symbol) for
4162/// which overload resolution occurs.
4163///
Mike Stump1eb44332009-09-09 15:08:12 +00004164/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00004165/// function, Best points to the candidate function found.
4166///
4167/// \returns The result of overload resolution.
Mike Stump1eb44332009-09-09 15:08:12 +00004168Sema::OverloadingResult
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004169Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregore0762c92009-06-19 23:52:42 +00004170 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00004171 OverloadCandidateSet::iterator& Best) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004172 // Find the best viable function.
4173 Best = CandidateSet.end();
4174 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4175 Cand != CandidateSet.end(); ++Cand) {
4176 if (Cand->Viable) {
4177 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4178 Best = Cand;
4179 }
4180 }
4181
4182 // If we didn't find any viable functions, abort.
4183 if (Best == CandidateSet.end())
4184 return OR_No_Viable_Function;
4185
4186 // Make sure that this function is better than every other viable
4187 // function. If not, we have an ambiguity.
4188 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4189 Cand != CandidateSet.end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00004190 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004191 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004192 !isBetterOverloadCandidate(*Best, *Cand)) {
4193 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004194 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004195 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004196 }
Mike Stump1eb44332009-09-09 15:08:12 +00004197
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004198 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004199 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00004200 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004201 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004202 return OR_Deleted;
4203
Douglas Gregore0762c92009-06-19 23:52:42 +00004204 // C++ [basic.def.odr]p2:
4205 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00004206 // when referred to from a potentially-evaluated expression. [Note: this
4207 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00004208 // (clause 13), user-defined conversions (12.3.2), allocation function for
4209 // placement new (5.3.4), as well as non-default initialization (8.5).
4210 if (Best->Function)
4211 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004212 return OR_Success;
4213}
4214
4215/// PrintOverloadCandidates - When overload resolution fails, prints
4216/// diagnostic messages containing the candidates in the candidate
4217/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump1eb44332009-09-09 15:08:12 +00004218void
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004219Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Fariborz Jahanian16a5eac2009-10-09 00:13:15 +00004220 bool OnlyViable,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004221 const char *Opc,
Fariborz Jahanian16a5eac2009-10-09 00:13:15 +00004222 SourceLocation OpLoc) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004223 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4224 LastCand = CandidateSet.end();
Fariborz Jahanian27687cf2009-10-12 17:51:19 +00004225 bool Reported = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004226 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004227 if (Cand->Viable || !OnlyViable) {
4228 if (Cand->Function) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004229 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004230 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004231 // Deleted or "unavailable" function.
4232 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
4233 << Cand->Function->isDeleted();
Douglas Gregor1fdd89b2009-09-15 20:11:42 +00004234 } else if (FunctionTemplateDecl *FunTmpl
4235 = Cand->Function->getPrimaryTemplate()) {
4236 // Function template specialization
4237 // FIXME: Give a better reason!
4238 Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
4239 << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
4240 *Cand->Function->getTemplateSpecializationArgs());
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004241 } else {
4242 // Normal function
Fariborz Jahanianb1663d02009-09-23 00:58:07 +00004243 bool errReported = false;
4244 if (!Cand->Viable && Cand->Conversions.size() > 0) {
4245 for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
4246 const ImplicitConversionSequence &Conversion =
4247 Cand->Conversions[i];
4248 if ((Conversion.ConversionKind !=
4249 ImplicitConversionSequence::BadConversion) ||
4250 Conversion.ConversionFunctionSet.size() == 0)
4251 continue;
4252 Diag(Cand->Function->getLocation(),
4253 diag::err_ovl_candidate_not_viable) << (i+1);
4254 errReported = true;
4255 for (int j = Conversion.ConversionFunctionSet.size()-1;
4256 j >= 0; j--) {
4257 FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
4258 Diag(Func->getLocation(), diag::err_ovl_candidate);
4259 }
4260 }
4261 }
4262 if (!errReported)
4263 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004264 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004265 } else if (Cand->IsSurrogate) {
Douglas Gregor621b3932008-11-21 02:54:28 +00004266 // Desugar the type of the surrogate down to a function type,
4267 // retaining as many typedefs as possible while still showing
4268 // the function type (and, therefore, its parameter types).
4269 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004270 bool isLValueReference = false;
4271 bool isRValueReference = false;
Douglas Gregor621b3932008-11-21 02:54:28 +00004272 bool isPointer = false;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004273 if (const LValueReferenceType *FnTypeRef =
Ted Kremenek6217b802009-07-29 21:53:49 +00004274 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor621b3932008-11-21 02:54:28 +00004275 FnType = FnTypeRef->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004276 isLValueReference = true;
4277 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenek6217b802009-07-29 21:53:49 +00004278 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004279 FnType = FnTypeRef->getPointeeType();
4280 isRValueReference = true;
Douglas Gregor621b3932008-11-21 02:54:28 +00004281 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004282 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor621b3932008-11-21 02:54:28 +00004283 FnType = FnTypePtr->getPointeeType();
4284 isPointer = true;
4285 }
4286 // Desugar down to a function type.
John McCall183700f2009-09-21 23:43:11 +00004287 FnType = QualType(FnType->getAs<FunctionType>(), 0);
Douglas Gregor621b3932008-11-21 02:54:28 +00004288 // Reconstruct the pointer/reference as appropriate.
4289 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004290 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
4291 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor621b3932008-11-21 02:54:28 +00004292
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004293 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattnerd1625842008-11-24 06:25:27 +00004294 << FnType;
Douglas Gregor33074752009-09-30 21:46:01 +00004295 } else if (OnlyViable) {
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004296 assert(Cand->Conversions.size() <= 2 &&
Fariborz Jahanianad3607d2009-10-09 17:09:58 +00004297 "builtin-binary-operator-not-binary");
Fariborz Jahanian866b2742009-10-16 23:25:02 +00004298 std::string TypeStr("operator");
4299 TypeStr += Opc;
4300 TypeStr += "(";
4301 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4302 if (Cand->Conversions.size() == 1) {
4303 TypeStr += ")";
4304 Diag(OpLoc, diag::err_ovl_builtin_unary_candidate) << TypeStr;
4305 }
4306 else {
4307 TypeStr += ", ";
4308 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4309 TypeStr += ")";
4310 Diag(OpLoc, diag::err_ovl_builtin_binary_candidate) << TypeStr;
4311 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004312 }
Fariborz Jahanian27687cf2009-10-12 17:51:19 +00004313 else if (!Cand->Viable && !Reported) {
4314 // Non-viability might be due to ambiguous user-defined conversions,
4315 // needed for built-in operators. Report them as well, but only once
4316 // as we have typically many built-in candidates.
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004317 unsigned NoOperands = Cand->Conversions.size();
4318 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
Fariborz Jahanian27687cf2009-10-12 17:51:19 +00004319 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
4320 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion ||
4321 ICS.ConversionFunctionSet.empty())
4322 continue;
4323 if (CXXConversionDecl *Func = dyn_cast<CXXConversionDecl>(
4324 Cand->Conversions[ArgIdx].ConversionFunctionSet[0])) {
4325 QualType FromTy =
4326 QualType(
4327 static_cast<Type*>(ICS.UserDefined.Before.FromTypePtr),0);
4328 Diag(OpLoc,diag::note_ambiguous_type_conversion)
4329 << FromTy << Func->getConversionType();
4330 }
4331 for (unsigned j = 0; j < ICS.ConversionFunctionSet.size(); j++) {
4332 FunctionDecl *Func =
4333 Cand->Conversions[ArgIdx].ConversionFunctionSet[j];
4334 Diag(Func->getLocation(),diag::err_ovl_candidate);
4335 }
4336 }
4337 Reported = true;
4338 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004339 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004340 }
4341}
4342
Douglas Gregor904eed32008-11-10 20:40:00 +00004343/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4344/// an overloaded function (C++ [over.over]), where @p From is an
4345/// expression with overloaded function type and @p ToType is the type
4346/// we're trying to resolve to. For example:
4347///
4348/// @code
4349/// int f(double);
4350/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00004351///
Douglas Gregor904eed32008-11-10 20:40:00 +00004352/// int (*pfd)(double) = f; // selects f(double)
4353/// @endcode
4354///
4355/// This routine returns the resulting FunctionDecl if it could be
4356/// resolved, and NULL otherwise. When @p Complain is true, this
4357/// routine will emit diagnostics if there is an error.
4358FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00004359Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor904eed32008-11-10 20:40:00 +00004360 bool Complain) {
4361 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00004362 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00004363 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00004364 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004365 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00004366 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00004367 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00004368 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00004369 FunctionType = MemTypePtr->getPointeeType();
4370 IsMember = true;
4371 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004372
4373 // We only look at pointers or references to functions.
Douglas Gregor72e771f2009-07-09 17:16:51 +00004374 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor83314aa2009-07-08 20:55:45 +00004375 if (!FunctionType->isFunctionType())
Douglas Gregor904eed32008-11-10 20:40:00 +00004376 return 0;
4377
4378 // Find the actual overloaded function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00004379
Douglas Gregor904eed32008-11-10 20:40:00 +00004380 // C++ [over.over]p1:
4381 // [...] [Note: any redundant set of parentheses surrounding the
4382 // overloaded function name is ignored (5.1). ]
4383 Expr *OvlExpr = From->IgnoreParens();
4384
4385 // C++ [over.over]p1:
4386 // [...] The overloaded function name can be preceded by the &
4387 // operator.
4388 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4389 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4390 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4391 }
4392
Anders Carlsson70534852009-10-20 22:53:47 +00004393 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00004394 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCallba135432009-11-21 08:51:07 +00004395
4396 llvm::SmallVector<NamedDecl*,8> Fns;
Anders Carlsson70534852009-10-20 22:53:47 +00004397
John McCall129e2df2009-11-30 22:42:35 +00004398 // Look into the overloaded expression.
John McCallf7a1a742009-11-24 19:00:30 +00004399 if (UnresolvedLookupExpr *UL
John McCallba135432009-11-21 08:51:07 +00004400 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4401 Fns.append(UL->decls_begin(), UL->decls_end());
John McCallf7a1a742009-11-24 19:00:30 +00004402 if (UL->hasExplicitTemplateArgs()) {
4403 HasExplicitTemplateArgs = true;
4404 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4405 }
John McCall129e2df2009-11-30 22:42:35 +00004406 } else if (UnresolvedMemberExpr *ME
4407 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4408 Fns.append(ME->decls_begin(), ME->decls_end());
4409 if (ME->hasExplicitTemplateArgs()) {
4410 HasExplicitTemplateArgs = true;
John McCalld5532b62009-11-23 01:53:49 +00004411 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004412 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00004413 }
Mike Stump1eb44332009-09-09 15:08:12 +00004414
John McCallba135432009-11-21 08:51:07 +00004415 // If we didn't actually find anything, we're done.
4416 if (Fns.empty())
4417 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004418
Douglas Gregor904eed32008-11-10 20:40:00 +00004419 // Look through all of the overloaded functions, searching for one
4420 // whose type matches exactly.
Douglas Gregor00aeb522009-07-08 23:33:52 +00004421 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004422 bool FoundNonTemplateFunction = false;
John McCallba135432009-11-21 08:51:07 +00004423 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4424 E = Fns.end(); I != E; ++I) {
Douglas Gregor904eed32008-11-10 20:40:00 +00004425 // C++ [over.over]p3:
4426 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00004427 // targets of type "pointer-to-function" or "reference-to-function."
4428 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00004429 // type "pointer-to-member-function."
4430 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00004431
Mike Stump1eb44332009-09-09 15:08:12 +00004432 if (FunctionTemplateDecl *FunctionTemplate
John McCallba135432009-11-21 08:51:07 +00004433 = dyn_cast<FunctionTemplateDecl>(*I)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004434 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00004435 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004436 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00004437 // static when converting to member pointer.
4438 if (Method->isStatic() == IsMember)
4439 continue;
4440 } else if (IsMember)
4441 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00004442
Douglas Gregor00aeb522009-07-08 23:33:52 +00004443 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004444 // If the name is a function template, template argument deduction is
4445 // done (14.8.2.2), and if the argument deduction succeeds, the
4446 // resulting template argument list is used to generate a single
4447 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00004448 // overloaded functions considered.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004449 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor83314aa2009-07-08 20:55:45 +00004450 FunctionDecl *Specialization = 0;
4451 TemplateDeductionInfo Info(Context);
4452 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00004453 = DeduceTemplateArguments(FunctionTemplate,
4454 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
Douglas Gregor83314aa2009-07-08 20:55:45 +00004455 FunctionType, Specialization, Info)) {
4456 // FIXME: make a note of the failed deduction for diagnostics.
4457 (void)Result;
4458 } else {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004459 // FIXME: If the match isn't exact, shouldn't we just drop this as
4460 // a candidate? Find a testcase before changing the code.
Mike Stump1eb44332009-09-09 15:08:12 +00004461 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00004462 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor00aeb522009-07-08 23:33:52 +00004463 Matches.insert(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00004464 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor83314aa2009-07-08 20:55:45 +00004465 }
John McCallba135432009-11-21 08:51:07 +00004466
4467 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00004468 }
Mike Stump1eb44332009-09-09 15:08:12 +00004469
John McCallba135432009-11-21 08:51:07 +00004470 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00004471 // Skip non-static functions when converting to pointer, and static
4472 // when converting to member pointer.
4473 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00004474 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00004475
4476 // If we have explicit template arguments, skip non-templates.
4477 if (HasExplicitTemplateArgs)
4478 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004479 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00004480 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00004481
John McCallba135432009-11-21 08:51:07 +00004482 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*I)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00004483 QualType ResultTy;
4484 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
4485 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
4486 ResultTy)) {
John McCallba135432009-11-21 08:51:07 +00004487 Matches.insert(cast<FunctionDecl>(FunDecl->getCanonicalDecl()));
Douglas Gregor00aeb522009-07-08 23:33:52 +00004488 FoundNonTemplateFunction = true;
4489 }
Mike Stump1eb44332009-09-09 15:08:12 +00004490 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004491 }
4492
Douglas Gregor00aeb522009-07-08 23:33:52 +00004493 // If there were 0 or 1 matches, we're done.
4494 if (Matches.empty())
4495 return 0;
Sebastian Redl07ab2022009-10-17 21:12:09 +00004496 else if (Matches.size() == 1) {
4497 FunctionDecl *Result = *Matches.begin();
4498 MarkDeclarationReferenced(From->getLocStart(), Result);
4499 return Result;
4500 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00004501
4502 // C++ [over.over]p4:
4503 // If more than one function is selected, [...]
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004504 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregor312a2022009-09-26 03:56:17 +00004505 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004506 // [...] and any given function template specialization F1 is
4507 // eliminated if the set contains a second function template
4508 // specialization whose function template is more specialized
4509 // than the function template of F1 according to the partial
4510 // ordering rules of 14.5.5.2.
4511
4512 // The algorithm specified above is quadratic. We instead use a
4513 // two-pass algorithm (similar to the one used to identify the
4514 // best viable function in an overload set) that identifies the
4515 // best function template (if it exists).
Sebastian Redl07ab2022009-10-17 21:12:09 +00004516 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
Douglas Gregor312a2022009-09-26 03:56:17 +00004517 Matches.end());
Sebastian Redl07ab2022009-10-17 21:12:09 +00004518 FunctionDecl *Result =
4519 getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4520 TPOC_Other, From->getLocStart(),
4521 PDiag(),
4522 PDiag(diag::err_addr_ovl_ambiguous)
4523 << TemplateMatches[0]->getDeclName(),
4524 PDiag(diag::err_ovl_template_candidate));
4525 MarkDeclarationReferenced(From->getLocStart(), Result);
4526 return Result;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004527 }
Mike Stump1eb44332009-09-09 15:08:12 +00004528
Douglas Gregor312a2022009-09-26 03:56:17 +00004529 // [...] any function template specializations in the set are
4530 // eliminated if the set also contains a non-template function, [...]
4531 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4532 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4533 if ((*M)->getPrimaryTemplate() == 0)
4534 RemainingMatches.push_back(*M);
4535
Mike Stump1eb44332009-09-09 15:08:12 +00004536 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00004537 // selected function.
Sebastian Redl07ab2022009-10-17 21:12:09 +00004538 if (RemainingMatches.size() == 1) {
4539 FunctionDecl *Result = RemainingMatches.front();
4540 MarkDeclarationReferenced(From->getLocStart(), Result);
4541 return Result;
4542 }
Mike Stump1eb44332009-09-09 15:08:12 +00004543
Douglas Gregor00aeb522009-07-08 23:33:52 +00004544 // FIXME: We should probably return the same thing that BestViableFunction
4545 // returns (even if we issue the diagnostics here).
4546 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4547 << RemainingMatches[0]->getDeclName();
4548 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4549 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregor904eed32008-11-10 20:40:00 +00004550 return 0;
4551}
4552
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004553/// \brief Add a single candidate to the overload set.
4554static void AddOverloadedCallCandidate(Sema &S,
John McCallba135432009-11-21 08:51:07 +00004555 NamedDecl *Callee,
John McCalld5532b62009-11-23 01:53:49 +00004556 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004557 Expr **Args, unsigned NumArgs,
4558 OverloadCandidateSet &CandidateSet,
4559 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00004560 if (isa<UsingShadowDecl>(Callee))
4561 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
4562
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004563 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00004564 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004565 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4566 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004567 return;
John McCallba135432009-11-21 08:51:07 +00004568 }
4569
4570 if (FunctionTemplateDecl *FuncTemplate
4571 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00004572 S.AddTemplateOverloadCandidate(FuncTemplate, ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00004573 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00004574 return;
4575 }
4576
4577 assert(false && "unhandled case in overloaded call candidate");
4578
4579 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004580}
4581
4582/// \brief Add the overload candidates named by callee and/or found by argument
4583/// dependent lookup to the given overload set.
John McCallba135432009-11-21 08:51:07 +00004584void Sema::AddOverloadedCallCandidates(llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004585 DeclarationName &UnqualifiedName,
John McCalld2ede7d2009-11-21 09:38:42 +00004586 bool ArgumentDependentLookup,
John McCalld5532b62009-11-23 01:53:49 +00004587 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004588 Expr **Args, unsigned NumArgs,
4589 OverloadCandidateSet &CandidateSet,
4590 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00004591
4592#ifndef NDEBUG
4593 // Verify that ArgumentDependentLookup is consistent with the rules
4594 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004595 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004596 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4597 // and let Y be the lookup set produced by argument dependent
4598 // lookup (defined as follows). If X contains
4599 //
4600 // -- a declaration of a class member, or
4601 //
4602 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00004603 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004604 //
4605 // -- a declaration that is neither a function or a function
4606 // template
4607 //
4608 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00004609
4610 if (ArgumentDependentLookup) {
4611 for (unsigned I = 0; I < Fns.size(); ++I) {
4612 assert(!Fns[I]->getDeclContext()->isRecord());
4613 assert(isa<UsingShadowDecl>(Fns[I]) ||
4614 !Fns[I]->getDeclContext()->isFunctionOrMethod());
4615 assert(Fns[I]->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
4616 }
4617 }
4618#endif
4619
4620 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4621 E = Fns.end(); I != E; ++I)
John McCalld5532b62009-11-23 01:53:49 +00004622 AddOverloadedCallCandidate(*this, *I, ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00004623 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004624 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00004625
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004626 if (ArgumentDependentLookup)
4627 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004628 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004629 CandidateSet,
4630 PartialOverloading);
4631}
4632
Douglas Gregorf6b89692008-11-26 05:54:23 +00004633/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00004634/// (which eventually refers to the declaration Func) and the call
4635/// arguments Args/NumArgs, attempt to resolve the function call down
4636/// to a specific function. If overload resolution succeeds, returns
4637/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00004638/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00004639/// arguments and Fn, and returns NULL.
John McCallba135432009-11-21 08:51:07 +00004640FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn,
4641 llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregor17330012009-02-04 15:01:18 +00004642 DeclarationName UnqualifiedName,
John McCalld5532b62009-11-23 01:53:49 +00004643 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor0a396682008-11-26 06:01:48 +00004644 SourceLocation LParenLoc,
4645 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00004646 SourceLocation *CommaLocs,
Douglas Gregorfa047642009-02-04 00:32:51 +00004647 SourceLocation RParenLoc,
John McCalld2ede7d2009-11-21 09:38:42 +00004648 bool ArgumentDependentLookup) {
Douglas Gregorf6b89692008-11-26 05:54:23 +00004649 OverloadCandidateSet CandidateSet;
Douglas Gregor17330012009-02-04 15:01:18 +00004650
4651 // Add the functions denoted by Callee to the set of candidate
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004652 // functions.
John McCallba135432009-11-21 08:51:07 +00004653 AddOverloadedCallCandidates(Fns, UnqualifiedName, ArgumentDependentLookup,
John McCalld5532b62009-11-23 01:53:49 +00004654 ExplicitTemplateArgs, Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004655 CandidateSet);
Douglas Gregorf6b89692008-11-26 05:54:23 +00004656 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004657 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregor0a396682008-11-26 06:01:48 +00004658 case OR_Success:
4659 return Best->Function;
Douglas Gregorf6b89692008-11-26 05:54:23 +00004660
4661 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00004662 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00004663 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00004664 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00004665 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4666 break;
4667
4668 case OR_Ambiguous:
4669 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor17330012009-02-04 15:01:18 +00004670 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00004671 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4672 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004673
4674 case OR_Deleted:
4675 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4676 << Best->Function->isDeleted()
4677 << UnqualifiedName
4678 << Fn->getSourceRange();
4679 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4680 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00004681 }
4682
4683 // Overload resolution failed. Destroy all of the subexpressions and
4684 // return NULL.
4685 Fn->Destroy(Context);
4686 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4687 Args[Arg]->Destroy(Context);
4688 return 0;
4689}
4690
John McCall7453ed42009-11-22 00:44:51 +00004691static bool IsOverloaded(const Sema::FunctionSet &Functions) {
4692 return Functions.size() > 1 ||
4693 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
4694}
4695
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004696/// \brief Create a unary operation that may resolve to an overloaded
4697/// operator.
4698///
4699/// \param OpLoc The location of the operator itself (e.g., '*').
4700///
4701/// \param OpcIn The UnaryOperator::Opcode that describes this
4702/// operator.
4703///
4704/// \param Functions The set of non-member functions that will be
4705/// considered by overload resolution. The caller needs to build this
4706/// set based on the context using, e.g.,
4707/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4708/// set should not contain any member functions; those will be added
4709/// by CreateOverloadedUnaryOp().
4710///
4711/// \param input The input argument.
4712Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4713 unsigned OpcIn,
4714 FunctionSet &Functions,
Mike Stump1eb44332009-09-09 15:08:12 +00004715 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004716 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4717 Expr *Input = (Expr *)input.get();
4718
4719 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4720 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4721 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4722
4723 Expr *Args[2] = { Input, 0 };
4724 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004725
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004726 // For post-increment and post-decrement, add the implicit '0' as
4727 // the second argument, so that we know this is a post-increment or
4728 // post-decrement.
4729 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4730 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump1eb44332009-09-09 15:08:12 +00004731 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004732 SourceLocation());
4733 NumArgs = 2;
4734 }
4735
4736 if (Input->isTypeDependent()) {
John McCallba135432009-11-21 08:51:07 +00004737 UnresolvedLookupExpr *Fn
John McCallf7a1a742009-11-24 19:00:30 +00004738 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
4739 0, SourceRange(), OpName, OpLoc,
John McCall7453ed42009-11-22 00:44:51 +00004740 /*ADL*/ true, IsOverloaded(Functions));
Mike Stump1eb44332009-09-09 15:08:12 +00004741 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004742 FuncEnd = Functions.end();
4743 Func != FuncEnd; ++Func)
John McCallba135432009-11-21 08:51:07 +00004744 Fn->addDecl(*Func);
Mike Stump1eb44332009-09-09 15:08:12 +00004745
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004746 input.release();
4747 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4748 &Args[0], NumArgs,
4749 Context.DependentTy,
4750 OpLoc));
4751 }
4752
4753 // Build an empty overload set.
4754 OverloadCandidateSet CandidateSet;
4755
4756 // Add the candidates from the given function set.
4757 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4758
4759 // Add operator candidates that are member functions.
4760 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4761
4762 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00004763 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004764
4765 // Perform overload resolution.
4766 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004767 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004768 case OR_Success: {
4769 // We found a built-in operator or an overloaded operator.
4770 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00004771
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004772 if (FnDecl) {
4773 // We matched an overloaded operator. Build a call to that
4774 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00004775
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004776 // Convert the arguments.
4777 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4778 if (PerformObjectArgumentInitialization(Input, Method))
4779 return ExprError();
4780 } else {
4781 // Convert the arguments.
4782 if (PerformCopyInitialization(Input,
4783 FnDecl->getParamDecl(0)->getType(),
4784 "passing"))
4785 return ExprError();
4786 }
4787
4788 // Determine the result type
Anders Carlsson26a2a072009-10-13 21:19:37 +00004789 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00004790
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004791 // Build the actual expression node.
4792 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4793 SourceLocation());
4794 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004795
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004796 input.release();
Eli Friedman4c3b8962009-11-18 03:58:17 +00004797 Args[0] = Input;
Anders Carlsson26a2a072009-10-13 21:19:37 +00004798 ExprOwningPtr<CallExpr> TheCall(this,
4799 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman4c3b8962009-11-18 03:58:17 +00004800 Args, NumArgs, ResultTy, OpLoc));
Anders Carlsson26a2a072009-10-13 21:19:37 +00004801
4802 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4803 FnDecl))
4804 return ExprError();
4805
4806 return MaybeBindToTemporary(TheCall.release());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004807 } else {
4808 // We matched a built-in operator. Convert the arguments, then
4809 // break out so that we will build the appropriate built-in
4810 // operator node.
4811 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4812 Best->Conversions[0], "passing"))
4813 return ExprError();
4814
4815 break;
4816 }
4817 }
4818
4819 case OR_No_Viable_Function:
4820 // No viable function; fall through to handling this as a
4821 // built-in operator, which will produce an error message for us.
4822 break;
4823
4824 case OR_Ambiguous:
4825 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4826 << UnaryOperator::getOpcodeStr(Opc)
4827 << Input->getSourceRange();
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004828 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4829 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004830 return ExprError();
4831
4832 case OR_Deleted:
4833 Diag(OpLoc, diag::err_ovl_deleted_oper)
4834 << Best->Function->isDeleted()
4835 << UnaryOperator::getOpcodeStr(Opc)
4836 << Input->getSourceRange();
4837 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4838 return ExprError();
4839 }
4840
4841 // Either we found no viable overloaded operator or we matched a
4842 // built-in operator. In either case, fall through to trying to
4843 // build a built-in operation.
4844 input.release();
4845 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4846}
4847
Douglas Gregor063daf62009-03-13 18:40:31 +00004848/// \brief Create a binary operation that may resolve to an overloaded
4849/// operator.
4850///
4851/// \param OpLoc The location of the operator itself (e.g., '+').
4852///
4853/// \param OpcIn The BinaryOperator::Opcode that describes this
4854/// operator.
4855///
4856/// \param Functions The set of non-member functions that will be
4857/// considered by overload resolution. The caller needs to build this
4858/// set based on the context using, e.g.,
4859/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4860/// set should not contain any member functions; those will be added
4861/// by CreateOverloadedBinOp().
4862///
4863/// \param LHS Left-hand argument.
4864/// \param RHS Right-hand argument.
Mike Stump1eb44332009-09-09 15:08:12 +00004865Sema::OwningExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00004866Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004867 unsigned OpcIn,
Douglas Gregor063daf62009-03-13 18:40:31 +00004868 FunctionSet &Functions,
4869 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00004870 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004871 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00004872
4873 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4874 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4875 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4876
4877 // If either side is type-dependent, create an appropriate dependent
4878 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004879 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00004880 if (Functions.empty()) {
4881 // If there are no functions to store, just build a dependent
4882 // BinaryOperator or CompoundAssignment.
4883 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
4884 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
4885 Context.DependentTy, OpLoc));
4886
4887 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
4888 Context.DependentTy,
4889 Context.DependentTy,
4890 Context.DependentTy,
4891 OpLoc));
4892 }
4893
John McCallba135432009-11-21 08:51:07 +00004894 UnresolvedLookupExpr *Fn
John McCallf7a1a742009-11-24 19:00:30 +00004895 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
4896 0, SourceRange(), OpName, OpLoc,
John McCall7453ed42009-11-22 00:44:51 +00004897 /* ADL */ true, IsOverloaded(Functions));
John McCallba135432009-11-21 08:51:07 +00004898
Mike Stump1eb44332009-09-09 15:08:12 +00004899 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004900 FuncEnd = Functions.end();
4901 Func != FuncEnd; ++Func)
John McCallba135432009-11-21 08:51:07 +00004902 Fn->addDecl(*Func);
Mike Stump1eb44332009-09-09 15:08:12 +00004903
Douglas Gregor063daf62009-03-13 18:40:31 +00004904 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00004905 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00004906 Context.DependentTy,
4907 OpLoc));
4908 }
4909
4910 // If this is the .* operator, which is not overloadable, just
4911 // create a built-in binary operator.
4912 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004913 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00004914
Sebastian Redl275c2b42009-11-18 23:10:33 +00004915 // If this is the assignment operator, we only perform overload resolution
4916 // if the left-hand side is a class or enumeration type. This is actually
4917 // a hack. The standard requires that we do overload resolution between the
4918 // various built-in candidates, but as DR507 points out, this can lead to
4919 // problems. So we do it this way, which pretty much follows what GCC does.
4920 // Note that we go the traditional code path for compound assignment forms.
4921 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004922 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00004923
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004924 // Build an empty overload set.
4925 OverloadCandidateSet CandidateSet;
Douglas Gregor063daf62009-03-13 18:40:31 +00004926
4927 // Add the candidates from the given function set.
4928 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4929
4930 // Add operator candidates that are member functions.
4931 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4932
4933 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00004934 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00004935
4936 // Perform overload resolution.
4937 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004938 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004939 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00004940 // We found a built-in operator or an overloaded operator.
4941 FunctionDecl *FnDecl = Best->Function;
4942
4943 if (FnDecl) {
4944 // We matched an overloaded operator. Build a call to that
4945 // operator.
4946
4947 // Convert the arguments.
4948 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004949 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4950 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004951 "passing"))
4952 return ExprError();
4953 } else {
4954 // Convert the arguments.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004955 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004956 "passing") ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004957 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004958 "passing"))
4959 return ExprError();
4960 }
4961
4962 // Determine the result type
4963 QualType ResultTy
John McCall183700f2009-09-21 23:43:11 +00004964 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor063daf62009-03-13 18:40:31 +00004965 ResultTy = ResultTy.getNonReferenceType();
4966
4967 // Build the actual expression node.
4968 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00004969 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00004970 UsualUnaryConversions(FnExpr);
4971
Anders Carlsson15ea3782009-10-13 22:43:21 +00004972 ExprOwningPtr<CXXOperatorCallExpr>
4973 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4974 Args, 2, ResultTy,
4975 OpLoc));
4976
4977 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4978 FnDecl))
4979 return ExprError();
4980
4981 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor063daf62009-03-13 18:40:31 +00004982 } else {
4983 // We matched a built-in operator. Convert the arguments, then
4984 // break out so that we will build the appropriate built-in
4985 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004986 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor063daf62009-03-13 18:40:31 +00004987 Best->Conversions[0], "passing") ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004988 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor063daf62009-03-13 18:40:31 +00004989 Best->Conversions[1], "passing"))
4990 return ExprError();
4991
4992 break;
4993 }
4994 }
4995
Douglas Gregor33074752009-09-30 21:46:01 +00004996 case OR_No_Viable_Function: {
4997 // C++ [over.match.oper]p9:
4998 // If the operator is the operator , [...] and there are no
4999 // viable functions, then the operator is assumed to be the
5000 // built-in operator and interpreted according to clause 5.
5001 if (Opc == BinaryOperator::Comma)
5002 break;
5003
Sebastian Redl8593c782009-05-21 11:50:50 +00005004 // For class as left operand for assignment or compound assigment operator
5005 // do not fall through to handling in built-in, but report that no overloaded
5006 // assignment operator found
Douglas Gregor33074752009-09-30 21:46:01 +00005007 OwningExprResult Result = ExprError();
5008 if (Args[0]->getType()->isRecordType() &&
5009 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00005010 Diag(OpLoc, diag::err_ovl_no_viable_oper)
5011 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005012 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00005013 } else {
5014 // No viable function; try to create a built-in operation, which will
5015 // produce an error. Then, show the non-viable candidates.
5016 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00005017 }
Douglas Gregor33074752009-09-30 21:46:01 +00005018 assert(Result.isInvalid() &&
5019 "C++ binary operator overloading is missing candidates!");
5020 if (Result.isInvalid())
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005021 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5022 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00005023 return move(Result);
5024 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005025
5026 case OR_Ambiguous:
5027 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5028 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005029 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005030 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5031 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00005032 return ExprError();
5033
5034 case OR_Deleted:
5035 Diag(OpLoc, diag::err_ovl_deleted_oper)
5036 << Best->Function->isDeleted()
5037 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005038 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor063daf62009-03-13 18:40:31 +00005039 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5040 return ExprError();
5041 }
5042
Douglas Gregor33074752009-09-30 21:46:01 +00005043 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005044 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00005045}
5046
Sebastian Redlf322ed62009-10-29 20:17:01 +00005047Action::OwningExprResult
5048Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5049 SourceLocation RLoc,
5050 ExprArg Base, ExprArg Idx) {
5051 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5052 static_cast<Expr*>(Idx.get()) };
5053 DeclarationName OpName =
5054 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5055
5056 // If either side is type-dependent, create an appropriate dependent
5057 // expression.
5058 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5059
John McCallba135432009-11-21 08:51:07 +00005060 UnresolvedLookupExpr *Fn
John McCallf7a1a742009-11-24 19:00:30 +00005061 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5062 0, SourceRange(), OpName, LLoc,
John McCall7453ed42009-11-22 00:44:51 +00005063 /*ADL*/ true, /*Overloaded*/ false);
John McCallf7a1a742009-11-24 19:00:30 +00005064 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00005065
5066 Base.release();
5067 Idx.release();
5068 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5069 Args, 2,
5070 Context.DependentTy,
5071 RLoc));
5072 }
5073
5074 // Build an empty overload set.
5075 OverloadCandidateSet CandidateSet;
5076
5077 // Subscript can only be overloaded as a member function.
5078
5079 // Add operator candidates that are member functions.
5080 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5081
5082 // Add builtin operator candidates.
5083 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5084
5085 // Perform overload resolution.
5086 OverloadCandidateSet::iterator Best;
5087 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5088 case OR_Success: {
5089 // We found a built-in operator or an overloaded operator.
5090 FunctionDecl *FnDecl = Best->Function;
5091
5092 if (FnDecl) {
5093 // We matched an overloaded operator. Build a call to that
5094 // operator.
5095
5096 // Convert the arguments.
5097 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5098 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5099 PerformCopyInitialization(Args[1],
5100 FnDecl->getParamDecl(0)->getType(),
5101 "passing"))
5102 return ExprError();
5103
5104 // Determine the result type
5105 QualType ResultTy
5106 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5107 ResultTy = ResultTy.getNonReferenceType();
5108
5109 // Build the actual expression node.
5110 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5111 LLoc);
5112 UsualUnaryConversions(FnExpr);
5113
5114 Base.release();
5115 Idx.release();
5116 ExprOwningPtr<CXXOperatorCallExpr>
5117 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5118 FnExpr, Args, 2,
5119 ResultTy, RLoc));
5120
5121 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5122 FnDecl))
5123 return ExprError();
5124
5125 return MaybeBindToTemporary(TheCall.release());
5126 } else {
5127 // We matched a built-in operator. Convert the arguments, then
5128 // break out so that we will build the appropriate built-in
5129 // operator node.
5130 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
5131 Best->Conversions[0], "passing") ||
5132 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
5133 Best->Conversions[1], "passing"))
5134 return ExprError();
5135
5136 break;
5137 }
5138 }
5139
5140 case OR_No_Viable_Function: {
5141 // No viable function; try to create a built-in operation, which will
5142 // produce an error. Then, show the non-viable candidates.
5143 OwningExprResult Result =
5144 CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
5145 assert(Result.isInvalid() &&
5146 "C++ subscript operator overloading is missing candidates!");
5147 if (Result.isInvalid())
5148 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5149 "[]", LLoc);
5150 return move(Result);
5151 }
5152
5153 case OR_Ambiguous:
5154 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5155 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5156 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5157 "[]", LLoc);
5158 return ExprError();
5159
5160 case OR_Deleted:
5161 Diag(LLoc, diag::err_ovl_deleted_oper)
5162 << Best->Function->isDeleted() << "[]"
5163 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5164 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5165 return ExprError();
5166 }
5167
5168 // We matched a built-in operator; build it.
5169 Base.release();
5170 Idx.release();
5171 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5172 Owned(Args[1]), RLoc);
5173}
5174
Douglas Gregor88a35142008-12-22 05:46:06 +00005175/// BuildCallToMemberFunction - Build a call to a member
5176/// function. MemExpr is the expression that refers to the member
5177/// function (and includes the object parameter), Args/NumArgs are the
5178/// arguments to the function call (not including the object
5179/// parameter). The caller needs to validate that the member
5180/// expression refers to a member function or an overloaded member
5181/// function.
John McCallaa81e162009-12-01 22:10:20 +00005182Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00005183Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5184 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor88a35142008-12-22 05:46:06 +00005185 unsigned NumArgs, SourceLocation *CommaLocs,
5186 SourceLocation RParenLoc) {
5187 // Dig out the member expression. This holds both the object
5188 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00005189 Expr *NakedMemExpr = MemExprE->IgnoreParens();
5190
John McCall129e2df2009-11-30 22:42:35 +00005191 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00005192 CXXMethodDecl *Method = 0;
John McCall129e2df2009-11-30 22:42:35 +00005193 if (isa<MemberExpr>(NakedMemExpr)) {
5194 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00005195 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5196 } else {
5197 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
John McCallaa81e162009-12-01 22:10:20 +00005198
John McCall701c89e2009-12-03 04:06:58 +00005199 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00005200
Douglas Gregor88a35142008-12-22 05:46:06 +00005201 // Add overload candidates
5202 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00005203
John McCallaa81e162009-12-01 22:10:20 +00005204 // FIXME: avoid copy.
5205 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5206 if (UnresExpr->hasExplicitTemplateArgs()) {
5207 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5208 TemplateArgs = &TemplateArgsBuffer;
5209 }
5210
John McCall129e2df2009-11-30 22:42:35 +00005211 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
5212 E = UnresExpr->decls_end(); I != E; ++I) {
5213
John McCall701c89e2009-12-03 04:06:58 +00005214 NamedDecl *Func = *I;
5215 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
5216 if (isa<UsingShadowDecl>(Func))
5217 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
5218
John McCall129e2df2009-11-30 22:42:35 +00005219 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005220 // If explicit template arguments were provided, we can't call a
5221 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00005222 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005223 continue;
5224
John McCall701c89e2009-12-03 04:06:58 +00005225 AddMethodCandidate(Method, ActingDC, ObjectType, Args, NumArgs,
5226 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00005227 } else {
John McCall129e2df2009-11-30 22:42:35 +00005228 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall701c89e2009-12-03 04:06:58 +00005229 ActingDC, TemplateArgs,
5230 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00005231 CandidateSet,
5232 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00005233 }
Douglas Gregordec06662009-08-21 18:42:58 +00005234 }
Mike Stump1eb44332009-09-09 15:08:12 +00005235
John McCall129e2df2009-11-30 22:42:35 +00005236 DeclarationName DeclName = UnresExpr->getMemberName();
5237
Douglas Gregor88a35142008-12-22 05:46:06 +00005238 OverloadCandidateSet::iterator Best;
John McCall129e2df2009-11-30 22:42:35 +00005239 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005240 case OR_Success:
5241 Method = cast<CXXMethodDecl>(Best->Function);
5242 break;
5243
5244 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00005245 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00005246 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00005247 << DeclName << MemExprE->getSourceRange();
Douglas Gregor88a35142008-12-22 05:46:06 +00005248 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5249 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00005250 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00005251
5252 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00005253 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00005254 << DeclName << MemExprE->getSourceRange();
Douglas Gregor88a35142008-12-22 05:46:06 +00005255 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5256 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00005257 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005258
5259 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00005260 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005261 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00005262 << DeclName << MemExprE->getSourceRange();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005263 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5264 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00005265 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00005266 }
5267
Douglas Gregor699ee522009-11-20 19:42:02 +00005268 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
John McCallaa81e162009-12-01 22:10:20 +00005269
John McCallaa81e162009-12-01 22:10:20 +00005270 // If overload resolution picked a static member, build a
5271 // non-member call based on that function.
5272 if (Method->isStatic()) {
5273 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
5274 Args, NumArgs, RParenLoc);
5275 }
5276
John McCall129e2df2009-11-30 22:42:35 +00005277 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00005278 }
5279
5280 assert(Method && "Member call to something that isn't a method?");
Mike Stump1eb44332009-09-09 15:08:12 +00005281 ExprOwningPtr<CXXMemberCallExpr>
John McCallaa81e162009-12-01 22:10:20 +00005282 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump1eb44332009-09-09 15:08:12 +00005283 NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00005284 Method->getResultType().getNonReferenceType(),
5285 RParenLoc));
5286
Anders Carlssoneed3e692009-10-10 00:06:20 +00005287 // Check for a valid return type.
5288 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5289 TheCall.get(), Method))
John McCallaa81e162009-12-01 22:10:20 +00005290 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00005291
Douglas Gregor88a35142008-12-22 05:46:06 +00005292 // Convert the object argument (for a non-static member function call).
John McCallaa81e162009-12-01 22:10:20 +00005293 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00005294 if (!Method->isStatic() &&
Douglas Gregor88a35142008-12-22 05:46:06 +00005295 PerformObjectArgumentInitialization(ObjectArg, Method))
John McCallaa81e162009-12-01 22:10:20 +00005296 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00005297 MemExpr->setBase(ObjectArg);
5298
5299 // Convert the rest of the arguments
Douglas Gregor72564e72009-02-26 23:50:07 +00005300 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00005301 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00005302 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00005303 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00005304
Anders Carlssond406bf02009-08-16 01:56:34 +00005305 if (CheckFunctionCall(Method, TheCall.get()))
John McCallaa81e162009-12-01 22:10:20 +00005306 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00005307
John McCallaa81e162009-12-01 22:10:20 +00005308 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor88a35142008-12-22 05:46:06 +00005309}
5310
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005311/// BuildCallToObjectOfClassType - Build a call to an object of class
5312/// type (C++ [over.call.object]), which can end up invoking an
5313/// overloaded function call operator (@c operator()) or performing a
5314/// user-defined conversion on the object argument.
Mike Stump1eb44332009-09-09 15:08:12 +00005315Sema::ExprResult
5316Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00005317 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005318 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00005319 SourceLocation *CommaLocs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005320 SourceLocation RParenLoc) {
5321 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00005322 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005323
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005324 // C++ [over.call.object]p1:
5325 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00005326 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005327 // candidate functions includes at least the function call
5328 // operators of T. The function call operators of T are obtained by
5329 // ordinary lookup of the name operator() in the context of
5330 // (E).operator().
5331 OverloadCandidateSet CandidateSet;
Douglas Gregor44b43212008-12-11 16:49:14 +00005332 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00005333
5334 if (RequireCompleteType(LParenLoc, Object->getType(),
5335 PartialDiagnostic(diag::err_incomplete_object_call)
5336 << Object->getSourceRange()))
5337 return true;
5338
John McCalla24dc2e2009-11-17 02:14:36 +00005339 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
5340 LookupQualifiedName(R, Record->getDecl());
5341 R.suppressDiagnostics();
5342
Douglas Gregor593564b2009-11-15 07:48:03 +00005343 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00005344 Oper != OperEnd; ++Oper) {
John McCall701c89e2009-12-03 04:06:58 +00005345 AddMethodCandidate(*Oper, Object->getType(), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00005346 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00005347 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00005348
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005349 // C++ [over.call.object]p2:
5350 // In addition, for each conversion function declared in T of the
5351 // form
5352 //
5353 // operator conversion-type-id () cv-qualifier;
5354 //
5355 // where cv-qualifier is the same cv-qualification as, or a
5356 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00005357 // denotes the type "pointer to function of (P1,...,Pn) returning
5358 // R", or the type "reference to pointer to function of
5359 // (P1,...,Pn) returning R", or the type "reference to function
5360 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005361 // is also considered as a candidate function. Similarly,
5362 // surrogate call functions are added to the set of candidate
5363 // functions for each conversion function declared in an
5364 // accessible base class provided the function is not hidden
5365 // within T by another intervening declaration.
Douglas Gregor4a27d702009-10-21 06:18:39 +00005366 // FIXME: Look in base classes for more conversion operators!
John McCallba135432009-11-21 08:51:07 +00005367 const UnresolvedSet *Conversions
Douglas Gregor4a27d702009-10-21 06:18:39 +00005368 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
John McCallba135432009-11-21 08:51:07 +00005369 for (UnresolvedSet::iterator I = Conversions->begin(),
5370 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00005371 NamedDecl *D = *I;
5372 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5373 if (isa<UsingShadowDecl>(D))
5374 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5375
Douglas Gregor4a27d702009-10-21 06:18:39 +00005376 // Skip over templated conversion functions; they aren't
5377 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00005378 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00005379 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005380
John McCall701c89e2009-12-03 04:06:58 +00005381 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00005382
Douglas Gregor4a27d702009-10-21 06:18:39 +00005383 // Strip the reference type (if any) and then the pointer type (if
5384 // any) to get down to what might be a function type.
5385 QualType ConvType = Conv->getConversionType().getNonReferenceType();
5386 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5387 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005388
Douglas Gregor4a27d702009-10-21 06:18:39 +00005389 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall701c89e2009-12-03 04:06:58 +00005390 AddSurrogateCandidate(Conv, ActingContext, Proto,
5391 Object->getType(), Args, NumArgs,
5392 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005393 }
Mike Stump1eb44332009-09-09 15:08:12 +00005394
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005395 // Perform overload resolution.
5396 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005397 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005398 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005399 // Overload resolution succeeded; we'll build the appropriate call
5400 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005401 break;
5402
5403 case OR_No_Viable_Function:
Mike Stump1eb44332009-09-09 15:08:12 +00005404 Diag(Object->getSourceRange().getBegin(),
Sebastian Redle4c452c2008-11-22 13:44:36 +00005405 diag::err_ovl_no_viable_object_call)
Chris Lattner4330d652009-02-17 07:29:20 +00005406 << Object->getType() << Object->getSourceRange();
Sebastian Redle4c452c2008-11-22 13:44:36 +00005407 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005408 break;
5409
5410 case OR_Ambiguous:
5411 Diag(Object->getSourceRange().getBegin(),
5412 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00005413 << Object->getType() << Object->getSourceRange();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005414 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5415 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005416
5417 case OR_Deleted:
5418 Diag(Object->getSourceRange().getBegin(),
5419 diag::err_ovl_deleted_object_call)
5420 << Best->Function->isDeleted()
5421 << Object->getType() << Object->getSourceRange();
5422 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5423 break;
Mike Stump1eb44332009-09-09 15:08:12 +00005424 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005425
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005426 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005427 // We had an error; delete all of the subexpressions and return
5428 // the error.
Ted Kremenek8189cde2009-02-07 01:47:29 +00005429 Object->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005430 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek8189cde2009-02-07 01:47:29 +00005431 Args[ArgIdx]->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005432 return true;
5433 }
5434
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005435 if (Best->Function == 0) {
5436 // Since there is no function declaration, this is one of the
5437 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00005438 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005439 = cast<CXXConversionDecl>(
5440 Best->Conversions[0].UserDefined.ConversionFunction);
5441
5442 // We selected one of the surrogate functions that converts the
5443 // object parameter to a function pointer. Perform the conversion
5444 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00005445
5446 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00005447 // and then call it.
Eli Friedmanc8c771e2009-12-09 04:52:43 +00005448 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00005449
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00005450 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00005451 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
5452 CommaLocs, RParenLoc).release();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005453 }
5454
5455 // We found an overloaded operator(). Build a CXXOperatorCallExpr
5456 // that calls this method, using Object for the implicit object
5457 // parameter and passing along the remaining arguments.
5458 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00005459 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005460
5461 unsigned NumArgsInProto = Proto->getNumArgs();
5462 unsigned NumArgsToCheck = NumArgs;
5463
5464 // Build the full argument list for the method call (the
5465 // implicit object parameter is placed at the beginning of the
5466 // list).
5467 Expr **MethodArgs;
5468 if (NumArgs < NumArgsInProto) {
5469 NumArgsToCheck = NumArgsInProto;
5470 MethodArgs = new Expr*[NumArgsInProto + 1];
5471 } else {
5472 MethodArgs = new Expr*[NumArgs + 1];
5473 }
5474 MethodArgs[0] = Object;
5475 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5476 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00005477
5478 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00005479 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005480 UsualUnaryConversions(NewFn);
5481
5482 // Once we've built TheCall, all of the expressions are properly
5483 // owned.
5484 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00005485 ExprOwningPtr<CXXOperatorCallExpr>
5486 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor063daf62009-03-13 18:40:31 +00005487 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00005488 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005489 delete [] MethodArgs;
5490
Anders Carlsson07d68f12009-10-13 21:49:31 +00005491 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
5492 Method))
5493 return true;
5494
Douglas Gregor518fda12009-01-13 05:10:00 +00005495 // We may have default arguments. If so, we need to allocate more
5496 // slots in the call for them.
5497 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00005498 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00005499 else if (NumArgs > NumArgsInProto)
5500 NumArgsToCheck = NumArgsInProto;
5501
Chris Lattner312531a2009-04-12 08:11:20 +00005502 bool IsError = false;
5503
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005504 // Initialize the implicit object parameter.
Chris Lattner312531a2009-04-12 08:11:20 +00005505 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005506 TheCall->setArg(0, Object);
5507
Chris Lattner312531a2009-04-12 08:11:20 +00005508
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005509 // Check the argument types.
5510 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005511 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00005512 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005513 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00005514
Douglas Gregor518fda12009-01-13 05:10:00 +00005515 // Pass the argument.
5516 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner312531a2009-04-12 08:11:20 +00005517 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor518fda12009-01-13 05:10:00 +00005518 } else {
Douglas Gregord47c47d2009-11-09 19:27:57 +00005519 OwningExprResult DefArg
5520 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
5521 if (DefArg.isInvalid()) {
5522 IsError = true;
5523 break;
5524 }
5525
5526 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00005527 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005528
5529 TheCall->setArg(i + 1, Arg);
5530 }
5531
5532 // If this is a variadic call, handle args passed through "...".
5533 if (Proto->isVariadic()) {
5534 // Promote the arguments (C99 6.5.2.2p7).
5535 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
5536 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00005537 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005538 TheCall->setArg(i + 1, Arg);
5539 }
5540 }
5541
Chris Lattner312531a2009-04-12 08:11:20 +00005542 if (IsError) return true;
5543
Anders Carlssond406bf02009-08-16 01:56:34 +00005544 if (CheckFunctionCall(Method, TheCall.get()))
5545 return true;
5546
Anders Carlssona303f9e2009-08-16 03:53:54 +00005547 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005548}
5549
Douglas Gregor8ba10742008-11-20 16:27:02 +00005550/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00005551/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00005552/// @c Member is the name of the member we're trying to find.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005553Sema::OwningExprResult
5554Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
5555 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor8ba10742008-11-20 16:27:02 +00005556 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00005557
Douglas Gregor8ba10742008-11-20 16:27:02 +00005558 // C++ [over.ref]p1:
5559 //
5560 // [...] An expression x->m is interpreted as (x.operator->())->m
5561 // for a class object x of type T if T::operator->() exists and if
5562 // the operator is selected as the best match function by the
5563 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00005564 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
5565 OverloadCandidateSet CandidateSet;
Ted Kremenek6217b802009-07-29 21:53:49 +00005566 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005567
Eli Friedmanf43fb722009-11-18 01:28:03 +00005568 if (RequireCompleteType(Base->getLocStart(), Base->getType(),
5569 PDiag(diag::err_typecheck_incomplete_tag)
5570 << Base->getSourceRange()))
5571 return ExprError();
5572
John McCalla24dc2e2009-11-17 02:14:36 +00005573 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
5574 LookupQualifiedName(R, BaseRecord->getDecl());
5575 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00005576
5577 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00005578 Oper != OperEnd; ++Oper) {
5579 NamedDecl *D = *Oper;
5580 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5581 if (isa<UsingShadowDecl>(D))
5582 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5583
5584 AddMethodCandidate(cast<CXXMethodDecl>(D), ActingContext,
5585 Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00005586 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00005587 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00005588
5589 // Perform overload resolution.
5590 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005591 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00005592 case OR_Success:
5593 // Overload resolution succeeded; we'll build the call below.
5594 break;
5595
5596 case OR_No_Viable_Function:
5597 if (CandidateSet.empty())
5598 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005599 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005600 else
5601 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005602 << "operator->" << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005603 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005604 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005605
5606 case OR_Ambiguous:
5607 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00005608 << "->" << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005609 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005610 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005611
5612 case OR_Deleted:
5613 Diag(OpLoc, diag::err_ovl_deleted_oper)
5614 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00005615 << "->" << Base->getSourceRange();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005616 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005617 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005618 }
5619
5620 // Convert the object parameter.
5621 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00005622 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005623 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00005624
5625 // No concerns about early exits now.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005626 BaseIn.release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005627
5628 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00005629 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5630 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00005631 UsualUnaryConversions(FnExpr);
Anders Carlsson15ea3782009-10-13 22:43:21 +00005632
5633 QualType ResultTy = Method->getResultType().getNonReferenceType();
5634 ExprOwningPtr<CXXOperatorCallExpr>
5635 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
5636 &Base, 1, ResultTy, OpLoc));
5637
5638 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
5639 Method))
5640 return ExprError();
5641 return move(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00005642}
5643
Douglas Gregor904eed32008-11-10 20:40:00 +00005644/// FixOverloadedFunctionReference - E is an expression that refers to
5645/// a C++ overloaded function (possibly with some parentheses and
5646/// perhaps a '&' around it). We have resolved the overloaded function
5647/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00005648/// refer (possibly indirectly) to Fn. Returns the new expr.
5649Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005650 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor699ee522009-11-20 19:42:02 +00005651 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
5652 if (SubExpr == PE->getSubExpr())
5653 return PE->Retain();
5654
5655 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
5656 }
5657
5658 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5659 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00005660 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00005661 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00005662 "Implicit cast type cannot be determined from overload");
Douglas Gregor699ee522009-11-20 19:42:02 +00005663 if (SubExpr == ICE->getSubExpr())
5664 return ICE->Retain();
5665
5666 return new (Context) ImplicitCastExpr(ICE->getType(),
5667 ICE->getCastKind(),
5668 SubExpr,
5669 ICE->isLvalueCast());
5670 }
5671
5672 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump1eb44332009-09-09 15:08:12 +00005673 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00005674 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00005675 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5676 if (Method->isStatic()) {
5677 // Do nothing: static member functions aren't any different
5678 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00005679 } else {
John McCallf7a1a742009-11-24 19:00:30 +00005680 // Fix the sub expression, which really has to be an
5681 // UnresolvedLookupExpr holding an overloaded member function
5682 // or template.
John McCallba135432009-11-21 08:51:07 +00005683 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5684 if (SubExpr == UnOp->getSubExpr())
5685 return UnOp->Retain();
Douglas Gregor699ee522009-11-20 19:42:02 +00005686
John McCallba135432009-11-21 08:51:07 +00005687 assert(isa<DeclRefExpr>(SubExpr)
5688 && "fixed to something other than a decl ref");
5689 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
5690 && "fixed to a member ref with no nested name qualifier");
5691
5692 // We have taken the address of a pointer to member
5693 // function. Perform the computation here so that we get the
5694 // appropriate pointer to member type.
5695 QualType ClassType
5696 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
5697 QualType MemPtrType
5698 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
5699
5700 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
5701 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00005702 }
5703 }
Douglas Gregor699ee522009-11-20 19:42:02 +00005704 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5705 if (SubExpr == UnOp->getSubExpr())
5706 return UnOp->Retain();
Anders Carlsson96ad5332009-10-21 17:16:23 +00005707
Douglas Gregor699ee522009-11-20 19:42:02 +00005708 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
5709 Context.getPointerType(SubExpr->getType()),
5710 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00005711 }
John McCallba135432009-11-21 08:51:07 +00005712
5713 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00005714 // FIXME: avoid copy.
5715 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00005716 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00005717 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
5718 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00005719 }
5720
John McCallba135432009-11-21 08:51:07 +00005721 return DeclRefExpr::Create(Context,
5722 ULE->getQualifier(),
5723 ULE->getQualifierRange(),
5724 Fn,
5725 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00005726 Fn->getType(),
5727 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00005728 }
5729
John McCall129e2df2009-11-30 22:42:35 +00005730 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00005731 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00005732 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5733 if (MemExpr->hasExplicitTemplateArgs()) {
5734 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5735 TemplateArgs = &TemplateArgsBuffer;
5736 }
John McCalld5532b62009-11-23 01:53:49 +00005737
John McCallaa81e162009-12-01 22:10:20 +00005738 Expr *Base;
5739
5740 // If we're filling in
5741 if (MemExpr->isImplicitAccess()) {
5742 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
5743 return DeclRefExpr::Create(Context,
5744 MemExpr->getQualifier(),
5745 MemExpr->getQualifierRange(),
5746 Fn,
5747 MemExpr->getMemberLoc(),
5748 Fn->getType(),
5749 TemplateArgs);
5750 } else
5751 Base = new (Context) CXXThisExpr(SourceLocation(),
5752 MemExpr->getBaseType());
5753 } else
5754 Base = MemExpr->getBase()->Retain();
5755
5756 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00005757 MemExpr->isArrow(),
5758 MemExpr->getQualifier(),
5759 MemExpr->getQualifierRange(),
5760 Fn,
John McCalld5532b62009-11-23 01:53:49 +00005761 MemExpr->getMemberLoc(),
John McCallaa81e162009-12-01 22:10:20 +00005762 TemplateArgs,
Douglas Gregor699ee522009-11-20 19:42:02 +00005763 Fn->getType());
5764 }
5765
Douglas Gregor699ee522009-11-20 19:42:02 +00005766 assert(false && "Invalid reference to overloaded function");
5767 return E->Retain();
Douglas Gregor904eed32008-11-10 20:40:00 +00005768}
5769
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005770} // end namespace clang