blob: d01bca718d0a282b24634c69b7ea670c0605e26f [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,
Douglas Gregor68647482009-12-16 03:45:30 +00002083 AssignmentAction Action, 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,
Douglas Gregor68647482009-12-16 03:45:30 +00002095 FromType, From, Action);
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
Douglas Gregor68647482009-12-16 03:45:30 +00002105 if (!PerformImplicitConversion(From, ToType, Action,
Sebastian Redle2b68332009-04-12 17:16:29 +00002106 /*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)
Douglas Gregor68647482009-12-16 03:45:30 +00002111 << ToType << From->getType() << Action << 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);
Douglas Gregor68647482009-12-16 03:45:30 +00002232 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting))
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002233 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.
John McCall578b69b2009-12-16 08:11:27 +00002625 (void) Result;
2626
2627 CandidateSet.push_back(OverloadCandidate());
2628 OverloadCandidate &Candidate = CandidateSet.back();
2629 Candidate.Function = FunctionTemplate->getTemplatedDecl();
2630 Candidate.Viable = false;
2631 Candidate.IsSurrogate = false;
2632 Candidate.IgnoreObjectArgument = false;
Douglas Gregore53060f2009-06-25 22:08:12 +00002633 return;
2634 }
Mike Stump1eb44332009-09-09 15:08:12 +00002635
Douglas Gregore53060f2009-06-25 22:08:12 +00002636 // Add the function template specialization produced by template argument
2637 // deduction as a candidate.
2638 assert(Specialization && "Missing function template specialization?");
2639 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2640 SuppressUserConversions, ForceRValue);
2641}
Mike Stump1eb44332009-09-09 15:08:12 +00002642
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002643/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00002644/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002645/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00002646/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002647/// (which may or may not be the same type as the type that the
2648/// conversion function produces).
2649void
2650Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall701c89e2009-12-03 04:06:58 +00002651 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002652 Expr *From, QualType ToType,
2653 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002654 assert(!Conversion->getDescribedFunctionTemplate() &&
2655 "Conversion function templates use AddTemplateConversionCandidate");
2656
Douglas Gregor3f396022009-09-28 04:47:19 +00002657 if (!CandidateSet.isNewCandidate(Conversion))
2658 return;
2659
Douglas Gregor7edfb692009-11-23 12:27:39 +00002660 // Overload resolution is always an unevaluated context.
2661 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2662
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002663 // Add this candidate
2664 CandidateSet.push_back(OverloadCandidate());
2665 OverloadCandidate& Candidate = CandidateSet.back();
2666 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002667 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002668 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002669 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump1eb44332009-09-09 15:08:12 +00002670 Candidate.FinalConversion.FromTypePtr
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002671 = Conversion->getConversionType().getAsOpaquePtr();
2672 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2673
Douglas Gregor96176b32008-11-18 23:14:02 +00002674 // Determine the implicit conversion sequence for the implicit
2675 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002676 Candidate.Viable = true;
2677 Candidate.Conversions.resize(1);
John McCall701c89e2009-12-03 04:06:58 +00002678 Candidate.Conversions[0]
2679 = TryObjectArgumentInitialization(From->getType(), Conversion,
2680 ActingContext);
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002681 // Conversion functions to a different type in the base class is visible in
2682 // the derived class. So, a derived to base conversion should not participate
2683 // in overload resolution.
2684 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2685 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump1eb44332009-09-09 15:08:12 +00002686 if (Candidate.Conversions[0].ConversionKind
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002687 == ImplicitConversionSequence::BadConversion) {
2688 Candidate.Viable = false;
2689 return;
2690 }
Fariborz Jahanian3759a032009-10-19 19:18:20 +00002691
2692 // We won't go through a user-define type conversion function to convert a
2693 // derived to base as such conversions are given Conversion Rank. They only
2694 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2695 QualType FromCanon
2696 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2697 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2698 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2699 Candidate.Viable = false;
2700 return;
2701 }
2702
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002703
2704 // To determine what the conversion from the result of calling the
2705 // conversion function to the type we're eventually trying to
2706 // convert to (ToType), we need to synthesize a call to the
2707 // conversion function and attempt copy initialization from it. This
2708 // makes sure that we get the right semantics with respect to
2709 // lvalues/rvalues and the type. Fortunately, we can allocate this
2710 // call on the stack and we don't need its arguments to be
2711 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00002712 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00002713 From->getLocStart());
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002714 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman73c39ab2009-10-20 08:27:19 +00002715 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002716 &ConversionRef, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002717
2718 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00002719 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2720 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00002721 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002722 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00002723 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00002724 ImplicitConversionSequence ICS =
2725 TryCopyInitialization(&Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002726 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002727 /*ForceRValue=*/false,
2728 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002729
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002730 switch (ICS.ConversionKind) {
2731 case ImplicitConversionSequence::StandardConversion:
2732 Candidate.FinalConversion = ICS.Standard;
2733 break;
2734
2735 case ImplicitConversionSequence::BadConversion:
2736 Candidate.Viable = false;
2737 break;
2738
2739 default:
Mike Stump1eb44332009-09-09 15:08:12 +00002740 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002741 "Can only end up with a standard conversion sequence or failure");
2742 }
2743}
2744
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002745/// \brief Adds a conversion function template specialization
2746/// candidate to the overload set, using template argument deduction
2747/// to deduce the template arguments of the conversion function
2748/// template from the type that we are converting to (C++
2749/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00002750void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002751Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall701c89e2009-12-03 04:06:58 +00002752 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002753 Expr *From, QualType ToType,
2754 OverloadCandidateSet &CandidateSet) {
2755 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2756 "Only conversion function templates permitted here");
2757
Douglas Gregor3f396022009-09-28 04:47:19 +00002758 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2759 return;
2760
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002761 TemplateDeductionInfo Info(Context);
2762 CXXConversionDecl *Specialization = 0;
2763 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00002764 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002765 Specialization, Info)) {
2766 // FIXME: Record what happened with template argument deduction, so
2767 // that we can give the user a beautiful diagnostic.
2768 (void)Result;
2769 return;
2770 }
Mike Stump1eb44332009-09-09 15:08:12 +00002771
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002772 // Add the conversion function template specialization produced by
2773 // template argument deduction as a candidate.
2774 assert(Specialization && "Missing function template specialization?");
John McCall701c89e2009-12-03 04:06:58 +00002775 AddConversionCandidate(Specialization, ActingDC, From, ToType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002776}
2777
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002778/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2779/// converts the given @c Object to a function pointer via the
2780/// conversion function @c Conversion, and then attempts to call it
2781/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2782/// the type of function that we'll eventually be calling.
2783void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall701c89e2009-12-03 04:06:58 +00002784 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00002785 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00002786 QualType ObjectType,
2787 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002788 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002789 if (!CandidateSet.isNewCandidate(Conversion))
2790 return;
2791
Douglas Gregor7edfb692009-11-23 12:27:39 +00002792 // Overload resolution is always an unevaluated context.
2793 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2794
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002795 CandidateSet.push_back(OverloadCandidate());
2796 OverloadCandidate& Candidate = CandidateSet.back();
2797 Candidate.Function = 0;
2798 Candidate.Surrogate = Conversion;
2799 Candidate.Viable = true;
2800 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002801 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002802 Candidate.Conversions.resize(NumArgs + 1);
2803
2804 // Determine the implicit conversion sequence for the implicit
2805 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00002806 ImplicitConversionSequence ObjectInit
John McCall701c89e2009-12-03 04:06:58 +00002807 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002808 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2809 Candidate.Viable = false;
2810 return;
2811 }
2812
2813 // The first conversion is actually a user-defined conversion whose
2814 // first conversion is ObjectInit's standard conversion (which is
2815 // effectively a reference binding). Record it as such.
Mike Stump1eb44332009-09-09 15:08:12 +00002816 Candidate.Conversions[0].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002817 = ImplicitConversionSequence::UserDefinedConversion;
2818 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002819 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002820 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00002821 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002822 = Candidate.Conversions[0].UserDefined.Before;
2823 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2824
Mike Stump1eb44332009-09-09 15:08:12 +00002825 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002826 unsigned NumArgsInProto = Proto->getNumArgs();
2827
2828 // (C++ 13.3.2p2): A candidate function having fewer than m
2829 // parameters is viable only if it has an ellipsis in its parameter
2830 // list (8.3.5).
2831 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2832 Candidate.Viable = false;
2833 return;
2834 }
2835
2836 // Function types don't have any default arguments, so just check if
2837 // we have enough arguments.
2838 if (NumArgs < NumArgsInProto) {
2839 // Not enough arguments.
2840 Candidate.Viable = false;
2841 return;
2842 }
2843
2844 // Determine the implicit conversion sequences for each of the
2845 // arguments.
2846 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2847 if (ArgIdx < NumArgsInProto) {
2848 // (C++ 13.3.2p3): for F to be a viable function, there shall
2849 // exist for each argument an implicit conversion sequence
2850 // (13.3.3.1) that converts that argument to the corresponding
2851 // parameter of F.
2852 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002853 Candidate.Conversions[ArgIdx + 1]
2854 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002855 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002856 /*ForceRValue=*/false,
2857 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002858 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002859 == ImplicitConversionSequence::BadConversion) {
2860 Candidate.Viable = false;
2861 break;
2862 }
2863 } else {
2864 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2865 // argument for which there is no corresponding parameter is
2866 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002867 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002868 = ImplicitConversionSequence::EllipsisConversion;
2869 }
2870 }
2871}
2872
Mike Stump390b4cc2009-05-16 07:39:55 +00002873// FIXME: This will eventually be removed, once we've migrated all of the
2874// operator overloading logic over to the scheme used by binary operators, which
2875// works for template instantiation.
Douglas Gregor063daf62009-03-13 18:40:31 +00002876void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002877 SourceLocation OpLoc,
Douglas Gregor96176b32008-11-18 23:14:02 +00002878 Expr **Args, unsigned NumArgs,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002879 OverloadCandidateSet& CandidateSet,
2880 SourceRange OpRange) {
Douglas Gregor063daf62009-03-13 18:40:31 +00002881 FunctionSet Functions;
2882
2883 QualType T1 = Args[0]->getType();
2884 QualType T2;
2885 if (NumArgs > 1)
2886 T2 = Args[1]->getType();
2887
2888 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002889 if (S)
2890 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Sebastian Redl644be852009-10-23 19:23:15 +00002891 ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00002892 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2893 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002894 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00002895}
2896
2897/// \brief Add overload candidates for overloaded operators that are
2898/// member functions.
2899///
2900/// Add the overloaded operator candidates that are member functions
2901/// for the operator Op that was used in an operator expression such
2902/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2903/// CandidateSet will store the added overload candidates. (C++
2904/// [over.match.oper]).
2905void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2906 SourceLocation OpLoc,
2907 Expr **Args, unsigned NumArgs,
2908 OverloadCandidateSet& CandidateSet,
2909 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002910 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2911
2912 // C++ [over.match.oper]p3:
2913 // For a unary operator @ with an operand of a type whose
2914 // cv-unqualified version is T1, and for a binary operator @ with
2915 // a left operand of a type whose cv-unqualified version is T1 and
2916 // a right operand of a type whose cv-unqualified version is T2,
2917 // three sets of candidate functions, designated member
2918 // candidates, non-member candidates and built-in candidates, are
2919 // constructed as follows:
2920 QualType T1 = Args[0]->getType();
2921 QualType T2;
2922 if (NumArgs > 1)
2923 T2 = Args[1]->getType();
2924
2925 // -- If T1 is a class type, the set of member candidates is the
2926 // result of the qualified lookup of T1::operator@
2927 // (13.3.1.1.1); otherwise, the set of member candidates is
2928 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00002929 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002930 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00002931 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002932 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002933
John McCalla24dc2e2009-11-17 02:14:36 +00002934 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
2935 LookupQualifiedName(Operators, T1Rec->getDecl());
2936 Operators.suppressDiagnostics();
2937
Mike Stump1eb44332009-09-09 15:08:12 +00002938 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002939 OperEnd = Operators.end();
2940 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00002941 ++Oper)
John McCall701c89e2009-12-03 04:06:58 +00002942 AddMethodCandidate(*Oper, Args[0]->getType(),
2943 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00002944 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00002945 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002946}
2947
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002948/// AddBuiltinCandidate - Add a candidate for a built-in
2949/// operator. ResultTy and ParamTys are the result and parameter types
2950/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002951/// arguments being passed to the candidate. IsAssignmentOperator
2952/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002953/// operator. NumContextualBoolArguments is the number of arguments
2954/// (at the beginning of the argument list) that will be contextually
2955/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00002956void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002957 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002958 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002959 bool IsAssignmentOperator,
2960 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00002961 // Overload resolution is always an unevaluated context.
2962 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2963
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002964 // Add this candidate
2965 CandidateSet.push_back(OverloadCandidate());
2966 OverloadCandidate& Candidate = CandidateSet.back();
2967 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00002968 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002969 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002970 Candidate.BuiltinTypes.ResultTy = ResultTy;
2971 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2972 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2973
2974 // Determine the implicit conversion sequences for each of the
2975 // arguments.
2976 Candidate.Viable = true;
2977 Candidate.Conversions.resize(NumArgs);
2978 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002979 // C++ [over.match.oper]p4:
2980 // For the built-in assignment operators, conversions of the
2981 // left operand are restricted as follows:
2982 // -- no temporaries are introduced to hold the left operand, and
2983 // -- no user-defined conversions are applied to the left
2984 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00002985 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002986 //
2987 // We block these conversions by turning off user-defined
2988 // conversions, since that is the only way that initialization of
2989 // a reference to a non-class type can occur from something that
2990 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002991 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00002992 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002993 "Contextual conversion to bool requires bool type");
2994 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2995 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002996 Candidate.Conversions[ArgIdx]
2997 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00002998 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002999 /*ForceRValue=*/false,
3000 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003001 }
Mike Stump1eb44332009-09-09 15:08:12 +00003002 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00003003 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003004 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003005 break;
3006 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003007 }
3008}
3009
3010/// BuiltinCandidateTypeSet - A set of types that will be used for the
3011/// candidate operator functions for built-in operators (C++
3012/// [over.built]). The types are separated into pointer types and
3013/// enumeration types.
3014class BuiltinCandidateTypeSet {
3015 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003016 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003017
3018 /// PointerTypes - The set of pointer types that will be used in the
3019 /// built-in candidates.
3020 TypeSet PointerTypes;
3021
Sebastian Redl78eb8742009-04-19 21:53:20 +00003022 /// MemberPointerTypes - The set of member pointer types that will be
3023 /// used in the built-in candidates.
3024 TypeSet MemberPointerTypes;
3025
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003026 /// EnumerationTypes - The set of enumeration types that will be
3027 /// used in the built-in candidates.
3028 TypeSet EnumerationTypes;
3029
Douglas Gregor5842ba92009-08-24 15:23:48 +00003030 /// Sema - The semantic analysis instance where we are building the
3031 /// candidate type set.
3032 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00003033
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003034 /// Context - The AST context in which we will build the type sets.
3035 ASTContext &Context;
3036
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003037 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3038 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00003039 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003040
3041public:
3042 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003043 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003044
Mike Stump1eb44332009-09-09 15:08:12 +00003045 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00003046 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003047
Douglas Gregor573d9c32009-10-21 23:19:44 +00003048 void AddTypesConvertedFrom(QualType Ty,
3049 SourceLocation Loc,
3050 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003051 bool AllowExplicitConversions,
3052 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003053
3054 /// pointer_begin - First pointer type found;
3055 iterator pointer_begin() { return PointerTypes.begin(); }
3056
Sebastian Redl78eb8742009-04-19 21:53:20 +00003057 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003058 iterator pointer_end() { return PointerTypes.end(); }
3059
Sebastian Redl78eb8742009-04-19 21:53:20 +00003060 /// member_pointer_begin - First member pointer type found;
3061 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3062
3063 /// member_pointer_end - Past the last member pointer type found;
3064 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3065
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003066 /// enumeration_begin - First enumeration type found;
3067 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3068
Sebastian Redl78eb8742009-04-19 21:53:20 +00003069 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003070 iterator enumeration_end() { return EnumerationTypes.end(); }
3071};
3072
Sebastian Redl78eb8742009-04-19 21:53:20 +00003073/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003074/// the set of pointer types along with any more-qualified variants of
3075/// that type. For example, if @p Ty is "int const *", this routine
3076/// will add "int const *", "int const volatile *", "int const
3077/// restrict *", and "int const volatile restrict *" to the set of
3078/// pointer types. Returns true if the add of @p Ty itself succeeded,
3079/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003080///
3081/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003082bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00003083BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3084 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00003085
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003086 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003087 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003088 return false;
3089
John McCall0953e762009-09-24 19:53:00 +00003090 const PointerType *PointerTy = Ty->getAs<PointerType>();
3091 assert(PointerTy && "type was not a pointer type!");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003092
John McCall0953e762009-09-24 19:53:00 +00003093 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003094 // Don't add qualified variants of arrays. For one, they're not allowed
3095 // (the qualifier would sink to the element type), and for another, the
3096 // only overload situation where it matters is subscript or pointer +- int,
3097 // and those shouldn't have qualifier variants anyway.
3098 if (PointeeTy->isArrayType())
3099 return true;
John McCall0953e762009-09-24 19:53:00 +00003100 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00003101 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00003102 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003103 bool hasVolatile = VisibleQuals.hasVolatile();
3104 bool hasRestrict = VisibleQuals.hasRestrict();
3105
John McCall0953e762009-09-24 19:53:00 +00003106 // Iterate through all strict supersets of BaseCVR.
3107 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3108 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003109 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3110 // in the types.
3111 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3112 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00003113 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3114 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003115 }
3116
3117 return true;
3118}
3119
Sebastian Redl78eb8742009-04-19 21:53:20 +00003120/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3121/// to the set of pointer types along with any more-qualified variants of
3122/// that type. For example, if @p Ty is "int const *", this routine
3123/// will add "int const *", "int const volatile *", "int const
3124/// restrict *", and "int const volatile restrict *" to the set of
3125/// pointer types. Returns true if the add of @p Ty itself succeeded,
3126/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003127///
3128/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003129bool
3130BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3131 QualType Ty) {
3132 // Insert this type.
3133 if (!MemberPointerTypes.insert(Ty))
3134 return false;
3135
John McCall0953e762009-09-24 19:53:00 +00003136 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3137 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00003138
John McCall0953e762009-09-24 19:53:00 +00003139 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003140 // Don't add qualified variants of arrays. For one, they're not allowed
3141 // (the qualifier would sink to the element type), and for another, the
3142 // only overload situation where it matters is subscript or pointer +- int,
3143 // and those shouldn't have qualifier variants anyway.
3144 if (PointeeTy->isArrayType())
3145 return true;
John McCall0953e762009-09-24 19:53:00 +00003146 const Type *ClassTy = PointerTy->getClass();
3147
3148 // Iterate through all strict supersets of the pointee type's CVR
3149 // qualifiers.
3150 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3151 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3152 if ((CVR | BaseCVR) != CVR) continue;
3153
3154 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3155 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00003156 }
3157
3158 return true;
3159}
3160
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003161/// AddTypesConvertedFrom - Add each of the types to which the type @p
3162/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00003163/// primarily interested in pointer types and enumeration types. We also
3164/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003165/// AllowUserConversions is true if we should look at the conversion
3166/// functions of a class type, and AllowExplicitConversions if we
3167/// should also include the explicit conversion functions of a class
3168/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003169void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003170BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003171 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003172 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003173 bool AllowExplicitConversions,
3174 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003175 // Only deal with canonical types.
3176 Ty = Context.getCanonicalType(Ty);
3177
3178 // Look through reference types; they aren't part of the type of an
3179 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00003180 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003181 Ty = RefTy->getPointeeType();
3182
3183 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003184 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003185
Sebastian Redla65b5512009-11-05 16:36:20 +00003186 // If we're dealing with an array type, decay to the pointer.
3187 if (Ty->isArrayType())
3188 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3189
Ted Kremenek6217b802009-07-29 21:53:49 +00003190 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003191 QualType PointeeTy = PointerTy->getPointeeType();
3192
3193 // Insert our type, and its more-qualified variants, into the set
3194 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003195 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003196 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00003197 } else if (Ty->isMemberPointerType()) {
3198 // Member pointers are far easier, since the pointee can't be converted.
3199 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3200 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003201 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00003202 EnumerationTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003203 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003204 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003205 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003206 // No conversion functions in incomplete types.
3207 return;
3208 }
Mike Stump1eb44332009-09-09 15:08:12 +00003209
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003210 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallba135432009-11-21 08:51:07 +00003211 const UnresolvedSet *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00003212 = ClassDecl->getVisibleConversionFunctions();
John McCallba135432009-11-21 08:51:07 +00003213 for (UnresolvedSet::iterator I = Conversions->begin(),
3214 E = Conversions->end(); I != E; ++I) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003215
Mike Stump1eb44332009-09-09 15:08:12 +00003216 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003217 // about which builtin types we can convert to.
John McCallba135432009-11-21 08:51:07 +00003218 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003219 continue;
3220
John McCallba135432009-11-21 08:51:07 +00003221 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003222 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003223 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003224 VisibleQuals);
3225 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003226 }
3227 }
3228 }
3229}
3230
Douglas Gregor19b7b152009-08-24 13:43:27 +00003231/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3232/// the volatile- and non-volatile-qualified assignment operators for the
3233/// given type to the candidate set.
3234static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3235 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00003236 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003237 unsigned NumArgs,
3238 OverloadCandidateSet &CandidateSet) {
3239 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00003240
Douglas Gregor19b7b152009-08-24 13:43:27 +00003241 // T& operator=(T&, T)
3242 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3243 ParamTypes[1] = T;
3244 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3245 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003246
Douglas Gregor19b7b152009-08-24 13:43:27 +00003247 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3248 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00003249 ParamTypes[0]
3250 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00003251 ParamTypes[1] = T;
3252 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00003253 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003254 }
3255}
Mike Stump1eb44332009-09-09 15:08:12 +00003256
Sebastian Redl9994a342009-10-25 17:03:50 +00003257/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3258/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003259static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3260 Qualifiers VRQuals;
3261 const RecordType *TyRec;
3262 if (const MemberPointerType *RHSMPType =
3263 ArgExpr->getType()->getAs<MemberPointerType>())
3264 TyRec = cast<RecordType>(RHSMPType->getClass());
3265 else
3266 TyRec = ArgExpr->getType()->getAs<RecordType>();
3267 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003268 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003269 VRQuals.addVolatile();
3270 VRQuals.addRestrict();
3271 return VRQuals;
3272 }
3273
3274 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallba135432009-11-21 08:51:07 +00003275 const UnresolvedSet *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00003276 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003277
John McCallba135432009-11-21 08:51:07 +00003278 for (UnresolvedSet::iterator I = Conversions->begin(),
3279 E = Conversions->end(); I != E; ++I) {
3280 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003281 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3282 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3283 CanTy = ResTypeRef->getPointeeType();
3284 // Need to go down the pointer/mempointer chain and add qualifiers
3285 // as see them.
3286 bool done = false;
3287 while (!done) {
3288 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3289 CanTy = ResTypePtr->getPointeeType();
3290 else if (const MemberPointerType *ResTypeMPtr =
3291 CanTy->getAs<MemberPointerType>())
3292 CanTy = ResTypeMPtr->getPointeeType();
3293 else
3294 done = true;
3295 if (CanTy.isVolatileQualified())
3296 VRQuals.addVolatile();
3297 if (CanTy.isRestrictQualified())
3298 VRQuals.addRestrict();
3299 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3300 return VRQuals;
3301 }
3302 }
3303 }
3304 return VRQuals;
3305}
3306
Douglas Gregor74253732008-11-19 15:42:04 +00003307/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3308/// operator overloads to the candidate set (C++ [over.built]), based
3309/// on the operator @p Op and the arguments given. For example, if the
3310/// operator is a binary '+', this routine might add "int
3311/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003312void
Mike Stump1eb44332009-09-09 15:08:12 +00003313Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003314 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00003315 Expr **Args, unsigned NumArgs,
3316 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003317 // The set of "promoted arithmetic types", which are the arithmetic
3318 // types are that preserved by promotion (C++ [over.built]p2). Note
3319 // that the first few of these types are the promoted integral
3320 // types; these types need to be first.
3321 // FIXME: What about complex?
3322 const unsigned FirstIntegralType = 0;
3323 const unsigned LastIntegralType = 13;
Mike Stump1eb44332009-09-09 15:08:12 +00003324 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003325 LastPromotedIntegralType = 13;
3326 const unsigned FirstPromotedArithmeticType = 7,
3327 LastPromotedArithmeticType = 16;
3328 const unsigned NumArithmeticTypes = 16;
3329 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00003330 Context.BoolTy, Context.CharTy, Context.WCharTy,
3331// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003332 Context.SignedCharTy, Context.ShortTy,
3333 Context.UnsignedCharTy, Context.UnsignedShortTy,
3334 Context.IntTy, Context.LongTy, Context.LongLongTy,
3335 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3336 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3337 };
Douglas Gregor652371a2009-10-21 22:01:30 +00003338 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3339 "Invalid first promoted integral type");
3340 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3341 == Context.UnsignedLongLongTy &&
3342 "Invalid last promoted integral type");
3343 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3344 "Invalid first promoted arithmetic type");
3345 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3346 == Context.LongDoubleTy &&
3347 "Invalid last promoted arithmetic type");
3348
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003349 // Find all of the types that the arguments can convert to, but only
3350 // if the operator we're looking at has built-in operator candidates
3351 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003352 Qualifiers VisibleTypeConversionsQuals;
3353 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003354 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3355 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3356
Douglas Gregor5842ba92009-08-24 15:23:48 +00003357 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003358 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3359 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00003360 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003361 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00003362 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003363 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor74253732008-11-19 15:42:04 +00003364 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003365 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregor573d9c32009-10-21 23:19:44 +00003366 OpLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003367 true,
3368 (Op == OO_Exclaim ||
3369 Op == OO_AmpAmp ||
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003370 Op == OO_PipePipe),
3371 VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003372 }
3373
3374 bool isComparison = false;
3375 switch (Op) {
3376 case OO_None:
3377 case NUM_OVERLOADED_OPERATORS:
3378 assert(false && "Expected an overloaded operator");
3379 break;
3380
Douglas Gregor74253732008-11-19 15:42:04 +00003381 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00003382 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00003383 goto UnaryStar;
3384 else
3385 goto BinaryStar;
3386 break;
3387
3388 case OO_Plus: // '+' is either unary or binary
3389 if (NumArgs == 1)
3390 goto UnaryPlus;
3391 else
3392 goto BinaryPlus;
3393 break;
3394
3395 case OO_Minus: // '-' is either unary or binary
3396 if (NumArgs == 1)
3397 goto UnaryMinus;
3398 else
3399 goto BinaryMinus;
3400 break;
3401
3402 case OO_Amp: // '&' is either unary or binary
3403 if (NumArgs == 1)
3404 goto UnaryAmp;
3405 else
3406 goto BinaryAmp;
3407
3408 case OO_PlusPlus:
3409 case OO_MinusMinus:
3410 // C++ [over.built]p3:
3411 //
3412 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3413 // is either volatile or empty, there exist candidate operator
3414 // functions of the form
3415 //
3416 // VQ T& operator++(VQ T&);
3417 // T operator++(VQ T&, int);
3418 //
3419 // C++ [over.built]p4:
3420 //
3421 // For every pair (T, VQ), where T is an arithmetic type other
3422 // than bool, and VQ is either volatile or empty, there exist
3423 // candidate operator functions of the form
3424 //
3425 // VQ T& operator--(VQ T&);
3426 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00003427 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00003428 Arith < NumArithmeticTypes; ++Arith) {
3429 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00003430 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003431 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00003432
3433 // Non-volatile version.
3434 if (NumArgs == 1)
3435 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3436 else
3437 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003438 // heuristic to reduce number of builtin candidates in the set.
3439 // Add volatile version only if there are conversions to a volatile type.
3440 if (VisibleTypeConversionsQuals.hasVolatile()) {
3441 // Volatile version
3442 ParamTypes[0]
3443 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3444 if (NumArgs == 1)
3445 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3446 else
3447 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3448 }
Douglas Gregor74253732008-11-19 15:42:04 +00003449 }
3450
3451 // C++ [over.built]p5:
3452 //
3453 // For every pair (T, VQ), where T is a cv-qualified or
3454 // cv-unqualified object type, and VQ is either volatile or
3455 // empty, there exist candidate operator functions of the form
3456 //
3457 // T*VQ& operator++(T*VQ&);
3458 // T*VQ& operator--(T*VQ&);
3459 // T* operator++(T*VQ&, int);
3460 // T* operator--(T*VQ&, int);
3461 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3462 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3463 // Skip pointer types that aren't pointers to object types.
Ted Kremenek6217b802009-07-29 21:53:49 +00003464 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00003465 continue;
3466
Mike Stump1eb44332009-09-09 15:08:12 +00003467 QualType ParamTypes[2] = {
3468 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00003469 };
Mike Stump1eb44332009-09-09 15:08:12 +00003470
Douglas Gregor74253732008-11-19 15:42:04 +00003471 // Without volatile
3472 if (NumArgs == 1)
3473 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3474 else
3475 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3476
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003477 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3478 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00003479 // With volatile
John McCall0953e762009-09-24 19:53:00 +00003480 ParamTypes[0]
3481 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00003482 if (NumArgs == 1)
3483 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3484 else
3485 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3486 }
3487 }
3488 break;
3489
3490 UnaryStar:
3491 // C++ [over.built]p6:
3492 // For every cv-qualified or cv-unqualified object type T, there
3493 // exist candidate operator functions of the form
3494 //
3495 // T& operator*(T*);
3496 //
3497 // C++ [over.built]p7:
3498 // For every function type T, there exist candidate operator
3499 // functions of the form
3500 // T& operator*(T*);
3501 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3502 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3503 QualType ParamTy = *Ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00003504 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003505 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00003506 &ParamTy, Args, 1, CandidateSet);
3507 }
3508 break;
3509
3510 UnaryPlus:
3511 // C++ [over.built]p8:
3512 // For every type T, there exist candidate operator functions of
3513 // the form
3514 //
3515 // T* operator+(T*);
3516 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3517 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3518 QualType ParamTy = *Ptr;
3519 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3520 }
Mike Stump1eb44332009-09-09 15:08:12 +00003521
Douglas Gregor74253732008-11-19 15:42:04 +00003522 // Fall through
3523
3524 UnaryMinus:
3525 // C++ [over.built]p9:
3526 // For every promoted arithmetic type T, there exist candidate
3527 // operator functions of the form
3528 //
3529 // T operator+(T);
3530 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003531 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00003532 Arith < LastPromotedArithmeticType; ++Arith) {
3533 QualType ArithTy = ArithmeticTypes[Arith];
3534 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3535 }
3536 break;
3537
3538 case OO_Tilde:
3539 // C++ [over.built]p10:
3540 // For every promoted integral type T, there exist candidate
3541 // operator functions of the form
3542 //
3543 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003544 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00003545 Int < LastPromotedIntegralType; ++Int) {
3546 QualType IntTy = ArithmeticTypes[Int];
3547 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3548 }
3549 break;
3550
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003551 case OO_New:
3552 case OO_Delete:
3553 case OO_Array_New:
3554 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003555 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00003556 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003557 break;
3558
3559 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00003560 UnaryAmp:
3561 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003562 // C++ [over.match.oper]p3:
3563 // -- For the operator ',', the unary operator '&', or the
3564 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003565 break;
3566
Douglas Gregor19b7b152009-08-24 13:43:27 +00003567 case OO_EqualEqual:
3568 case OO_ExclaimEqual:
3569 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00003570 // For every pointer to member type T, there exist candidate operator
3571 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00003572 //
3573 // bool operator==(T,T);
3574 // bool operator!=(T,T);
Mike Stump1eb44332009-09-09 15:08:12 +00003575 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor19b7b152009-08-24 13:43:27 +00003576 MemPtr = CandidateTypes.member_pointer_begin(),
3577 MemPtrEnd = CandidateTypes.member_pointer_end();
3578 MemPtr != MemPtrEnd;
3579 ++MemPtr) {
3580 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3581 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3582 }
Mike Stump1eb44332009-09-09 15:08:12 +00003583
Douglas Gregor19b7b152009-08-24 13:43:27 +00003584 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00003585
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003586 case OO_Less:
3587 case OO_Greater:
3588 case OO_LessEqual:
3589 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003590 // C++ [over.built]p15:
3591 //
3592 // For every pointer or enumeration type T, there exist
3593 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003594 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003595 // bool operator<(T, T);
3596 // bool operator>(T, T);
3597 // bool operator<=(T, T);
3598 // bool operator>=(T, T);
3599 // bool operator==(T, T);
3600 // bool operator!=(T, T);
3601 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3602 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3603 QualType ParamTypes[2] = { *Ptr, *Ptr };
3604 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3605 }
Mike Stump1eb44332009-09-09 15:08:12 +00003606 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003607 = CandidateTypes.enumeration_begin();
3608 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3609 QualType ParamTypes[2] = { *Enum, *Enum };
3610 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3611 }
3612
3613 // Fall through.
3614 isComparison = true;
3615
Douglas Gregor74253732008-11-19 15:42:04 +00003616 BinaryPlus:
3617 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003618 if (!isComparison) {
3619 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3620
3621 // C++ [over.built]p13:
3622 //
3623 // For every cv-qualified or cv-unqualified object type T
3624 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003625 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003626 // T* operator+(T*, ptrdiff_t);
3627 // T& operator[](T*, ptrdiff_t); [BELOW]
3628 // T* operator-(T*, ptrdiff_t);
3629 // T* operator+(ptrdiff_t, T*);
3630 // T& operator[](ptrdiff_t, T*); [BELOW]
3631 //
3632 // C++ [over.built]p14:
3633 //
3634 // For every T, where T is a pointer to object type, there
3635 // exist candidate operator functions of the form
3636 //
3637 // ptrdiff_t operator-(T, T);
Mike Stump1eb44332009-09-09 15:08:12 +00003638 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003639 = CandidateTypes.pointer_begin();
3640 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3641 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3642
3643 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3644 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3645
3646 if (Op == OO_Plus) {
3647 // T* operator+(ptrdiff_t, T*);
3648 ParamTypes[0] = ParamTypes[1];
3649 ParamTypes[1] = *Ptr;
3650 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3651 } else {
3652 // ptrdiff_t operator-(T, T);
3653 ParamTypes[1] = *Ptr;
3654 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3655 Args, 2, CandidateSet);
3656 }
3657 }
3658 }
3659 // Fall through
3660
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003661 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00003662 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003663 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003664 // C++ [over.built]p12:
3665 //
3666 // For every pair of promoted arithmetic types L and R, there
3667 // exist candidate operator functions of the form
3668 //
3669 // LR operator*(L, R);
3670 // LR operator/(L, R);
3671 // LR operator+(L, R);
3672 // LR operator-(L, R);
3673 // bool operator<(L, R);
3674 // bool operator>(L, R);
3675 // bool operator<=(L, R);
3676 // bool operator>=(L, R);
3677 // bool operator==(L, R);
3678 // bool operator!=(L, R);
3679 //
3680 // where LR is the result of the usual arithmetic conversions
3681 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003682 //
3683 // C++ [over.built]p24:
3684 //
3685 // For every pair of promoted arithmetic types L and R, there exist
3686 // candidate operator functions of the form
3687 //
3688 // LR operator?(bool, L, R);
3689 //
3690 // where LR is the result of the usual arithmetic conversions
3691 // between types L and R.
3692 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003693 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003694 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003695 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003696 Right < LastPromotedArithmeticType; ++Right) {
3697 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00003698 QualType Result
3699 = isComparison
3700 ? Context.BoolTy
3701 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003702 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3703 }
3704 }
3705 break;
3706
3707 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00003708 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003709 case OO_Caret:
3710 case OO_Pipe:
3711 case OO_LessLess:
3712 case OO_GreaterGreater:
3713 // C++ [over.built]p17:
3714 //
3715 // For every pair of promoted integral types L and R, there
3716 // exist candidate operator functions of the form
3717 //
3718 // LR operator%(L, R);
3719 // LR operator&(L, R);
3720 // LR operator^(L, R);
3721 // LR operator|(L, R);
3722 // L operator<<(L, R);
3723 // L operator>>(L, R);
3724 //
3725 // where LR is the result of the usual arithmetic conversions
3726 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00003727 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003728 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003729 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003730 Right < LastPromotedIntegralType; ++Right) {
3731 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3732 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3733 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00003734 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003735 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3736 }
3737 }
3738 break;
3739
3740 case OO_Equal:
3741 // C++ [over.built]p20:
3742 //
3743 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00003744 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003745 // empty, there exist candidate operator functions of the form
3746 //
3747 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003748 for (BuiltinCandidateTypeSet::iterator
3749 Enum = CandidateTypes.enumeration_begin(),
3750 EnumEnd = CandidateTypes.enumeration_end();
3751 Enum != EnumEnd; ++Enum)
Mike Stump1eb44332009-09-09 15:08:12 +00003752 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003753 CandidateSet);
3754 for (BuiltinCandidateTypeSet::iterator
3755 MemPtr = CandidateTypes.member_pointer_begin(),
3756 MemPtrEnd = CandidateTypes.member_pointer_end();
3757 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump1eb44332009-09-09 15:08:12 +00003758 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003759 CandidateSet);
3760 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003761
3762 case OO_PlusEqual:
3763 case OO_MinusEqual:
3764 // C++ [over.built]p19:
3765 //
3766 // For every pair (T, VQ), where T is any type and VQ is either
3767 // volatile or empty, there exist candidate operator functions
3768 // of the form
3769 //
3770 // T*VQ& operator=(T*VQ&, T*);
3771 //
3772 // C++ [over.built]p21:
3773 //
3774 // For every pair (T, VQ), where T is a cv-qualified or
3775 // cv-unqualified object type and VQ is either volatile or
3776 // empty, there exist candidate operator functions of the form
3777 //
3778 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3779 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3780 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3781 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3782 QualType ParamTypes[2];
3783 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3784
3785 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003786 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003787 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3788 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003789
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003790 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3791 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00003792 // volatile version
John McCall0953e762009-09-24 19:53:00 +00003793 ParamTypes[0]
3794 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003795 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3796 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00003797 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003798 }
3799 // Fall through.
3800
3801 case OO_StarEqual:
3802 case OO_SlashEqual:
3803 // C++ [over.built]p18:
3804 //
3805 // For every triple (L, VQ, R), where L is an arithmetic type,
3806 // VQ is either volatile or empty, and R is a promoted
3807 // arithmetic type, there exist candidate operator functions of
3808 // the form
3809 //
3810 // VQ L& operator=(VQ L&, R);
3811 // VQ L& operator*=(VQ L&, R);
3812 // VQ L& operator/=(VQ L&, R);
3813 // VQ L& operator+=(VQ L&, R);
3814 // VQ L& operator-=(VQ L&, R);
3815 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003816 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003817 Right < LastPromotedArithmeticType; ++Right) {
3818 QualType ParamTypes[2];
3819 ParamTypes[1] = ArithmeticTypes[Right];
3820
3821 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003822 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003823 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3824 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003825
3826 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003827 if (VisibleTypeConversionsQuals.hasVolatile()) {
3828 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3829 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3830 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3831 /*IsAssigmentOperator=*/Op == OO_Equal);
3832 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003833 }
3834 }
3835 break;
3836
3837 case OO_PercentEqual:
3838 case OO_LessLessEqual:
3839 case OO_GreaterGreaterEqual:
3840 case OO_AmpEqual:
3841 case OO_CaretEqual:
3842 case OO_PipeEqual:
3843 // C++ [over.built]p22:
3844 //
3845 // For every triple (L, VQ, R), where L is an integral type, VQ
3846 // is either volatile or empty, and R is a promoted integral
3847 // type, there exist candidate operator functions of the form
3848 //
3849 // VQ L& operator%=(VQ L&, R);
3850 // VQ L& operator<<=(VQ L&, R);
3851 // VQ L& operator>>=(VQ L&, R);
3852 // VQ L& operator&=(VQ L&, R);
3853 // VQ L& operator^=(VQ L&, R);
3854 // VQ L& operator|=(VQ L&, R);
3855 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003856 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003857 Right < LastPromotedIntegralType; ++Right) {
3858 QualType ParamTypes[2];
3859 ParamTypes[1] = ArithmeticTypes[Right];
3860
3861 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003862 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003863 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00003864 if (VisibleTypeConversionsQuals.hasVolatile()) {
3865 // Add this built-in operator as a candidate (VQ is 'volatile').
3866 ParamTypes[0] = ArithmeticTypes[Left];
3867 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3868 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3869 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3870 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003871 }
3872 }
3873 break;
3874
Douglas Gregor74253732008-11-19 15:42:04 +00003875 case OO_Exclaim: {
3876 // C++ [over.operator]p23:
3877 //
3878 // There also exist candidate operator functions of the form
3879 //
Mike Stump1eb44332009-09-09 15:08:12 +00003880 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00003881 // bool operator&&(bool, bool); [BELOW]
3882 // bool operator||(bool, bool); [BELOW]
3883 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003884 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3885 /*IsAssignmentOperator=*/false,
3886 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00003887 break;
3888 }
3889
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003890 case OO_AmpAmp:
3891 case OO_PipePipe: {
3892 // C++ [over.operator]p23:
3893 //
3894 // There also exist candidate operator functions of the form
3895 //
Douglas Gregor74253732008-11-19 15:42:04 +00003896 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003897 // bool operator&&(bool, bool);
3898 // bool operator||(bool, bool);
3899 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003900 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3901 /*IsAssignmentOperator=*/false,
3902 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003903 break;
3904 }
3905
3906 case OO_Subscript:
3907 // C++ [over.built]p13:
3908 //
3909 // For every cv-qualified or cv-unqualified object type T there
3910 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003911 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003912 // T* operator+(T*, ptrdiff_t); [ABOVE]
3913 // T& operator[](T*, ptrdiff_t);
3914 // T* operator-(T*, ptrdiff_t); [ABOVE]
3915 // T* operator+(ptrdiff_t, T*); [ABOVE]
3916 // T& operator[](ptrdiff_t, T*);
3917 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3918 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3919 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenek6217b802009-07-29 21:53:49 +00003920 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003921 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003922
3923 // T& operator[](T*, ptrdiff_t)
3924 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3925
3926 // T& operator[](ptrdiff_t, T*);
3927 ParamTypes[0] = ParamTypes[1];
3928 ParamTypes[1] = *Ptr;
3929 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3930 }
3931 break;
3932
3933 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003934 // C++ [over.built]p11:
3935 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
3936 // C1 is the same type as C2 or is a derived class of C2, T is an object
3937 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
3938 // there exist candidate operator functions of the form
3939 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
3940 // where CV12 is the union of CV1 and CV2.
3941 {
3942 for (BuiltinCandidateTypeSet::iterator Ptr =
3943 CandidateTypes.pointer_begin();
3944 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3945 QualType C1Ty = (*Ptr);
3946 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00003947 QualifierCollector Q1;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003948 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00003949 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003950 if (!isa<RecordType>(C1))
3951 continue;
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003952 // heuristic to reduce number of builtin candidates in the set.
3953 // Add volatile/restrict version only if there are conversions to a
3954 // volatile/restrict type.
3955 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
3956 continue;
3957 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
3958 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003959 }
3960 for (BuiltinCandidateTypeSet::iterator
3961 MemPtr = CandidateTypes.member_pointer_begin(),
3962 MemPtrEnd = CandidateTypes.member_pointer_end();
3963 MemPtr != MemPtrEnd; ++MemPtr) {
3964 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
3965 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00003966 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003967 if (C1 != C2 && !IsDerivedFrom(C1, C2))
3968 break;
3969 QualType ParamTypes[2] = { *Ptr, *MemPtr };
3970 // build CV12 T&
3971 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003972 if (!VisibleTypeConversionsQuals.hasVolatile() &&
3973 T.isVolatileQualified())
3974 continue;
3975 if (!VisibleTypeConversionsQuals.hasRestrict() &&
3976 T.isRestrictQualified())
3977 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00003978 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003979 QualType ResultTy = Context.getLValueReferenceType(T);
3980 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3981 }
3982 }
3983 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003984 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003985
3986 case OO_Conditional:
3987 // Note that we don't consider the first argument, since it has been
3988 // contextually converted to bool long ago. The candidates below are
3989 // therefore added as binary.
3990 //
3991 // C++ [over.built]p24:
3992 // For every type T, where T is a pointer or pointer-to-member type,
3993 // there exist candidate operator functions of the form
3994 //
3995 // T operator?(bool, T, T);
3996 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003997 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3998 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3999 QualType ParamTypes[2] = { *Ptr, *Ptr };
4000 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4001 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00004002 for (BuiltinCandidateTypeSet::iterator Ptr =
4003 CandidateTypes.member_pointer_begin(),
4004 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4005 QualType ParamTypes[2] = { *Ptr, *Ptr };
4006 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4007 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004008 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004009 }
4010}
4011
Douglas Gregorfa047642009-02-04 00:32:51 +00004012/// \brief Add function candidates found via argument-dependent lookup
4013/// to the set of overloading candidates.
4014///
4015/// This routine performs argument-dependent name lookup based on the
4016/// given function name (which may also be an operator name) and adds
4017/// all of the overload candidates found by ADL to the overload
4018/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00004019void
Douglas Gregorfa047642009-02-04 00:32:51 +00004020Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
4021 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00004022 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004023 OverloadCandidateSet& CandidateSet,
4024 bool PartialOverloading) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004025 FunctionSet Functions;
Douglas Gregorfa047642009-02-04 00:32:51 +00004026
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004027 // FIXME: Should we be trafficking in canonical function decls throughout?
4028
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004029 // Record all of the function candidates that we've already
4030 // added to the overload set, so that we don't add those same
4031 // candidates a second time.
4032 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4033 CandEnd = CandidateSet.end();
4034 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00004035 if (Cand->Function) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004036 Functions.insert(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00004037 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4038 Functions.insert(FunTmpl);
4039 }
Douglas Gregorfa047642009-02-04 00:32:51 +00004040
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004041 // FIXME: Pass in the explicit template arguments?
Sebastian Redl644be852009-10-23 19:23:15 +00004042 ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
Douglas Gregorfa047642009-02-04 00:32:51 +00004043
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004044 // Erase all of the candidates we already knew about.
4045 // FIXME: This is suboptimal. Is there a better way?
4046 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4047 CandEnd = CandidateSet.end();
4048 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00004049 if (Cand->Function) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004050 Functions.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00004051 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4052 Functions.erase(FunTmpl);
4053 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004054
4055 // For each of the ADL candidates we found, add it to the overload
4056 // set.
4057 for (FunctionSet::iterator Func = Functions.begin(),
4058 FuncEnd = Functions.end();
Douglas Gregor364e0212009-06-27 21:05:07 +00004059 Func != FuncEnd; ++Func) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004060 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
John McCalld5532b62009-11-23 01:53:49 +00004061 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004062 continue;
4063
4064 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
4065 false, false, PartialOverloading);
4066 } else
Mike Stump1eb44332009-09-09 15:08:12 +00004067 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004068 ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004069 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00004070 }
Douglas Gregorfa047642009-02-04 00:32:51 +00004071}
4072
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004073/// isBetterOverloadCandidate - Determines whether the first overload
4074/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00004075bool
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004076Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump1eb44332009-09-09 15:08:12 +00004077 const OverloadCandidate& Cand2) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004078 // Define viable functions to be better candidates than non-viable
4079 // functions.
4080 if (!Cand2.Viable)
4081 return Cand1.Viable;
4082 else if (!Cand1.Viable)
4083 return false;
4084
Douglas Gregor88a35142008-12-22 05:46:06 +00004085 // C++ [over.match.best]p1:
4086 //
4087 // -- if F is a static member function, ICS1(F) is defined such
4088 // that ICS1(F) is neither better nor worse than ICS1(G) for
4089 // any function G, and, symmetrically, ICS1(G) is neither
4090 // better nor worse than ICS1(F).
4091 unsigned StartArg = 0;
4092 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4093 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004094
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004095 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00004096 // A viable function F1 is defined to be a better function than another
4097 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004098 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004099 unsigned NumArgs = Cand1.Conversions.size();
4100 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4101 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004102 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004103 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4104 Cand2.Conversions[ArgIdx])) {
4105 case ImplicitConversionSequence::Better:
4106 // Cand1 has a better conversion sequence.
4107 HasBetterConversion = true;
4108 break;
4109
4110 case ImplicitConversionSequence::Worse:
4111 // Cand1 can't be better than Cand2.
4112 return false;
4113
4114 case ImplicitConversionSequence::Indistinguishable:
4115 // Do nothing.
4116 break;
4117 }
4118 }
4119
Mike Stump1eb44332009-09-09 15:08:12 +00004120 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004121 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004122 if (HasBetterConversion)
4123 return true;
4124
Mike Stump1eb44332009-09-09 15:08:12 +00004125 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004126 // specialization, or, if not that,
4127 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4128 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4129 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004130
4131 // -- F1 and F2 are function template specializations, and the function
4132 // template for F1 is more specialized than the template for F2
4133 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004134 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00004135 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4136 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004137 if (FunctionTemplateDecl *BetterTemplate
4138 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4139 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor5d7d3752009-09-14 23:02:14 +00004140 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4141 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004142 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004143
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004144 // -- the context is an initialization by user-defined conversion
4145 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4146 // from the return type of F1 to the destination type (i.e.,
4147 // the type of the entity being initialized) is a better
4148 // conversion sequence than the standard conversion sequence
4149 // from the return type of F2 to the destination type.
Mike Stump1eb44332009-09-09 15:08:12 +00004150 if (Cand1.Function && Cand2.Function &&
4151 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004152 isa<CXXConversionDecl>(Cand2.Function)) {
4153 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4154 Cand2.FinalConversion)) {
4155 case ImplicitConversionSequence::Better:
4156 // Cand1 has a better conversion sequence.
4157 return true;
4158
4159 case ImplicitConversionSequence::Worse:
4160 // Cand1 can't be better than Cand2.
4161 return false;
4162
4163 case ImplicitConversionSequence::Indistinguishable:
4164 // Do nothing
4165 break;
4166 }
4167 }
4168
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004169 return false;
4170}
4171
Mike Stump1eb44332009-09-09 15:08:12 +00004172/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00004173/// within an overload candidate set.
4174///
4175/// \param CandidateSet the set of candidate functions.
4176///
4177/// \param Loc the location of the function name (or operator symbol) for
4178/// which overload resolution occurs.
4179///
Mike Stump1eb44332009-09-09 15:08:12 +00004180/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00004181/// function, Best points to the candidate function found.
4182///
4183/// \returns The result of overload resolution.
Douglas Gregor20093b42009-12-09 23:02:17 +00004184OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4185 SourceLocation Loc,
4186 OverloadCandidateSet::iterator& Best) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004187 // Find the best viable function.
4188 Best = CandidateSet.end();
4189 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4190 Cand != CandidateSet.end(); ++Cand) {
4191 if (Cand->Viable) {
4192 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4193 Best = Cand;
4194 }
4195 }
4196
4197 // If we didn't find any viable functions, abort.
4198 if (Best == CandidateSet.end())
4199 return OR_No_Viable_Function;
4200
4201 // Make sure that this function is better than every other viable
4202 // function. If not, we have an ambiguity.
4203 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4204 Cand != CandidateSet.end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00004205 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004206 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004207 !isBetterOverloadCandidate(*Best, *Cand)) {
4208 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004209 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004210 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004211 }
Mike Stump1eb44332009-09-09 15:08:12 +00004212
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004213 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004214 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00004215 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004216 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004217 return OR_Deleted;
4218
Douglas Gregore0762c92009-06-19 23:52:42 +00004219 // C++ [basic.def.odr]p2:
4220 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00004221 // when referred to from a potentially-evaluated expression. [Note: this
4222 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00004223 // (clause 13), user-defined conversions (12.3.2), allocation function for
4224 // placement new (5.3.4), as well as non-default initialization (8.5).
4225 if (Best->Function)
4226 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004227 return OR_Success;
4228}
4229
4230/// PrintOverloadCandidates - When overload resolution fails, prints
4231/// diagnostic messages containing the candidates in the candidate
4232/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump1eb44332009-09-09 15:08:12 +00004233void
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004234Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Fariborz Jahanian16a5eac2009-10-09 00:13:15 +00004235 bool OnlyViable,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004236 const char *Opc,
Fariborz Jahanian16a5eac2009-10-09 00:13:15 +00004237 SourceLocation OpLoc) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004238 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4239 LastCand = CandidateSet.end();
Fariborz Jahanian27687cf2009-10-12 17:51:19 +00004240 bool Reported = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004241 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004242 if (Cand->Viable || !OnlyViable) {
4243 if (Cand->Function) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004244 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004245 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004246 // Deleted or "unavailable" function.
4247 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
4248 << Cand->Function->isDeleted();
Douglas Gregor1fdd89b2009-09-15 20:11:42 +00004249 } else if (FunctionTemplateDecl *FunTmpl
4250 = Cand->Function->getPrimaryTemplate()) {
4251 // Function template specialization
4252 // FIXME: Give a better reason!
4253 Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
4254 << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
4255 *Cand->Function->getTemplateSpecializationArgs());
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004256 } else {
4257 // Normal function
Fariborz Jahanianb1663d02009-09-23 00:58:07 +00004258 bool errReported = false;
4259 if (!Cand->Viable && Cand->Conversions.size() > 0) {
4260 for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
4261 const ImplicitConversionSequence &Conversion =
4262 Cand->Conversions[i];
4263 if ((Conversion.ConversionKind !=
4264 ImplicitConversionSequence::BadConversion) ||
4265 Conversion.ConversionFunctionSet.size() == 0)
4266 continue;
4267 Diag(Cand->Function->getLocation(),
4268 diag::err_ovl_candidate_not_viable) << (i+1);
4269 errReported = true;
4270 for (int j = Conversion.ConversionFunctionSet.size()-1;
4271 j >= 0; j--) {
4272 FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
4273 Diag(Func->getLocation(), diag::err_ovl_candidate);
4274 }
4275 }
4276 }
4277 if (!errReported)
4278 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004279 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004280 } else if (Cand->IsSurrogate) {
Douglas Gregor621b3932008-11-21 02:54:28 +00004281 // Desugar the type of the surrogate down to a function type,
4282 // retaining as many typedefs as possible while still showing
4283 // the function type (and, therefore, its parameter types).
4284 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004285 bool isLValueReference = false;
4286 bool isRValueReference = false;
Douglas Gregor621b3932008-11-21 02:54:28 +00004287 bool isPointer = false;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004288 if (const LValueReferenceType *FnTypeRef =
Ted Kremenek6217b802009-07-29 21:53:49 +00004289 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor621b3932008-11-21 02:54:28 +00004290 FnType = FnTypeRef->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004291 isLValueReference = true;
4292 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenek6217b802009-07-29 21:53:49 +00004293 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004294 FnType = FnTypeRef->getPointeeType();
4295 isRValueReference = true;
Douglas Gregor621b3932008-11-21 02:54:28 +00004296 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004297 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor621b3932008-11-21 02:54:28 +00004298 FnType = FnTypePtr->getPointeeType();
4299 isPointer = true;
4300 }
4301 // Desugar down to a function type.
John McCall183700f2009-09-21 23:43:11 +00004302 FnType = QualType(FnType->getAs<FunctionType>(), 0);
Douglas Gregor621b3932008-11-21 02:54:28 +00004303 // Reconstruct the pointer/reference as appropriate.
4304 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004305 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
4306 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor621b3932008-11-21 02:54:28 +00004307
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004308 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattnerd1625842008-11-24 06:25:27 +00004309 << FnType;
Douglas Gregor33074752009-09-30 21:46:01 +00004310 } else if (OnlyViable) {
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004311 assert(Cand->Conversions.size() <= 2 &&
Fariborz Jahanianad3607d2009-10-09 17:09:58 +00004312 "builtin-binary-operator-not-binary");
Fariborz Jahanian866b2742009-10-16 23:25:02 +00004313 std::string TypeStr("operator");
4314 TypeStr += Opc;
4315 TypeStr += "(";
4316 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4317 if (Cand->Conversions.size() == 1) {
4318 TypeStr += ")";
4319 Diag(OpLoc, diag::err_ovl_builtin_unary_candidate) << TypeStr;
4320 }
4321 else {
4322 TypeStr += ", ";
4323 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4324 TypeStr += ")";
4325 Diag(OpLoc, diag::err_ovl_builtin_binary_candidate) << TypeStr;
4326 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004327 }
Fariborz Jahanian27687cf2009-10-12 17:51:19 +00004328 else if (!Cand->Viable && !Reported) {
4329 // Non-viability might be due to ambiguous user-defined conversions,
4330 // needed for built-in operators. Report them as well, but only once
4331 // as we have typically many built-in candidates.
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004332 unsigned NoOperands = Cand->Conversions.size();
4333 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
Fariborz Jahanian27687cf2009-10-12 17:51:19 +00004334 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
4335 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion ||
4336 ICS.ConversionFunctionSet.empty())
4337 continue;
4338 if (CXXConversionDecl *Func = dyn_cast<CXXConversionDecl>(
4339 Cand->Conversions[ArgIdx].ConversionFunctionSet[0])) {
4340 QualType FromTy =
4341 QualType(
4342 static_cast<Type*>(ICS.UserDefined.Before.FromTypePtr),0);
4343 Diag(OpLoc,diag::note_ambiguous_type_conversion)
4344 << FromTy << Func->getConversionType();
4345 }
4346 for (unsigned j = 0; j < ICS.ConversionFunctionSet.size(); j++) {
4347 FunctionDecl *Func =
4348 Cand->Conversions[ArgIdx].ConversionFunctionSet[j];
4349 Diag(Func->getLocation(),diag::err_ovl_candidate);
4350 }
4351 }
4352 Reported = true;
4353 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004354 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004355 }
4356}
4357
Douglas Gregor904eed32008-11-10 20:40:00 +00004358/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4359/// an overloaded function (C++ [over.over]), where @p From is an
4360/// expression with overloaded function type and @p ToType is the type
4361/// we're trying to resolve to. For example:
4362///
4363/// @code
4364/// int f(double);
4365/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00004366///
Douglas Gregor904eed32008-11-10 20:40:00 +00004367/// int (*pfd)(double) = f; // selects f(double)
4368/// @endcode
4369///
4370/// This routine returns the resulting FunctionDecl if it could be
4371/// resolved, and NULL otherwise. When @p Complain is true, this
4372/// routine will emit diagnostics if there is an error.
4373FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00004374Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor904eed32008-11-10 20:40:00 +00004375 bool Complain) {
4376 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00004377 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00004378 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00004379 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004380 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00004381 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00004382 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00004383 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00004384 FunctionType = MemTypePtr->getPointeeType();
4385 IsMember = true;
4386 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004387
4388 // We only look at pointers or references to functions.
Douglas Gregor72e771f2009-07-09 17:16:51 +00004389 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor83314aa2009-07-08 20:55:45 +00004390 if (!FunctionType->isFunctionType())
Douglas Gregor904eed32008-11-10 20:40:00 +00004391 return 0;
4392
4393 // Find the actual overloaded function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00004394
Douglas Gregor904eed32008-11-10 20:40:00 +00004395 // C++ [over.over]p1:
4396 // [...] [Note: any redundant set of parentheses surrounding the
4397 // overloaded function name is ignored (5.1). ]
4398 Expr *OvlExpr = From->IgnoreParens();
4399
4400 // C++ [over.over]p1:
4401 // [...] The overloaded function name can be preceded by the &
4402 // operator.
4403 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4404 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4405 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4406 }
4407
Anders Carlsson70534852009-10-20 22:53:47 +00004408 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00004409 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCallba135432009-11-21 08:51:07 +00004410
4411 llvm::SmallVector<NamedDecl*,8> Fns;
Anders Carlsson70534852009-10-20 22:53:47 +00004412
John McCall129e2df2009-11-30 22:42:35 +00004413 // Look into the overloaded expression.
John McCallf7a1a742009-11-24 19:00:30 +00004414 if (UnresolvedLookupExpr *UL
John McCallba135432009-11-21 08:51:07 +00004415 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4416 Fns.append(UL->decls_begin(), UL->decls_end());
John McCallf7a1a742009-11-24 19:00:30 +00004417 if (UL->hasExplicitTemplateArgs()) {
4418 HasExplicitTemplateArgs = true;
4419 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4420 }
John McCall129e2df2009-11-30 22:42:35 +00004421 } else if (UnresolvedMemberExpr *ME
4422 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4423 Fns.append(ME->decls_begin(), ME->decls_end());
4424 if (ME->hasExplicitTemplateArgs()) {
4425 HasExplicitTemplateArgs = true;
John McCalld5532b62009-11-23 01:53:49 +00004426 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004427 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00004428 }
Mike Stump1eb44332009-09-09 15:08:12 +00004429
John McCallba135432009-11-21 08:51:07 +00004430 // If we didn't actually find anything, we're done.
4431 if (Fns.empty())
4432 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004433
Douglas Gregor904eed32008-11-10 20:40:00 +00004434 // Look through all of the overloaded functions, searching for one
4435 // whose type matches exactly.
Douglas Gregor00aeb522009-07-08 23:33:52 +00004436 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004437 bool FoundNonTemplateFunction = false;
John McCallba135432009-11-21 08:51:07 +00004438 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4439 E = Fns.end(); I != E; ++I) {
Douglas Gregor904eed32008-11-10 20:40:00 +00004440 // C++ [over.over]p3:
4441 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00004442 // targets of type "pointer-to-function" or "reference-to-function."
4443 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00004444 // type "pointer-to-member-function."
4445 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00004446
Mike Stump1eb44332009-09-09 15:08:12 +00004447 if (FunctionTemplateDecl *FunctionTemplate
John McCallba135432009-11-21 08:51:07 +00004448 = dyn_cast<FunctionTemplateDecl>(*I)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004449 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00004450 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004451 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00004452 // static when converting to member pointer.
4453 if (Method->isStatic() == IsMember)
4454 continue;
4455 } else if (IsMember)
4456 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00004457
Douglas Gregor00aeb522009-07-08 23:33:52 +00004458 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004459 // If the name is a function template, template argument deduction is
4460 // done (14.8.2.2), and if the argument deduction succeeds, the
4461 // resulting template argument list is used to generate a single
4462 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00004463 // overloaded functions considered.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004464 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor83314aa2009-07-08 20:55:45 +00004465 FunctionDecl *Specialization = 0;
4466 TemplateDeductionInfo Info(Context);
4467 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00004468 = DeduceTemplateArguments(FunctionTemplate,
4469 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
Douglas Gregor83314aa2009-07-08 20:55:45 +00004470 FunctionType, Specialization, Info)) {
4471 // FIXME: make a note of the failed deduction for diagnostics.
4472 (void)Result;
4473 } else {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004474 // FIXME: If the match isn't exact, shouldn't we just drop this as
4475 // a candidate? Find a testcase before changing the code.
Mike Stump1eb44332009-09-09 15:08:12 +00004476 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00004477 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor00aeb522009-07-08 23:33:52 +00004478 Matches.insert(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00004479 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor83314aa2009-07-08 20:55:45 +00004480 }
John McCallba135432009-11-21 08:51:07 +00004481
4482 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00004483 }
Mike Stump1eb44332009-09-09 15:08:12 +00004484
John McCallba135432009-11-21 08:51:07 +00004485 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00004486 // Skip non-static functions when converting to pointer, and static
4487 // when converting to member pointer.
4488 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00004489 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00004490
4491 // If we have explicit template arguments, skip non-templates.
4492 if (HasExplicitTemplateArgs)
4493 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004494 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00004495 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00004496
John McCallba135432009-11-21 08:51:07 +00004497 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*I)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00004498 QualType ResultTy;
4499 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
4500 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
4501 ResultTy)) {
John McCallba135432009-11-21 08:51:07 +00004502 Matches.insert(cast<FunctionDecl>(FunDecl->getCanonicalDecl()));
Douglas Gregor00aeb522009-07-08 23:33:52 +00004503 FoundNonTemplateFunction = true;
4504 }
Mike Stump1eb44332009-09-09 15:08:12 +00004505 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004506 }
4507
Douglas Gregor00aeb522009-07-08 23:33:52 +00004508 // If there were 0 or 1 matches, we're done.
4509 if (Matches.empty())
4510 return 0;
Sebastian Redl07ab2022009-10-17 21:12:09 +00004511 else if (Matches.size() == 1) {
4512 FunctionDecl *Result = *Matches.begin();
4513 MarkDeclarationReferenced(From->getLocStart(), Result);
4514 return Result;
4515 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00004516
4517 // C++ [over.over]p4:
4518 // If more than one function is selected, [...]
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004519 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregor312a2022009-09-26 03:56:17 +00004520 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004521 // [...] and any given function template specialization F1 is
4522 // eliminated if the set contains a second function template
4523 // specialization whose function template is more specialized
4524 // than the function template of F1 according to the partial
4525 // ordering rules of 14.5.5.2.
4526
4527 // The algorithm specified above is quadratic. We instead use a
4528 // two-pass algorithm (similar to the one used to identify the
4529 // best viable function in an overload set) that identifies the
4530 // best function template (if it exists).
Sebastian Redl07ab2022009-10-17 21:12:09 +00004531 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
Douglas Gregor312a2022009-09-26 03:56:17 +00004532 Matches.end());
Sebastian Redl07ab2022009-10-17 21:12:09 +00004533 FunctionDecl *Result =
4534 getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4535 TPOC_Other, From->getLocStart(),
4536 PDiag(),
4537 PDiag(diag::err_addr_ovl_ambiguous)
4538 << TemplateMatches[0]->getDeclName(),
4539 PDiag(diag::err_ovl_template_candidate));
4540 MarkDeclarationReferenced(From->getLocStart(), Result);
4541 return Result;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004542 }
Mike Stump1eb44332009-09-09 15:08:12 +00004543
Douglas Gregor312a2022009-09-26 03:56:17 +00004544 // [...] any function template specializations in the set are
4545 // eliminated if the set also contains a non-template function, [...]
4546 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4547 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4548 if ((*M)->getPrimaryTemplate() == 0)
4549 RemainingMatches.push_back(*M);
4550
Mike Stump1eb44332009-09-09 15:08:12 +00004551 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00004552 // selected function.
Sebastian Redl07ab2022009-10-17 21:12:09 +00004553 if (RemainingMatches.size() == 1) {
4554 FunctionDecl *Result = RemainingMatches.front();
4555 MarkDeclarationReferenced(From->getLocStart(), Result);
4556 return Result;
4557 }
Mike Stump1eb44332009-09-09 15:08:12 +00004558
Douglas Gregor00aeb522009-07-08 23:33:52 +00004559 // FIXME: We should probably return the same thing that BestViableFunction
4560 // returns (even if we issue the diagnostics here).
4561 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4562 << RemainingMatches[0]->getDeclName();
4563 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4564 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregor904eed32008-11-10 20:40:00 +00004565 return 0;
4566}
4567
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004568/// \brief Add a single candidate to the overload set.
4569static void AddOverloadedCallCandidate(Sema &S,
John McCallba135432009-11-21 08:51:07 +00004570 NamedDecl *Callee,
John McCalld5532b62009-11-23 01:53:49 +00004571 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004572 Expr **Args, unsigned NumArgs,
4573 OverloadCandidateSet &CandidateSet,
4574 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00004575 if (isa<UsingShadowDecl>(Callee))
4576 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
4577
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004578 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00004579 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004580 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4581 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004582 return;
John McCallba135432009-11-21 08:51:07 +00004583 }
4584
4585 if (FunctionTemplateDecl *FuncTemplate
4586 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00004587 S.AddTemplateOverloadCandidate(FuncTemplate, ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00004588 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00004589 return;
4590 }
4591
4592 assert(false && "unhandled case in overloaded call candidate");
4593
4594 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004595}
4596
4597/// \brief Add the overload candidates named by callee and/or found by argument
4598/// dependent lookup to the given overload set.
John McCallba135432009-11-21 08:51:07 +00004599void Sema::AddOverloadedCallCandidates(llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004600 DeclarationName &UnqualifiedName,
John McCalld2ede7d2009-11-21 09:38:42 +00004601 bool ArgumentDependentLookup,
John McCalld5532b62009-11-23 01:53:49 +00004602 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004603 Expr **Args, unsigned NumArgs,
4604 OverloadCandidateSet &CandidateSet,
4605 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00004606
4607#ifndef NDEBUG
4608 // Verify that ArgumentDependentLookup is consistent with the rules
4609 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004610 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004611 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4612 // and let Y be the lookup set produced by argument dependent
4613 // lookup (defined as follows). If X contains
4614 //
4615 // -- a declaration of a class member, or
4616 //
4617 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00004618 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004619 //
4620 // -- a declaration that is neither a function or a function
4621 // template
4622 //
4623 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00004624
4625 if (ArgumentDependentLookup) {
4626 for (unsigned I = 0; I < Fns.size(); ++I) {
4627 assert(!Fns[I]->getDeclContext()->isRecord());
4628 assert(isa<UsingShadowDecl>(Fns[I]) ||
4629 !Fns[I]->getDeclContext()->isFunctionOrMethod());
4630 assert(Fns[I]->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
4631 }
4632 }
4633#endif
4634
4635 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4636 E = Fns.end(); I != E; ++I)
John McCalld5532b62009-11-23 01:53:49 +00004637 AddOverloadedCallCandidate(*this, *I, ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00004638 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004639 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00004640
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004641 if (ArgumentDependentLookup)
4642 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004643 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004644 CandidateSet,
4645 PartialOverloading);
4646}
John McCall578b69b2009-12-16 08:11:27 +00004647
4648/// Attempts to recover from a call where no functions were found.
4649///
4650/// Returns true if new candidates were found.
4651static bool AddRecoveryCallCandidates(Sema &SemaRef, Expr *Fn,
4652 const TemplateArgumentListInfo *ExplicitTemplateArgs,
4653 Expr **Args, unsigned NumArgs,
4654 OverloadCandidateSet &CandidateSet) {
4655 UnresolvedLookupExpr *ULE
4656 = cast<UnresolvedLookupExpr>(Fn->IgnoreParenCasts());
4657
4658 CXXScopeSpec SS;
4659 if (ULE->getQualifier()) {
4660 SS.setScopeRep(ULE->getQualifier());
4661 SS.setRange(ULE->getQualifierRange());
4662 }
4663
4664 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
4665 Sema::LookupOrdinaryName);
4666 if (SemaRef.DiagnoseEmptyLookup(SS, R))
4667 return false;
4668
4669 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4670 AddOverloadedCallCandidate(SemaRef, *I, ExplicitTemplateArgs,
4671 Args, NumArgs, CandidateSet, false);
4672 }
4673 return true;
4674}
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004675
Douglas Gregorf6b89692008-11-26 05:54:23 +00004676/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00004677/// (which eventually refers to the declaration Func) and the call
4678/// arguments Args/NumArgs, attempt to resolve the function call down
4679/// to a specific function. If overload resolution succeeds, returns
4680/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00004681/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00004682/// arguments and Fn, and returns NULL.
John McCallba135432009-11-21 08:51:07 +00004683FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn,
4684 llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregor17330012009-02-04 15:01:18 +00004685 DeclarationName UnqualifiedName,
John McCalld5532b62009-11-23 01:53:49 +00004686 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor0a396682008-11-26 06:01:48 +00004687 SourceLocation LParenLoc,
4688 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00004689 SourceLocation *CommaLocs,
Douglas Gregorfa047642009-02-04 00:32:51 +00004690 SourceLocation RParenLoc,
John McCalld2ede7d2009-11-21 09:38:42 +00004691 bool ArgumentDependentLookup) {
Douglas Gregorf6b89692008-11-26 05:54:23 +00004692 OverloadCandidateSet CandidateSet;
Douglas Gregor17330012009-02-04 15:01:18 +00004693
4694 // Add the functions denoted by Callee to the set of candidate
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004695 // functions.
John McCallba135432009-11-21 08:51:07 +00004696 AddOverloadedCallCandidates(Fns, UnqualifiedName, ArgumentDependentLookup,
John McCalld5532b62009-11-23 01:53:49 +00004697 ExplicitTemplateArgs, Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004698 CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00004699
4700 // If we found nothing, try to recover.
4701 // AddRecoveryCallCandidates diagnoses the error itself, so we just
4702 // bailout out if it fails.
4703 if (CandidateSet.empty() &&
4704 !AddRecoveryCallCandidates(*this, Fn, ExplicitTemplateArgs,
4705 Args, NumArgs, CandidateSet)) {
4706 Fn->Destroy(Context);
4707 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4708 Args[Arg]->Destroy(Context);
4709 return 0;
4710 }
4711
Douglas Gregorf6b89692008-11-26 05:54:23 +00004712 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004713 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregor0a396682008-11-26 06:01:48 +00004714 case OR_Success:
4715 return Best->Function;
Douglas Gregorf6b89692008-11-26 05:54:23 +00004716
4717 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00004718 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00004719 diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00004720 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00004721 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4722 break;
4723
4724 case OR_Ambiguous:
4725 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregor17330012009-02-04 15:01:18 +00004726 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00004727 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4728 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004729
4730 case OR_Deleted:
4731 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4732 << Best->Function->isDeleted()
4733 << UnqualifiedName
4734 << Fn->getSourceRange();
4735 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4736 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00004737 }
4738
4739 // Overload resolution failed. Destroy all of the subexpressions and
4740 // return NULL.
4741 Fn->Destroy(Context);
4742 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4743 Args[Arg]->Destroy(Context);
4744 return 0;
4745}
4746
John McCall7453ed42009-11-22 00:44:51 +00004747static bool IsOverloaded(const Sema::FunctionSet &Functions) {
4748 return Functions.size() > 1 ||
4749 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
4750}
4751
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004752/// \brief Create a unary operation that may resolve to an overloaded
4753/// operator.
4754///
4755/// \param OpLoc The location of the operator itself (e.g., '*').
4756///
4757/// \param OpcIn The UnaryOperator::Opcode that describes this
4758/// operator.
4759///
4760/// \param Functions The set of non-member functions that will be
4761/// considered by overload resolution. The caller needs to build this
4762/// set based on the context using, e.g.,
4763/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4764/// set should not contain any member functions; those will be added
4765/// by CreateOverloadedUnaryOp().
4766///
4767/// \param input The input argument.
4768Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4769 unsigned OpcIn,
4770 FunctionSet &Functions,
Mike Stump1eb44332009-09-09 15:08:12 +00004771 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004772 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4773 Expr *Input = (Expr *)input.get();
4774
4775 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4776 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4777 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4778
4779 Expr *Args[2] = { Input, 0 };
4780 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004781
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004782 // For post-increment and post-decrement, add the implicit '0' as
4783 // the second argument, so that we know this is a post-increment or
4784 // post-decrement.
4785 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4786 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump1eb44332009-09-09 15:08:12 +00004787 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004788 SourceLocation());
4789 NumArgs = 2;
4790 }
4791
4792 if (Input->isTypeDependent()) {
John McCallba135432009-11-21 08:51:07 +00004793 UnresolvedLookupExpr *Fn
John McCallf7a1a742009-11-24 19:00:30 +00004794 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
4795 0, SourceRange(), OpName, OpLoc,
John McCall7453ed42009-11-22 00:44:51 +00004796 /*ADL*/ true, IsOverloaded(Functions));
Mike Stump1eb44332009-09-09 15:08:12 +00004797 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004798 FuncEnd = Functions.end();
4799 Func != FuncEnd; ++Func)
John McCallba135432009-11-21 08:51:07 +00004800 Fn->addDecl(*Func);
Mike Stump1eb44332009-09-09 15:08:12 +00004801
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004802 input.release();
4803 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4804 &Args[0], NumArgs,
4805 Context.DependentTy,
4806 OpLoc));
4807 }
4808
4809 // Build an empty overload set.
4810 OverloadCandidateSet CandidateSet;
4811
4812 // Add the candidates from the given function set.
4813 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4814
4815 // Add operator candidates that are member functions.
4816 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4817
4818 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00004819 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004820
4821 // Perform overload resolution.
4822 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004823 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004824 case OR_Success: {
4825 // We found a built-in operator or an overloaded operator.
4826 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00004827
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004828 if (FnDecl) {
4829 // We matched an overloaded operator. Build a call to that
4830 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00004831
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004832 // Convert the arguments.
4833 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4834 if (PerformObjectArgumentInitialization(Input, Method))
4835 return ExprError();
4836 } else {
4837 // Convert the arguments.
4838 if (PerformCopyInitialization(Input,
4839 FnDecl->getParamDecl(0)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +00004840 AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004841 return ExprError();
4842 }
4843
4844 // Determine the result type
Anders Carlsson26a2a072009-10-13 21:19:37 +00004845 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00004846
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004847 // Build the actual expression node.
4848 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4849 SourceLocation());
4850 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00004851
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004852 input.release();
Eli Friedman4c3b8962009-11-18 03:58:17 +00004853 Args[0] = Input;
Anders Carlsson26a2a072009-10-13 21:19:37 +00004854 ExprOwningPtr<CallExpr> TheCall(this,
4855 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman4c3b8962009-11-18 03:58:17 +00004856 Args, NumArgs, ResultTy, OpLoc));
Anders Carlsson26a2a072009-10-13 21:19:37 +00004857
4858 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4859 FnDecl))
4860 return ExprError();
4861
4862 return MaybeBindToTemporary(TheCall.release());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004863 } else {
4864 // We matched a built-in operator. Convert the arguments, then
4865 // break out so that we will build the appropriate built-in
4866 // operator node.
4867 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00004868 Best->Conversions[0], AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004869 return ExprError();
4870
4871 break;
4872 }
4873 }
4874
4875 case OR_No_Viable_Function:
4876 // No viable function; fall through to handling this as a
4877 // built-in operator, which will produce an error message for us.
4878 break;
4879
4880 case OR_Ambiguous:
4881 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4882 << UnaryOperator::getOpcodeStr(Opc)
4883 << Input->getSourceRange();
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004884 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4885 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004886 return ExprError();
4887
4888 case OR_Deleted:
4889 Diag(OpLoc, diag::err_ovl_deleted_oper)
4890 << Best->Function->isDeleted()
4891 << UnaryOperator::getOpcodeStr(Opc)
4892 << Input->getSourceRange();
4893 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4894 return ExprError();
4895 }
4896
4897 // Either we found no viable overloaded operator or we matched a
4898 // built-in operator. In either case, fall through to trying to
4899 // build a built-in operation.
4900 input.release();
4901 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4902}
4903
Douglas Gregor063daf62009-03-13 18:40:31 +00004904/// \brief Create a binary operation that may resolve to an overloaded
4905/// operator.
4906///
4907/// \param OpLoc The location of the operator itself (e.g., '+').
4908///
4909/// \param OpcIn The BinaryOperator::Opcode that describes this
4910/// operator.
4911///
4912/// \param Functions The set of non-member functions that will be
4913/// considered by overload resolution. The caller needs to build this
4914/// set based on the context using, e.g.,
4915/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4916/// set should not contain any member functions; those will be added
4917/// by CreateOverloadedBinOp().
4918///
4919/// \param LHS Left-hand argument.
4920/// \param RHS Right-hand argument.
Mike Stump1eb44332009-09-09 15:08:12 +00004921Sema::OwningExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00004922Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004923 unsigned OpcIn,
Douglas Gregor063daf62009-03-13 18:40:31 +00004924 FunctionSet &Functions,
4925 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00004926 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004927 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00004928
4929 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4930 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4931 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4932
4933 // If either side is type-dependent, create an appropriate dependent
4934 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004935 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00004936 if (Functions.empty()) {
4937 // If there are no functions to store, just build a dependent
4938 // BinaryOperator or CompoundAssignment.
4939 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
4940 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
4941 Context.DependentTy, OpLoc));
4942
4943 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
4944 Context.DependentTy,
4945 Context.DependentTy,
4946 Context.DependentTy,
4947 OpLoc));
4948 }
4949
John McCallba135432009-11-21 08:51:07 +00004950 UnresolvedLookupExpr *Fn
John McCallf7a1a742009-11-24 19:00:30 +00004951 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
4952 0, SourceRange(), OpName, OpLoc,
John McCall7453ed42009-11-22 00:44:51 +00004953 /* ADL */ true, IsOverloaded(Functions));
John McCallba135432009-11-21 08:51:07 +00004954
Mike Stump1eb44332009-09-09 15:08:12 +00004955 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor063daf62009-03-13 18:40:31 +00004956 FuncEnd = Functions.end();
4957 Func != FuncEnd; ++Func)
John McCallba135432009-11-21 08:51:07 +00004958 Fn->addDecl(*Func);
Mike Stump1eb44332009-09-09 15:08:12 +00004959
Douglas Gregor063daf62009-03-13 18:40:31 +00004960 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00004961 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00004962 Context.DependentTy,
4963 OpLoc));
4964 }
4965
4966 // If this is the .* operator, which is not overloadable, just
4967 // create a built-in binary operator.
4968 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004969 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00004970
Sebastian Redl275c2b42009-11-18 23:10:33 +00004971 // If this is the assignment operator, we only perform overload resolution
4972 // if the left-hand side is a class or enumeration type. This is actually
4973 // a hack. The standard requires that we do overload resolution between the
4974 // various built-in candidates, but as DR507 points out, this can lead to
4975 // problems. So we do it this way, which pretty much follows what GCC does.
4976 // Note that we go the traditional code path for compound assignment forms.
4977 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00004978 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00004979
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004980 // Build an empty overload set.
4981 OverloadCandidateSet CandidateSet;
Douglas Gregor063daf62009-03-13 18:40:31 +00004982
4983 // Add the candidates from the given function set.
4984 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4985
4986 // Add operator candidates that are member functions.
4987 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4988
4989 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00004990 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00004991
4992 // Perform overload resolution.
4993 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004994 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004995 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00004996 // We found a built-in operator or an overloaded operator.
4997 FunctionDecl *FnDecl = Best->Function;
4998
4999 if (FnDecl) {
5000 // We matched an overloaded operator. Build a call to that
5001 // operator.
5002
5003 // Convert the arguments.
5004 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005005 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5006 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +00005007 AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00005008 return ExprError();
5009 } else {
5010 // Convert the arguments.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005011 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +00005012 AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005013 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +00005014 AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00005015 return ExprError();
5016 }
5017
5018 // Determine the result type
5019 QualType ResultTy
John McCall183700f2009-09-21 23:43:11 +00005020 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor063daf62009-03-13 18:40:31 +00005021 ResultTy = ResultTy.getNonReferenceType();
5022
5023 // Build the actual expression node.
5024 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00005025 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00005026 UsualUnaryConversions(FnExpr);
5027
Anders Carlsson15ea3782009-10-13 22:43:21 +00005028 ExprOwningPtr<CXXOperatorCallExpr>
5029 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
5030 Args, 2, ResultTy,
5031 OpLoc));
5032
5033 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5034 FnDecl))
5035 return ExprError();
5036
5037 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor063daf62009-03-13 18:40:31 +00005038 } else {
5039 // We matched a built-in operator. Convert the arguments, then
5040 // break out so that we will build the appropriate built-in
5041 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005042 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00005043 Best->Conversions[0], AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005044 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00005045 Best->Conversions[1], AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00005046 return ExprError();
5047
5048 break;
5049 }
5050 }
5051
Douglas Gregor33074752009-09-30 21:46:01 +00005052 case OR_No_Viable_Function: {
5053 // C++ [over.match.oper]p9:
5054 // If the operator is the operator , [...] and there are no
5055 // viable functions, then the operator is assumed to be the
5056 // built-in operator and interpreted according to clause 5.
5057 if (Opc == BinaryOperator::Comma)
5058 break;
5059
Sebastian Redl8593c782009-05-21 11:50:50 +00005060 // For class as left operand for assignment or compound assigment operator
5061 // do not fall through to handling in built-in, but report that no overloaded
5062 // assignment operator found
Douglas Gregor33074752009-09-30 21:46:01 +00005063 OwningExprResult Result = ExprError();
5064 if (Args[0]->getType()->isRecordType() &&
5065 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00005066 Diag(OpLoc, diag::err_ovl_no_viable_oper)
5067 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005068 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00005069 } else {
5070 // No viable function; try to create a built-in operation, which will
5071 // produce an error. Then, show the non-viable candidates.
5072 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00005073 }
Douglas Gregor33074752009-09-30 21:46:01 +00005074 assert(Result.isInvalid() &&
5075 "C++ binary operator overloading is missing candidates!");
5076 if (Result.isInvalid())
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005077 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5078 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00005079 return move(Result);
5080 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005081
5082 case OR_Ambiguous:
5083 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5084 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005085 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005086 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5087 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00005088 return ExprError();
5089
5090 case OR_Deleted:
5091 Diag(OpLoc, diag::err_ovl_deleted_oper)
5092 << Best->Function->isDeleted()
5093 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005094 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor063daf62009-03-13 18:40:31 +00005095 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5096 return ExprError();
5097 }
5098
Douglas Gregor33074752009-09-30 21:46:01 +00005099 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005100 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00005101}
5102
Sebastian Redlf322ed62009-10-29 20:17:01 +00005103Action::OwningExprResult
5104Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5105 SourceLocation RLoc,
5106 ExprArg Base, ExprArg Idx) {
5107 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5108 static_cast<Expr*>(Idx.get()) };
5109 DeclarationName OpName =
5110 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5111
5112 // If either side is type-dependent, create an appropriate dependent
5113 // expression.
5114 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5115
John McCallba135432009-11-21 08:51:07 +00005116 UnresolvedLookupExpr *Fn
John McCallf7a1a742009-11-24 19:00:30 +00005117 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5118 0, SourceRange(), OpName, LLoc,
John McCall7453ed42009-11-22 00:44:51 +00005119 /*ADL*/ true, /*Overloaded*/ false);
John McCallf7a1a742009-11-24 19:00:30 +00005120 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00005121
5122 Base.release();
5123 Idx.release();
5124 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5125 Args, 2,
5126 Context.DependentTy,
5127 RLoc));
5128 }
5129
5130 // Build an empty overload set.
5131 OverloadCandidateSet CandidateSet;
5132
5133 // Subscript can only be overloaded as a member function.
5134
5135 // Add operator candidates that are member functions.
5136 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5137
5138 // Add builtin operator candidates.
5139 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5140
5141 // Perform overload resolution.
5142 OverloadCandidateSet::iterator Best;
5143 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5144 case OR_Success: {
5145 // We found a built-in operator or an overloaded operator.
5146 FunctionDecl *FnDecl = Best->Function;
5147
5148 if (FnDecl) {
5149 // We matched an overloaded operator. Build a call to that
5150 // operator.
5151
5152 // Convert the arguments.
5153 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5154 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5155 PerformCopyInitialization(Args[1],
5156 FnDecl->getParamDecl(0)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +00005157 AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00005158 return ExprError();
5159
5160 // Determine the result type
5161 QualType ResultTy
5162 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5163 ResultTy = ResultTy.getNonReferenceType();
5164
5165 // Build the actual expression node.
5166 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5167 LLoc);
5168 UsualUnaryConversions(FnExpr);
5169
5170 Base.release();
5171 Idx.release();
5172 ExprOwningPtr<CXXOperatorCallExpr>
5173 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5174 FnExpr, Args, 2,
5175 ResultTy, RLoc));
5176
5177 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5178 FnDecl))
5179 return ExprError();
5180
5181 return MaybeBindToTemporary(TheCall.release());
5182 } else {
5183 // We matched a built-in operator. Convert the arguments, then
5184 // break out so that we will build the appropriate built-in
5185 // operator node.
5186 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00005187 Best->Conversions[0], AA_Passing) ||
Sebastian Redlf322ed62009-10-29 20:17:01 +00005188 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00005189 Best->Conversions[1], AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00005190 return ExprError();
5191
5192 break;
5193 }
5194 }
5195
5196 case OR_No_Viable_Function: {
5197 // No viable function; try to create a built-in operation, which will
5198 // produce an error. Then, show the non-viable candidates.
5199 OwningExprResult Result =
5200 CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
5201 assert(Result.isInvalid() &&
5202 "C++ subscript operator overloading is missing candidates!");
5203 if (Result.isInvalid())
5204 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5205 "[]", LLoc);
5206 return move(Result);
5207 }
5208
5209 case OR_Ambiguous:
5210 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5211 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5212 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5213 "[]", LLoc);
5214 return ExprError();
5215
5216 case OR_Deleted:
5217 Diag(LLoc, diag::err_ovl_deleted_oper)
5218 << Best->Function->isDeleted() << "[]"
5219 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5220 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5221 return ExprError();
5222 }
5223
5224 // We matched a built-in operator; build it.
5225 Base.release();
5226 Idx.release();
5227 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5228 Owned(Args[1]), RLoc);
5229}
5230
Douglas Gregor88a35142008-12-22 05:46:06 +00005231/// BuildCallToMemberFunction - Build a call to a member
5232/// function. MemExpr is the expression that refers to the member
5233/// function (and includes the object parameter), Args/NumArgs are the
5234/// arguments to the function call (not including the object
5235/// parameter). The caller needs to validate that the member
5236/// expression refers to a member function or an overloaded member
5237/// function.
John McCallaa81e162009-12-01 22:10:20 +00005238Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00005239Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5240 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor88a35142008-12-22 05:46:06 +00005241 unsigned NumArgs, SourceLocation *CommaLocs,
5242 SourceLocation RParenLoc) {
5243 // Dig out the member expression. This holds both the object
5244 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00005245 Expr *NakedMemExpr = MemExprE->IgnoreParens();
5246
John McCall129e2df2009-11-30 22:42:35 +00005247 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00005248 CXXMethodDecl *Method = 0;
John McCall129e2df2009-11-30 22:42:35 +00005249 if (isa<MemberExpr>(NakedMemExpr)) {
5250 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00005251 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5252 } else {
5253 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
John McCallaa81e162009-12-01 22:10:20 +00005254
John McCall701c89e2009-12-03 04:06:58 +00005255 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00005256
Douglas Gregor88a35142008-12-22 05:46:06 +00005257 // Add overload candidates
5258 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00005259
John McCallaa81e162009-12-01 22:10:20 +00005260 // FIXME: avoid copy.
5261 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5262 if (UnresExpr->hasExplicitTemplateArgs()) {
5263 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5264 TemplateArgs = &TemplateArgsBuffer;
5265 }
5266
John McCall129e2df2009-11-30 22:42:35 +00005267 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
5268 E = UnresExpr->decls_end(); I != E; ++I) {
5269
John McCall701c89e2009-12-03 04:06:58 +00005270 NamedDecl *Func = *I;
5271 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
5272 if (isa<UsingShadowDecl>(Func))
5273 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
5274
John McCall129e2df2009-11-30 22:42:35 +00005275 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005276 // If explicit template arguments were provided, we can't call a
5277 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00005278 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005279 continue;
5280
John McCall701c89e2009-12-03 04:06:58 +00005281 AddMethodCandidate(Method, ActingDC, ObjectType, Args, NumArgs,
5282 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00005283 } else {
John McCall129e2df2009-11-30 22:42:35 +00005284 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall701c89e2009-12-03 04:06:58 +00005285 ActingDC, TemplateArgs,
5286 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00005287 CandidateSet,
5288 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00005289 }
Douglas Gregordec06662009-08-21 18:42:58 +00005290 }
Mike Stump1eb44332009-09-09 15:08:12 +00005291
John McCall129e2df2009-11-30 22:42:35 +00005292 DeclarationName DeclName = UnresExpr->getMemberName();
5293
Douglas Gregor88a35142008-12-22 05:46:06 +00005294 OverloadCandidateSet::iterator Best;
John McCall129e2df2009-11-30 22:42:35 +00005295 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005296 case OR_Success:
5297 Method = cast<CXXMethodDecl>(Best->Function);
5298 break;
5299
5300 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00005301 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00005302 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00005303 << DeclName << MemExprE->getSourceRange();
Douglas Gregor88a35142008-12-22 05:46:06 +00005304 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5305 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00005306 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00005307
5308 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00005309 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00005310 << DeclName << MemExprE->getSourceRange();
Douglas Gregor88a35142008-12-22 05:46:06 +00005311 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5312 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00005313 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005314
5315 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00005316 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005317 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00005318 << DeclName << MemExprE->getSourceRange();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005319 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5320 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00005321 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00005322 }
5323
Douglas Gregor699ee522009-11-20 19:42:02 +00005324 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
John McCallaa81e162009-12-01 22:10:20 +00005325
John McCallaa81e162009-12-01 22:10:20 +00005326 // If overload resolution picked a static member, build a
5327 // non-member call based on that function.
5328 if (Method->isStatic()) {
5329 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
5330 Args, NumArgs, RParenLoc);
5331 }
5332
John McCall129e2df2009-11-30 22:42:35 +00005333 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00005334 }
5335
5336 assert(Method && "Member call to something that isn't a method?");
Mike Stump1eb44332009-09-09 15:08:12 +00005337 ExprOwningPtr<CXXMemberCallExpr>
John McCallaa81e162009-12-01 22:10:20 +00005338 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump1eb44332009-09-09 15:08:12 +00005339 NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00005340 Method->getResultType().getNonReferenceType(),
5341 RParenLoc));
5342
Anders Carlssoneed3e692009-10-10 00:06:20 +00005343 // Check for a valid return type.
5344 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5345 TheCall.get(), Method))
John McCallaa81e162009-12-01 22:10:20 +00005346 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00005347
Douglas Gregor88a35142008-12-22 05:46:06 +00005348 // Convert the object argument (for a non-static member function call).
John McCallaa81e162009-12-01 22:10:20 +00005349 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00005350 if (!Method->isStatic() &&
Douglas Gregor88a35142008-12-22 05:46:06 +00005351 PerformObjectArgumentInitialization(ObjectArg, Method))
John McCallaa81e162009-12-01 22:10:20 +00005352 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00005353 MemExpr->setBase(ObjectArg);
5354
5355 // Convert the rest of the arguments
Douglas Gregor72564e72009-02-26 23:50:07 +00005356 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00005357 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00005358 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00005359 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00005360
Anders Carlssond406bf02009-08-16 01:56:34 +00005361 if (CheckFunctionCall(Method, TheCall.get()))
John McCallaa81e162009-12-01 22:10:20 +00005362 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00005363
John McCallaa81e162009-12-01 22:10:20 +00005364 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor88a35142008-12-22 05:46:06 +00005365}
5366
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005367/// BuildCallToObjectOfClassType - Build a call to an object of class
5368/// type (C++ [over.call.object]), which can end up invoking an
5369/// overloaded function call operator (@c operator()) or performing a
5370/// user-defined conversion on the object argument.
Mike Stump1eb44332009-09-09 15:08:12 +00005371Sema::ExprResult
5372Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00005373 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005374 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00005375 SourceLocation *CommaLocs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005376 SourceLocation RParenLoc) {
5377 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00005378 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005379
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005380 // C++ [over.call.object]p1:
5381 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00005382 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005383 // candidate functions includes at least the function call
5384 // operators of T. The function call operators of T are obtained by
5385 // ordinary lookup of the name operator() in the context of
5386 // (E).operator().
5387 OverloadCandidateSet CandidateSet;
Douglas Gregor44b43212008-12-11 16:49:14 +00005388 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00005389
5390 if (RequireCompleteType(LParenLoc, Object->getType(),
5391 PartialDiagnostic(diag::err_incomplete_object_call)
5392 << Object->getSourceRange()))
5393 return true;
5394
John McCalla24dc2e2009-11-17 02:14:36 +00005395 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
5396 LookupQualifiedName(R, Record->getDecl());
5397 R.suppressDiagnostics();
5398
Douglas Gregor593564b2009-11-15 07:48:03 +00005399 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00005400 Oper != OperEnd; ++Oper) {
John McCall701c89e2009-12-03 04:06:58 +00005401 AddMethodCandidate(*Oper, Object->getType(), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00005402 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00005403 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00005404
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005405 // C++ [over.call.object]p2:
5406 // In addition, for each conversion function declared in T of the
5407 // form
5408 //
5409 // operator conversion-type-id () cv-qualifier;
5410 //
5411 // where cv-qualifier is the same cv-qualification as, or a
5412 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00005413 // denotes the type "pointer to function of (P1,...,Pn) returning
5414 // R", or the type "reference to pointer to function of
5415 // (P1,...,Pn) returning R", or the type "reference to function
5416 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005417 // is also considered as a candidate function. Similarly,
5418 // surrogate call functions are added to the set of candidate
5419 // functions for each conversion function declared in an
5420 // accessible base class provided the function is not hidden
5421 // within T by another intervening declaration.
Douglas Gregor4a27d702009-10-21 06:18:39 +00005422 // FIXME: Look in base classes for more conversion operators!
John McCallba135432009-11-21 08:51:07 +00005423 const UnresolvedSet *Conversions
Douglas Gregor4a27d702009-10-21 06:18:39 +00005424 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
John McCallba135432009-11-21 08:51:07 +00005425 for (UnresolvedSet::iterator I = Conversions->begin(),
5426 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00005427 NamedDecl *D = *I;
5428 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5429 if (isa<UsingShadowDecl>(D))
5430 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5431
Douglas Gregor4a27d702009-10-21 06:18:39 +00005432 // Skip over templated conversion functions; they aren't
5433 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00005434 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00005435 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005436
John McCall701c89e2009-12-03 04:06:58 +00005437 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00005438
Douglas Gregor4a27d702009-10-21 06:18:39 +00005439 // Strip the reference type (if any) and then the pointer type (if
5440 // any) to get down to what might be a function type.
5441 QualType ConvType = Conv->getConversionType().getNonReferenceType();
5442 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5443 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005444
Douglas Gregor4a27d702009-10-21 06:18:39 +00005445 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall701c89e2009-12-03 04:06:58 +00005446 AddSurrogateCandidate(Conv, ActingContext, Proto,
5447 Object->getType(), Args, NumArgs,
5448 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005449 }
Mike Stump1eb44332009-09-09 15:08:12 +00005450
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005451 // Perform overload resolution.
5452 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005453 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005454 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005455 // Overload resolution succeeded; we'll build the appropriate call
5456 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005457 break;
5458
5459 case OR_No_Viable_Function:
Mike Stump1eb44332009-09-09 15:08:12 +00005460 Diag(Object->getSourceRange().getBegin(),
Sebastian Redle4c452c2008-11-22 13:44:36 +00005461 diag::err_ovl_no_viable_object_call)
Chris Lattner4330d652009-02-17 07:29:20 +00005462 << Object->getType() << Object->getSourceRange();
Sebastian Redle4c452c2008-11-22 13:44:36 +00005463 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005464 break;
5465
5466 case OR_Ambiguous:
5467 Diag(Object->getSourceRange().getBegin(),
5468 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00005469 << Object->getType() << Object->getSourceRange();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005470 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5471 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005472
5473 case OR_Deleted:
5474 Diag(Object->getSourceRange().getBegin(),
5475 diag::err_ovl_deleted_object_call)
5476 << Best->Function->isDeleted()
5477 << Object->getType() << Object->getSourceRange();
5478 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5479 break;
Mike Stump1eb44332009-09-09 15:08:12 +00005480 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005481
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005482 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005483 // We had an error; delete all of the subexpressions and return
5484 // the error.
Ted Kremenek8189cde2009-02-07 01:47:29 +00005485 Object->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005486 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek8189cde2009-02-07 01:47:29 +00005487 Args[ArgIdx]->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005488 return true;
5489 }
5490
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005491 if (Best->Function == 0) {
5492 // Since there is no function declaration, this is one of the
5493 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00005494 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005495 = cast<CXXConversionDecl>(
5496 Best->Conversions[0].UserDefined.ConversionFunction);
5497
5498 // We selected one of the surrogate functions that converts the
5499 // object parameter to a function pointer. Perform the conversion
5500 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00005501
5502 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00005503 // and then call it.
Eli Friedmanc8c771e2009-12-09 04:52:43 +00005504 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00005505
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00005506 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00005507 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
5508 CommaLocs, RParenLoc).release();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005509 }
5510
5511 // We found an overloaded operator(). Build a CXXOperatorCallExpr
5512 // that calls this method, using Object for the implicit object
5513 // parameter and passing along the remaining arguments.
5514 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00005515 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005516
5517 unsigned NumArgsInProto = Proto->getNumArgs();
5518 unsigned NumArgsToCheck = NumArgs;
5519
5520 // Build the full argument list for the method call (the
5521 // implicit object parameter is placed at the beginning of the
5522 // list).
5523 Expr **MethodArgs;
5524 if (NumArgs < NumArgsInProto) {
5525 NumArgsToCheck = NumArgsInProto;
5526 MethodArgs = new Expr*[NumArgsInProto + 1];
5527 } else {
5528 MethodArgs = new Expr*[NumArgs + 1];
5529 }
5530 MethodArgs[0] = Object;
5531 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5532 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00005533
5534 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00005535 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005536 UsualUnaryConversions(NewFn);
5537
5538 // Once we've built TheCall, all of the expressions are properly
5539 // owned.
5540 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00005541 ExprOwningPtr<CXXOperatorCallExpr>
5542 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor063daf62009-03-13 18:40:31 +00005543 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00005544 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005545 delete [] MethodArgs;
5546
Anders Carlsson07d68f12009-10-13 21:49:31 +00005547 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
5548 Method))
5549 return true;
5550
Douglas Gregor518fda12009-01-13 05:10:00 +00005551 // We may have default arguments. If so, we need to allocate more
5552 // slots in the call for them.
5553 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00005554 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00005555 else if (NumArgs > NumArgsInProto)
5556 NumArgsToCheck = NumArgsInProto;
5557
Chris Lattner312531a2009-04-12 08:11:20 +00005558 bool IsError = false;
5559
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005560 // Initialize the implicit object parameter.
Chris Lattner312531a2009-04-12 08:11:20 +00005561 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005562 TheCall->setArg(0, Object);
5563
Chris Lattner312531a2009-04-12 08:11:20 +00005564
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005565 // Check the argument types.
5566 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005567 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00005568 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005569 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00005570
Douglas Gregor518fda12009-01-13 05:10:00 +00005571 // Pass the argument.
5572 QualType ProtoArgType = Proto->getArgType(i);
Douglas Gregor68647482009-12-16 03:45:30 +00005573 IsError |= PerformCopyInitialization(Arg, ProtoArgType, AA_Passing);
Douglas Gregor518fda12009-01-13 05:10:00 +00005574 } else {
Douglas Gregord47c47d2009-11-09 19:27:57 +00005575 OwningExprResult DefArg
5576 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
5577 if (DefArg.isInvalid()) {
5578 IsError = true;
5579 break;
5580 }
5581
5582 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00005583 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005584
5585 TheCall->setArg(i + 1, Arg);
5586 }
5587
5588 // If this is a variadic call, handle args passed through "...".
5589 if (Proto->isVariadic()) {
5590 // Promote the arguments (C99 6.5.2.2p7).
5591 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
5592 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00005593 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005594 TheCall->setArg(i + 1, Arg);
5595 }
5596 }
5597
Chris Lattner312531a2009-04-12 08:11:20 +00005598 if (IsError) return true;
5599
Anders Carlssond406bf02009-08-16 01:56:34 +00005600 if (CheckFunctionCall(Method, TheCall.get()))
5601 return true;
5602
Anders Carlssona303f9e2009-08-16 03:53:54 +00005603 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005604}
5605
Douglas Gregor8ba10742008-11-20 16:27:02 +00005606/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00005607/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00005608/// @c Member is the name of the member we're trying to find.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005609Sema::OwningExprResult
5610Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
5611 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor8ba10742008-11-20 16:27:02 +00005612 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00005613
Douglas Gregor8ba10742008-11-20 16:27:02 +00005614 // C++ [over.ref]p1:
5615 //
5616 // [...] An expression x->m is interpreted as (x.operator->())->m
5617 // for a class object x of type T if T::operator->() exists and if
5618 // the operator is selected as the best match function by the
5619 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00005620 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
5621 OverloadCandidateSet CandidateSet;
Ted Kremenek6217b802009-07-29 21:53:49 +00005622 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005623
Eli Friedmanf43fb722009-11-18 01:28:03 +00005624 if (RequireCompleteType(Base->getLocStart(), Base->getType(),
5625 PDiag(diag::err_typecheck_incomplete_tag)
5626 << Base->getSourceRange()))
5627 return ExprError();
5628
John McCalla24dc2e2009-11-17 02:14:36 +00005629 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
5630 LookupQualifiedName(R, BaseRecord->getDecl());
5631 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00005632
5633 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00005634 Oper != OperEnd; ++Oper) {
5635 NamedDecl *D = *Oper;
5636 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5637 if (isa<UsingShadowDecl>(D))
5638 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5639
5640 AddMethodCandidate(cast<CXXMethodDecl>(D), ActingContext,
5641 Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00005642 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00005643 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00005644
5645 // Perform overload resolution.
5646 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005647 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00005648 case OR_Success:
5649 // Overload resolution succeeded; we'll build the call below.
5650 break;
5651
5652 case OR_No_Viable_Function:
5653 if (CandidateSet.empty())
5654 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005655 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005656 else
5657 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005658 << "operator->" << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005659 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005660 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005661
5662 case OR_Ambiguous:
5663 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00005664 << "->" << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005665 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005666 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005667
5668 case OR_Deleted:
5669 Diag(OpLoc, diag::err_ovl_deleted_oper)
5670 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00005671 << "->" << Base->getSourceRange();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005672 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005673 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005674 }
5675
5676 // Convert the object parameter.
5677 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00005678 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005679 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00005680
5681 // No concerns about early exits now.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005682 BaseIn.release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005683
5684 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00005685 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5686 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00005687 UsualUnaryConversions(FnExpr);
Anders Carlsson15ea3782009-10-13 22:43:21 +00005688
5689 QualType ResultTy = Method->getResultType().getNonReferenceType();
5690 ExprOwningPtr<CXXOperatorCallExpr>
5691 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
5692 &Base, 1, ResultTy, OpLoc));
5693
5694 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
5695 Method))
5696 return ExprError();
5697 return move(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00005698}
5699
Douglas Gregor904eed32008-11-10 20:40:00 +00005700/// FixOverloadedFunctionReference - E is an expression that refers to
5701/// a C++ overloaded function (possibly with some parentheses and
5702/// perhaps a '&' around it). We have resolved the overloaded function
5703/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00005704/// refer (possibly indirectly) to Fn. Returns the new expr.
5705Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005706 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor699ee522009-11-20 19:42:02 +00005707 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
5708 if (SubExpr == PE->getSubExpr())
5709 return PE->Retain();
5710
5711 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
5712 }
5713
5714 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5715 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00005716 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00005717 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00005718 "Implicit cast type cannot be determined from overload");
Douglas Gregor699ee522009-11-20 19:42:02 +00005719 if (SubExpr == ICE->getSubExpr())
5720 return ICE->Retain();
5721
5722 return new (Context) ImplicitCastExpr(ICE->getType(),
5723 ICE->getCastKind(),
5724 SubExpr,
5725 ICE->isLvalueCast());
5726 }
5727
5728 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump1eb44332009-09-09 15:08:12 +00005729 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00005730 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00005731 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5732 if (Method->isStatic()) {
5733 // Do nothing: static member functions aren't any different
5734 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00005735 } else {
John McCallf7a1a742009-11-24 19:00:30 +00005736 // Fix the sub expression, which really has to be an
5737 // UnresolvedLookupExpr holding an overloaded member function
5738 // or template.
John McCallba135432009-11-21 08:51:07 +00005739 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5740 if (SubExpr == UnOp->getSubExpr())
5741 return UnOp->Retain();
Douglas Gregor699ee522009-11-20 19:42:02 +00005742
John McCallba135432009-11-21 08:51:07 +00005743 assert(isa<DeclRefExpr>(SubExpr)
5744 && "fixed to something other than a decl ref");
5745 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
5746 && "fixed to a member ref with no nested name qualifier");
5747
5748 // We have taken the address of a pointer to member
5749 // function. Perform the computation here so that we get the
5750 // appropriate pointer to member type.
5751 QualType ClassType
5752 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
5753 QualType MemPtrType
5754 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
5755
5756 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
5757 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00005758 }
5759 }
Douglas Gregor699ee522009-11-20 19:42:02 +00005760 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5761 if (SubExpr == UnOp->getSubExpr())
5762 return UnOp->Retain();
Anders Carlsson96ad5332009-10-21 17:16:23 +00005763
Douglas Gregor699ee522009-11-20 19:42:02 +00005764 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
5765 Context.getPointerType(SubExpr->getType()),
5766 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00005767 }
John McCallba135432009-11-21 08:51:07 +00005768
5769 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00005770 // FIXME: avoid copy.
5771 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00005772 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00005773 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
5774 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00005775 }
5776
John McCallba135432009-11-21 08:51:07 +00005777 return DeclRefExpr::Create(Context,
5778 ULE->getQualifier(),
5779 ULE->getQualifierRange(),
5780 Fn,
5781 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00005782 Fn->getType(),
5783 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00005784 }
5785
John McCall129e2df2009-11-30 22:42:35 +00005786 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00005787 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00005788 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5789 if (MemExpr->hasExplicitTemplateArgs()) {
5790 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5791 TemplateArgs = &TemplateArgsBuffer;
5792 }
John McCalld5532b62009-11-23 01:53:49 +00005793
John McCallaa81e162009-12-01 22:10:20 +00005794 Expr *Base;
5795
5796 // If we're filling in
5797 if (MemExpr->isImplicitAccess()) {
5798 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
5799 return DeclRefExpr::Create(Context,
5800 MemExpr->getQualifier(),
5801 MemExpr->getQualifierRange(),
5802 Fn,
5803 MemExpr->getMemberLoc(),
5804 Fn->getType(),
5805 TemplateArgs);
5806 } else
5807 Base = new (Context) CXXThisExpr(SourceLocation(),
5808 MemExpr->getBaseType());
5809 } else
5810 Base = MemExpr->getBase()->Retain();
5811
5812 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00005813 MemExpr->isArrow(),
5814 MemExpr->getQualifier(),
5815 MemExpr->getQualifierRange(),
5816 Fn,
John McCalld5532b62009-11-23 01:53:49 +00005817 MemExpr->getMemberLoc(),
John McCallaa81e162009-12-01 22:10:20 +00005818 TemplateArgs,
Douglas Gregor699ee522009-11-20 19:42:02 +00005819 Fn->getType());
5820 }
5821
Douglas Gregor699ee522009-11-20 19:42:02 +00005822 assert(false && "Invalid reference to overloaded function");
5823 return E->Retain();
Douglas Gregor904eed32008-11-10 20:40:00 +00005824}
5825
Douglas Gregor20093b42009-12-09 23:02:17 +00005826Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
5827 FunctionDecl *Fn) {
5828 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Fn));
5829}
5830
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005831} // end namespace clang