blob: 561cfdb52e0bcf429aa021c1233683beb1360a5f [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
Douglas Gregor01919692009-12-13 21:37:05 +0000178 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
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
John McCall9f54ad42009-12-10 09:41:52 +0000290Sema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
291 NamedDecl *&Match) {
John McCall51fa86f2009-12-02 08:47:38 +0000292 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000293 I != E; ++I) {
John McCall51fa86f2009-12-02 08:47:38 +0000294 NamedDecl *OldD = (*I)->getUnderlyingDecl();
295 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCall68263142009-11-18 22:49:29 +0000296 if (!IsOverload(New, OldT->getTemplatedDecl())) {
John McCall871b2e72009-12-09 03:35:25 +0000297 Match = *I;
298 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000299 }
John McCall51fa86f2009-12-02 08:47:38 +0000300 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCall68263142009-11-18 22:49:29 +0000301 if (!IsOverload(New, OldF)) {
John McCall871b2e72009-12-09 03:35:25 +0000302 Match = *I;
303 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000304 }
John McCall9f54ad42009-12-10 09:41:52 +0000305 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
306 // We can overload with these, which can show up when doing
307 // redeclaration checks for UsingDecls.
308 assert(Old.getLookupKind() == LookupUsingDeclName);
309 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
310 // Optimistically assume that an unresolved using decl will
311 // overload; if it doesn't, we'll have to diagnose during
312 // template instantiation.
313 } else {
John McCall68263142009-11-18 22:49:29 +0000314 // (C++ 13p1):
315 // Only function declarations can be overloaded; object and type
316 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000317 Match = *I;
318 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000319 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000320 }
John McCall68263142009-11-18 22:49:29 +0000321
John McCall871b2e72009-12-09 03:35:25 +0000322 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000323}
324
325bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
326 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
327 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
328
329 // C++ [temp.fct]p2:
330 // A function template can be overloaded with other function templates
331 // and with normal (non-template) functions.
332 if ((OldTemplate == 0) != (NewTemplate == 0))
333 return true;
334
335 // Is the function New an overload of the function Old?
336 QualType OldQType = Context.getCanonicalType(Old->getType());
337 QualType NewQType = Context.getCanonicalType(New->getType());
338
339 // Compare the signatures (C++ 1.3.10) of the two functions to
340 // determine whether they are overloads. If we find any mismatch
341 // in the signature, they are overloads.
342
343 // If either of these functions is a K&R-style function (no
344 // prototype), then we consider them to have matching signatures.
345 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
346 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
347 return false;
348
349 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
350 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
351
352 // The signature of a function includes the types of its
353 // parameters (C++ 1.3.10), which includes the presence or absence
354 // of the ellipsis; see C++ DR 357).
355 if (OldQType != NewQType &&
356 (OldType->getNumArgs() != NewType->getNumArgs() ||
357 OldType->isVariadic() != NewType->isVariadic() ||
358 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
359 NewType->arg_type_begin())))
360 return true;
361
362 // C++ [temp.over.link]p4:
363 // The signature of a function template consists of its function
364 // signature, its return type and its template parameter list. The names
365 // of the template parameters are significant only for establishing the
366 // relationship between the template parameters and the rest of the
367 // signature.
368 //
369 // We check the return type and template parameter lists for function
370 // templates first; the remaining checks follow.
371 if (NewTemplate &&
372 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
373 OldTemplate->getTemplateParameters(),
374 false, TPL_TemplateMatch) ||
375 OldType->getResultType() != NewType->getResultType()))
376 return true;
377
378 // If the function is a class member, its signature includes the
379 // cv-qualifiers (if any) on the function itself.
380 //
381 // As part of this, also check whether one of the member functions
382 // is static, in which case they are not overloads (C++
383 // 13.1p2). While not part of the definition of the signature,
384 // this check is important to determine whether these functions
385 // can be overloaded.
386 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
387 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
388 if (OldMethod && NewMethod &&
389 !OldMethod->isStatic() && !NewMethod->isStatic() &&
390 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
391 return true;
392
393 // The signatures match; this is not an overload.
394 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000395}
396
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000397/// TryImplicitConversion - Attempt to perform an implicit conversion
398/// from the given expression (Expr) to the given type (ToType). This
399/// function returns an implicit conversion sequence that can be used
400/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000401///
402/// void f(float f);
403/// void g(int i) { f(i); }
404///
405/// this routine would produce an implicit conversion sequence to
406/// describe the initialization of f from i, which will be a standard
407/// conversion sequence containing an lvalue-to-rvalue conversion (C++
408/// 4.1) followed by a floating-integral conversion (C++ 4.9).
409//
410/// Note that this routine only determines how the conversion can be
411/// performed; it does not actually perform the conversion. As such,
412/// it will not produce any diagnostics if no conversion is available,
413/// but will instead return an implicit conversion sequence of kind
414/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000415///
416/// If @p SuppressUserConversions, then user-defined conversions are
417/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000418/// If @p AllowExplicit, then explicit user-defined conversions are
419/// permitted.
Sebastian Redle2b68332009-04-12 17:16:29 +0000420/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
421/// no matter its actual lvalueness.
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000422/// If @p UserCast, the implicit conversion is being done for a user-specified
423/// cast.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000424ImplicitConversionSequence
Anders Carlsson2974b5c2009-08-27 17:14:02 +0000425Sema::TryImplicitConversion(Expr* From, QualType ToType,
426 bool SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +0000427 bool AllowExplicit, bool ForceRValue,
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000428 bool InOverloadResolution,
429 bool UserCast) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000430 ImplicitConversionSequence ICS;
Fariborz Jahanian78cf9a22009-09-15 00:10:11 +0000431 OverloadCandidateSet Conversions;
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000432 OverloadingResult UserDefResult = OR_Success;
Anders Carlsson08972922009-08-28 15:33:32 +0000433 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
Douglas Gregor60d62c22008-10-31 16:23:19 +0000434 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000435 else if (getLangOptions().CPlusPlus &&
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000436 (UserDefResult = IsUserDefinedConversion(From, ToType,
437 ICS.UserDefined,
Fariborz Jahanian78cf9a22009-09-15 00:10:11 +0000438 Conversions,
Sebastian Redle2b68332009-04-12 17:16:29 +0000439 !SuppressUserConversions, AllowExplicit,
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000440 ForceRValue, UserCast)) == OR_Success) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000441 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000442 // C++ [over.ics.user]p4:
443 // A conversion of an expression of class type to the same class
444 // type is given Exact Match rank, and a conversion of an
445 // expression of class type to a base class of that type is
446 // given Conversion rank, in spite of the fact that a copy
447 // constructor (i.e., a user-defined conversion function) is
448 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000449 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000450 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000451 QualType FromCanon
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000452 = Context.getCanonicalType(From->getType().getUnqualifiedType());
453 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
454 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000455 // Turn this into a "standard" conversion sequence, so that it
456 // gets ranked with standard conversion sequences.
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000457 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
458 ICS.Standard.setAsIdentityConversion();
459 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
460 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000461 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000462 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000463 ICS.Standard.Second = ICK_Derived_To_Base;
464 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000465 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000466
467 // C++ [over.best.ics]p4:
468 // However, when considering the argument of a user-defined
469 // conversion function that is a candidate by 13.3.1.3 when
470 // invoked for the copying of the temporary in the second step
471 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
472 // 13.3.1.6 in all cases, only standard conversion sequences and
473 // ellipsis conversion sequences are allowed.
474 if (SuppressUserConversions &&
475 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
476 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000477 } else {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000478 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000479 if (UserDefResult == OR_Ambiguous) {
480 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
481 Cand != Conversions.end(); ++Cand)
Fariborz Jahanian27687cf2009-10-12 17:51:19 +0000482 if (Cand->Viable)
483 ICS.ConversionFunctionSet.push_back(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000484 }
485 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000486
487 return ICS;
488}
489
Douglas Gregor43c79c22009-12-09 00:47:37 +0000490/// \brief Determine whether the conversion from FromType to ToType is a valid
491/// conversion that strips "noreturn" off the nested function type.
492static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
493 QualType ToType, QualType &ResultTy) {
494 if (Context.hasSameUnqualifiedType(FromType, ToType))
495 return false;
496
497 // Strip the noreturn off the type we're converting from; noreturn can
498 // safely be removed.
499 FromType = Context.getNoReturnType(FromType, false);
500 if (!Context.hasSameUnqualifiedType(FromType, ToType))
501 return false;
502
503 ResultTy = FromType;
504 return true;
505}
506
Douglas Gregor60d62c22008-10-31 16:23:19 +0000507/// IsStandardConversion - Determines whether there is a standard
508/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
509/// expression From to the type ToType. Standard conversion sequences
510/// only consider non-class types; for conversions that involve class
511/// types, use TryImplicitConversion. If a conversion exists, SCS will
512/// contain the standard conversion sequence required to perform this
513/// conversion and this routine will return true. Otherwise, this
514/// routine will return false and the value of SCS is unspecified.
Mike Stump1eb44332009-09-09 15:08:12 +0000515bool
516Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000517 bool InOverloadResolution,
Mike Stump1eb44332009-09-09 15:08:12 +0000518 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000519 QualType FromType = From->getType();
520
Douglas Gregor60d62c22008-10-31 16:23:19 +0000521 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000522 SCS.setAsIdentityConversion();
Douglas Gregor60d62c22008-10-31 16:23:19 +0000523 SCS.Deprecated = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000524 SCS.IncompatibleObjC = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000525 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000526 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000527
Douglas Gregorf9201e02009-02-11 23:02:49 +0000528 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000529 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000530 if (FromType->isRecordType() || ToType->isRecordType()) {
531 if (getLangOptions().CPlusPlus)
532 return false;
533
Mike Stump1eb44332009-09-09 15:08:12 +0000534 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000535 }
536
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000537 // The first conversion can be an lvalue-to-rvalue conversion,
538 // array-to-pointer conversion, or function-to-pointer conversion
539 // (C++ 4p1).
540
Mike Stump1eb44332009-09-09 15:08:12 +0000541 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000542 // An lvalue (3.10) of a non-function, non-array type T can be
543 // converted to an rvalue.
544 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000545 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000546 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor063daf62009-03-13 18:40:31 +0000547 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000548 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000549
550 // If T is a non-class type, the type of the rvalue is the
551 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +0000552 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
553 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000554 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000555 } else if (FromType->isArrayType()) {
556 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000557 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000558
559 // An lvalue or rvalue of type "array of N T" or "array of unknown
560 // bound of T" can be converted to an rvalue of type "pointer to
561 // T" (C++ 4.2p1).
562 FromType = Context.getArrayDecayedType(FromType);
563
564 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
565 // This conversion is deprecated. (C++ D.4).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000566 SCS.Deprecated = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000567
568 // For the purpose of ranking in overload resolution
569 // (13.3.3.1.1), this conversion is considered an
570 // array-to-pointer conversion followed by a qualification
571 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000572 SCS.Second = ICK_Identity;
573 SCS.Third = ICK_Qualification;
574 SCS.ToTypePtr = ToType.getAsOpaquePtr();
575 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000576 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000577 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
578 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000579 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000580
581 // An lvalue of function type T can be converted to an rvalue of
582 // type "pointer to T." The result is a pointer to the
583 // function. (C++ 4.3p1).
584 FromType = Context.getPointerType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000585 } else if (FunctionDecl *Fn
Douglas Gregor43c79c22009-12-09 00:47:37 +0000586 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000587 // Address of overloaded function (C++ [over.over]).
Douglas Gregor904eed32008-11-10 20:40:00 +0000588 SCS.First = ICK_Function_To_Pointer;
589
590 // We were able to resolve the address of the overloaded function,
591 // so we can convert to the type of that function.
592 FromType = Fn->getType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000593 if (ToType->isLValueReferenceType())
594 FromType = Context.getLValueReferenceType(FromType);
595 else if (ToType->isRValueReferenceType())
596 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl33b399a2009-02-04 21:23:32 +0000597 else if (ToType->isMemberPointerType()) {
598 // Resolve address only succeeds if both sides are member pointers,
599 // but it doesn't have to be the same class. See DR 247.
600 // Note that this means that the type of &Derived::fn can be
601 // Ret (Base::*)(Args) if the fn overload actually found is from the
602 // base class, even if it was brought into the derived class via a
603 // using declaration. The standard isn't clear on this issue at all.
604 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
605 FromType = Context.getMemberPointerType(FromType,
606 Context.getTypeDeclType(M->getParent()).getTypePtr());
607 } else
Douglas Gregor904eed32008-11-10 20:40:00 +0000608 FromType = Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000609 } else {
610 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000611 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000612 }
613
614 // The second conversion can be an integral promotion, floating
615 // point promotion, integral conversion, floating point conversion,
616 // floating-integral conversion, pointer conversion,
617 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +0000618 // For overloading in C, this can also be a "compatible-type"
619 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +0000620 bool IncompatibleObjC = false;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000621 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000622 // The unqualified versions of the types are the same: there's no
623 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000624 SCS.Second = ICK_Identity;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000625 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000626 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000627 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000628 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000629 } else if (IsFloatingPointPromotion(FromType, ToType)) {
630 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000631 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000632 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000633 } else if (IsComplexPromotion(FromType, ToType)) {
634 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000635 SCS.Second = ICK_Complex_Promotion;
636 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000637 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000638 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000639 // Integral conversions (C++ 4.7).
640 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000641 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000642 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000643 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
644 // Floating point conversions (C++ 4.8).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000645 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000646 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000647 } else if (FromType->isComplexType() && ToType->isComplexType()) {
648 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000649 SCS.Second = ICK_Complex_Conversion;
650 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000651 } else if ((FromType->isFloatingType() &&
652 ToType->isIntegralType() && (!ToType->isBooleanType() &&
653 !ToType->isEnumeralType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000654 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000655 ToType->isFloatingType())) {
656 // Floating-integral conversions (C++ 4.9).
657 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000658 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000659 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000660 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
661 (ToType->isComplexType() && FromType->isArithmeticType())) {
662 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000663 SCS.Second = ICK_Complex_Real;
664 FromType = ToType.getUnqualifiedType();
Anders Carlsson08972922009-08-28 15:33:32 +0000665 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
666 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000667 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000668 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000669 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregorce940492009-09-25 04:25:58 +0000670 } else if (IsMemberPointerConversion(From, FromType, ToType,
671 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000672 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000673 SCS.Second = ICK_Pointer_Member;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000674 } else if (ToType->isBooleanType() &&
675 (FromType->isArithmeticType() ||
676 FromType->isEnumeralType() ||
Fariborz Jahanian1f7711d2009-12-11 21:23:13 +0000677 FromType->isAnyPointerType() ||
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000678 FromType->isBlockPointerType() ||
679 FromType->isMemberPointerType() ||
680 FromType->isNullPtrType())) {
681 // Boolean conversions (C++ 4.12).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000682 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000683 FromType = Context.BoolTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000684 } else if (!getLangOptions().CPlusPlus &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000685 Context.typesAreCompatible(ToType, FromType)) {
686 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000687 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor43c79c22009-12-09 00:47:37 +0000688 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
689 // Treat a conversion that strips "noreturn" as an identity conversion.
690 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000691 } else {
692 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000693 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000694 }
695
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000696 QualType CanonFrom;
697 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000698 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000699 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000700 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000701 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000702 CanonFrom = Context.getCanonicalType(FromType);
703 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000704 } else {
705 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000706 SCS.Third = ICK_Identity;
707
Mike Stump1eb44332009-09-09 15:08:12 +0000708 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +0000709 // [...] Any difference in top-level cv-qualification is
710 // subsumed by the initialization itself and does not constitute
711 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000712 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000713 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregora4923eb2009-11-16 21:35:15 +0000714 if (CanonFrom.getLocalUnqualifiedType()
715 == CanonTo.getLocalUnqualifiedType() &&
716 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000717 FromType = ToType;
718 CanonFrom = CanonTo;
719 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000720 }
721
722 // If we have not converted the argument type to the parameter type,
723 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000724 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000725 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000726
Douglas Gregor60d62c22008-10-31 16:23:19 +0000727 SCS.ToTypePtr = FromType.getAsOpaquePtr();
728 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000729}
730
731/// IsIntegralPromotion - Determines whether the conversion from the
732/// expression From (whose potentially-adjusted type is FromType) to
733/// ToType is an integral promotion (C++ 4.5). If so, returns true and
734/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000735bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +0000736 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000737 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000738 if (!To) {
739 return false;
740 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000741
742 // An rvalue of type char, signed char, unsigned char, short int, or
743 // unsigned short int can be converted to an rvalue of type int if
744 // int can represent all the values of the source type; otherwise,
745 // the source rvalue can be converted to an rvalue of type unsigned
746 // int (C++ 4.5p1).
Sebastian Redl07779722008-10-31 14:43:28 +0000747 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000748 if (// We can promote any signed, promotable integer type to an int
749 (FromType->isSignedIntegerType() ||
750 // We can promote any unsigned integer type whose size is
751 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +0000752 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000753 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000754 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000755 }
756
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000757 return To->getKind() == BuiltinType::UInt;
758 }
759
760 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
761 // can be converted to an rvalue of the first of the following types
762 // that can represent all the values of its underlying type: int,
763 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall842aef82009-12-09 09:09:27 +0000764
765 // We pre-calculate the promotion type for enum types.
766 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
767 if (ToType->isIntegerType())
768 return Context.hasSameUnqualifiedType(ToType,
769 FromEnumType->getDecl()->getPromotionType());
770
771 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000772 // Determine whether the type we're converting from is signed or
773 // unsigned.
774 bool FromIsSigned;
775 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall842aef82009-12-09 09:09:27 +0000776
777 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
778 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000779
780 // The types we'll try to promote to, in the appropriate
781 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +0000782 QualType PromoteTypes[6] = {
783 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000784 Context.LongTy, Context.UnsignedLongTy ,
785 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000786 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000787 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000788 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
789 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +0000790 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000791 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
792 // We found the type that we can promote to. If this is the
793 // type we wanted, we have a promotion. Otherwise, no
794 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000795 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000796 }
797 }
798 }
799
800 // An rvalue for an integral bit-field (9.6) can be converted to an
801 // rvalue of type int if int can represent all the values of the
802 // bit-field; otherwise, it can be converted to unsigned int if
803 // unsigned int can represent all the values of the bit-field. If
804 // the bit-field is larger yet, no integral promotion applies to
805 // it. If the bit-field has an enumerated type, it is treated as any
806 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +0000807 // FIXME: We should delay checking of bit-fields until we actually perform the
808 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000809 using llvm::APSInt;
810 if (From)
811 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +0000812 APSInt BitWidth;
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000813 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
814 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
815 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
816 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Douglas Gregor86f19402008-12-20 23:49:58 +0000818 // Are we promoting to an int from a bitfield that fits in an int?
819 if (BitWidth < ToSize ||
820 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
821 return To->getKind() == BuiltinType::Int;
822 }
Mike Stump1eb44332009-09-09 15:08:12 +0000823
Douglas Gregor86f19402008-12-20 23:49:58 +0000824 // Are we promoting to an unsigned int from an unsigned bitfield
825 // that fits into an unsigned int?
826 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
827 return To->getKind() == BuiltinType::UInt;
828 }
Mike Stump1eb44332009-09-09 15:08:12 +0000829
Douglas Gregor86f19402008-12-20 23:49:58 +0000830 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000831 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000832 }
Mike Stump1eb44332009-09-09 15:08:12 +0000833
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000834 // An rvalue of type bool can be converted to an rvalue of type int,
835 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000836 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000837 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000838 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000839
840 return false;
841}
842
843/// IsFloatingPointPromotion - Determines whether the conversion from
844/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
845/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000846bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000847 /// An rvalue of type float can be converted to an rvalue of type
848 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +0000849 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
850 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000851 if (FromBuiltin->getKind() == BuiltinType::Float &&
852 ToBuiltin->getKind() == BuiltinType::Double)
853 return true;
854
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000855 // C99 6.3.1.5p1:
856 // When a float is promoted to double or long double, or a
857 // double is promoted to long double [...].
858 if (!getLangOptions().CPlusPlus &&
859 (FromBuiltin->getKind() == BuiltinType::Float ||
860 FromBuiltin->getKind() == BuiltinType::Double) &&
861 (ToBuiltin->getKind() == BuiltinType::LongDouble))
862 return true;
863 }
864
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000865 return false;
866}
867
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000868/// \brief Determine if a conversion is a complex promotion.
869///
870/// A complex promotion is defined as a complex -> complex conversion
871/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000872/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000873bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +0000874 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000875 if (!FromComplex)
876 return false;
877
John McCall183700f2009-09-21 23:43:11 +0000878 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000879 if (!ToComplex)
880 return false;
881
882 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000883 ToComplex->getElementType()) ||
884 IsIntegralPromotion(0, FromComplex->getElementType(),
885 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000886}
887
Douglas Gregorcb7de522008-11-26 23:31:11 +0000888/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
889/// the pointer type FromPtr to a pointer to type ToPointee, with the
890/// same type qualifiers as FromPtr has on its pointee type. ToType,
891/// if non-empty, will be a pointer to ToType that may or may not have
892/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +0000893static QualType
894BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000895 QualType ToPointee, QualType ToType,
896 ASTContext &Context) {
897 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
898 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +0000899 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +0000900
901 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000902 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +0000903 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +0000904 if (!ToType.isNull())
Douglas Gregorcb7de522008-11-26 23:31:11 +0000905 return ToType;
906
907 // Build a pointer to ToPointee. It has the right qualifiers
908 // already.
909 return Context.getPointerType(ToPointee);
910 }
911
912 // Just build a canonical type that has the right qualifiers.
John McCall0953e762009-09-24 19:53:00 +0000913 return Context.getPointerType(
Douglas Gregora4923eb2009-11-16 21:35:15 +0000914 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
915 Quals));
Douglas Gregorcb7de522008-11-26 23:31:11 +0000916}
917
Mike Stump1eb44332009-09-09 15:08:12 +0000918static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000919 bool InOverloadResolution,
920 ASTContext &Context) {
921 // Handle value-dependent integral null pointer constants correctly.
922 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
923 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
924 Expr->getType()->isIntegralType())
925 return !InOverloadResolution;
926
Douglas Gregorce940492009-09-25 04:25:58 +0000927 return Expr->isNullPointerConstant(Context,
928 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
929 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000930}
Mike Stump1eb44332009-09-09 15:08:12 +0000931
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000932/// IsPointerConversion - Determines whether the conversion of the
933/// expression From, which has the (possibly adjusted) type FromType,
934/// can be converted to the type ToType via a pointer conversion (C++
935/// 4.10). If so, returns true and places the converted type (that
936/// might differ from ToType in its cv-qualifiers at some level) into
937/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000938///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000939/// This routine also supports conversions to and from block pointers
940/// and conversions with Objective-C's 'id', 'id<protocols...>', and
941/// pointers to interfaces. FIXME: Once we've determined the
942/// appropriate overloading rules for Objective-C, we may want to
943/// split the Objective-C checks into a different routine; however,
944/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000945/// conversions, so for now they live here. IncompatibleObjC will be
946/// set if the conversion is an allowed Objective-C conversion that
947/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000948bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000949 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +0000950 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +0000951 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +0000952 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +0000953 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
954 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +0000955
Mike Stump1eb44332009-09-09 15:08:12 +0000956 // Conversion from a null pointer constant to any Objective-C pointer type.
957 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000958 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +0000959 ConvertedType = ToType;
960 return true;
961 }
962
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000963 // Blocks: Block pointers can be converted to void*.
964 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000965 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000966 ConvertedType = ToType;
967 return true;
968 }
969 // Blocks: A null pointer constant can be converted to a block
970 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +0000971 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000972 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000973 ConvertedType = ToType;
974 return true;
975 }
976
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000977 // If the left-hand-side is nullptr_t, the right side can be a null
978 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +0000979 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000980 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000981 ConvertedType = ToType;
982 return true;
983 }
984
Ted Kremenek6217b802009-07-29 21:53:49 +0000985 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000986 if (!ToTypePtr)
987 return false;
988
989 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000990 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000991 ConvertedType = ToType;
992 return true;
993 }
Sebastian Redl07779722008-10-31 14:43:28 +0000994
Douglas Gregorcb7de522008-11-26 23:31:11 +0000995 // Beyond this point, both types need to be pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +0000996 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +0000997 if (!FromTypePtr)
998 return false;
999
1000 QualType FromPointeeType = FromTypePtr->getPointeeType();
1001 QualType ToPointeeType = ToTypePtr->getPointeeType();
1002
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001003 // An rvalue of type "pointer to cv T," where T is an object type,
1004 // can be converted to an rvalue of type "pointer to cv void" (C++
1005 // 4.10p2).
Douglas Gregorbad0e652009-03-24 20:32:41 +00001006 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001007 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001008 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001009 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001010 return true;
1011 }
1012
Douglas Gregorf9201e02009-02-11 23:02:49 +00001013 // When we're overloading in C, we allow a special kind of pointer
1014 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001015 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001016 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001017 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001018 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001019 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001020 return true;
1021 }
1022
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001023 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001024 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001025 // An rvalue of type "pointer to cv D," where D is a class type,
1026 // can be converted to an rvalue of type "pointer to cv B," where
1027 // B is a base class (clause 10) of D. If B is an inaccessible
1028 // (clause 11) or ambiguous (10.2) base class of D, a program that
1029 // necessitates this conversion is ill-formed. The result of the
1030 // conversion is a pointer to the base class sub-object of the
1031 // derived class object. The null pointer value is converted to
1032 // the null pointer value of the destination type.
1033 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001034 // Note that we do not check for ambiguity or inaccessibility
1035 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001036 if (getLangOptions().CPlusPlus &&
1037 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001038 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001039 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001040 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001041 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001042 ToType, Context);
1043 return true;
1044 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001045
Douglas Gregorc7887512008-12-19 19:13:09 +00001046 return false;
1047}
1048
1049/// isObjCPointerConversion - Determines whether this is an
1050/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1051/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001052bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001053 QualType& ConvertedType,
1054 bool &IncompatibleObjC) {
1055 if (!getLangOptions().ObjC1)
1056 return false;
1057
Steve Naroff14108da2009-07-10 23:34:53 +00001058 // First, we handle all conversions on ObjC object pointer types.
John McCall183700f2009-09-21 23:43:11 +00001059 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001060 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001061 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001062
Steve Naroff14108da2009-07-10 23:34:53 +00001063 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001064 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001065 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001066 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001067 ConvertedType = ToType;
1068 return true;
1069 }
1070 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001071 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001072 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001073 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001074 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001075 ConvertedType = ToType;
1076 return true;
1077 }
1078 // Objective C++: We're able to convert from a pointer to an
1079 // interface to a pointer to a different interface.
1080 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1081 ConvertedType = ToType;
1082 return true;
1083 }
1084
1085 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1086 // Okay: this is some kind of implicit downcast of Objective-C
1087 // interfaces, which is permitted. However, we're going to
1088 // complain about it.
1089 IncompatibleObjC = true;
1090 ConvertedType = FromType;
1091 return true;
1092 }
Mike Stump1eb44332009-09-09 15:08:12 +00001093 }
Steve Naroff14108da2009-07-10 23:34:53 +00001094 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001095 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001096 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001097 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001098 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001099 ToPointeeType = ToBlockPtr->getPointeeType();
1100 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001101 return false;
1102
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001103 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001104 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001105 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001106 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001107 FromPointeeType = FromBlockPtr->getPointeeType();
1108 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001109 return false;
1110
Douglas Gregorc7887512008-12-19 19:13:09 +00001111 // If we have pointers to pointers, recursively check whether this
1112 // is an Objective-C conversion.
1113 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1114 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1115 IncompatibleObjC)) {
1116 // We always complain about this conversion.
1117 IncompatibleObjC = true;
1118 ConvertedType = ToType;
1119 return true;
1120 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001121 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001122 // differences in the argument and result types are in Objective-C
1123 // pointer conversions. If so, we permit the conversion (but
1124 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001125 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001126 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001127 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001128 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001129 if (FromFunctionType && ToFunctionType) {
1130 // If the function types are exactly the same, this isn't an
1131 // Objective-C pointer conversion.
1132 if (Context.getCanonicalType(FromPointeeType)
1133 == Context.getCanonicalType(ToPointeeType))
1134 return false;
1135
1136 // Perform the quick checks that will tell us whether these
1137 // function types are obviously different.
1138 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1139 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1140 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1141 return false;
1142
1143 bool HasObjCConversion = false;
1144 if (Context.getCanonicalType(FromFunctionType->getResultType())
1145 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1146 // Okay, the types match exactly. Nothing to do.
1147 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1148 ToFunctionType->getResultType(),
1149 ConvertedType, IncompatibleObjC)) {
1150 // Okay, we have an Objective-C pointer conversion.
1151 HasObjCConversion = true;
1152 } else {
1153 // Function types are too different. Abort.
1154 return false;
1155 }
Mike Stump1eb44332009-09-09 15:08:12 +00001156
Douglas Gregorc7887512008-12-19 19:13:09 +00001157 // Check argument types.
1158 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1159 ArgIdx != NumArgs; ++ArgIdx) {
1160 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1161 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1162 if (Context.getCanonicalType(FromArgType)
1163 == Context.getCanonicalType(ToArgType)) {
1164 // Okay, the types match exactly. Nothing to do.
1165 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1166 ConvertedType, IncompatibleObjC)) {
1167 // Okay, we have an Objective-C pointer conversion.
1168 HasObjCConversion = true;
1169 } else {
1170 // Argument types are too different. Abort.
1171 return false;
1172 }
1173 }
1174
1175 if (HasObjCConversion) {
1176 // We had an Objective-C conversion. Allow this pointer
1177 // conversion, but complain about it.
1178 ConvertedType = ToType;
1179 IncompatibleObjC = true;
1180 return true;
1181 }
1182 }
1183
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001184 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001185}
1186
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001187/// CheckPointerConversion - Check the pointer conversion from the
1188/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001189/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001190/// conversions for which IsPointerConversion has already returned
1191/// true. It returns true and produces a diagnostic if there was an
1192/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001193bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001194 CastExpr::CastKind &Kind,
1195 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001196 QualType FromType = From->getType();
1197
Ted Kremenek6217b802009-07-29 21:53:49 +00001198 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1199 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001200 QualType FromPointeeType = FromPtrType->getPointeeType(),
1201 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001202
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001203 if (FromPointeeType->isRecordType() &&
1204 ToPointeeType->isRecordType()) {
1205 // We must have a derived-to-base conversion. Check an
1206 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001207 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1208 From->getExprLoc(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001209 From->getSourceRange(),
1210 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001211 return true;
1212
1213 // The conversion was successful.
1214 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001215 }
1216 }
Mike Stump1eb44332009-09-09 15:08:12 +00001217 if (const ObjCObjectPointerType *FromPtrType =
John McCall183700f2009-09-21 23:43:11 +00001218 FromType->getAs<ObjCObjectPointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001219 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001220 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001221 // Objective-C++ conversions are always okay.
1222 // FIXME: We should have a different class of conversions for the
1223 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001224 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001225 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001226
Steve Naroff14108da2009-07-10 23:34:53 +00001227 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001228 return false;
1229}
1230
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001231/// IsMemberPointerConversion - Determines whether the conversion of the
1232/// expression From, which has the (possibly adjusted) type FromType, can be
1233/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1234/// If so, returns true and places the converted type (that might differ from
1235/// ToType in its cv-qualifiers at some level) into ConvertedType.
1236bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001237 QualType ToType,
1238 bool InOverloadResolution,
1239 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001240 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001241 if (!ToTypePtr)
1242 return false;
1243
1244 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001245 if (From->isNullPointerConstant(Context,
1246 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1247 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001248 ConvertedType = ToType;
1249 return true;
1250 }
1251
1252 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001253 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001254 if (!FromTypePtr)
1255 return false;
1256
1257 // A pointer to member of B can be converted to a pointer to member of D,
1258 // where D is derived from B (C++ 4.11p2).
1259 QualType FromClass(FromTypePtr->getClass(), 0);
1260 QualType ToClass(ToTypePtr->getClass(), 0);
1261 // FIXME: What happens when these are dependent? Is this function even called?
1262
1263 if (IsDerivedFrom(ToClass, FromClass)) {
1264 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1265 ToClass.getTypePtr());
1266 return true;
1267 }
1268
1269 return false;
1270}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001271
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001272/// CheckMemberPointerConversion - Check the member pointer conversion from the
1273/// expression From to the type ToType. This routine checks for ambiguous or
1274/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1275/// for which IsMemberPointerConversion has already returned true. It returns
1276/// true and produces a diagnostic if there was an error, or returns false
1277/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001278bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001279 CastExpr::CastKind &Kind,
1280 bool IgnoreBaseAccess) {
1281 (void)IgnoreBaseAccess;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001282 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001283 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001284 if (!FromPtrType) {
1285 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001286 assert(From->isNullPointerConstant(Context,
1287 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001288 "Expr must be null pointer constant!");
1289 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001290 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001291 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001292
Ted Kremenek6217b802009-07-29 21:53:49 +00001293 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001294 assert(ToPtrType && "No member pointer cast has a target type "
1295 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001296
Sebastian Redl21593ac2009-01-28 18:33:18 +00001297 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1298 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001299
Sebastian Redl21593ac2009-01-28 18:33:18 +00001300 // FIXME: What about dependent types?
1301 assert(FromClass->isRecordType() && "Pointer into non-class.");
1302 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001303
Douglas Gregora8f32e02009-10-06 17:59:45 +00001304 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1305 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001306 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1307 assert(DerivationOkay &&
1308 "Should not have been called if derivation isn't OK.");
1309 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001310
Sebastian Redl21593ac2009-01-28 18:33:18 +00001311 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1312 getUnqualifiedType())) {
1313 // Derivation is ambiguous. Redo the check to find the exact paths.
1314 Paths.clear();
1315 Paths.setRecordingPaths(true);
1316 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1317 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1318 (void)StillOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001319
Sebastian Redl21593ac2009-01-28 18:33:18 +00001320 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1321 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1322 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1323 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001324 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001325
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001326 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001327 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1328 << FromClass << ToClass << QualType(VBase, 0)
1329 << From->getSourceRange();
1330 return true;
1331 }
1332
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001333 // Must be a base to derived member conversion.
1334 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001335 return false;
1336}
1337
Douglas Gregor98cd5992008-10-21 23:43:52 +00001338/// IsQualificationConversion - Determines whether the conversion from
1339/// an rvalue of type FromType to ToType is a qualification conversion
1340/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001341bool
1342Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001343 FromType = Context.getCanonicalType(FromType);
1344 ToType = Context.getCanonicalType(ToType);
1345
1346 // If FromType and ToType are the same type, this is not a
1347 // qualification conversion.
1348 if (FromType == ToType)
1349 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001350
Douglas Gregor98cd5992008-10-21 23:43:52 +00001351 // (C++ 4.4p4):
1352 // A conversion can add cv-qualifiers at levels other than the first
1353 // in multi-level pointers, subject to the following rules: [...]
1354 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001355 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001356 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001357 // Within each iteration of the loop, we check the qualifiers to
1358 // determine if this still looks like a qualification
1359 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001360 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001361 // until there are no more pointers or pointers-to-members left to
1362 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001363 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001364
1365 // -- for every j > 0, if const is in cv 1,j then const is in cv
1366 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001367 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001368 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001369
Douglas Gregor98cd5992008-10-21 23:43:52 +00001370 // -- if the cv 1,j and cv 2,j are different, then const is in
1371 // every cv for 0 < k < j.
1372 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001373 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001374 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001375
Douglas Gregor98cd5992008-10-21 23:43:52 +00001376 // Keep track of whether all prior cv-qualifiers in the "to" type
1377 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001378 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001379 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001380 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001381
1382 // We are left with FromType and ToType being the pointee types
1383 // after unwrapping the original FromType and ToType the same number
1384 // of types. If we unwrapped any pointers, and if FromType and
1385 // ToType have the same unqualified type (since we checked
1386 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001387 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00001388}
1389
Douglas Gregor734d9862009-01-30 23:27:23 +00001390/// Determines whether there is a user-defined conversion sequence
1391/// (C++ [over.ics.user]) that converts expression From to the type
1392/// ToType. If such a conversion exists, User will contain the
1393/// user-defined conversion sequence that performs such a conversion
1394/// and this routine will return true. Otherwise, this routine returns
1395/// false and User is unspecified.
1396///
1397/// \param AllowConversionFunctions true if the conversion should
1398/// consider conversion functions at all. If false, only constructors
1399/// will be considered.
1400///
1401/// \param AllowExplicit true if the conversion should consider C++0x
1402/// "explicit" conversion functions as well as non-explicit conversion
1403/// functions (C++0x [class.conv.fct]p2).
Sebastian Redle2b68332009-04-12 17:16:29 +00001404///
1405/// \param ForceRValue true if the expression should be treated as an rvalue
1406/// for overload resolution.
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001407/// \param UserCast true if looking for user defined conversion for a static
1408/// cast.
Douglas Gregor20093b42009-12-09 23:02:17 +00001409OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1410 UserDefinedConversionSequence& User,
1411 OverloadCandidateSet& CandidateSet,
1412 bool AllowConversionFunctions,
1413 bool AllowExplicit,
1414 bool ForceRValue,
1415 bool UserCast) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001416 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00001417 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1418 // We're not going to find any constructors.
1419 } else if (CXXRecordDecl *ToRecordDecl
1420 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001421 // C++ [over.match.ctor]p1:
1422 // When objects of class type are direct-initialized (8.5), or
1423 // copy-initialized from an expression of the same or a
1424 // derived class type (8.5), overload resolution selects the
1425 // constructor. [...] For copy-initialization, the candidate
1426 // functions are all the converting constructors (12.3.1) of
1427 // that class. The argument list is the expression-list within
1428 // the parentheses of the initializer.
Douglas Gregor79b680e2009-11-13 18:44:21 +00001429 bool SuppressUserConversions = !UserCast;
1430 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1431 IsDerivedFrom(From->getType(), ToType)) {
1432 SuppressUserConversions = false;
1433 AllowConversionFunctions = false;
1434 }
1435
Mike Stump1eb44332009-09-09 15:08:12 +00001436 DeclarationName ConstructorName
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001437 = Context.DeclarationNames.getCXXConstructorName(
1438 Context.getCanonicalType(ToType).getUnqualifiedType());
1439 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump1eb44332009-09-09 15:08:12 +00001440 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001441 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001442 Con != ConEnd; ++Con) {
Douglas Gregordec06662009-08-21 18:42:58 +00001443 // Find the constructor (which may be a template).
1444 CXXConstructorDecl *Constructor = 0;
1445 FunctionTemplateDecl *ConstructorTmpl
1446 = dyn_cast<FunctionTemplateDecl>(*Con);
1447 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001448 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00001449 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1450 else
1451 Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001452
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00001453 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00001454 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001455 if (ConstructorTmpl)
John McCalld5532b62009-11-23 01:53:49 +00001456 AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
1457 &From, 1, CandidateSet,
Douglas Gregor79b680e2009-11-13 18:44:21 +00001458 SuppressUserConversions, ForceRValue);
Douglas Gregordec06662009-08-21 18:42:58 +00001459 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001460 // Allow one user-defined conversion when user specifies a
1461 // From->ToType conversion via an static cast (c-style, etc).
Douglas Gregordec06662009-08-21 18:42:58 +00001462 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Douglas Gregor79b680e2009-11-13 18:44:21 +00001463 SuppressUserConversions, ForceRValue);
Douglas Gregordec06662009-08-21 18:42:58 +00001464 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001465 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001466 }
1467 }
1468
Douglas Gregor734d9862009-01-30 23:27:23 +00001469 if (!AllowConversionFunctions) {
1470 // Don't allow any conversion functions to enter the overload set.
Mike Stump1eb44332009-09-09 15:08:12 +00001471 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1472 PDiag(0)
Anders Carlssonb7906612009-08-26 23:45:07 +00001473 << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00001474 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00001475 } else if (const RecordType *FromRecordType
Ted Kremenek6217b802009-07-29 21:53:49 +00001476 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001477 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001478 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1479 // Add all of the conversion functions as candidates.
John McCallba135432009-11-21 08:51:07 +00001480 const UnresolvedSet *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00001481 = FromRecordDecl->getVisibleConversionFunctions();
John McCallba135432009-11-21 08:51:07 +00001482 for (UnresolvedSet::iterator I = Conversions->begin(),
1483 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00001484 NamedDecl *D = *I;
1485 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1486 if (isa<UsingShadowDecl>(D))
1487 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1488
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001489 CXXConversionDecl *Conv;
1490 FunctionTemplateDecl *ConvTemplate;
John McCallba135432009-11-21 08:51:07 +00001491 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001492 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1493 else
John McCallba135432009-11-21 08:51:07 +00001494 Conv = dyn_cast<CXXConversionDecl>(*I);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001495
1496 if (AllowExplicit || !Conv->isExplicit()) {
1497 if (ConvTemplate)
John McCall701c89e2009-12-03 04:06:58 +00001498 AddTemplateConversionCandidate(ConvTemplate, ActingContext,
1499 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001500 else
John McCall701c89e2009-12-03 04:06:58 +00001501 AddConversionCandidate(Conv, ActingContext, From, ToType,
1502 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001503 }
1504 }
1505 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001506 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001507
1508 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001509 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001510 case OR_Success:
1511 // Record the standard conversion we used and the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00001512 if (CXXConstructorDecl *Constructor
Douglas Gregor60d62c22008-10-31 16:23:19 +00001513 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1514 // C++ [over.ics.user]p1:
1515 // If the user-defined conversion is specified by a
1516 // constructor (12.3.1), the initial standard conversion
1517 // sequence converts the source type to the type required by
1518 // the argument of the constructor.
1519 //
Douglas Gregor60d62c22008-10-31 16:23:19 +00001520 QualType ThisType = Constructor->getThisType(Context);
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001521 if (Best->Conversions[0].ConversionKind ==
1522 ImplicitConversionSequence::EllipsisConversion)
1523 User.EllipsisConversion = true;
1524 else {
1525 User.Before = Best->Conversions[0].Standard;
1526 User.EllipsisConversion = false;
1527 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001528 User.ConversionFunction = Constructor;
1529 User.After.setAsIdentityConversion();
Mike Stump1eb44332009-09-09 15:08:12 +00001530 User.After.FromTypePtr
Ted Kremenek6217b802009-07-29 21:53:49 +00001531 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor60d62c22008-10-31 16:23:19 +00001532 User.After.ToTypePtr = ToType.getAsOpaquePtr();
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001533 return OR_Success;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001534 } else if (CXXConversionDecl *Conversion
1535 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1536 // C++ [over.ics.user]p1:
1537 //
1538 // [...] If the user-defined conversion is specified by a
1539 // conversion function (12.3.2), the initial standard
1540 // conversion sequence converts the source type to the
1541 // implicit object parameter of the conversion function.
1542 User.Before = Best->Conversions[0].Standard;
1543 User.ConversionFunction = Conversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001544 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001545
1546 // C++ [over.ics.user]p2:
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001547 // The second standard conversion sequence converts the
1548 // result of the user-defined conversion to the target type
1549 // for the sequence. Since an implicit conversion sequence
1550 // is an initialization, the special rules for
1551 // initialization by user-defined conversion apply when
1552 // selecting the best user-defined conversion for a
1553 // user-defined conversion sequence (see 13.3.3 and
1554 // 13.3.3.1).
1555 User.After = Best->FinalConversion;
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001556 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001557 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001558 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001559 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001560 }
Mike Stump1eb44332009-09-09 15:08:12 +00001561
Douglas Gregor60d62c22008-10-31 16:23:19 +00001562 case OR_No_Viable_Function:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001563 return OR_No_Viable_Function;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001564 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001565 // No conversion here! We're done.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001566 return OR_Deleted;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001567
1568 case OR_Ambiguous:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001569 return OR_Ambiguous;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001570 }
1571
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001572 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001573}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001574
1575bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001576Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001577 ImplicitConversionSequence ICS;
1578 OverloadCandidateSet CandidateSet;
1579 OverloadingResult OvResult =
1580 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1581 CandidateSet, true, false, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001582 if (OvResult == OR_Ambiguous)
1583 Diag(From->getSourceRange().getBegin(),
1584 diag::err_typecheck_ambiguous_condition)
1585 << From->getType() << ToType << From->getSourceRange();
1586 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1587 Diag(From->getSourceRange().getBegin(),
1588 diag::err_typecheck_nonviable_condition)
1589 << From->getType() << ToType << From->getSourceRange();
1590 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001591 return false;
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001592 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001593 return true;
1594}
Douglas Gregor60d62c22008-10-31 16:23:19 +00001595
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001596/// CompareImplicitConversionSequences - Compare two implicit
1597/// conversion sequences to determine whether one is better than the
1598/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump1eb44332009-09-09 15:08:12 +00001599ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001600Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1601 const ImplicitConversionSequence& ICS2)
1602{
1603 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1604 // conversion sequences (as defined in 13.3.3.1)
1605 // -- a standard conversion sequence (13.3.3.1.1) is a better
1606 // conversion sequence than a user-defined conversion sequence or
1607 // an ellipsis conversion sequence, and
1608 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1609 // conversion sequence than an ellipsis conversion sequence
1610 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00001611 //
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001612 if (ICS1.ConversionKind < ICS2.ConversionKind)
1613 return ImplicitConversionSequence::Better;
1614 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1615 return ImplicitConversionSequence::Worse;
1616
1617 // Two implicit conversion sequences of the same form are
1618 // indistinguishable conversion sequences unless one of the
1619 // following rules apply: (C++ 13.3.3.2p3):
1620 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1621 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump1eb44332009-09-09 15:08:12 +00001622 else if (ICS1.ConversionKind ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001623 ImplicitConversionSequence::UserDefinedConversion) {
1624 // User-defined conversion sequence U1 is a better conversion
1625 // sequence than another user-defined conversion sequence U2 if
1626 // they contain the same user-defined conversion function or
1627 // constructor and if the second standard conversion sequence of
1628 // U1 is better than the second standard conversion sequence of
1629 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001630 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001631 ICS2.UserDefined.ConversionFunction)
1632 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1633 ICS2.UserDefined.After);
1634 }
1635
1636 return ImplicitConversionSequence::Indistinguishable;
1637}
1638
1639/// CompareStandardConversionSequences - Compare two standard
1640/// conversion sequences to determine whether one is better than the
1641/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001642ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001643Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1644 const StandardConversionSequence& SCS2)
1645{
1646 // Standard conversion sequence S1 is a better conversion sequence
1647 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1648
1649 // -- S1 is a proper subsequence of S2 (comparing the conversion
1650 // sequences in the canonical form defined by 13.3.3.1.1,
1651 // excluding any Lvalue Transformation; the identity conversion
1652 // sequence is considered to be a subsequence of any
1653 // non-identity conversion sequence) or, if not that,
1654 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1655 // Neither is a proper subsequence of the other. Do nothing.
1656 ;
1657 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1658 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001659 (SCS1.Second == ICK_Identity &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001660 SCS1.Third == ICK_Identity))
1661 // SCS1 is a proper subsequence of SCS2.
1662 return ImplicitConversionSequence::Better;
1663 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1664 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001665 (SCS2.Second == ICK_Identity &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001666 SCS2.Third == ICK_Identity))
1667 // SCS2 is a proper subsequence of SCS1.
1668 return ImplicitConversionSequence::Worse;
1669
1670 // -- the rank of S1 is better than the rank of S2 (by the rules
1671 // defined below), or, if not that,
1672 ImplicitConversionRank Rank1 = SCS1.getRank();
1673 ImplicitConversionRank Rank2 = SCS2.getRank();
1674 if (Rank1 < Rank2)
1675 return ImplicitConversionSequence::Better;
1676 else if (Rank2 < Rank1)
1677 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001678
Douglas Gregor57373262008-10-22 14:17:15 +00001679 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1680 // are indistinguishable unless one of the following rules
1681 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00001682
Douglas Gregor57373262008-10-22 14:17:15 +00001683 // A conversion that is not a conversion of a pointer, or
1684 // pointer to member, to bool is better than another conversion
1685 // that is such a conversion.
1686 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1687 return SCS2.isPointerConversionToBool()
1688 ? ImplicitConversionSequence::Better
1689 : ImplicitConversionSequence::Worse;
1690
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001691 // C++ [over.ics.rank]p4b2:
1692 //
1693 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001694 // conversion of B* to A* is better than conversion of B* to
1695 // void*, and conversion of A* to void* is better than conversion
1696 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00001697 bool SCS1ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001698 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001699 bool SCS2ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001700 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001701 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1702 // Exactly one of the conversion sequences is a conversion to
1703 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001704 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1705 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001706 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1707 // Neither conversion sequence converts to a void pointer; compare
1708 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001709 if (ImplicitConversionSequence::CompareKind DerivedCK
1710 = CompareDerivedToBaseConversions(SCS1, SCS2))
1711 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001712 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1713 // Both conversion sequences are conversions to void
1714 // pointers. Compare the source types to determine if there's an
1715 // inheritance relationship in their sources.
1716 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1717 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1718
1719 // Adjust the types we're converting from via the array-to-pointer
1720 // conversion, if we need to.
1721 if (SCS1.First == ICK_Array_To_Pointer)
1722 FromType1 = Context.getArrayDecayedType(FromType1);
1723 if (SCS2.First == ICK_Array_To_Pointer)
1724 FromType2 = Context.getArrayDecayedType(FromType2);
1725
Douglas Gregor01919692009-12-13 21:37:05 +00001726 QualType FromPointee1
1727 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1728 QualType FromPointee2
1729 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001730
Douglas Gregor01919692009-12-13 21:37:05 +00001731 if (IsDerivedFrom(FromPointee2, FromPointee1))
1732 return ImplicitConversionSequence::Better;
1733 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1734 return ImplicitConversionSequence::Worse;
1735
1736 // Objective-C++: If one interface is more specific than the
1737 // other, it is the better one.
1738 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1739 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1740 if (FromIface1 && FromIface1) {
1741 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1742 return ImplicitConversionSequence::Better;
1743 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1744 return ImplicitConversionSequence::Worse;
1745 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001746 }
Douglas Gregor57373262008-10-22 14:17:15 +00001747
1748 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1749 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00001750 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001751 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001752 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001753
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001754 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001755 // C++0x [over.ics.rank]p3b4:
1756 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1757 // implicit object parameter of a non-static member function declared
1758 // without a ref-qualifier, and S1 binds an rvalue reference to an
1759 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00001760 // FIXME: We don't know if we're dealing with the implicit object parameter,
1761 // or if the member function in this case has a ref qualifier.
1762 // (Of course, we don't have ref qualifiers yet.)
1763 if (SCS1.RRefBinding != SCS2.RRefBinding)
1764 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1765 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001766
1767 // C++ [over.ics.rank]p3b4:
1768 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1769 // which the references refer are the same type except for
1770 // top-level cv-qualifiers, and the type to which the reference
1771 // initialized by S2 refers is more cv-qualified than the type
1772 // to which the reference initialized by S1 refers.
Sebastian Redla9845802009-03-29 15:27:50 +00001773 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1774 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001775 T1 = Context.getCanonicalType(T1);
1776 T2 = Context.getCanonicalType(T2);
Douglas Gregora4923eb2009-11-16 21:35:15 +00001777 if (Context.hasSameUnqualifiedType(T1, T2)) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001778 if (T2.isMoreQualifiedThan(T1))
1779 return ImplicitConversionSequence::Better;
1780 else if (T1.isMoreQualifiedThan(T2))
1781 return ImplicitConversionSequence::Worse;
1782 }
1783 }
Douglas Gregor57373262008-10-22 14:17:15 +00001784
1785 return ImplicitConversionSequence::Indistinguishable;
1786}
1787
1788/// CompareQualificationConversions - Compares two standard conversion
1789/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00001790/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1791ImplicitConversionSequence::CompareKind
Douglas Gregor57373262008-10-22 14:17:15 +00001792Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump1eb44332009-09-09 15:08:12 +00001793 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00001794 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001795 // -- S1 and S2 differ only in their qualification conversion and
1796 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1797 // cv-qualification signature of type T1 is a proper subset of
1798 // the cv-qualification signature of type T2, and S1 is not the
1799 // deprecated string literal array-to-pointer conversion (4.2).
1800 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1801 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1802 return ImplicitConversionSequence::Indistinguishable;
1803
1804 // FIXME: the example in the standard doesn't use a qualification
1805 // conversion (!)
1806 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1807 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1808 T1 = Context.getCanonicalType(T1);
1809 T2 = Context.getCanonicalType(T2);
1810
1811 // If the types are the same, we won't learn anything by unwrapped
1812 // them.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001813 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00001814 return ImplicitConversionSequence::Indistinguishable;
1815
Mike Stump1eb44332009-09-09 15:08:12 +00001816 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00001817 = ImplicitConversionSequence::Indistinguishable;
1818 while (UnwrapSimilarPointerTypes(T1, T2)) {
1819 // Within each iteration of the loop, we check the qualifiers to
1820 // determine if this still looks like a qualification
1821 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001822 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001823 // until there are no more pointers or pointers-to-members left
1824 // to unwrap. This essentially mimics what
1825 // IsQualificationConversion does, but here we're checking for a
1826 // strict subset of qualifiers.
1827 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1828 // The qualifiers are the same, so this doesn't tell us anything
1829 // about how the sequences rank.
1830 ;
1831 else if (T2.isMoreQualifiedThan(T1)) {
1832 // T1 has fewer qualifiers, so it could be the better sequence.
1833 if (Result == ImplicitConversionSequence::Worse)
1834 // Neither has qualifiers that are a subset of the other's
1835 // qualifiers.
1836 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001837
Douglas Gregor57373262008-10-22 14:17:15 +00001838 Result = ImplicitConversionSequence::Better;
1839 } else if (T1.isMoreQualifiedThan(T2)) {
1840 // T2 has fewer qualifiers, so it could be the better sequence.
1841 if (Result == ImplicitConversionSequence::Better)
1842 // Neither has qualifiers that are a subset of the other's
1843 // qualifiers.
1844 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001845
Douglas Gregor57373262008-10-22 14:17:15 +00001846 Result = ImplicitConversionSequence::Worse;
1847 } else {
1848 // Qualifiers are disjoint.
1849 return ImplicitConversionSequence::Indistinguishable;
1850 }
1851
1852 // If the types after this point are equivalent, we're done.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001853 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00001854 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001855 }
1856
Douglas Gregor57373262008-10-22 14:17:15 +00001857 // Check that the winning standard conversion sequence isn't using
1858 // the deprecated string literal array to pointer conversion.
1859 switch (Result) {
1860 case ImplicitConversionSequence::Better:
1861 if (SCS1.Deprecated)
1862 Result = ImplicitConversionSequence::Indistinguishable;
1863 break;
1864
1865 case ImplicitConversionSequence::Indistinguishable:
1866 break;
1867
1868 case ImplicitConversionSequence::Worse:
1869 if (SCS2.Deprecated)
1870 Result = ImplicitConversionSequence::Indistinguishable;
1871 break;
1872 }
1873
1874 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001875}
1876
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001877/// CompareDerivedToBaseConversions - Compares two standard conversion
1878/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00001879/// various kinds of derived-to-base conversions (C++
1880/// [over.ics.rank]p4b3). As part of these checks, we also look at
1881/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001882ImplicitConversionSequence::CompareKind
1883Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1884 const StandardConversionSequence& SCS2) {
1885 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1886 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1887 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1888 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1889
1890 // Adjust the types we're converting from via the array-to-pointer
1891 // conversion, if we need to.
1892 if (SCS1.First == ICK_Array_To_Pointer)
1893 FromType1 = Context.getArrayDecayedType(FromType1);
1894 if (SCS2.First == ICK_Array_To_Pointer)
1895 FromType2 = Context.getArrayDecayedType(FromType2);
1896
1897 // Canonicalize all of the types.
1898 FromType1 = Context.getCanonicalType(FromType1);
1899 ToType1 = Context.getCanonicalType(ToType1);
1900 FromType2 = Context.getCanonicalType(FromType2);
1901 ToType2 = Context.getCanonicalType(ToType2);
1902
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001903 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001904 //
1905 // If class B is derived directly or indirectly from class A and
1906 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001907 //
1908 // For Objective-C, we let A, B, and C also be Objective-C
1909 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001910
1911 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00001912 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00001913 SCS2.Second == ICK_Pointer_Conversion &&
1914 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1915 FromType1->isPointerType() && FromType2->isPointerType() &&
1916 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001917 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00001918 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00001919 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00001920 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001921 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00001922 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001923 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00001924 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001925
John McCall183700f2009-09-21 23:43:11 +00001926 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1927 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1928 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1929 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001930
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001931 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001932 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1933 if (IsDerivedFrom(ToPointee1, ToPointee2))
1934 return ImplicitConversionSequence::Better;
1935 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1936 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001937
1938 if (ToIface1 && ToIface2) {
1939 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1940 return ImplicitConversionSequence::Better;
1941 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1942 return ImplicitConversionSequence::Worse;
1943 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001944 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001945
1946 // -- conversion of B* to A* is better than conversion of C* to A*,
1947 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1948 if (IsDerivedFrom(FromPointee2, FromPointee1))
1949 return ImplicitConversionSequence::Better;
1950 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1951 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00001952
Douglas Gregorcb7de522008-11-26 23:31:11 +00001953 if (FromIface1 && FromIface2) {
1954 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1955 return ImplicitConversionSequence::Better;
1956 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1957 return ImplicitConversionSequence::Worse;
1958 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001959 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001960 }
1961
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001962 // Compare based on reference bindings.
1963 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1964 SCS1.Second == ICK_Derived_To_Base) {
1965 // -- binding of an expression of type C to a reference of type
1966 // B& is better than binding an expression of type C to a
1967 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00001968 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1969 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001970 if (IsDerivedFrom(ToType1, ToType2))
1971 return ImplicitConversionSequence::Better;
1972 else if (IsDerivedFrom(ToType2, ToType1))
1973 return ImplicitConversionSequence::Worse;
1974 }
1975
Douglas Gregor225c41e2008-11-03 19:09:14 +00001976 // -- binding of an expression of type B to a reference of type
1977 // A& is better than binding an expression of type C to a
1978 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00001979 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1980 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001981 if (IsDerivedFrom(FromType2, FromType1))
1982 return ImplicitConversionSequence::Better;
1983 else if (IsDerivedFrom(FromType1, FromType2))
1984 return ImplicitConversionSequence::Worse;
1985 }
1986 }
Fariborz Jahanian2357da02009-10-20 20:07:35 +00001987
1988 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00001989 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
1990 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
1991 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
1992 const MemberPointerType * FromMemPointer1 =
1993 FromType1->getAs<MemberPointerType>();
1994 const MemberPointerType * ToMemPointer1 =
1995 ToType1->getAs<MemberPointerType>();
1996 const MemberPointerType * FromMemPointer2 =
1997 FromType2->getAs<MemberPointerType>();
1998 const MemberPointerType * ToMemPointer2 =
1999 ToType2->getAs<MemberPointerType>();
2000 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2001 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2002 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2003 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2004 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2005 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2006 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2007 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002008 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002009 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2010 if (IsDerivedFrom(ToPointee1, ToPointee2))
2011 return ImplicitConversionSequence::Worse;
2012 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2013 return ImplicitConversionSequence::Better;
2014 }
2015 // conversion of B::* to C::* is better than conversion of A::* to C::*
2016 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2017 if (IsDerivedFrom(FromPointee1, FromPointee2))
2018 return ImplicitConversionSequence::Better;
2019 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2020 return ImplicitConversionSequence::Worse;
2021 }
2022 }
2023
Douglas Gregor225c41e2008-11-03 19:09:14 +00002024 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
2025 SCS1.Second == ICK_Derived_To_Base) {
2026 // -- conversion of C to B 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(ToType1, ToType2))
2030 return ImplicitConversionSequence::Better;
2031 else if (IsDerivedFrom(ToType2, ToType1))
2032 return ImplicitConversionSequence::Worse;
2033 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002034
Douglas Gregor225c41e2008-11-03 19:09:14 +00002035 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002036 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2037 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002038 if (IsDerivedFrom(FromType2, FromType1))
2039 return ImplicitConversionSequence::Better;
2040 else if (IsDerivedFrom(FromType1, FromType2))
2041 return ImplicitConversionSequence::Worse;
2042 }
2043 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002044
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002045 return ImplicitConversionSequence::Indistinguishable;
2046}
2047
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002048/// TryCopyInitialization - Try to copy-initialize a value of type
2049/// ToType from the expression From. Return the implicit conversion
2050/// sequence required to pass this argument, which may be a bad
2051/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00002052/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redle2b68332009-04-12 17:16:29 +00002053/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2054/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump1eb44332009-09-09 15:08:12 +00002055ImplicitConversionSequence
2056Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002057 bool SuppressUserConversions, bool ForceRValue,
2058 bool InOverloadResolution) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00002059 if (ToType->isReferenceType()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002060 ImplicitConversionSequence ICS;
Mike Stump1eb44332009-09-09 15:08:12 +00002061 CheckReferenceInit(From, ToType,
Douglas Gregor739d8282009-09-23 23:04:10 +00002062 /*FIXME:*/From->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002063 SuppressUserConversions,
2064 /*AllowExplicit=*/false,
2065 ForceRValue,
2066 &ICS);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002067 return ICS;
2068 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002069 return TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002070 SuppressUserConversions,
2071 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002072 ForceRValue,
2073 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002074 }
2075}
2076
Sebastian Redle2b68332009-04-12 17:16:29 +00002077/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2078/// the expression @p From. Returns true (and emits a diagnostic) if there was
2079/// an error, returns false if the initialization succeeded. Elidable should
2080/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2081/// differently in C++0x for this case.
Mike Stump1eb44332009-09-09 15:08:12 +00002082bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redle2b68332009-04-12 17:16:29 +00002083 const char* Flavor, bool Elidable) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002084 if (!getLangOptions().CPlusPlus) {
2085 // In C, argument passing is the same as performing an assignment.
2086 QualType FromType = From->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002088 AssignConvertType ConvTy =
2089 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00002090 if (ConvTy != Compatible &&
2091 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2092 ConvTy = Compatible;
Mike Stump1eb44332009-09-09 15:08:12 +00002093
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002094 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
2095 FromType, From, Flavor);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002096 }
Sebastian Redle2b68332009-04-12 17:16:29 +00002097
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002098 if (ToType->isReferenceType())
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002099 return CheckReferenceInit(From, ToType,
Douglas Gregor739d8282009-09-23 23:04:10 +00002100 /*FIXME:*/From->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002101 /*SuppressUserConversions=*/false,
2102 /*AllowExplicit=*/false,
2103 /*ForceRValue=*/false);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002104
Sebastian Redle2b68332009-04-12 17:16:29 +00002105 if (!PerformImplicitConversion(From, ToType, Flavor,
2106 /*AllowExplicit=*/false, Elidable))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002107 return false;
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002108 if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
Fariborz Jahanian455acd92009-09-22 19:53:15 +00002109 return Diag(From->getSourceRange().getBegin(),
2110 diag::err_typecheck_convert_incompatible)
2111 << ToType << From->getType() << Flavor << From->getSourceRange();
Fariborz Jahanian455acd92009-09-22 19:53:15 +00002112 return true;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002113}
2114
Douglas Gregor96176b32008-11-18 23:14:02 +00002115/// TryObjectArgumentInitialization - Try to initialize the object
2116/// parameter of the given member function (@c Method) from the
2117/// expression @p From.
2118ImplicitConversionSequence
John McCall701c89e2009-12-03 04:06:58 +00002119Sema::TryObjectArgumentInitialization(QualType FromType,
2120 CXXMethodDecl *Method,
2121 CXXRecordDecl *ActingContext) {
2122 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002123 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2124 // const volatile object.
2125 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2126 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2127 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00002128
2129 // Set up the conversion sequence as a "bad" conversion, to allow us
2130 // to exit early.
2131 ImplicitConversionSequence ICS;
2132 ICS.Standard.setAsIdentityConversion();
2133 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2134
2135 // We need to have an object of class type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002136 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00002137 FromType = PT->getPointeeType();
2138
2139 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002140
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002141 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00002142 // where X is the class of which the function is a member
2143 // (C++ [over.match.funcs]p4). However, when finding an implicit
2144 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00002145 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00002146 // (C++ [over.match.funcs]p5). We perform a simplified version of
2147 // reference binding here, that allows class rvalues to bind to
2148 // non-constant references.
2149
2150 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2151 // with the implicit object parameter (C++ [over.match.funcs]p5).
2152 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00002153 if (ImplicitParamType.getCVRQualifiers()
2154 != FromTypeCanon.getLocalCVRQualifiers() &&
Douglas Gregorb1c2ea52009-11-05 00:07:36 +00002155 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon))
Douglas Gregor96176b32008-11-18 23:14:02 +00002156 return ICS;
2157
2158 // Check that we have either the same type or a derived type. It
2159 // affects the conversion rank.
2160 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00002161 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType())
Douglas Gregor96176b32008-11-18 23:14:02 +00002162 ICS.Standard.Second = ICK_Identity;
2163 else if (IsDerivedFrom(FromType, ClassType))
2164 ICS.Standard.Second = ICK_Derived_To_Base;
2165 else
2166 return ICS;
2167
2168 // Success. Mark this as a reference binding.
2169 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2170 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2171 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2172 ICS.Standard.ReferenceBinding = true;
2173 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00002174 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002175 return ICS;
2176}
2177
2178/// PerformObjectArgumentInitialization - Perform initialization of
2179/// the implicit object parameter for the given Method with the given
2180/// expression.
2181bool
2182Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002183 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00002184 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00002185 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002186
Ted Kremenek6217b802009-07-29 21:53:49 +00002187 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002188 FromRecordType = PT->getPointeeType();
2189 DestType = Method->getThisType(Context);
2190 } else {
2191 FromRecordType = From->getType();
2192 DestType = ImplicitParamRecordType;
2193 }
2194
John McCall701c89e2009-12-03 04:06:58 +00002195 // Note that we always use the true parent context when performing
2196 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002197 ImplicitConversionSequence ICS
John McCall701c89e2009-12-03 04:06:58 +00002198 = TryObjectArgumentInitialization(From->getType(), Method,
2199 Method->getParent());
Douglas Gregor96176b32008-11-18 23:14:02 +00002200 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2201 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002202 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00002203 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002204
Douglas Gregor96176b32008-11-18 23:14:02 +00002205 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssona552f7c2009-05-01 18:34:30 +00002206 CheckDerivedToBaseConversion(FromRecordType,
2207 ImplicitParamRecordType,
Douglas Gregor96176b32008-11-18 23:14:02 +00002208 From->getSourceRange().getBegin(),
2209 From->getSourceRange()))
2210 return true;
2211
Mike Stump1eb44332009-09-09 15:08:12 +00002212 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson116b7d92009-08-07 18:45:49 +00002213 /*isLvalue=*/true);
Douglas Gregor96176b32008-11-18 23:14:02 +00002214 return false;
2215}
2216
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002217/// TryContextuallyConvertToBool - Attempt to contextually convert the
2218/// expression From to bool (C++0x [conv]p3).
2219ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump1eb44332009-09-09 15:08:12 +00002220 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002221 // FIXME: Are these flags correct?
2222 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00002223 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00002224 /*ForceRValue=*/false,
2225 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002226}
2227
2228/// PerformContextuallyConvertToBool - Perform a contextual conversion
2229/// of the expression From to bool (C++0x [conv]p3).
2230bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2231 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2232 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2233 return false;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002234
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002235 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002236 return Diag(From->getSourceRange().getBegin(),
2237 diag::err_typecheck_bool_condition)
2238 << From->getType() << From->getSourceRange();
2239 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002240}
2241
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002242/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00002243/// candidate functions, using the given function call arguments. If
2244/// @p SuppressUserConversions, then don't allow user-defined
2245/// conversions via constructors or conversion operators.
Sebastian Redle2b68332009-04-12 17:16:29 +00002246/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2247/// hacky way to implement the overloading rules for elidable copy
2248/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002249///
2250/// \para PartialOverloading true if we are performing "partial" overloading
2251/// based on an incomplete set of function arguments. This feature is used by
2252/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00002253void
2254Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002255 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002256 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00002257 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002258 bool ForceRValue,
2259 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00002260 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002261 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002262 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00002263 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002264 "Use AddConversionCandidate for conversion functions");
Mike Stump1eb44332009-09-09 15:08:12 +00002265 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00002266 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00002267
Douglas Gregor88a35142008-12-22 05:46:06 +00002268 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002269 if (!isa<CXXConstructorDecl>(Method)) {
2270 // If we get here, it's because we're calling a member function
2271 // that is named without a member access expression (e.g.,
2272 // "this->f") that was either written explicitly or created
2273 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00002274 // function, e.g., X::f(). We use an empty type for the implied
2275 // object argument (C++ [over.call.func]p3), and the acting context
2276 // is irrelevant.
2277 AddMethodCandidate(Method, Method->getParent(),
2278 QualType(), Args, NumArgs, CandidateSet,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002279 SuppressUserConversions, ForceRValue);
2280 return;
2281 }
2282 // We treat a constructor like a non-member function, since its object
2283 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00002284 }
2285
Douglas Gregorfd476482009-11-13 23:59:09 +00002286 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00002287 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00002288
Douglas Gregor7edfb692009-11-23 12:27:39 +00002289 // Overload resolution is always an unevaluated context.
2290 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2291
Douglas Gregor66724ea2009-11-14 01:20:54 +00002292 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2293 // C++ [class.copy]p3:
2294 // A member function template is never instantiated to perform the copy
2295 // of a class object to an object of its class type.
2296 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2297 if (NumArgs == 1 &&
2298 Constructor->isCopyConstructorLikeSpecialization() &&
2299 Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2300 return;
2301 }
2302
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002303 // Add this candidate
2304 CandidateSet.push_back(OverloadCandidate());
2305 OverloadCandidate& Candidate = CandidateSet.back();
2306 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00002307 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002308 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002309 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002310
2311 unsigned NumArgsInProto = Proto->getNumArgs();
2312
2313 // (C++ 13.3.2p2): A candidate function having fewer than m
2314 // parameters is viable only if it has an ellipsis in its parameter
2315 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00002316 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2317 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002318 Candidate.Viable = false;
2319 return;
2320 }
2321
2322 // (C++ 13.3.2p2): A candidate function having more than m parameters
2323 // is viable only if the (m+1)st parameter has a default argument
2324 // (8.3.6). For the purposes of overload resolution, the
2325 // parameter list is truncated on the right, so that there are
2326 // exactly m parameters.
2327 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002328 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002329 // Not enough arguments.
2330 Candidate.Viable = false;
2331 return;
2332 }
2333
2334 // Determine the implicit conversion sequences for each of the
2335 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002336 Candidate.Conversions.resize(NumArgs);
2337 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2338 if (ArgIdx < NumArgsInProto) {
2339 // (C++ 13.3.2p3): for F to be a viable function, there shall
2340 // exist for each argument an implicit conversion sequence
2341 // (13.3.3.1) that converts that argument to the corresponding
2342 // parameter of F.
2343 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002344 Candidate.Conversions[ArgIdx]
2345 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002346 SuppressUserConversions, ForceRValue,
2347 /*InOverloadResolution=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00002348 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002349 == ImplicitConversionSequence::BadConversion) {
Fariborz Jahanian99d6c442009-09-28 19:06:58 +00002350 // 13.3.3.1-p10 If several different sequences of conversions exist that
2351 // each convert the argument to the parameter type, the implicit conversion
2352 // sequence associated with the parameter is defined to be the unique conversion
2353 // sequence designated the ambiguous conversion sequence. For the purpose of
2354 // ranking implicit conversion sequences as described in 13.3.3.2, the ambiguous
2355 // conversion sequence is treated as a user-defined sequence that is
2356 // indistinguishable from any other user-defined conversion sequence
Fariborz Jahanian4a6a2b82009-09-29 17:31:54 +00002357 if (!Candidate.Conversions[ArgIdx].ConversionFunctionSet.empty()) {
Fariborz Jahanian99d6c442009-09-28 19:06:58 +00002358 Candidate.Conversions[ArgIdx].ConversionKind =
2359 ImplicitConversionSequence::UserDefinedConversion;
Fariborz Jahanian4a6a2b82009-09-29 17:31:54 +00002360 // Set the conversion function to one of them. As due to ambiguity,
2361 // they carry the same weight and is needed for overload resolution
2362 // later.
2363 Candidate.Conversions[ArgIdx].UserDefined.ConversionFunction =
2364 Candidate.Conversions[ArgIdx].ConversionFunctionSet[0];
2365 }
Fariborz Jahanian99d6c442009-09-28 19:06:58 +00002366 else {
2367 Candidate.Viable = false;
2368 break;
2369 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002370 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002371 } else {
2372 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2373 // argument for which there is no corresponding parameter is
2374 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002375 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002376 = ImplicitConversionSequence::EllipsisConversion;
2377 }
2378 }
2379}
2380
Douglas Gregor063daf62009-03-13 18:40:31 +00002381/// \brief Add all of the function declarations in the given function set to
2382/// the overload canddiate set.
2383void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2384 Expr **Args, unsigned NumArgs,
2385 OverloadCandidateSet& CandidateSet,
2386 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00002387 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor063daf62009-03-13 18:40:31 +00002388 FEnd = Functions.end();
Douglas Gregor364e0212009-06-27 21:05:07 +00002389 F != FEnd; ++F) {
John McCall701c89e2009-12-03 04:06:58 +00002390 // FIXME: using declarations
Douglas Gregor3f396022009-09-28 04:47:19 +00002391 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2392 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2393 AddMethodCandidate(cast<CXXMethodDecl>(FD),
John McCall701c89e2009-12-03 04:06:58 +00002394 cast<CXXMethodDecl>(FD)->getParent(),
2395 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00002396 CandidateSet, SuppressUserConversions);
2397 else
2398 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2399 SuppressUserConversions);
2400 } else {
2401 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2402 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2403 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2404 AddMethodTemplateCandidate(FunTmpl,
John McCall701c89e2009-12-03 04:06:58 +00002405 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00002406 /*FIXME: explicit args */ 0,
John McCall701c89e2009-12-03 04:06:58 +00002407 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00002408 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00002409 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00002410 else
2411 AddTemplateOverloadCandidate(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00002412 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00002413 Args, NumArgs, CandidateSet,
2414 SuppressUserConversions);
2415 }
Douglas Gregor364e0212009-06-27 21:05:07 +00002416 }
Douglas Gregor063daf62009-03-13 18:40:31 +00002417}
2418
John McCall314be4e2009-11-17 07:50:12 +00002419/// AddMethodCandidate - Adds a named decl (which is some kind of
2420/// method) as a method candidate to the given overload set.
John McCall701c89e2009-12-03 04:06:58 +00002421void Sema::AddMethodCandidate(NamedDecl *Decl,
2422 QualType ObjectType,
John McCall314be4e2009-11-17 07:50:12 +00002423 Expr **Args, unsigned NumArgs,
2424 OverloadCandidateSet& CandidateSet,
2425 bool SuppressUserConversions, bool ForceRValue) {
2426
2427 // FIXME: use this
John McCall701c89e2009-12-03 04:06:58 +00002428 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00002429
2430 if (isa<UsingShadowDecl>(Decl))
2431 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2432
2433 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2434 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2435 "Expected a member function template");
John McCall701c89e2009-12-03 04:06:58 +00002436 AddMethodTemplateCandidate(TD, ActingContext, /*ExplicitArgs*/ 0,
2437 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00002438 CandidateSet,
2439 SuppressUserConversions,
2440 ForceRValue);
2441 } else {
John McCall701c89e2009-12-03 04:06:58 +00002442 AddMethodCandidate(cast<CXXMethodDecl>(Decl), ActingContext,
2443 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00002444 CandidateSet, SuppressUserConversions, ForceRValue);
2445 }
2446}
2447
Douglas Gregor96176b32008-11-18 23:14:02 +00002448/// AddMethodCandidate - Adds the given C++ member function to the set
2449/// of candidate functions, using the given function call arguments
2450/// and the object argument (@c Object). For example, in a call
2451/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2452/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2453/// allow user-defined conversions via constructors or conversion
Sebastian Redle2b68332009-04-12 17:16:29 +00002454/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2455/// a slightly hacky way to implement the overloading rules for elidable copy
2456/// initialization in C++0x (C++0x 12.8p15).
Mike Stump1eb44332009-09-09 15:08:12 +00002457void
John McCall701c89e2009-12-03 04:06:58 +00002458Sema::AddMethodCandidate(CXXMethodDecl *Method, CXXRecordDecl *ActingContext,
2459 QualType ObjectType, Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00002460 OverloadCandidateSet& CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00002461 bool SuppressUserConversions, bool ForceRValue) {
2462 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002463 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00002464 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002465 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor96176b32008-11-18 23:14:02 +00002466 "Use AddConversionCandidate for conversion functions");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002467 assert(!isa<CXXConstructorDecl>(Method) &&
2468 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00002469
Douglas Gregor3f396022009-09-28 04:47:19 +00002470 if (!CandidateSet.isNewCandidate(Method))
2471 return;
2472
Douglas Gregor7edfb692009-11-23 12:27:39 +00002473 // Overload resolution is always an unevaluated context.
2474 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2475
Douglas Gregor96176b32008-11-18 23:14:02 +00002476 // Add this candidate
2477 CandidateSet.push_back(OverloadCandidate());
2478 OverloadCandidate& Candidate = CandidateSet.back();
2479 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002480 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002481 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002482
2483 unsigned NumArgsInProto = Proto->getNumArgs();
2484
2485 // (C++ 13.3.2p2): A candidate function having fewer than m
2486 // parameters is viable only if it has an ellipsis in its parameter
2487 // list (8.3.5).
2488 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2489 Candidate.Viable = false;
2490 return;
2491 }
2492
2493 // (C++ 13.3.2p2): A candidate function having more than m parameters
2494 // is viable only if the (m+1)st parameter has a default argument
2495 // (8.3.6). For the purposes of overload resolution, the
2496 // parameter list is truncated on the right, so that there are
2497 // exactly m parameters.
2498 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2499 if (NumArgs < MinRequiredArgs) {
2500 // Not enough arguments.
2501 Candidate.Viable = false;
2502 return;
2503 }
2504
2505 Candidate.Viable = true;
2506 Candidate.Conversions.resize(NumArgs + 1);
2507
John McCall701c89e2009-12-03 04:06:58 +00002508 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00002509 // The implicit object argument is ignored.
2510 Candidate.IgnoreObjectArgument = true;
2511 else {
2512 // Determine the implicit conversion sequence for the object
2513 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00002514 Candidate.Conversions[0]
2515 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
Mike Stump1eb44332009-09-09 15:08:12 +00002516 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor88a35142008-12-22 05:46:06 +00002517 == ImplicitConversionSequence::BadConversion) {
2518 Candidate.Viable = false;
2519 return;
2520 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002521 }
2522
2523 // Determine the implicit conversion sequences for each of the
2524 // arguments.
2525 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2526 if (ArgIdx < NumArgsInProto) {
2527 // (C++ 13.3.2p3): for F to be a viable function, there shall
2528 // exist for each argument an implicit conversion sequence
2529 // (13.3.3.1) that converts that argument to the corresponding
2530 // parameter of F.
2531 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002532 Candidate.Conversions[ArgIdx + 1]
2533 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002534 SuppressUserConversions, ForceRValue,
Anders Carlsson08972922009-08-28 15:33:32 +00002535 /*InOverloadResolution=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00002536 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002537 == ImplicitConversionSequence::BadConversion) {
2538 Candidate.Viable = false;
2539 break;
2540 }
2541 } else {
2542 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2543 // argument for which there is no corresponding parameter is
2544 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002545 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002546 = ImplicitConversionSequence::EllipsisConversion;
2547 }
2548 }
2549}
2550
Douglas Gregor6b906862009-08-21 00:16:32 +00002551/// \brief Add a C++ member function template as a candidate to the candidate
2552/// set, using template argument deduction to produce an appropriate member
2553/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002554void
Douglas Gregor6b906862009-08-21 00:16:32 +00002555Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall701c89e2009-12-03 04:06:58 +00002556 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00002557 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00002558 QualType ObjectType,
2559 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002560 OverloadCandidateSet& CandidateSet,
2561 bool SuppressUserConversions,
2562 bool ForceRValue) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002563 if (!CandidateSet.isNewCandidate(MethodTmpl))
2564 return;
2565
Douglas Gregor6b906862009-08-21 00:16:32 +00002566 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002567 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00002568 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002569 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00002570 // candidate functions in the usual way.113) A given name can refer to one
2571 // or more function templates and also to a set of overloaded non-template
2572 // functions. In such a case, the candidate functions generated from each
2573 // function template are combined with the set of non-template candidate
2574 // functions.
2575 TemplateDeductionInfo Info(Context);
2576 FunctionDecl *Specialization = 0;
2577 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00002578 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002579 Args, NumArgs, Specialization, Info)) {
2580 // FIXME: Record what happened with template argument deduction, so
2581 // that we can give the user a beautiful diagnostic.
2582 (void)Result;
2583 return;
2584 }
Mike Stump1eb44332009-09-09 15:08:12 +00002585
Douglas Gregor6b906862009-08-21 00:16:32 +00002586 // Add the function template specialization produced by template argument
2587 // deduction as a candidate.
2588 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00002589 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00002590 "Specialization is not a member function?");
John McCall701c89e2009-12-03 04:06:58 +00002591 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), ActingContext,
2592 ObjectType, Args, NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002593 CandidateSet, SuppressUserConversions, ForceRValue);
2594}
2595
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002596/// \brief Add a C++ function template specialization as a candidate
2597/// in the candidate set, using template argument deduction to produce
2598/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002599void
Douglas Gregore53060f2009-06-25 22:08:12 +00002600Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002601 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002602 Expr **Args, unsigned NumArgs,
2603 OverloadCandidateSet& CandidateSet,
2604 bool SuppressUserConversions,
2605 bool ForceRValue) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002606 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2607 return;
2608
Douglas Gregore53060f2009-06-25 22:08:12 +00002609 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002610 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00002611 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002612 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00002613 // candidate functions in the usual way.113) A given name can refer to one
2614 // or more function templates and also to a set of overloaded non-template
2615 // functions. In such a case, the candidate functions generated from each
2616 // function template are combined with the set of non-template candidate
2617 // functions.
2618 TemplateDeductionInfo Info(Context);
2619 FunctionDecl *Specialization = 0;
2620 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00002621 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002622 Args, NumArgs, Specialization, Info)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002623 // FIXME: Record what happened with template argument deduction, so
2624 // that we can give the user a beautiful diagnostic.
2625 (void)Result;
2626 return;
2627 }
Mike Stump1eb44332009-09-09 15:08:12 +00002628
Douglas Gregore53060f2009-06-25 22:08:12 +00002629 // Add the function template specialization produced by template argument
2630 // deduction as a candidate.
2631 assert(Specialization && "Missing function template specialization?");
2632 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2633 SuppressUserConversions, ForceRValue);
2634}
Mike Stump1eb44332009-09-09 15:08:12 +00002635
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002636/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00002637/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002638/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00002639/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002640/// (which may or may not be the same type as the type that the
2641/// conversion function produces).
2642void
2643Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall701c89e2009-12-03 04:06:58 +00002644 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002645 Expr *From, QualType ToType,
2646 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002647 assert(!Conversion->getDescribedFunctionTemplate() &&
2648 "Conversion function templates use AddTemplateConversionCandidate");
2649
Douglas Gregor3f396022009-09-28 04:47:19 +00002650 if (!CandidateSet.isNewCandidate(Conversion))
2651 return;
2652
Douglas Gregor7edfb692009-11-23 12:27:39 +00002653 // Overload resolution is always an unevaluated context.
2654 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2655
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002656 // Add this candidate
2657 CandidateSet.push_back(OverloadCandidate());
2658 OverloadCandidate& Candidate = CandidateSet.back();
2659 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002660 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002661 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002662 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump1eb44332009-09-09 15:08:12 +00002663 Candidate.FinalConversion.FromTypePtr
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002664 = Conversion->getConversionType().getAsOpaquePtr();
2665 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2666
Douglas Gregor96176b32008-11-18 23:14:02 +00002667 // Determine the implicit conversion sequence for the implicit
2668 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002669 Candidate.Viable = true;
2670 Candidate.Conversions.resize(1);
John McCall701c89e2009-12-03 04:06:58 +00002671 Candidate.Conversions[0]
2672 = TryObjectArgumentInitialization(From->getType(), Conversion,
2673 ActingContext);
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002674 // Conversion functions to a different type in the base class is visible in
2675 // the derived class. So, a derived to base conversion should not participate
2676 // in overload resolution.
2677 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2678 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump1eb44332009-09-09 15:08:12 +00002679 if (Candidate.Conversions[0].ConversionKind
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002680 == ImplicitConversionSequence::BadConversion) {
2681 Candidate.Viable = false;
2682 return;
2683 }
Fariborz Jahanian3759a032009-10-19 19:18:20 +00002684
2685 // We won't go through a user-define type conversion function to convert a
2686 // derived to base as such conversions are given Conversion Rank. They only
2687 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2688 QualType FromCanon
2689 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2690 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2691 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2692 Candidate.Viable = false;
2693 return;
2694 }
2695
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002696
2697 // To determine what the conversion from the result of calling the
2698 // conversion function to the type we're eventually trying to
2699 // convert to (ToType), we need to synthesize a call to the
2700 // conversion function and attempt copy initialization from it. This
2701 // makes sure that we get the right semantics with respect to
2702 // lvalues/rvalues and the type. Fortunately, we can allocate this
2703 // call on the stack and we don't need its arguments to be
2704 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00002705 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00002706 From->getLocStart());
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002707 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman73c39ab2009-10-20 08:27:19 +00002708 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002709 &ConversionRef, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002710
2711 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00002712 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2713 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00002714 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002715 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00002716 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00002717 ImplicitConversionSequence ICS =
2718 TryCopyInitialization(&Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002719 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002720 /*ForceRValue=*/false,
2721 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002722
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002723 switch (ICS.ConversionKind) {
2724 case ImplicitConversionSequence::StandardConversion:
2725 Candidate.FinalConversion = ICS.Standard;
2726 break;
2727
2728 case ImplicitConversionSequence::BadConversion:
2729 Candidate.Viable = false;
2730 break;
2731
2732 default:
Mike Stump1eb44332009-09-09 15:08:12 +00002733 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002734 "Can only end up with a standard conversion sequence or failure");
2735 }
2736}
2737
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002738/// \brief Adds a conversion function template specialization
2739/// candidate to the overload set, using template argument deduction
2740/// to deduce the template arguments of the conversion function
2741/// template from the type that we are converting to (C++
2742/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00002743void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002744Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall701c89e2009-12-03 04:06:58 +00002745 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002746 Expr *From, QualType ToType,
2747 OverloadCandidateSet &CandidateSet) {
2748 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2749 "Only conversion function templates permitted here");
2750
Douglas Gregor3f396022009-09-28 04:47:19 +00002751 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2752 return;
2753
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002754 TemplateDeductionInfo Info(Context);
2755 CXXConversionDecl *Specialization = 0;
2756 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00002757 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002758 Specialization, Info)) {
2759 // FIXME: Record what happened with template argument deduction, so
2760 // that we can give the user a beautiful diagnostic.
2761 (void)Result;
2762 return;
2763 }
Mike Stump1eb44332009-09-09 15:08:12 +00002764
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002765 // Add the conversion function template specialization produced by
2766 // template argument deduction as a candidate.
2767 assert(Specialization && "Missing function template specialization?");
John McCall701c89e2009-12-03 04:06:58 +00002768 AddConversionCandidate(Specialization, ActingDC, From, ToType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002769}
2770
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002771/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2772/// converts the given @c Object to a function pointer via the
2773/// conversion function @c Conversion, and then attempts to call it
2774/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2775/// the type of function that we'll eventually be calling.
2776void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall701c89e2009-12-03 04:06:58 +00002777 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00002778 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00002779 QualType ObjectType,
2780 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002781 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002782 if (!CandidateSet.isNewCandidate(Conversion))
2783 return;
2784
Douglas Gregor7edfb692009-11-23 12:27:39 +00002785 // Overload resolution is always an unevaluated context.
2786 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2787
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002788 CandidateSet.push_back(OverloadCandidate());
2789 OverloadCandidate& Candidate = CandidateSet.back();
2790 Candidate.Function = 0;
2791 Candidate.Surrogate = Conversion;
2792 Candidate.Viable = true;
2793 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002794 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002795 Candidate.Conversions.resize(NumArgs + 1);
2796
2797 // Determine the implicit conversion sequence for the implicit
2798 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00002799 ImplicitConversionSequence ObjectInit
John McCall701c89e2009-12-03 04:06:58 +00002800 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002801 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2802 Candidate.Viable = false;
2803 return;
2804 }
2805
2806 // The first conversion is actually a user-defined conversion whose
2807 // first conversion is ObjectInit's standard conversion (which is
2808 // effectively a reference binding). Record it as such.
Mike Stump1eb44332009-09-09 15:08:12 +00002809 Candidate.Conversions[0].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002810 = ImplicitConversionSequence::UserDefinedConversion;
2811 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002812 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002813 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00002814 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002815 = Candidate.Conversions[0].UserDefined.Before;
2816 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2817
Mike Stump1eb44332009-09-09 15:08:12 +00002818 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002819 unsigned NumArgsInProto = Proto->getNumArgs();
2820
2821 // (C++ 13.3.2p2): A candidate function having fewer than m
2822 // parameters is viable only if it has an ellipsis in its parameter
2823 // list (8.3.5).
2824 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2825 Candidate.Viable = false;
2826 return;
2827 }
2828
2829 // Function types don't have any default arguments, so just check if
2830 // we have enough arguments.
2831 if (NumArgs < NumArgsInProto) {
2832 // Not enough arguments.
2833 Candidate.Viable = false;
2834 return;
2835 }
2836
2837 // Determine the implicit conversion sequences for each of the
2838 // arguments.
2839 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2840 if (ArgIdx < NumArgsInProto) {
2841 // (C++ 13.3.2p3): for F to be a viable function, there shall
2842 // exist for each argument an implicit conversion sequence
2843 // (13.3.3.1) that converts that argument to the corresponding
2844 // parameter of F.
2845 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002846 Candidate.Conversions[ArgIdx + 1]
2847 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002848 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002849 /*ForceRValue=*/false,
2850 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002851 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002852 == ImplicitConversionSequence::BadConversion) {
2853 Candidate.Viable = false;
2854 break;
2855 }
2856 } else {
2857 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2858 // argument for which there is no corresponding parameter is
2859 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002860 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002861 = ImplicitConversionSequence::EllipsisConversion;
2862 }
2863 }
2864}
2865
Mike Stump390b4cc2009-05-16 07:39:55 +00002866// FIXME: This will eventually be removed, once we've migrated all of the
2867// operator overloading logic over to the scheme used by binary operators, which
2868// works for template instantiation.
Douglas Gregor063daf62009-03-13 18:40:31 +00002869void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002870 SourceLocation OpLoc,
Douglas Gregor96176b32008-11-18 23:14:02 +00002871 Expr **Args, unsigned NumArgs,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002872 OverloadCandidateSet& CandidateSet,
2873 SourceRange OpRange) {
Douglas Gregor063daf62009-03-13 18:40:31 +00002874 FunctionSet Functions;
2875
2876 QualType T1 = Args[0]->getType();
2877 QualType T2;
2878 if (NumArgs > 1)
2879 T2 = Args[1]->getType();
2880
2881 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002882 if (S)
2883 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Sebastian Redl644be852009-10-23 19:23:15 +00002884 ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00002885 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2886 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002887 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00002888}
2889
2890/// \brief Add overload candidates for overloaded operators that are
2891/// member functions.
2892///
2893/// Add the overloaded operator candidates that are member functions
2894/// for the operator Op that was used in an operator expression such
2895/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2896/// CandidateSet will store the added overload candidates. (C++
2897/// [over.match.oper]).
2898void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2899 SourceLocation OpLoc,
2900 Expr **Args, unsigned NumArgs,
2901 OverloadCandidateSet& CandidateSet,
2902 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002903 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2904
2905 // C++ [over.match.oper]p3:
2906 // For a unary operator @ with an operand of a type whose
2907 // cv-unqualified version is T1, and for a binary operator @ with
2908 // a left operand of a type whose cv-unqualified version is T1 and
2909 // a right operand of a type whose cv-unqualified version is T2,
2910 // three sets of candidate functions, designated member
2911 // candidates, non-member candidates and built-in candidates, are
2912 // constructed as follows:
2913 QualType T1 = Args[0]->getType();
2914 QualType T2;
2915 if (NumArgs > 1)
2916 T2 = Args[1]->getType();
2917
2918 // -- If T1 is a class type, the set of member candidates is the
2919 // result of the qualified lookup of T1::operator@
2920 // (13.3.1.1.1); otherwise, the set of member candidates is
2921 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00002922 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002923 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00002924 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002925 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002926
John McCalla24dc2e2009-11-17 02:14:36 +00002927 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
2928 LookupQualifiedName(Operators, T1Rec->getDecl());
2929 Operators.suppressDiagnostics();
2930
Mike Stump1eb44332009-09-09 15:08:12 +00002931 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002932 OperEnd = Operators.end();
2933 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00002934 ++Oper)
John McCall701c89e2009-12-03 04:06:58 +00002935 AddMethodCandidate(*Oper, Args[0]->getType(),
2936 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00002937 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00002938 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002939}
2940
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002941/// AddBuiltinCandidate - Add a candidate for a built-in
2942/// operator. ResultTy and ParamTys are the result and parameter types
2943/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002944/// arguments being passed to the candidate. IsAssignmentOperator
2945/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002946/// operator. NumContextualBoolArguments is the number of arguments
2947/// (at the beginning of the argument list) that will be contextually
2948/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00002949void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002950 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002951 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002952 bool IsAssignmentOperator,
2953 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00002954 // Overload resolution is always an unevaluated context.
2955 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2956
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002957 // Add this candidate
2958 CandidateSet.push_back(OverloadCandidate());
2959 OverloadCandidate& Candidate = CandidateSet.back();
2960 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00002961 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002962 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002963 Candidate.BuiltinTypes.ResultTy = ResultTy;
2964 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2965 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2966
2967 // Determine the implicit conversion sequences for each of the
2968 // arguments.
2969 Candidate.Viable = true;
2970 Candidate.Conversions.resize(NumArgs);
2971 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002972 // C++ [over.match.oper]p4:
2973 // For the built-in assignment operators, conversions of the
2974 // left operand are restricted as follows:
2975 // -- no temporaries are introduced to hold the left operand, and
2976 // -- no user-defined conversions are applied to the left
2977 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00002978 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002979 //
2980 // We block these conversions by turning off user-defined
2981 // conversions, since that is the only way that initialization of
2982 // a reference to a non-class type can occur from something that
2983 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002984 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00002985 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002986 "Contextual conversion to bool requires bool type");
2987 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2988 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002989 Candidate.Conversions[ArgIdx]
2990 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00002991 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002992 /*ForceRValue=*/false,
2993 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002994 }
Mike Stump1eb44332009-09-09 15:08:12 +00002995 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002996 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002997 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002998 break;
2999 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003000 }
3001}
3002
3003/// BuiltinCandidateTypeSet - A set of types that will be used for the
3004/// candidate operator functions for built-in operators (C++
3005/// [over.built]). The types are separated into pointer types and
3006/// enumeration types.
3007class BuiltinCandidateTypeSet {
3008 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003009 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003010
3011 /// PointerTypes - The set of pointer types that will be used in the
3012 /// built-in candidates.
3013 TypeSet PointerTypes;
3014
Sebastian Redl78eb8742009-04-19 21:53:20 +00003015 /// MemberPointerTypes - The set of member pointer types that will be
3016 /// used in the built-in candidates.
3017 TypeSet MemberPointerTypes;
3018
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003019 /// EnumerationTypes - The set of enumeration types that will be
3020 /// used in the built-in candidates.
3021 TypeSet EnumerationTypes;
3022
Douglas Gregor5842ba92009-08-24 15:23:48 +00003023 /// Sema - The semantic analysis instance where we are building the
3024 /// candidate type set.
3025 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00003026
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003027 /// Context - The AST context in which we will build the type sets.
3028 ASTContext &Context;
3029
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003030 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3031 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00003032 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003033
3034public:
3035 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003036 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003037
Mike Stump1eb44332009-09-09 15:08:12 +00003038 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00003039 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003040
Douglas Gregor573d9c32009-10-21 23:19:44 +00003041 void AddTypesConvertedFrom(QualType Ty,
3042 SourceLocation Loc,
3043 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003044 bool AllowExplicitConversions,
3045 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003046
3047 /// pointer_begin - First pointer type found;
3048 iterator pointer_begin() { return PointerTypes.begin(); }
3049
Sebastian Redl78eb8742009-04-19 21:53:20 +00003050 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003051 iterator pointer_end() { return PointerTypes.end(); }
3052
Sebastian Redl78eb8742009-04-19 21:53:20 +00003053 /// member_pointer_begin - First member pointer type found;
3054 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3055
3056 /// member_pointer_end - Past the last member pointer type found;
3057 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3058
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003059 /// enumeration_begin - First enumeration type found;
3060 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3061
Sebastian Redl78eb8742009-04-19 21:53:20 +00003062 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003063 iterator enumeration_end() { return EnumerationTypes.end(); }
3064};
3065
Sebastian Redl78eb8742009-04-19 21:53:20 +00003066/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003067/// the set of pointer types along with any more-qualified variants of
3068/// that type. For example, if @p Ty is "int const *", this routine
3069/// will add "int const *", "int const volatile *", "int const
3070/// restrict *", and "int const volatile restrict *" to the set of
3071/// pointer types. Returns true if the add of @p Ty itself succeeded,
3072/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003073///
3074/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003075bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00003076BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3077 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00003078
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003079 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003080 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003081 return false;
3082
John McCall0953e762009-09-24 19:53:00 +00003083 const PointerType *PointerTy = Ty->getAs<PointerType>();
3084 assert(PointerTy && "type was not a pointer type!");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003085
John McCall0953e762009-09-24 19:53:00 +00003086 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003087 // Don't add qualified variants of arrays. For one, they're not allowed
3088 // (the qualifier would sink to the element type), and for another, the
3089 // only overload situation where it matters is subscript or pointer +- int,
3090 // and those shouldn't have qualifier variants anyway.
3091 if (PointeeTy->isArrayType())
3092 return true;
John McCall0953e762009-09-24 19:53:00 +00003093 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00003094 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00003095 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003096 bool hasVolatile = VisibleQuals.hasVolatile();
3097 bool hasRestrict = VisibleQuals.hasRestrict();
3098
John McCall0953e762009-09-24 19:53:00 +00003099 // Iterate through all strict supersets of BaseCVR.
3100 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3101 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003102 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3103 // in the types.
3104 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3105 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00003106 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3107 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003108 }
3109
3110 return true;
3111}
3112
Sebastian Redl78eb8742009-04-19 21:53:20 +00003113/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3114/// to the set of pointer types along with any more-qualified variants of
3115/// that type. For example, if @p Ty is "int const *", this routine
3116/// will add "int const *", "int const volatile *", "int const
3117/// restrict *", and "int const volatile restrict *" to the set of
3118/// pointer types. Returns true if the add of @p Ty itself succeeded,
3119/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003120///
3121/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003122bool
3123BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3124 QualType Ty) {
3125 // Insert this type.
3126 if (!MemberPointerTypes.insert(Ty))
3127 return false;
3128
John McCall0953e762009-09-24 19:53:00 +00003129 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3130 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00003131
John McCall0953e762009-09-24 19:53:00 +00003132 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003133 // Don't add qualified variants of arrays. For one, they're not allowed
3134 // (the qualifier would sink to the element type), and for another, the
3135 // only overload situation where it matters is subscript or pointer +- int,
3136 // and those shouldn't have qualifier variants anyway.
3137 if (PointeeTy->isArrayType())
3138 return true;
John McCall0953e762009-09-24 19:53:00 +00003139 const Type *ClassTy = PointerTy->getClass();
3140
3141 // Iterate through all strict supersets of the pointee type's CVR
3142 // qualifiers.
3143 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3144 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3145 if ((CVR | BaseCVR) != CVR) continue;
3146
3147 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3148 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00003149 }
3150
3151 return true;
3152}
3153
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003154/// AddTypesConvertedFrom - Add each of the types to which the type @p
3155/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00003156/// primarily interested in pointer types and enumeration types. We also
3157/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003158/// AllowUserConversions is true if we should look at the conversion
3159/// functions of a class type, and AllowExplicitConversions if we
3160/// should also include the explicit conversion functions of a class
3161/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003162void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003163BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003164 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003165 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003166 bool AllowExplicitConversions,
3167 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003168 // Only deal with canonical types.
3169 Ty = Context.getCanonicalType(Ty);
3170
3171 // Look through reference types; they aren't part of the type of an
3172 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00003173 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003174 Ty = RefTy->getPointeeType();
3175
3176 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003177 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003178
Sebastian Redla65b5512009-11-05 16:36:20 +00003179 // If we're dealing with an array type, decay to the pointer.
3180 if (Ty->isArrayType())
3181 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3182
Ted Kremenek6217b802009-07-29 21:53:49 +00003183 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003184 QualType PointeeTy = PointerTy->getPointeeType();
3185
3186 // Insert our type, and its more-qualified variants, into the set
3187 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003188 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003189 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00003190 } else if (Ty->isMemberPointerType()) {
3191 // Member pointers are far easier, since the pointee can't be converted.
3192 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3193 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003194 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00003195 EnumerationTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003196 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003197 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003198 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003199 // No conversion functions in incomplete types.
3200 return;
3201 }
Mike Stump1eb44332009-09-09 15:08:12 +00003202
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003203 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallba135432009-11-21 08:51:07 +00003204 const UnresolvedSet *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00003205 = ClassDecl->getVisibleConversionFunctions();
John McCallba135432009-11-21 08:51:07 +00003206 for (UnresolvedSet::iterator I = Conversions->begin(),
3207 E = Conversions->end(); I != E; ++I) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003208
Mike Stump1eb44332009-09-09 15:08:12 +00003209 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003210 // about which builtin types we can convert to.
John McCallba135432009-11-21 08:51:07 +00003211 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003212 continue;
3213
John McCallba135432009-11-21 08:51:07 +00003214 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003215 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003216 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003217 VisibleQuals);
3218 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003219 }
3220 }
3221 }
3222}
3223
Douglas Gregor19b7b152009-08-24 13:43:27 +00003224/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3225/// the volatile- and non-volatile-qualified assignment operators for the
3226/// given type to the candidate set.
3227static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3228 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00003229 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003230 unsigned NumArgs,
3231 OverloadCandidateSet &CandidateSet) {
3232 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00003233
Douglas Gregor19b7b152009-08-24 13:43:27 +00003234 // T& operator=(T&, T)
3235 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3236 ParamTypes[1] = T;
3237 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3238 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003239
Douglas Gregor19b7b152009-08-24 13:43:27 +00003240 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3241 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00003242 ParamTypes[0]
3243 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00003244 ParamTypes[1] = T;
3245 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00003246 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003247 }
3248}
Mike Stump1eb44332009-09-09 15:08:12 +00003249
Sebastian Redl9994a342009-10-25 17:03:50 +00003250/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3251/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003252static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3253 Qualifiers VRQuals;
3254 const RecordType *TyRec;
3255 if (const MemberPointerType *RHSMPType =
3256 ArgExpr->getType()->getAs<MemberPointerType>())
3257 TyRec = cast<RecordType>(RHSMPType->getClass());
3258 else
3259 TyRec = ArgExpr->getType()->getAs<RecordType>();
3260 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003261 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003262 VRQuals.addVolatile();
3263 VRQuals.addRestrict();
3264 return VRQuals;
3265 }
3266
3267 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallba135432009-11-21 08:51:07 +00003268 const UnresolvedSet *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00003269 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003270
John McCallba135432009-11-21 08:51:07 +00003271 for (UnresolvedSet::iterator I = Conversions->begin(),
3272 E = Conversions->end(); I != E; ++I) {
3273 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003274 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3275 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3276 CanTy = ResTypeRef->getPointeeType();
3277 // Need to go down the pointer/mempointer chain and add qualifiers
3278 // as see them.
3279 bool done = false;
3280 while (!done) {
3281 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3282 CanTy = ResTypePtr->getPointeeType();
3283 else if (const MemberPointerType *ResTypeMPtr =
3284 CanTy->getAs<MemberPointerType>())
3285 CanTy = ResTypeMPtr->getPointeeType();
3286 else
3287 done = true;
3288 if (CanTy.isVolatileQualified())
3289 VRQuals.addVolatile();
3290 if (CanTy.isRestrictQualified())
3291 VRQuals.addRestrict();
3292 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3293 return VRQuals;
3294 }
3295 }
3296 }
3297 return VRQuals;
3298}
3299
Douglas Gregor74253732008-11-19 15:42:04 +00003300/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3301/// operator overloads to the candidate set (C++ [over.built]), based
3302/// on the operator @p Op and the arguments given. For example, if the
3303/// operator is a binary '+', this routine might add "int
3304/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003305void
Mike Stump1eb44332009-09-09 15:08:12 +00003306Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003307 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00003308 Expr **Args, unsigned NumArgs,
3309 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003310 // The set of "promoted arithmetic types", which are the arithmetic
3311 // types are that preserved by promotion (C++ [over.built]p2). Note
3312 // that the first few of these types are the promoted integral
3313 // types; these types need to be first.
3314 // FIXME: What about complex?
3315 const unsigned FirstIntegralType = 0;
3316 const unsigned LastIntegralType = 13;
Mike Stump1eb44332009-09-09 15:08:12 +00003317 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003318 LastPromotedIntegralType = 13;
3319 const unsigned FirstPromotedArithmeticType = 7,
3320 LastPromotedArithmeticType = 16;
3321 const unsigned NumArithmeticTypes = 16;
3322 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00003323 Context.BoolTy, Context.CharTy, Context.WCharTy,
3324// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003325 Context.SignedCharTy, Context.ShortTy,
3326 Context.UnsignedCharTy, Context.UnsignedShortTy,
3327 Context.IntTy, Context.LongTy, Context.LongLongTy,
3328 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3329 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3330 };
Douglas Gregor652371a2009-10-21 22:01:30 +00003331 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3332 "Invalid first promoted integral type");
3333 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3334 == Context.UnsignedLongLongTy &&
3335 "Invalid last promoted integral type");
3336 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3337 "Invalid first promoted arithmetic type");
3338 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3339 == Context.LongDoubleTy &&
3340 "Invalid last promoted arithmetic type");
3341
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003342 // Find all of the types that the arguments can convert to, but only
3343 // if the operator we're looking at has built-in operator candidates
3344 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003345 Qualifiers VisibleTypeConversionsQuals;
3346 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003347 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3348 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3349
Douglas Gregor5842ba92009-08-24 15:23:48 +00003350 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003351 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3352 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00003353 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003354 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00003355 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003356 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor74253732008-11-19 15:42:04 +00003357 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003358 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregor573d9c32009-10-21 23:19:44 +00003359 OpLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003360 true,
3361 (Op == OO_Exclaim ||
3362 Op == OO_AmpAmp ||
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003363 Op == OO_PipePipe),
3364 VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003365 }
3366
3367 bool isComparison = false;
3368 switch (Op) {
3369 case OO_None:
3370 case NUM_OVERLOADED_OPERATORS:
3371 assert(false && "Expected an overloaded operator");
3372 break;
3373
Douglas Gregor74253732008-11-19 15:42:04 +00003374 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00003375 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00003376 goto UnaryStar;
3377 else
3378 goto BinaryStar;
3379 break;
3380
3381 case OO_Plus: // '+' is either unary or binary
3382 if (NumArgs == 1)
3383 goto UnaryPlus;
3384 else
3385 goto BinaryPlus;
3386 break;
3387
3388 case OO_Minus: // '-' is either unary or binary
3389 if (NumArgs == 1)
3390 goto UnaryMinus;
3391 else
3392 goto BinaryMinus;
3393 break;
3394
3395 case OO_Amp: // '&' is either unary or binary
3396 if (NumArgs == 1)
3397 goto UnaryAmp;
3398 else
3399 goto BinaryAmp;
3400
3401 case OO_PlusPlus:
3402 case OO_MinusMinus:
3403 // C++ [over.built]p3:
3404 //
3405 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3406 // is either volatile or empty, there exist candidate operator
3407 // functions of the form
3408 //
3409 // VQ T& operator++(VQ T&);
3410 // T operator++(VQ T&, int);
3411 //
3412 // C++ [over.built]p4:
3413 //
3414 // For every pair (T, VQ), where T is an arithmetic type other
3415 // than bool, and VQ is either volatile or empty, there exist
3416 // candidate operator functions of the form
3417 //
3418 // VQ T& operator--(VQ T&);
3419 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00003420 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00003421 Arith < NumArithmeticTypes; ++Arith) {
3422 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00003423 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003424 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00003425
3426 // Non-volatile version.
3427 if (NumArgs == 1)
3428 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3429 else
3430 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003431 // heuristic to reduce number of builtin candidates in the set.
3432 // Add volatile version only if there are conversions to a volatile type.
3433 if (VisibleTypeConversionsQuals.hasVolatile()) {
3434 // Volatile version
3435 ParamTypes[0]
3436 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3437 if (NumArgs == 1)
3438 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3439 else
3440 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3441 }
Douglas Gregor74253732008-11-19 15:42:04 +00003442 }
3443
3444 // C++ [over.built]p5:
3445 //
3446 // For every pair (T, VQ), where T is a cv-qualified or
3447 // cv-unqualified object type, and VQ is either volatile or
3448 // empty, there exist candidate operator functions of the form
3449 //
3450 // T*VQ& operator++(T*VQ&);
3451 // T*VQ& operator--(T*VQ&);
3452 // T* operator++(T*VQ&, int);
3453 // T* operator--(T*VQ&, int);
3454 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3455 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3456 // Skip pointer types that aren't pointers to object types.
Ted Kremenek6217b802009-07-29 21:53:49 +00003457 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00003458 continue;
3459
Mike Stump1eb44332009-09-09 15:08:12 +00003460 QualType ParamTypes[2] = {
3461 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00003462 };
Mike Stump1eb44332009-09-09 15:08:12 +00003463
Douglas Gregor74253732008-11-19 15:42:04 +00003464 // Without volatile
3465 if (NumArgs == 1)
3466 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3467 else
3468 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3469
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003470 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3471 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00003472 // With volatile
John McCall0953e762009-09-24 19:53:00 +00003473 ParamTypes[0]
3474 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00003475 if (NumArgs == 1)
3476 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3477 else
3478 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3479 }
3480 }
3481 break;
3482
3483 UnaryStar:
3484 // C++ [over.built]p6:
3485 // For every cv-qualified or cv-unqualified object type T, there
3486 // exist candidate operator functions of the form
3487 //
3488 // T& operator*(T*);
3489 //
3490 // C++ [over.built]p7:
3491 // For every function type T, there exist candidate operator
3492 // functions of the form
3493 // T& operator*(T*);
3494 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3495 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3496 QualType ParamTy = *Ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00003497 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003498 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00003499 &ParamTy, Args, 1, CandidateSet);
3500 }
3501 break;
3502
3503 UnaryPlus:
3504 // C++ [over.built]p8:
3505 // For every type T, there exist candidate operator functions of
3506 // the form
3507 //
3508 // T* operator+(T*);
3509 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3510 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3511 QualType ParamTy = *Ptr;
3512 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3513 }
Mike Stump1eb44332009-09-09 15:08:12 +00003514
Douglas Gregor74253732008-11-19 15:42:04 +00003515 // Fall through
3516
3517 UnaryMinus:
3518 // C++ [over.built]p9:
3519 // For every promoted arithmetic type T, there exist candidate
3520 // operator functions of the form
3521 //
3522 // T operator+(T);
3523 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003524 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00003525 Arith < LastPromotedArithmeticType; ++Arith) {
3526 QualType ArithTy = ArithmeticTypes[Arith];
3527 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3528 }
3529 break;
3530
3531 case OO_Tilde:
3532 // C++ [over.built]p10:
3533 // For every promoted integral type T, there exist candidate
3534 // operator functions of the form
3535 //
3536 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003537 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00003538 Int < LastPromotedIntegralType; ++Int) {
3539 QualType IntTy = ArithmeticTypes[Int];
3540 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3541 }
3542 break;
3543
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003544 case OO_New:
3545 case OO_Delete:
3546 case OO_Array_New:
3547 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003548 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00003549 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003550 break;
3551
3552 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00003553 UnaryAmp:
3554 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003555 // C++ [over.match.oper]p3:
3556 // -- For the operator ',', the unary operator '&', or the
3557 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003558 break;
3559
Douglas Gregor19b7b152009-08-24 13:43:27 +00003560 case OO_EqualEqual:
3561 case OO_ExclaimEqual:
3562 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00003563 // For every pointer to member type T, there exist candidate operator
3564 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00003565 //
3566 // bool operator==(T,T);
3567 // bool operator!=(T,T);
Mike Stump1eb44332009-09-09 15:08:12 +00003568 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor19b7b152009-08-24 13:43:27 +00003569 MemPtr = CandidateTypes.member_pointer_begin(),
3570 MemPtrEnd = CandidateTypes.member_pointer_end();
3571 MemPtr != MemPtrEnd;
3572 ++MemPtr) {
3573 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3574 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3575 }
Mike Stump1eb44332009-09-09 15:08:12 +00003576
Douglas Gregor19b7b152009-08-24 13:43:27 +00003577 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00003578
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003579 case OO_Less:
3580 case OO_Greater:
3581 case OO_LessEqual:
3582 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003583 // C++ [over.built]p15:
3584 //
3585 // For every pointer or enumeration type T, there exist
3586 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003587 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003588 // bool operator<(T, T);
3589 // bool operator>(T, T);
3590 // bool operator<=(T, T);
3591 // bool operator>=(T, T);
3592 // bool operator==(T, T);
3593 // bool operator!=(T, T);
3594 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3595 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3596 QualType ParamTypes[2] = { *Ptr, *Ptr };
3597 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3598 }
Mike Stump1eb44332009-09-09 15:08:12 +00003599 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003600 = CandidateTypes.enumeration_begin();
3601 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3602 QualType ParamTypes[2] = { *Enum, *Enum };
3603 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3604 }
3605
3606 // Fall through.
3607 isComparison = true;
3608
Douglas Gregor74253732008-11-19 15:42:04 +00003609 BinaryPlus:
3610 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003611 if (!isComparison) {
3612 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3613
3614 // C++ [over.built]p13:
3615 //
3616 // For every cv-qualified or cv-unqualified object type T
3617 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003618 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003619 // T* operator+(T*, ptrdiff_t);
3620 // T& operator[](T*, ptrdiff_t); [BELOW]
3621 // T* operator-(T*, ptrdiff_t);
3622 // T* operator+(ptrdiff_t, T*);
3623 // T& operator[](ptrdiff_t, T*); [BELOW]
3624 //
3625 // C++ [over.built]p14:
3626 //
3627 // For every T, where T is a pointer to object type, there
3628 // exist candidate operator functions of the form
3629 //
3630 // ptrdiff_t operator-(T, T);
Mike Stump1eb44332009-09-09 15:08:12 +00003631 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003632 = CandidateTypes.pointer_begin();
3633 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3634 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3635
3636 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3637 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3638
3639 if (Op == OO_Plus) {
3640 // T* operator+(ptrdiff_t, T*);
3641 ParamTypes[0] = ParamTypes[1];
3642 ParamTypes[1] = *Ptr;
3643 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3644 } else {
3645 // ptrdiff_t operator-(T, T);
3646 ParamTypes[1] = *Ptr;
3647 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3648 Args, 2, CandidateSet);
3649 }
3650 }
3651 }
3652 // Fall through
3653
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003654 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00003655 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003656 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003657 // C++ [over.built]p12:
3658 //
3659 // For every pair of promoted arithmetic types L and R, there
3660 // exist candidate operator functions of the form
3661 //
3662 // LR operator*(L, R);
3663 // LR operator/(L, R);
3664 // LR operator+(L, R);
3665 // LR operator-(L, R);
3666 // bool operator<(L, R);
3667 // bool operator>(L, R);
3668 // bool operator<=(L, R);
3669 // bool operator>=(L, R);
3670 // bool operator==(L, R);
3671 // bool operator!=(L, R);
3672 //
3673 // where LR is the result of the usual arithmetic conversions
3674 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003675 //
3676 // C++ [over.built]p24:
3677 //
3678 // For every pair of promoted arithmetic types L and R, there exist
3679 // candidate operator functions of the form
3680 //
3681 // LR operator?(bool, L, R);
3682 //
3683 // where LR is the result of the usual arithmetic conversions
3684 // between types L and R.
3685 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003686 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003687 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003688 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003689 Right < LastPromotedArithmeticType; ++Right) {
3690 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00003691 QualType Result
3692 = isComparison
3693 ? Context.BoolTy
3694 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003695 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3696 }
3697 }
3698 break;
3699
3700 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00003701 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003702 case OO_Caret:
3703 case OO_Pipe:
3704 case OO_LessLess:
3705 case OO_GreaterGreater:
3706 // C++ [over.built]p17:
3707 //
3708 // For every pair of promoted integral types L and R, there
3709 // exist candidate operator functions of the form
3710 //
3711 // LR operator%(L, R);
3712 // LR operator&(L, R);
3713 // LR operator^(L, R);
3714 // LR operator|(L, R);
3715 // L operator<<(L, R);
3716 // L operator>>(L, R);
3717 //
3718 // where LR is the result of the usual arithmetic conversions
3719 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00003720 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003721 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003722 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003723 Right < LastPromotedIntegralType; ++Right) {
3724 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3725 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3726 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00003727 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003728 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3729 }
3730 }
3731 break;
3732
3733 case OO_Equal:
3734 // C++ [over.built]p20:
3735 //
3736 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00003737 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003738 // empty, there exist candidate operator functions of the form
3739 //
3740 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003741 for (BuiltinCandidateTypeSet::iterator
3742 Enum = CandidateTypes.enumeration_begin(),
3743 EnumEnd = CandidateTypes.enumeration_end();
3744 Enum != EnumEnd; ++Enum)
Mike Stump1eb44332009-09-09 15:08:12 +00003745 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003746 CandidateSet);
3747 for (BuiltinCandidateTypeSet::iterator
3748 MemPtr = CandidateTypes.member_pointer_begin(),
3749 MemPtrEnd = CandidateTypes.member_pointer_end();
3750 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump1eb44332009-09-09 15:08:12 +00003751 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003752 CandidateSet);
3753 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003754
3755 case OO_PlusEqual:
3756 case OO_MinusEqual:
3757 // C++ [over.built]p19:
3758 //
3759 // For every pair (T, VQ), where T is any type and VQ is either
3760 // volatile or empty, there exist candidate operator functions
3761 // of the form
3762 //
3763 // T*VQ& operator=(T*VQ&, T*);
3764 //
3765 // C++ [over.built]p21:
3766 //
3767 // For every pair (T, VQ), where T is a cv-qualified or
3768 // cv-unqualified object type and VQ is either volatile or
3769 // empty, there exist candidate operator functions of the form
3770 //
3771 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3772 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3773 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3774 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3775 QualType ParamTypes[2];
3776 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3777
3778 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003779 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003780 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3781 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003782
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003783 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3784 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00003785 // volatile version
John McCall0953e762009-09-24 19:53:00 +00003786 ParamTypes[0]
3787 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003788 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3789 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00003790 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003791 }
3792 // Fall through.
3793
3794 case OO_StarEqual:
3795 case OO_SlashEqual:
3796 // C++ [over.built]p18:
3797 //
3798 // For every triple (L, VQ, R), where L is an arithmetic type,
3799 // VQ is either volatile or empty, and R is a promoted
3800 // arithmetic type, there exist candidate operator functions of
3801 // the form
3802 //
3803 // VQ L& operator=(VQ L&, R);
3804 // VQ L& operator*=(VQ L&, R);
3805 // VQ L& operator/=(VQ L&, R);
3806 // VQ L& operator+=(VQ L&, R);
3807 // VQ L& operator-=(VQ L&, R);
3808 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003809 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003810 Right < LastPromotedArithmeticType; ++Right) {
3811 QualType ParamTypes[2];
3812 ParamTypes[1] = ArithmeticTypes[Right];
3813
3814 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003815 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003816 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3817 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003818
3819 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003820 if (VisibleTypeConversionsQuals.hasVolatile()) {
3821 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3822 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3823 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3824 /*IsAssigmentOperator=*/Op == OO_Equal);
3825 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003826 }
3827 }
3828 break;
3829
3830 case OO_PercentEqual:
3831 case OO_LessLessEqual:
3832 case OO_GreaterGreaterEqual:
3833 case OO_AmpEqual:
3834 case OO_CaretEqual:
3835 case OO_PipeEqual:
3836 // C++ [over.built]p22:
3837 //
3838 // For every triple (L, VQ, R), where L is an integral type, VQ
3839 // is either volatile or empty, and R is a promoted integral
3840 // type, there exist candidate operator functions of the form
3841 //
3842 // VQ L& operator%=(VQ L&, R);
3843 // VQ L& operator<<=(VQ L&, R);
3844 // VQ L& operator>>=(VQ L&, R);
3845 // VQ L& operator&=(VQ L&, R);
3846 // VQ L& operator^=(VQ L&, R);
3847 // VQ L& operator|=(VQ L&, R);
3848 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003849 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003850 Right < LastPromotedIntegralType; ++Right) {
3851 QualType ParamTypes[2];
3852 ParamTypes[1] = ArithmeticTypes[Right];
3853
3854 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003855 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003856 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00003857 if (VisibleTypeConversionsQuals.hasVolatile()) {
3858 // Add this built-in operator as a candidate (VQ is 'volatile').
3859 ParamTypes[0] = ArithmeticTypes[Left];
3860 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3861 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3862 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3863 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003864 }
3865 }
3866 break;
3867
Douglas Gregor74253732008-11-19 15:42:04 +00003868 case OO_Exclaim: {
3869 // C++ [over.operator]p23:
3870 //
3871 // There also exist candidate operator functions of the form
3872 //
Mike Stump1eb44332009-09-09 15:08:12 +00003873 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00003874 // bool operator&&(bool, bool); [BELOW]
3875 // bool operator||(bool, bool); [BELOW]
3876 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003877 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3878 /*IsAssignmentOperator=*/false,
3879 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00003880 break;
3881 }
3882
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003883 case OO_AmpAmp:
3884 case OO_PipePipe: {
3885 // C++ [over.operator]p23:
3886 //
3887 // There also exist candidate operator functions of the form
3888 //
Douglas Gregor74253732008-11-19 15:42:04 +00003889 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003890 // bool operator&&(bool, bool);
3891 // bool operator||(bool, bool);
3892 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003893 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3894 /*IsAssignmentOperator=*/false,
3895 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003896 break;
3897 }
3898
3899 case OO_Subscript:
3900 // C++ [over.built]p13:
3901 //
3902 // For every cv-qualified or cv-unqualified object type T there
3903 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003904 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003905 // T* operator+(T*, ptrdiff_t); [ABOVE]
3906 // T& operator[](T*, ptrdiff_t);
3907 // T* operator-(T*, ptrdiff_t); [ABOVE]
3908 // T* operator+(ptrdiff_t, T*); [ABOVE]
3909 // T& operator[](ptrdiff_t, T*);
3910 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3911 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3912 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenek6217b802009-07-29 21:53:49 +00003913 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003914 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003915
3916 // T& operator[](T*, ptrdiff_t)
3917 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3918
3919 // T& operator[](ptrdiff_t, T*);
3920 ParamTypes[0] = ParamTypes[1];
3921 ParamTypes[1] = *Ptr;
3922 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3923 }
3924 break;
3925
3926 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003927 // C++ [over.built]p11:
3928 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
3929 // C1 is the same type as C2 or is a derived class of C2, T is an object
3930 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
3931 // there exist candidate operator functions of the form
3932 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
3933 // where CV12 is the union of CV1 and CV2.
3934 {
3935 for (BuiltinCandidateTypeSet::iterator Ptr =
3936 CandidateTypes.pointer_begin();
3937 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3938 QualType C1Ty = (*Ptr);
3939 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00003940 QualifierCollector Q1;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003941 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00003942 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003943 if (!isa<RecordType>(C1))
3944 continue;
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003945 // heuristic to reduce number of builtin candidates in the set.
3946 // Add volatile/restrict version only if there are conversions to a
3947 // volatile/restrict type.
3948 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
3949 continue;
3950 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
3951 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003952 }
3953 for (BuiltinCandidateTypeSet::iterator
3954 MemPtr = CandidateTypes.member_pointer_begin(),
3955 MemPtrEnd = CandidateTypes.member_pointer_end();
3956 MemPtr != MemPtrEnd; ++MemPtr) {
3957 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
3958 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00003959 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003960 if (C1 != C2 && !IsDerivedFrom(C1, C2))
3961 break;
3962 QualType ParamTypes[2] = { *Ptr, *MemPtr };
3963 // build CV12 T&
3964 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003965 if (!VisibleTypeConversionsQuals.hasVolatile() &&
3966 T.isVolatileQualified())
3967 continue;
3968 if (!VisibleTypeConversionsQuals.hasRestrict() &&
3969 T.isRestrictQualified())
3970 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00003971 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003972 QualType ResultTy = Context.getLValueReferenceType(T);
3973 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3974 }
3975 }
3976 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003977 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003978
3979 case OO_Conditional:
3980 // Note that we don't consider the first argument, since it has been
3981 // contextually converted to bool long ago. The candidates below are
3982 // therefore added as binary.
3983 //
3984 // C++ [over.built]p24:
3985 // For every type T, where T is a pointer or pointer-to-member type,
3986 // there exist candidate operator functions of the form
3987 //
3988 // T operator?(bool, T, T);
3989 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003990 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3991 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3992 QualType ParamTypes[2] = { *Ptr, *Ptr };
3993 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3994 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00003995 for (BuiltinCandidateTypeSet::iterator Ptr =
3996 CandidateTypes.member_pointer_begin(),
3997 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3998 QualType ParamTypes[2] = { *Ptr, *Ptr };
3999 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4000 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004001 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004002 }
4003}
4004
Douglas Gregorfa047642009-02-04 00:32:51 +00004005/// \brief Add function candidates found via argument-dependent lookup
4006/// to the set of overloading candidates.
4007///
4008/// This routine performs argument-dependent name lookup based on the
4009/// given function name (which may also be an operator name) and adds
4010/// all of the overload candidates found by ADL to the overload
4011/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00004012void
Douglas Gregorfa047642009-02-04 00:32:51 +00004013Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
4014 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00004015 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004016 OverloadCandidateSet& CandidateSet,
4017 bool PartialOverloading) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004018 FunctionSet Functions;
Douglas Gregorfa047642009-02-04 00:32:51 +00004019
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004020 // FIXME: Should we be trafficking in canonical function decls throughout?
4021
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004022 // Record all of the function candidates that we've already
4023 // added to the overload set, so that we don't add those same
4024 // candidates a second time.
4025 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4026 CandEnd = CandidateSet.end();
4027 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00004028 if (Cand->Function) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004029 Functions.insert(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00004030 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4031 Functions.insert(FunTmpl);
4032 }
Douglas Gregorfa047642009-02-04 00:32:51 +00004033
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004034 // FIXME: Pass in the explicit template arguments?
Sebastian Redl644be852009-10-23 19:23:15 +00004035 ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
Douglas Gregorfa047642009-02-04 00:32:51 +00004036
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004037 // Erase all of the candidates we already knew about.
4038 // FIXME: This is suboptimal. Is there a better way?
4039 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4040 CandEnd = CandidateSet.end();
4041 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00004042 if (Cand->Function) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004043 Functions.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00004044 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4045 Functions.erase(FunTmpl);
4046 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004047
4048 // For each of the ADL candidates we found, add it to the overload
4049 // set.
4050 for (FunctionSet::iterator Func = Functions.begin(),
4051 FuncEnd = Functions.end();
Douglas Gregor364e0212009-06-27 21:05:07 +00004052 Func != FuncEnd; ++Func) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004053 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
John McCalld5532b62009-11-23 01:53:49 +00004054 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004055 continue;
4056
4057 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
4058 false, false, PartialOverloading);
4059 } else
Mike Stump1eb44332009-09-09 15:08:12 +00004060 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004061 ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004062 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00004063 }
Douglas Gregorfa047642009-02-04 00:32:51 +00004064}
4065
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004066/// isBetterOverloadCandidate - Determines whether the first overload
4067/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00004068bool
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004069Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump1eb44332009-09-09 15:08:12 +00004070 const OverloadCandidate& Cand2) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004071 // Define viable functions to be better candidates than non-viable
4072 // functions.
4073 if (!Cand2.Viable)
4074 return Cand1.Viable;
4075 else if (!Cand1.Viable)
4076 return false;
4077
Douglas Gregor88a35142008-12-22 05:46:06 +00004078 // C++ [over.match.best]p1:
4079 //
4080 // -- if F is a static member function, ICS1(F) is defined such
4081 // that ICS1(F) is neither better nor worse than ICS1(G) for
4082 // any function G, and, symmetrically, ICS1(G) is neither
4083 // better nor worse than ICS1(F).
4084 unsigned StartArg = 0;
4085 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4086 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004087
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004088 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00004089 // A viable function F1 is defined to be a better function than another
4090 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004091 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004092 unsigned NumArgs = Cand1.Conversions.size();
4093 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4094 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004095 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004096 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4097 Cand2.Conversions[ArgIdx])) {
4098 case ImplicitConversionSequence::Better:
4099 // Cand1 has a better conversion sequence.
4100 HasBetterConversion = true;
4101 break;
4102
4103 case ImplicitConversionSequence::Worse:
4104 // Cand1 can't be better than Cand2.
4105 return false;
4106
4107 case ImplicitConversionSequence::Indistinguishable:
4108 // Do nothing.
4109 break;
4110 }
4111 }
4112
Mike Stump1eb44332009-09-09 15:08:12 +00004113 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004114 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004115 if (HasBetterConversion)
4116 return true;
4117
Mike Stump1eb44332009-09-09 15:08:12 +00004118 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004119 // specialization, or, if not that,
4120 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4121 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4122 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004123
4124 // -- F1 and F2 are function template specializations, and the function
4125 // template for F1 is more specialized than the template for F2
4126 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004127 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00004128 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4129 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004130 if (FunctionTemplateDecl *BetterTemplate
4131 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4132 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor5d7d3752009-09-14 23:02:14 +00004133 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4134 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004135 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004136
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004137 // -- the context is an initialization by user-defined conversion
4138 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4139 // from the return type of F1 to the destination type (i.e.,
4140 // the type of the entity being initialized) is a better
4141 // conversion sequence than the standard conversion sequence
4142 // from the return type of F2 to the destination type.
Mike Stump1eb44332009-09-09 15:08:12 +00004143 if (Cand1.Function && Cand2.Function &&
4144 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004145 isa<CXXConversionDecl>(Cand2.Function)) {
4146 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4147 Cand2.FinalConversion)) {
4148 case ImplicitConversionSequence::Better:
4149 // Cand1 has a better conversion sequence.
4150 return true;
4151
4152 case ImplicitConversionSequence::Worse:
4153 // Cand1 can't be better than Cand2.
4154 return false;
4155
4156 case ImplicitConversionSequence::Indistinguishable:
4157 // Do nothing
4158 break;
4159 }
4160 }
4161
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004162 return false;
4163}
4164
Mike Stump1eb44332009-09-09 15:08:12 +00004165/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00004166/// within an overload candidate set.
4167///
4168/// \param CandidateSet the set of candidate functions.
4169///
4170/// \param Loc the location of the function name (or operator symbol) for
4171/// which overload resolution occurs.
4172///
Mike Stump1eb44332009-09-09 15:08:12 +00004173/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00004174/// function, Best points to the candidate function found.
4175///
4176/// \returns The result of overload resolution.
Douglas Gregor20093b42009-12-09 23:02:17 +00004177OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4178 SourceLocation Loc,
4179 OverloadCandidateSet::iterator& Best) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004180 // Find the best viable function.
4181 Best = CandidateSet.end();
4182 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4183 Cand != CandidateSet.end(); ++Cand) {
4184 if (Cand->Viable) {
4185 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4186 Best = Cand;
4187 }
4188 }
4189
4190 // If we didn't find any viable functions, abort.
4191 if (Best == CandidateSet.end())
4192 return OR_No_Viable_Function;
4193
4194 // Make sure that this function is better than every other viable
4195 // function. If not, we have an ambiguity.
4196 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4197 Cand != CandidateSet.end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00004198 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004199 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004200 !isBetterOverloadCandidate(*Best, *Cand)) {
4201 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004202 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004203 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004204 }
Mike Stump1eb44332009-09-09 15:08:12 +00004205
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004206 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004207 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00004208 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004209 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004210 return OR_Deleted;
4211
Douglas Gregore0762c92009-06-19 23:52:42 +00004212 // C++ [basic.def.odr]p2:
4213 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00004214 // when referred to from a potentially-evaluated expression. [Note: this
4215 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00004216 // (clause 13), user-defined conversions (12.3.2), allocation function for
4217 // placement new (5.3.4), as well as non-default initialization (8.5).
4218 if (Best->Function)
4219 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004220 return OR_Success;
4221}
4222
4223/// PrintOverloadCandidates - When overload resolution fails, prints
4224/// diagnostic messages containing the candidates in the candidate
4225/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump1eb44332009-09-09 15:08:12 +00004226void
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004227Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Fariborz Jahanian16a5eac2009-10-09 00:13:15 +00004228 bool OnlyViable,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004229 const char *Opc,
Fariborz Jahanian16a5eac2009-10-09 00:13:15 +00004230 SourceLocation OpLoc) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004231 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4232 LastCand = CandidateSet.end();
Fariborz Jahanian27687cf2009-10-12 17:51:19 +00004233 bool Reported = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004234 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004235 if (Cand->Viable || !OnlyViable) {
4236 if (Cand->Function) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004237 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004238 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004239 // Deleted or "unavailable" function.
4240 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
4241 << Cand->Function->isDeleted();
Douglas Gregor1fdd89b2009-09-15 20:11:42 +00004242 } else if (FunctionTemplateDecl *FunTmpl
4243 = Cand->Function->getPrimaryTemplate()) {
4244 // Function template specialization
4245 // FIXME: Give a better reason!
4246 Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
4247 << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
4248 *Cand->Function->getTemplateSpecializationArgs());
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004249 } else {
4250 // Normal function
Fariborz Jahanianb1663d02009-09-23 00:58:07 +00004251 bool errReported = false;
4252 if (!Cand->Viable && Cand->Conversions.size() > 0) {
4253 for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
4254 const ImplicitConversionSequence &Conversion =
4255 Cand->Conversions[i];
4256 if ((Conversion.ConversionKind !=
4257 ImplicitConversionSequence::BadConversion) ||
4258 Conversion.ConversionFunctionSet.size() == 0)
4259 continue;
4260 Diag(Cand->Function->getLocation(),
4261 diag::err_ovl_candidate_not_viable) << (i+1);
4262 errReported = true;
4263 for (int j = Conversion.ConversionFunctionSet.size()-1;
4264 j >= 0; j--) {
4265 FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
4266 Diag(Func->getLocation(), diag::err_ovl_candidate);
4267 }
4268 }
4269 }
4270 if (!errReported)
4271 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004272 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004273 } else if (Cand->IsSurrogate) {
Douglas Gregor621b3932008-11-21 02:54:28 +00004274 // Desugar the type of the surrogate down to a function type,
4275 // retaining as many typedefs as possible while still showing
4276 // the function type (and, therefore, its parameter types).
4277 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004278 bool isLValueReference = false;
4279 bool isRValueReference = false;
Douglas Gregor621b3932008-11-21 02:54:28 +00004280 bool isPointer = false;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004281 if (const LValueReferenceType *FnTypeRef =
Ted Kremenek6217b802009-07-29 21:53:49 +00004282 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor621b3932008-11-21 02:54:28 +00004283 FnType = FnTypeRef->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004284 isLValueReference = true;
4285 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenek6217b802009-07-29 21:53:49 +00004286 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004287 FnType = FnTypeRef->getPointeeType();
4288 isRValueReference = true;
Douglas Gregor621b3932008-11-21 02:54:28 +00004289 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004290 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor621b3932008-11-21 02:54:28 +00004291 FnType = FnTypePtr->getPointeeType();
4292 isPointer = true;
4293 }
4294 // Desugar down to a function type.
John McCall183700f2009-09-21 23:43:11 +00004295 FnType = QualType(FnType->getAs<FunctionType>(), 0);
Douglas Gregor621b3932008-11-21 02:54:28 +00004296 // Reconstruct the pointer/reference as appropriate.
4297 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004298 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
4299 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor621b3932008-11-21 02:54:28 +00004300
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004301 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattnerd1625842008-11-24 06:25:27 +00004302 << FnType;
Douglas Gregor33074752009-09-30 21:46:01 +00004303 } else if (OnlyViable) {
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004304 assert(Cand->Conversions.size() <= 2 &&
Fariborz Jahanianad3607d2009-10-09 17:09:58 +00004305 "builtin-binary-operator-not-binary");
Fariborz Jahanian866b2742009-10-16 23:25:02 +00004306 std::string TypeStr("operator");
4307 TypeStr += Opc;
4308 TypeStr += "(";
4309 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4310 if (Cand->Conversions.size() == 1) {
4311 TypeStr += ")";
4312 Diag(OpLoc, diag::err_ovl_builtin_unary_candidate) << TypeStr;
4313 }
4314 else {
4315 TypeStr += ", ";
4316 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4317 TypeStr += ")";
4318 Diag(OpLoc, diag::err_ovl_builtin_binary_candidate) << TypeStr;
4319 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004320 }
Fariborz Jahanian27687cf2009-10-12 17:51:19 +00004321 else if (!Cand->Viable && !Reported) {
4322 // Non-viability might be due to ambiguous user-defined conversions,
4323 // needed for built-in operators. Report them as well, but only once
4324 // as we have typically many built-in candidates.
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004325 unsigned NoOperands = Cand->Conversions.size();
4326 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
Fariborz Jahanian27687cf2009-10-12 17:51:19 +00004327 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
4328 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion ||
4329 ICS.ConversionFunctionSet.empty())
4330 continue;
4331 if (CXXConversionDecl *Func = dyn_cast<CXXConversionDecl>(
4332 Cand->Conversions[ArgIdx].ConversionFunctionSet[0])) {
4333 QualType FromTy =
4334 QualType(
4335 static_cast<Type*>(ICS.UserDefined.Before.FromTypePtr),0);
4336 Diag(OpLoc,diag::note_ambiguous_type_conversion)
4337 << FromTy << Func->getConversionType();
4338 }
4339 for (unsigned j = 0; j < ICS.ConversionFunctionSet.size(); j++) {
4340 FunctionDecl *Func =
4341 Cand->Conversions[ArgIdx].ConversionFunctionSet[j];
4342 Diag(Func->getLocation(),diag::err_ovl_candidate);
4343 }
4344 }
4345 Reported = true;
4346 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004347 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004348 }
4349}
4350
Douglas Gregor904eed32008-11-10 20:40:00 +00004351/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4352/// an overloaded function (C++ [over.over]), where @p From is an
4353/// expression with overloaded function type and @p ToType is the type
4354/// we're trying to resolve to. For example:
4355///
4356/// @code
4357/// int f(double);
4358/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00004359///
Douglas Gregor904eed32008-11-10 20:40:00 +00004360/// int (*pfd)(double) = f; // selects f(double)
4361/// @endcode
4362///
4363/// This routine returns the resulting FunctionDecl if it could be
4364/// resolved, and NULL otherwise. When @p Complain is true, this
4365/// routine will emit diagnostics if there is an error.
4366FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00004367Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor904eed32008-11-10 20:40:00 +00004368 bool Complain) {
4369 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00004370 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00004371 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00004372 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004373 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00004374 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00004375 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00004376 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00004377 FunctionType = MemTypePtr->getPointeeType();
4378 IsMember = true;
4379 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004380
4381 // We only look at pointers or references to functions.
Douglas Gregor72e771f2009-07-09 17:16:51 +00004382 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor83314aa2009-07-08 20:55:45 +00004383 if (!FunctionType->isFunctionType())
Douglas Gregor904eed32008-11-10 20:40:00 +00004384 return 0;
4385
4386 // Find the actual overloaded function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00004387
Douglas Gregor904eed32008-11-10 20:40:00 +00004388 // C++ [over.over]p1:
4389 // [...] [Note: any redundant set of parentheses surrounding the
4390 // overloaded function name is ignored (5.1). ]
4391 Expr *OvlExpr = From->IgnoreParens();
4392
4393 // C++ [over.over]p1:
4394 // [...] The overloaded function name can be preceded by the &
4395 // operator.
4396 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4397 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4398 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4399 }
4400
Anders Carlsson70534852009-10-20 22:53:47 +00004401 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00004402 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCallba135432009-11-21 08:51:07 +00004403
4404 llvm::SmallVector<NamedDecl*,8> Fns;
Anders Carlsson70534852009-10-20 22:53:47 +00004405
John McCall129e2df2009-11-30 22:42:35 +00004406 // Look into the overloaded expression.
John McCallf7a1a742009-11-24 19:00:30 +00004407 if (UnresolvedLookupExpr *UL
John McCallba135432009-11-21 08:51:07 +00004408 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4409 Fns.append(UL->decls_begin(), UL->decls_end());
John McCallf7a1a742009-11-24 19:00:30 +00004410 if (UL->hasExplicitTemplateArgs()) {
4411 HasExplicitTemplateArgs = true;
4412 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4413 }
John McCall129e2df2009-11-30 22:42:35 +00004414 } else if (UnresolvedMemberExpr *ME
4415 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4416 Fns.append(ME->decls_begin(), ME->decls_end());
4417 if (ME->hasExplicitTemplateArgs()) {
4418 HasExplicitTemplateArgs = true;
John McCalld5532b62009-11-23 01:53:49 +00004419 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004420 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00004421 }
Mike Stump1eb44332009-09-09 15:08:12 +00004422
John McCallba135432009-11-21 08:51:07 +00004423 // If we didn't actually find anything, we're done.
4424 if (Fns.empty())
4425 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004426
Douglas Gregor904eed32008-11-10 20:40:00 +00004427 // Look through all of the overloaded functions, searching for one
4428 // whose type matches exactly.
Douglas Gregor00aeb522009-07-08 23:33:52 +00004429 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004430 bool FoundNonTemplateFunction = false;
John McCallba135432009-11-21 08:51:07 +00004431 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4432 E = Fns.end(); I != E; ++I) {
Douglas Gregor904eed32008-11-10 20:40:00 +00004433 // C++ [over.over]p3:
4434 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00004435 // targets of type "pointer-to-function" or "reference-to-function."
4436 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00004437 // type "pointer-to-member-function."
4438 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00004439
Mike Stump1eb44332009-09-09 15:08:12 +00004440 if (FunctionTemplateDecl *FunctionTemplate
John McCallba135432009-11-21 08:51:07 +00004441 = dyn_cast<FunctionTemplateDecl>(*I)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004442 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00004443 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004444 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00004445 // static when converting to member pointer.
4446 if (Method->isStatic() == IsMember)
4447 continue;
4448 } else if (IsMember)
4449 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00004450
Douglas Gregor00aeb522009-07-08 23:33:52 +00004451 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004452 // If the name is a function template, template argument deduction is
4453 // done (14.8.2.2), and if the argument deduction succeeds, the
4454 // resulting template argument list is used to generate a single
4455 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00004456 // overloaded functions considered.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004457 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor83314aa2009-07-08 20:55:45 +00004458 FunctionDecl *Specialization = 0;
4459 TemplateDeductionInfo Info(Context);
4460 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00004461 = DeduceTemplateArguments(FunctionTemplate,
4462 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
Douglas Gregor83314aa2009-07-08 20:55:45 +00004463 FunctionType, Specialization, Info)) {
4464 // FIXME: make a note of the failed deduction for diagnostics.
4465 (void)Result;
4466 } else {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004467 // FIXME: If the match isn't exact, shouldn't we just drop this as
4468 // a candidate? Find a testcase before changing the code.
Mike Stump1eb44332009-09-09 15:08:12 +00004469 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00004470 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor00aeb522009-07-08 23:33:52 +00004471 Matches.insert(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00004472 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor83314aa2009-07-08 20:55:45 +00004473 }
John McCallba135432009-11-21 08:51:07 +00004474
4475 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00004476 }
Mike Stump1eb44332009-09-09 15:08:12 +00004477
John McCallba135432009-11-21 08:51:07 +00004478 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00004479 // Skip non-static functions when converting to pointer, and static
4480 // when converting to member pointer.
4481 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00004482 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00004483
4484 // If we have explicit template arguments, skip non-templates.
4485 if (HasExplicitTemplateArgs)
4486 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004487 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00004488 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00004489
John McCallba135432009-11-21 08:51:07 +00004490 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*I)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00004491 QualType ResultTy;
4492 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
4493 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
4494 ResultTy)) {
John McCallba135432009-11-21 08:51:07 +00004495 Matches.insert(cast<FunctionDecl>(FunDecl->getCanonicalDecl()));
Douglas Gregor00aeb522009-07-08 23:33:52 +00004496 FoundNonTemplateFunction = true;
4497 }
Mike Stump1eb44332009-09-09 15:08:12 +00004498 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004499 }
4500
Douglas Gregor00aeb522009-07-08 23:33:52 +00004501 // If there were 0 or 1 matches, we're done.
4502 if (Matches.empty())
4503 return 0;
Sebastian Redl07ab2022009-10-17 21:12:09 +00004504 else if (Matches.size() == 1) {
4505 FunctionDecl *Result = *Matches.begin();
4506 MarkDeclarationReferenced(From->getLocStart(), Result);
4507 return Result;
4508 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00004509
4510 // C++ [over.over]p4:
4511 // If more than one function is selected, [...]
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004512 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregor312a2022009-09-26 03:56:17 +00004513 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004514 // [...] and any given function template specialization F1 is
4515 // eliminated if the set contains a second function template
4516 // specialization whose function template is more specialized
4517 // than the function template of F1 according to the partial
4518 // ordering rules of 14.5.5.2.
4519
4520 // The algorithm specified above is quadratic. We instead use a
4521 // two-pass algorithm (similar to the one used to identify the
4522 // best viable function in an overload set) that identifies the
4523 // best function template (if it exists).
Sebastian Redl07ab2022009-10-17 21:12:09 +00004524 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
Douglas Gregor312a2022009-09-26 03:56:17 +00004525 Matches.end());
Sebastian Redl07ab2022009-10-17 21:12:09 +00004526 FunctionDecl *Result =
4527 getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4528 TPOC_Other, From->getLocStart(),
4529 PDiag(),
4530 PDiag(diag::err_addr_ovl_ambiguous)
4531 << TemplateMatches[0]->getDeclName(),
4532 PDiag(diag::err_ovl_template_candidate));
4533 MarkDeclarationReferenced(From->getLocStart(), Result);
4534 return Result;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004535 }
Mike Stump1eb44332009-09-09 15:08:12 +00004536
Douglas Gregor312a2022009-09-26 03:56:17 +00004537 // [...] any function template specializations in the set are
4538 // eliminated if the set also contains a non-template function, [...]
4539 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4540 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4541 if ((*M)->getPrimaryTemplate() == 0)
4542 RemainingMatches.push_back(*M);
4543
Mike Stump1eb44332009-09-09 15:08:12 +00004544 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00004545 // selected function.
Sebastian Redl07ab2022009-10-17 21:12:09 +00004546 if (RemainingMatches.size() == 1) {
4547 FunctionDecl *Result = RemainingMatches.front();
4548 MarkDeclarationReferenced(From->getLocStart(), Result);
4549 return Result;
4550 }
Mike Stump1eb44332009-09-09 15:08:12 +00004551
Douglas Gregor00aeb522009-07-08 23:33:52 +00004552 // FIXME: We should probably return the same thing that BestViableFunction
4553 // returns (even if we issue the diagnostics here).
4554 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4555 << RemainingMatches[0]->getDeclName();
4556 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4557 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregor904eed32008-11-10 20:40:00 +00004558 return 0;
4559}
4560
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004561/// \brief Add a single candidate to the overload set.
4562static void AddOverloadedCallCandidate(Sema &S,
John McCallba135432009-11-21 08:51:07 +00004563 NamedDecl *Callee,
John McCalld5532b62009-11-23 01:53:49 +00004564 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004565 Expr **Args, unsigned NumArgs,
4566 OverloadCandidateSet &CandidateSet,
4567 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00004568 if (isa<UsingShadowDecl>(Callee))
4569 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
4570
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004571 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00004572 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004573 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4574 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004575 return;
John McCallba135432009-11-21 08:51:07 +00004576 }
4577
4578 if (FunctionTemplateDecl *FuncTemplate
4579 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00004580 S.AddTemplateOverloadCandidate(FuncTemplate, ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00004581 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00004582 return;
4583 }
4584
4585 assert(false && "unhandled case in overloaded call candidate");
4586
4587 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004588}
4589
4590/// \brief Add the overload candidates named by callee and/or found by argument
4591/// dependent lookup to the given overload set.
John McCallba135432009-11-21 08:51:07 +00004592void Sema::AddOverloadedCallCandidates(llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004593 DeclarationName &UnqualifiedName,
John McCalld2ede7d2009-11-21 09:38:42 +00004594 bool ArgumentDependentLookup,
John McCalld5532b62009-11-23 01:53:49 +00004595 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004596 Expr **Args, unsigned NumArgs,
4597 OverloadCandidateSet &CandidateSet,
4598 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00004599
4600#ifndef NDEBUG
4601 // Verify that ArgumentDependentLookup is consistent with the rules
4602 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004603 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004604 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4605 // and let Y be the lookup set produced by argument dependent
4606 // lookup (defined as follows). If X contains
4607 //
4608 // -- a declaration of a class member, or
4609 //
4610 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00004611 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004612 //
4613 // -- a declaration that is neither a function or a function
4614 // template
4615 //
4616 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00004617
4618 if (ArgumentDependentLookup) {
4619 for (unsigned I = 0; I < Fns.size(); ++I) {
4620 assert(!Fns[I]->getDeclContext()->isRecord());
4621 assert(isa<UsingShadowDecl>(Fns[I]) ||
4622 !Fns[I]->getDeclContext()->isFunctionOrMethod());
4623 assert(Fns[I]->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
4624 }
4625 }
4626#endif
4627
4628 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4629 E = Fns.end(); I != E; ++I)
John McCalld5532b62009-11-23 01:53:49 +00004630 AddOverloadedCallCandidate(*this, *I, ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00004631 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004632 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00004633
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004634 if (ArgumentDependentLookup)
4635 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004636 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004637 CandidateSet,
4638 PartialOverloading);
4639}
4640
Douglas Gregorf6b89692008-11-26 05:54:23 +00004641/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00004642/// (which eventually refers to the declaration Func) and the call
4643/// arguments Args/NumArgs, attempt to resolve the function call down
4644/// to a specific function. If overload resolution succeeds, returns
4645/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00004646/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00004647/// arguments and Fn, and returns NULL.
John McCallba135432009-11-21 08:51:07 +00004648FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn,
4649 llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregor17330012009-02-04 15:01:18 +00004650 DeclarationName UnqualifiedName,
John McCalld5532b62009-11-23 01:53:49 +00004651 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor0a396682008-11-26 06:01:48 +00004652 SourceLocation LParenLoc,
4653 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00004654 SourceLocation *CommaLocs,
Douglas Gregorfa047642009-02-04 00:32:51 +00004655 SourceLocation RParenLoc,
John McCalld2ede7d2009-11-21 09:38:42 +00004656 bool ArgumentDependentLookup) {
Douglas Gregorf6b89692008-11-26 05:54:23 +00004657 OverloadCandidateSet CandidateSet;
Douglas Gregor17330012009-02-04 15:01:18 +00004658
4659 // Add the functions denoted by Callee to the set of candidate
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004660 // functions.
John McCallba135432009-11-21 08:51:07 +00004661 AddOverloadedCallCandidates(Fns, UnqualifiedName, ArgumentDependentLookup,
John McCalld5532b62009-11-23 01:53:49 +00004662 ExplicitTemplateArgs, Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004663 CandidateSet);
Douglas Gregorf6b89692008-11-26 05:54:23 +00004664 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004665 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregor0a396682008-11-26 06:01:48 +00004666 case OR_Success:
4667 return Best->Function;
Douglas Gregorf6b89692008-11-26 05:54:23 +00004668
4669 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00004670 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00004671 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00004672 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00004673 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4674 break;
4675
4676 case OR_Ambiguous:
4677 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor17330012009-02-04 15:01:18 +00004678 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00004679 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4680 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004681
4682 case OR_Deleted:
4683 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4684 << Best->Function->isDeleted()
4685 << UnqualifiedName
4686 << Fn->getSourceRange();
4687 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4688 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00004689 }
4690
4691 // Overload resolution failed. Destroy all of the subexpressions and
4692 // return NULL.
4693 Fn->Destroy(Context);
4694 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4695 Args[Arg]->Destroy(Context);
4696 return 0;
4697}
4698
John McCall7453ed42009-11-22 00:44:51 +00004699static bool IsOverloaded(const Sema::FunctionSet &Functions) {
4700 return Functions.size() > 1 ||
4701 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
4702}
4703
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004704/// \brief Create a unary operation that may resolve to an overloaded
4705/// operator.
4706///
4707/// \param OpLoc The location of the operator itself (e.g., '*').
4708///
4709/// \param OpcIn The UnaryOperator::Opcode that describes this
4710/// operator.
4711///
4712/// \param Functions The set of non-member functions that will be
4713/// considered by overload resolution. The caller needs to build this
4714/// set based on the context using, e.g.,
4715/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4716/// set should not contain any member functions; those will be added
4717/// by CreateOverloadedUnaryOp().
4718///
4719/// \param input The input argument.
4720Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4721 unsigned OpcIn,
4722 FunctionSet &Functions,
Mike Stump1eb44332009-09-09 15:08:12 +00004723 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004724 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4725 Expr *Input = (Expr *)input.get();
4726
4727 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4728 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4729 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4730
4731 Expr *Args[2] = { Input, 0 };
4732 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004733
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004734 // For post-increment and post-decrement, add the implicit '0' as
4735 // the second argument, so that we know this is a post-increment or
4736 // post-decrement.
4737 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4738 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump1eb44332009-09-09 15:08:12 +00004739 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004740 SourceLocation());
4741 NumArgs = 2;
4742 }
4743
4744 if (Input->isTypeDependent()) {
John McCallba135432009-11-21 08:51:07 +00004745 UnresolvedLookupExpr *Fn
John McCallf7a1a742009-11-24 19:00:30 +00004746 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
4747 0, SourceRange(), OpName, OpLoc,
John McCall7453ed42009-11-22 00:44:51 +00004748 /*ADL*/ true, IsOverloaded(Functions));
Mike Stump1eb44332009-09-09 15:08:12 +00004749 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004750 FuncEnd = Functions.end();
4751 Func != FuncEnd; ++Func)
John McCallba135432009-11-21 08:51:07 +00004752 Fn->addDecl(*Func);
Mike Stump1eb44332009-09-09 15:08:12 +00004753
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004754 input.release();
4755 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4756 &Args[0], NumArgs,
4757 Context.DependentTy,
4758 OpLoc));
4759 }
4760
4761 // Build an empty overload set.
4762 OverloadCandidateSet CandidateSet;
4763
4764 // Add the candidates from the given function set.
4765 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4766
4767 // Add operator candidates that are member functions.
4768 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4769
4770 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00004771 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004772
4773 // Perform overload resolution.
4774 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004775 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004776 case OR_Success: {
4777 // We found a built-in operator or an overloaded operator.
4778 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00004779
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004780 if (FnDecl) {
4781 // We matched an overloaded operator. Build a call to that
4782 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00004783
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004784 // Convert the arguments.
4785 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4786 if (PerformObjectArgumentInitialization(Input, Method))
4787 return ExprError();
4788 } else {
4789 // Convert the arguments.
4790 if (PerformCopyInitialization(Input,
4791 FnDecl->getParamDecl(0)->getType(),
4792 "passing"))
4793 return ExprError();
4794 }
4795
4796 // Determine the result type
Anders Carlsson26a2a072009-10-13 21:19:37 +00004797 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00004798
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004799 // Build the actual expression node.
4800 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4801 SourceLocation());
4802 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004803
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004804 input.release();
Eli Friedman4c3b8962009-11-18 03:58:17 +00004805 Args[0] = Input;
Anders Carlsson26a2a072009-10-13 21:19:37 +00004806 ExprOwningPtr<CallExpr> TheCall(this,
4807 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman4c3b8962009-11-18 03:58:17 +00004808 Args, NumArgs, ResultTy, OpLoc));
Anders Carlsson26a2a072009-10-13 21:19:37 +00004809
4810 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4811 FnDecl))
4812 return ExprError();
4813
4814 return MaybeBindToTemporary(TheCall.release());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004815 } else {
4816 // We matched a built-in operator. Convert the arguments, then
4817 // break out so that we will build the appropriate built-in
4818 // operator node.
4819 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4820 Best->Conversions[0], "passing"))
4821 return ExprError();
4822
4823 break;
4824 }
4825 }
4826
4827 case OR_No_Viable_Function:
4828 // No viable function; fall through to handling this as a
4829 // built-in operator, which will produce an error message for us.
4830 break;
4831
4832 case OR_Ambiguous:
4833 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4834 << UnaryOperator::getOpcodeStr(Opc)
4835 << Input->getSourceRange();
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004836 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4837 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004838 return ExprError();
4839
4840 case OR_Deleted:
4841 Diag(OpLoc, diag::err_ovl_deleted_oper)
4842 << Best->Function->isDeleted()
4843 << UnaryOperator::getOpcodeStr(Opc)
4844 << Input->getSourceRange();
4845 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4846 return ExprError();
4847 }
4848
4849 // Either we found no viable overloaded operator or we matched a
4850 // built-in operator. In either case, fall through to trying to
4851 // build a built-in operation.
4852 input.release();
4853 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4854}
4855
Douglas Gregor063daf62009-03-13 18:40:31 +00004856/// \brief Create a binary operation that may resolve to an overloaded
4857/// operator.
4858///
4859/// \param OpLoc The location of the operator itself (e.g., '+').
4860///
4861/// \param OpcIn The BinaryOperator::Opcode that describes this
4862/// operator.
4863///
4864/// \param Functions The set of non-member functions that will be
4865/// considered by overload resolution. The caller needs to build this
4866/// set based on the context using, e.g.,
4867/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4868/// set should not contain any member functions; those will be added
4869/// by CreateOverloadedBinOp().
4870///
4871/// \param LHS Left-hand argument.
4872/// \param RHS Right-hand argument.
Mike Stump1eb44332009-09-09 15:08:12 +00004873Sema::OwningExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00004874Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004875 unsigned OpcIn,
Douglas Gregor063daf62009-03-13 18:40:31 +00004876 FunctionSet &Functions,
4877 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00004878 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004879 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00004880
4881 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4882 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4883 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4884
4885 // If either side is type-dependent, create an appropriate dependent
4886 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004887 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00004888 if (Functions.empty()) {
4889 // If there are no functions to store, just build a dependent
4890 // BinaryOperator or CompoundAssignment.
4891 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
4892 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
4893 Context.DependentTy, OpLoc));
4894
4895 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
4896 Context.DependentTy,
4897 Context.DependentTy,
4898 Context.DependentTy,
4899 OpLoc));
4900 }
4901
John McCallba135432009-11-21 08:51:07 +00004902 UnresolvedLookupExpr *Fn
John McCallf7a1a742009-11-24 19:00:30 +00004903 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
4904 0, SourceRange(), OpName, OpLoc,
John McCall7453ed42009-11-22 00:44:51 +00004905 /* ADL */ true, IsOverloaded(Functions));
John McCallba135432009-11-21 08:51:07 +00004906
Mike Stump1eb44332009-09-09 15:08:12 +00004907 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004908 FuncEnd = Functions.end();
4909 Func != FuncEnd; ++Func)
John McCallba135432009-11-21 08:51:07 +00004910 Fn->addDecl(*Func);
Mike Stump1eb44332009-09-09 15:08:12 +00004911
Douglas Gregor063daf62009-03-13 18:40:31 +00004912 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00004913 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00004914 Context.DependentTy,
4915 OpLoc));
4916 }
4917
4918 // If this is the .* operator, which is not overloadable, just
4919 // create a built-in binary operator.
4920 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004921 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00004922
Sebastian Redl275c2b42009-11-18 23:10:33 +00004923 // If this is the assignment operator, we only perform overload resolution
4924 // if the left-hand side is a class or enumeration type. This is actually
4925 // a hack. The standard requires that we do overload resolution between the
4926 // various built-in candidates, but as DR507 points out, this can lead to
4927 // problems. So we do it this way, which pretty much follows what GCC does.
4928 // Note that we go the traditional code path for compound assignment forms.
4929 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004930 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00004931
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004932 // Build an empty overload set.
4933 OverloadCandidateSet CandidateSet;
Douglas Gregor063daf62009-03-13 18:40:31 +00004934
4935 // Add the candidates from the given function set.
4936 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4937
4938 // Add operator candidates that are member functions.
4939 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4940
4941 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00004942 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00004943
4944 // Perform overload resolution.
4945 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004946 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004947 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00004948 // We found a built-in operator or an overloaded operator.
4949 FunctionDecl *FnDecl = Best->Function;
4950
4951 if (FnDecl) {
4952 // We matched an overloaded operator. Build a call to that
4953 // operator.
4954
4955 // Convert the arguments.
4956 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004957 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4958 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004959 "passing"))
4960 return ExprError();
4961 } else {
4962 // Convert the arguments.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004963 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004964 "passing") ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004965 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004966 "passing"))
4967 return ExprError();
4968 }
4969
4970 // Determine the result type
4971 QualType ResultTy
John McCall183700f2009-09-21 23:43:11 +00004972 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor063daf62009-03-13 18:40:31 +00004973 ResultTy = ResultTy.getNonReferenceType();
4974
4975 // Build the actual expression node.
4976 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00004977 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00004978 UsualUnaryConversions(FnExpr);
4979
Anders Carlsson15ea3782009-10-13 22:43:21 +00004980 ExprOwningPtr<CXXOperatorCallExpr>
4981 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4982 Args, 2, ResultTy,
4983 OpLoc));
4984
4985 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4986 FnDecl))
4987 return ExprError();
4988
4989 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor063daf62009-03-13 18:40:31 +00004990 } else {
4991 // We matched a built-in operator. Convert the arguments, then
4992 // break out so that we will build the appropriate built-in
4993 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004994 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor063daf62009-03-13 18:40:31 +00004995 Best->Conversions[0], "passing") ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004996 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor063daf62009-03-13 18:40:31 +00004997 Best->Conversions[1], "passing"))
4998 return ExprError();
4999
5000 break;
5001 }
5002 }
5003
Douglas Gregor33074752009-09-30 21:46:01 +00005004 case OR_No_Viable_Function: {
5005 // C++ [over.match.oper]p9:
5006 // If the operator is the operator , [...] and there are no
5007 // viable functions, then the operator is assumed to be the
5008 // built-in operator and interpreted according to clause 5.
5009 if (Opc == BinaryOperator::Comma)
5010 break;
5011
Sebastian Redl8593c782009-05-21 11:50:50 +00005012 // For class as left operand for assignment or compound assigment operator
5013 // do not fall through to handling in built-in, but report that no overloaded
5014 // assignment operator found
Douglas Gregor33074752009-09-30 21:46:01 +00005015 OwningExprResult Result = ExprError();
5016 if (Args[0]->getType()->isRecordType() &&
5017 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00005018 Diag(OpLoc, diag::err_ovl_no_viable_oper)
5019 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005020 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00005021 } else {
5022 // No viable function; try to create a built-in operation, which will
5023 // produce an error. Then, show the non-viable candidates.
5024 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00005025 }
Douglas Gregor33074752009-09-30 21:46:01 +00005026 assert(Result.isInvalid() &&
5027 "C++ binary operator overloading is missing candidates!");
5028 if (Result.isInvalid())
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005029 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5030 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00005031 return move(Result);
5032 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005033
5034 case OR_Ambiguous:
5035 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5036 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005037 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005038 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5039 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00005040 return ExprError();
5041
5042 case OR_Deleted:
5043 Diag(OpLoc, diag::err_ovl_deleted_oper)
5044 << Best->Function->isDeleted()
5045 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005046 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor063daf62009-03-13 18:40:31 +00005047 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5048 return ExprError();
5049 }
5050
Douglas Gregor33074752009-09-30 21:46:01 +00005051 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005052 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00005053}
5054
Sebastian Redlf322ed62009-10-29 20:17:01 +00005055Action::OwningExprResult
5056Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5057 SourceLocation RLoc,
5058 ExprArg Base, ExprArg Idx) {
5059 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5060 static_cast<Expr*>(Idx.get()) };
5061 DeclarationName OpName =
5062 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5063
5064 // If either side is type-dependent, create an appropriate dependent
5065 // expression.
5066 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5067
John McCallba135432009-11-21 08:51:07 +00005068 UnresolvedLookupExpr *Fn
John McCallf7a1a742009-11-24 19:00:30 +00005069 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5070 0, SourceRange(), OpName, LLoc,
John McCall7453ed42009-11-22 00:44:51 +00005071 /*ADL*/ true, /*Overloaded*/ false);
John McCallf7a1a742009-11-24 19:00:30 +00005072 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00005073
5074 Base.release();
5075 Idx.release();
5076 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5077 Args, 2,
5078 Context.DependentTy,
5079 RLoc));
5080 }
5081
5082 // Build an empty overload set.
5083 OverloadCandidateSet CandidateSet;
5084
5085 // Subscript can only be overloaded as a member function.
5086
5087 // Add operator candidates that are member functions.
5088 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5089
5090 // Add builtin operator candidates.
5091 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5092
5093 // Perform overload resolution.
5094 OverloadCandidateSet::iterator Best;
5095 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5096 case OR_Success: {
5097 // We found a built-in operator or an overloaded operator.
5098 FunctionDecl *FnDecl = Best->Function;
5099
5100 if (FnDecl) {
5101 // We matched an overloaded operator. Build a call to that
5102 // operator.
5103
5104 // Convert the arguments.
5105 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5106 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5107 PerformCopyInitialization(Args[1],
5108 FnDecl->getParamDecl(0)->getType(),
5109 "passing"))
5110 return ExprError();
5111
5112 // Determine the result type
5113 QualType ResultTy
5114 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5115 ResultTy = ResultTy.getNonReferenceType();
5116
5117 // Build the actual expression node.
5118 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5119 LLoc);
5120 UsualUnaryConversions(FnExpr);
5121
5122 Base.release();
5123 Idx.release();
5124 ExprOwningPtr<CXXOperatorCallExpr>
5125 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5126 FnExpr, Args, 2,
5127 ResultTy, RLoc));
5128
5129 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5130 FnDecl))
5131 return ExprError();
5132
5133 return MaybeBindToTemporary(TheCall.release());
5134 } else {
5135 // We matched a built-in operator. Convert the arguments, then
5136 // break out so that we will build the appropriate built-in
5137 // operator node.
5138 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
5139 Best->Conversions[0], "passing") ||
5140 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
5141 Best->Conversions[1], "passing"))
5142 return ExprError();
5143
5144 break;
5145 }
5146 }
5147
5148 case OR_No_Viable_Function: {
5149 // No viable function; try to create a built-in operation, which will
5150 // produce an error. Then, show the non-viable candidates.
5151 OwningExprResult Result =
5152 CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
5153 assert(Result.isInvalid() &&
5154 "C++ subscript operator overloading is missing candidates!");
5155 if (Result.isInvalid())
5156 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5157 "[]", LLoc);
5158 return move(Result);
5159 }
5160
5161 case OR_Ambiguous:
5162 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5163 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5164 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5165 "[]", LLoc);
5166 return ExprError();
5167
5168 case OR_Deleted:
5169 Diag(LLoc, diag::err_ovl_deleted_oper)
5170 << Best->Function->isDeleted() << "[]"
5171 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5172 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5173 return ExprError();
5174 }
5175
5176 // We matched a built-in operator; build it.
5177 Base.release();
5178 Idx.release();
5179 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5180 Owned(Args[1]), RLoc);
5181}
5182
Douglas Gregor88a35142008-12-22 05:46:06 +00005183/// BuildCallToMemberFunction - Build a call to a member
5184/// function. MemExpr is the expression that refers to the member
5185/// function (and includes the object parameter), Args/NumArgs are the
5186/// arguments to the function call (not including the object
5187/// parameter). The caller needs to validate that the member
5188/// expression refers to a member function or an overloaded member
5189/// function.
John McCallaa81e162009-12-01 22:10:20 +00005190Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00005191Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5192 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor88a35142008-12-22 05:46:06 +00005193 unsigned NumArgs, SourceLocation *CommaLocs,
5194 SourceLocation RParenLoc) {
5195 // Dig out the member expression. This holds both the object
5196 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00005197 Expr *NakedMemExpr = MemExprE->IgnoreParens();
5198
John McCall129e2df2009-11-30 22:42:35 +00005199 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00005200 CXXMethodDecl *Method = 0;
John McCall129e2df2009-11-30 22:42:35 +00005201 if (isa<MemberExpr>(NakedMemExpr)) {
5202 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00005203 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5204 } else {
5205 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
John McCallaa81e162009-12-01 22:10:20 +00005206
John McCall701c89e2009-12-03 04:06:58 +00005207 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00005208
Douglas Gregor88a35142008-12-22 05:46:06 +00005209 // Add overload candidates
5210 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00005211
John McCallaa81e162009-12-01 22:10:20 +00005212 // FIXME: avoid copy.
5213 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5214 if (UnresExpr->hasExplicitTemplateArgs()) {
5215 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5216 TemplateArgs = &TemplateArgsBuffer;
5217 }
5218
John McCall129e2df2009-11-30 22:42:35 +00005219 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
5220 E = UnresExpr->decls_end(); I != E; ++I) {
5221
John McCall701c89e2009-12-03 04:06:58 +00005222 NamedDecl *Func = *I;
5223 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
5224 if (isa<UsingShadowDecl>(Func))
5225 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
5226
John McCall129e2df2009-11-30 22:42:35 +00005227 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005228 // If explicit template arguments were provided, we can't call a
5229 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00005230 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005231 continue;
5232
John McCall701c89e2009-12-03 04:06:58 +00005233 AddMethodCandidate(Method, ActingDC, ObjectType, Args, NumArgs,
5234 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00005235 } else {
John McCall129e2df2009-11-30 22:42:35 +00005236 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall701c89e2009-12-03 04:06:58 +00005237 ActingDC, TemplateArgs,
5238 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00005239 CandidateSet,
5240 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00005241 }
Douglas Gregordec06662009-08-21 18:42:58 +00005242 }
Mike Stump1eb44332009-09-09 15:08:12 +00005243
John McCall129e2df2009-11-30 22:42:35 +00005244 DeclarationName DeclName = UnresExpr->getMemberName();
5245
Douglas Gregor88a35142008-12-22 05:46:06 +00005246 OverloadCandidateSet::iterator Best;
John McCall129e2df2009-11-30 22:42:35 +00005247 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005248 case OR_Success:
5249 Method = cast<CXXMethodDecl>(Best->Function);
5250 break;
5251
5252 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00005253 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00005254 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00005255 << DeclName << MemExprE->getSourceRange();
Douglas Gregor88a35142008-12-22 05:46:06 +00005256 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5257 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00005258 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00005259
5260 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00005261 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00005262 << DeclName << MemExprE->getSourceRange();
Douglas Gregor88a35142008-12-22 05:46:06 +00005263 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5264 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00005265 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005266
5267 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00005268 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005269 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00005270 << DeclName << MemExprE->getSourceRange();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005271 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5272 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00005273 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00005274 }
5275
Douglas Gregor699ee522009-11-20 19:42:02 +00005276 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
John McCallaa81e162009-12-01 22:10:20 +00005277
John McCallaa81e162009-12-01 22:10:20 +00005278 // If overload resolution picked a static member, build a
5279 // non-member call based on that function.
5280 if (Method->isStatic()) {
5281 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
5282 Args, NumArgs, RParenLoc);
5283 }
5284
John McCall129e2df2009-11-30 22:42:35 +00005285 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00005286 }
5287
5288 assert(Method && "Member call to something that isn't a method?");
Mike Stump1eb44332009-09-09 15:08:12 +00005289 ExprOwningPtr<CXXMemberCallExpr>
John McCallaa81e162009-12-01 22:10:20 +00005290 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump1eb44332009-09-09 15:08:12 +00005291 NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00005292 Method->getResultType().getNonReferenceType(),
5293 RParenLoc));
5294
Anders Carlssoneed3e692009-10-10 00:06:20 +00005295 // Check for a valid return type.
5296 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5297 TheCall.get(), Method))
John McCallaa81e162009-12-01 22:10:20 +00005298 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00005299
Douglas Gregor88a35142008-12-22 05:46:06 +00005300 // Convert the object argument (for a non-static member function call).
John McCallaa81e162009-12-01 22:10:20 +00005301 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00005302 if (!Method->isStatic() &&
Douglas Gregor88a35142008-12-22 05:46:06 +00005303 PerformObjectArgumentInitialization(ObjectArg, Method))
John McCallaa81e162009-12-01 22:10:20 +00005304 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00005305 MemExpr->setBase(ObjectArg);
5306
5307 // Convert the rest of the arguments
Douglas Gregor72564e72009-02-26 23:50:07 +00005308 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00005309 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00005310 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00005311 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00005312
Anders Carlssond406bf02009-08-16 01:56:34 +00005313 if (CheckFunctionCall(Method, TheCall.get()))
John McCallaa81e162009-12-01 22:10:20 +00005314 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00005315
John McCallaa81e162009-12-01 22:10:20 +00005316 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor88a35142008-12-22 05:46:06 +00005317}
5318
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005319/// BuildCallToObjectOfClassType - Build a call to an object of class
5320/// type (C++ [over.call.object]), which can end up invoking an
5321/// overloaded function call operator (@c operator()) or performing a
5322/// user-defined conversion on the object argument.
Mike Stump1eb44332009-09-09 15:08:12 +00005323Sema::ExprResult
5324Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00005325 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005326 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00005327 SourceLocation *CommaLocs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005328 SourceLocation RParenLoc) {
5329 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00005330 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005331
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005332 // C++ [over.call.object]p1:
5333 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00005334 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005335 // candidate functions includes at least the function call
5336 // operators of T. The function call operators of T are obtained by
5337 // ordinary lookup of the name operator() in the context of
5338 // (E).operator().
5339 OverloadCandidateSet CandidateSet;
Douglas Gregor44b43212008-12-11 16:49:14 +00005340 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00005341
5342 if (RequireCompleteType(LParenLoc, Object->getType(),
5343 PartialDiagnostic(diag::err_incomplete_object_call)
5344 << Object->getSourceRange()))
5345 return true;
5346
John McCalla24dc2e2009-11-17 02:14:36 +00005347 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
5348 LookupQualifiedName(R, Record->getDecl());
5349 R.suppressDiagnostics();
5350
Douglas Gregor593564b2009-11-15 07:48:03 +00005351 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00005352 Oper != OperEnd; ++Oper) {
John McCall701c89e2009-12-03 04:06:58 +00005353 AddMethodCandidate(*Oper, Object->getType(), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00005354 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00005355 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00005356
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005357 // C++ [over.call.object]p2:
5358 // In addition, for each conversion function declared in T of the
5359 // form
5360 //
5361 // operator conversion-type-id () cv-qualifier;
5362 //
5363 // where cv-qualifier is the same cv-qualification as, or a
5364 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00005365 // denotes the type "pointer to function of (P1,...,Pn) returning
5366 // R", or the type "reference to pointer to function of
5367 // (P1,...,Pn) returning R", or the type "reference to function
5368 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005369 // is also considered as a candidate function. Similarly,
5370 // surrogate call functions are added to the set of candidate
5371 // functions for each conversion function declared in an
5372 // accessible base class provided the function is not hidden
5373 // within T by another intervening declaration.
Douglas Gregor4a27d702009-10-21 06:18:39 +00005374 // FIXME: Look in base classes for more conversion operators!
John McCallba135432009-11-21 08:51:07 +00005375 const UnresolvedSet *Conversions
Douglas Gregor4a27d702009-10-21 06:18:39 +00005376 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
John McCallba135432009-11-21 08:51:07 +00005377 for (UnresolvedSet::iterator I = Conversions->begin(),
5378 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00005379 NamedDecl *D = *I;
5380 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5381 if (isa<UsingShadowDecl>(D))
5382 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5383
Douglas Gregor4a27d702009-10-21 06:18:39 +00005384 // Skip over templated conversion functions; they aren't
5385 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00005386 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00005387 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005388
John McCall701c89e2009-12-03 04:06:58 +00005389 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00005390
Douglas Gregor4a27d702009-10-21 06:18:39 +00005391 // Strip the reference type (if any) and then the pointer type (if
5392 // any) to get down to what might be a function type.
5393 QualType ConvType = Conv->getConversionType().getNonReferenceType();
5394 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5395 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005396
Douglas Gregor4a27d702009-10-21 06:18:39 +00005397 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall701c89e2009-12-03 04:06:58 +00005398 AddSurrogateCandidate(Conv, ActingContext, Proto,
5399 Object->getType(), Args, NumArgs,
5400 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005401 }
Mike Stump1eb44332009-09-09 15:08:12 +00005402
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005403 // Perform overload resolution.
5404 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005405 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005406 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005407 // Overload resolution succeeded; we'll build the appropriate call
5408 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005409 break;
5410
5411 case OR_No_Viable_Function:
Mike Stump1eb44332009-09-09 15:08:12 +00005412 Diag(Object->getSourceRange().getBegin(),
Sebastian Redle4c452c2008-11-22 13:44:36 +00005413 diag::err_ovl_no_viable_object_call)
Chris Lattner4330d652009-02-17 07:29:20 +00005414 << Object->getType() << Object->getSourceRange();
Sebastian Redle4c452c2008-11-22 13:44:36 +00005415 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005416 break;
5417
5418 case OR_Ambiguous:
5419 Diag(Object->getSourceRange().getBegin(),
5420 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00005421 << Object->getType() << Object->getSourceRange();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005422 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5423 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005424
5425 case OR_Deleted:
5426 Diag(Object->getSourceRange().getBegin(),
5427 diag::err_ovl_deleted_object_call)
5428 << Best->Function->isDeleted()
5429 << Object->getType() << Object->getSourceRange();
5430 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5431 break;
Mike Stump1eb44332009-09-09 15:08:12 +00005432 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005433
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005434 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005435 // We had an error; delete all of the subexpressions and return
5436 // the error.
Ted Kremenek8189cde2009-02-07 01:47:29 +00005437 Object->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005438 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek8189cde2009-02-07 01:47:29 +00005439 Args[ArgIdx]->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005440 return true;
5441 }
5442
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005443 if (Best->Function == 0) {
5444 // Since there is no function declaration, this is one of the
5445 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00005446 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005447 = cast<CXXConversionDecl>(
5448 Best->Conversions[0].UserDefined.ConversionFunction);
5449
5450 // We selected one of the surrogate functions that converts the
5451 // object parameter to a function pointer. Perform the conversion
5452 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00005453
5454 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00005455 // and then call it.
Eli Friedmanc8c771e2009-12-09 04:52:43 +00005456 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00005457
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00005458 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00005459 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
5460 CommaLocs, RParenLoc).release();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005461 }
5462
5463 // We found an overloaded operator(). Build a CXXOperatorCallExpr
5464 // that calls this method, using Object for the implicit object
5465 // parameter and passing along the remaining arguments.
5466 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00005467 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005468
5469 unsigned NumArgsInProto = Proto->getNumArgs();
5470 unsigned NumArgsToCheck = NumArgs;
5471
5472 // Build the full argument list for the method call (the
5473 // implicit object parameter is placed at the beginning of the
5474 // list).
5475 Expr **MethodArgs;
5476 if (NumArgs < NumArgsInProto) {
5477 NumArgsToCheck = NumArgsInProto;
5478 MethodArgs = new Expr*[NumArgsInProto + 1];
5479 } else {
5480 MethodArgs = new Expr*[NumArgs + 1];
5481 }
5482 MethodArgs[0] = Object;
5483 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5484 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00005485
5486 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00005487 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005488 UsualUnaryConversions(NewFn);
5489
5490 // Once we've built TheCall, all of the expressions are properly
5491 // owned.
5492 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00005493 ExprOwningPtr<CXXOperatorCallExpr>
5494 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor063daf62009-03-13 18:40:31 +00005495 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00005496 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005497 delete [] MethodArgs;
5498
Anders Carlsson07d68f12009-10-13 21:49:31 +00005499 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
5500 Method))
5501 return true;
5502
Douglas Gregor518fda12009-01-13 05:10:00 +00005503 // We may have default arguments. If so, we need to allocate more
5504 // slots in the call for them.
5505 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00005506 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00005507 else if (NumArgs > NumArgsInProto)
5508 NumArgsToCheck = NumArgsInProto;
5509
Chris Lattner312531a2009-04-12 08:11:20 +00005510 bool IsError = false;
5511
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005512 // Initialize the implicit object parameter.
Chris Lattner312531a2009-04-12 08:11:20 +00005513 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005514 TheCall->setArg(0, Object);
5515
Chris Lattner312531a2009-04-12 08:11:20 +00005516
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005517 // Check the argument types.
5518 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005519 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00005520 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005521 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00005522
Douglas Gregor518fda12009-01-13 05:10:00 +00005523 // Pass the argument.
5524 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattner312531a2009-04-12 08:11:20 +00005525 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor518fda12009-01-13 05:10:00 +00005526 } else {
Douglas Gregord47c47d2009-11-09 19:27:57 +00005527 OwningExprResult DefArg
5528 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
5529 if (DefArg.isInvalid()) {
5530 IsError = true;
5531 break;
5532 }
5533
5534 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00005535 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005536
5537 TheCall->setArg(i + 1, Arg);
5538 }
5539
5540 // If this is a variadic call, handle args passed through "...".
5541 if (Proto->isVariadic()) {
5542 // Promote the arguments (C99 6.5.2.2p7).
5543 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
5544 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00005545 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005546 TheCall->setArg(i + 1, Arg);
5547 }
5548 }
5549
Chris Lattner312531a2009-04-12 08:11:20 +00005550 if (IsError) return true;
5551
Anders Carlssond406bf02009-08-16 01:56:34 +00005552 if (CheckFunctionCall(Method, TheCall.get()))
5553 return true;
5554
Anders Carlssona303f9e2009-08-16 03:53:54 +00005555 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005556}
5557
Douglas Gregor8ba10742008-11-20 16:27:02 +00005558/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00005559/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00005560/// @c Member is the name of the member we're trying to find.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005561Sema::OwningExprResult
5562Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
5563 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor8ba10742008-11-20 16:27:02 +00005564 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00005565
Douglas Gregor8ba10742008-11-20 16:27:02 +00005566 // C++ [over.ref]p1:
5567 //
5568 // [...] An expression x->m is interpreted as (x.operator->())->m
5569 // for a class object x of type T if T::operator->() exists and if
5570 // the operator is selected as the best match function by the
5571 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00005572 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
5573 OverloadCandidateSet CandidateSet;
Ted Kremenek6217b802009-07-29 21:53:49 +00005574 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005575
Eli Friedmanf43fb722009-11-18 01:28:03 +00005576 if (RequireCompleteType(Base->getLocStart(), Base->getType(),
5577 PDiag(diag::err_typecheck_incomplete_tag)
5578 << Base->getSourceRange()))
5579 return ExprError();
5580
John McCalla24dc2e2009-11-17 02:14:36 +00005581 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
5582 LookupQualifiedName(R, BaseRecord->getDecl());
5583 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00005584
5585 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00005586 Oper != OperEnd; ++Oper) {
5587 NamedDecl *D = *Oper;
5588 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5589 if (isa<UsingShadowDecl>(D))
5590 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5591
5592 AddMethodCandidate(cast<CXXMethodDecl>(D), ActingContext,
5593 Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00005594 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00005595 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00005596
5597 // Perform overload resolution.
5598 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005599 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00005600 case OR_Success:
5601 // Overload resolution succeeded; we'll build the call below.
5602 break;
5603
5604 case OR_No_Viable_Function:
5605 if (CandidateSet.empty())
5606 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005607 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005608 else
5609 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005610 << "operator->" << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005611 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005612 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005613
5614 case OR_Ambiguous:
5615 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00005616 << "->" << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005617 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005618 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005619
5620 case OR_Deleted:
5621 Diag(OpLoc, diag::err_ovl_deleted_oper)
5622 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00005623 << "->" << Base->getSourceRange();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005624 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005625 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005626 }
5627
5628 // Convert the object parameter.
5629 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00005630 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005631 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00005632
5633 // No concerns about early exits now.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005634 BaseIn.release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005635
5636 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00005637 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5638 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00005639 UsualUnaryConversions(FnExpr);
Anders Carlsson15ea3782009-10-13 22:43:21 +00005640
5641 QualType ResultTy = Method->getResultType().getNonReferenceType();
5642 ExprOwningPtr<CXXOperatorCallExpr>
5643 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
5644 &Base, 1, ResultTy, OpLoc));
5645
5646 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
5647 Method))
5648 return ExprError();
5649 return move(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00005650}
5651
Douglas Gregor904eed32008-11-10 20:40:00 +00005652/// FixOverloadedFunctionReference - E is an expression that refers to
5653/// a C++ overloaded function (possibly with some parentheses and
5654/// perhaps a '&' around it). We have resolved the overloaded function
5655/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00005656/// refer (possibly indirectly) to Fn. Returns the new expr.
5657Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005658 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor699ee522009-11-20 19:42:02 +00005659 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
5660 if (SubExpr == PE->getSubExpr())
5661 return PE->Retain();
5662
5663 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
5664 }
5665
5666 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5667 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00005668 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00005669 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00005670 "Implicit cast type cannot be determined from overload");
Douglas Gregor699ee522009-11-20 19:42:02 +00005671 if (SubExpr == ICE->getSubExpr())
5672 return ICE->Retain();
5673
5674 return new (Context) ImplicitCastExpr(ICE->getType(),
5675 ICE->getCastKind(),
5676 SubExpr,
5677 ICE->isLvalueCast());
5678 }
5679
5680 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump1eb44332009-09-09 15:08:12 +00005681 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00005682 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00005683 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5684 if (Method->isStatic()) {
5685 // Do nothing: static member functions aren't any different
5686 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00005687 } else {
John McCallf7a1a742009-11-24 19:00:30 +00005688 // Fix the sub expression, which really has to be an
5689 // UnresolvedLookupExpr holding an overloaded member function
5690 // or template.
John McCallba135432009-11-21 08:51:07 +00005691 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5692 if (SubExpr == UnOp->getSubExpr())
5693 return UnOp->Retain();
Douglas Gregor699ee522009-11-20 19:42:02 +00005694
John McCallba135432009-11-21 08:51:07 +00005695 assert(isa<DeclRefExpr>(SubExpr)
5696 && "fixed to something other than a decl ref");
5697 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
5698 && "fixed to a member ref with no nested name qualifier");
5699
5700 // We have taken the address of a pointer to member
5701 // function. Perform the computation here so that we get the
5702 // appropriate pointer to member type.
5703 QualType ClassType
5704 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
5705 QualType MemPtrType
5706 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
5707
5708 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
5709 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00005710 }
5711 }
Douglas Gregor699ee522009-11-20 19:42:02 +00005712 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5713 if (SubExpr == UnOp->getSubExpr())
5714 return UnOp->Retain();
Anders Carlsson96ad5332009-10-21 17:16:23 +00005715
Douglas Gregor699ee522009-11-20 19:42:02 +00005716 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
5717 Context.getPointerType(SubExpr->getType()),
5718 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00005719 }
John McCallba135432009-11-21 08:51:07 +00005720
5721 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00005722 // FIXME: avoid copy.
5723 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00005724 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00005725 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
5726 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00005727 }
5728
John McCallba135432009-11-21 08:51:07 +00005729 return DeclRefExpr::Create(Context,
5730 ULE->getQualifier(),
5731 ULE->getQualifierRange(),
5732 Fn,
5733 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00005734 Fn->getType(),
5735 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00005736 }
5737
John McCall129e2df2009-11-30 22:42:35 +00005738 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00005739 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00005740 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5741 if (MemExpr->hasExplicitTemplateArgs()) {
5742 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5743 TemplateArgs = &TemplateArgsBuffer;
5744 }
John McCalld5532b62009-11-23 01:53:49 +00005745
John McCallaa81e162009-12-01 22:10:20 +00005746 Expr *Base;
5747
5748 // If we're filling in
5749 if (MemExpr->isImplicitAccess()) {
5750 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
5751 return DeclRefExpr::Create(Context,
5752 MemExpr->getQualifier(),
5753 MemExpr->getQualifierRange(),
5754 Fn,
5755 MemExpr->getMemberLoc(),
5756 Fn->getType(),
5757 TemplateArgs);
5758 } else
5759 Base = new (Context) CXXThisExpr(SourceLocation(),
5760 MemExpr->getBaseType());
5761 } else
5762 Base = MemExpr->getBase()->Retain();
5763
5764 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00005765 MemExpr->isArrow(),
5766 MemExpr->getQualifier(),
5767 MemExpr->getQualifierRange(),
5768 Fn,
John McCalld5532b62009-11-23 01:53:49 +00005769 MemExpr->getMemberLoc(),
John McCallaa81e162009-12-01 22:10:20 +00005770 TemplateArgs,
Douglas Gregor699ee522009-11-20 19:42:02 +00005771 Fn->getType());
5772 }
5773
Douglas Gregor699ee522009-11-20 19:42:02 +00005774 assert(false && "Invalid reference to overloaded function");
5775 return E->Retain();
Douglas Gregor904eed32008-11-10 20:40:00 +00005776}
5777
Douglas Gregor20093b42009-12-09 23:02:17 +00005778Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
5779 FunctionDecl *Fn) {
5780 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Fn));
5781}
5782
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005783} // end namespace clang