blob: 8236ad7eecb7a1c8c47ab7167b9e3adb381938f2 [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();
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000454 if (Constructor->isCopyConstructor() &&
Douglas Gregor0d6d12b2009-12-22 00:21:20 +0000455 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000456 // Turn this into a "standard" conversion sequence, so that it
457 // gets ranked with standard conversion sequences.
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000458 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
459 ICS.Standard.setAsIdentityConversion();
460 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
461 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000462 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000463 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000464 ICS.Standard.Second = ICK_Derived_To_Base;
465 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000466 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000467
468 // C++ [over.best.ics]p4:
469 // However, when considering the argument of a user-defined
470 // conversion function that is a candidate by 13.3.1.3 when
471 // invoked for the copying of the temporary in the second step
472 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
473 // 13.3.1.6 in all cases, only standard conversion sequences and
474 // ellipsis conversion sequences are allowed.
475 if (SuppressUserConversions &&
476 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
477 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000478 } else {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000479 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000480 if (UserDefResult == OR_Ambiguous) {
481 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
482 Cand != Conversions.end(); ++Cand)
Fariborz Jahanian27687cf2009-10-12 17:51:19 +0000483 if (Cand->Viable)
484 ICS.ConversionFunctionSet.push_back(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000485 }
486 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000487
488 return ICS;
489}
490
Douglas Gregor43c79c22009-12-09 00:47:37 +0000491/// \brief Determine whether the conversion from FromType to ToType is a valid
492/// conversion that strips "noreturn" off the nested function type.
493static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
494 QualType ToType, QualType &ResultTy) {
495 if (Context.hasSameUnqualifiedType(FromType, ToType))
496 return false;
497
498 // Strip the noreturn off the type we're converting from; noreturn can
499 // safely be removed.
500 FromType = Context.getNoReturnType(FromType, false);
501 if (!Context.hasSameUnqualifiedType(FromType, ToType))
502 return false;
503
504 ResultTy = FromType;
505 return true;
506}
507
Douglas Gregor60d62c22008-10-31 16:23:19 +0000508/// IsStandardConversion - Determines whether there is a standard
509/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
510/// expression From to the type ToType. Standard conversion sequences
511/// only consider non-class types; for conversions that involve class
512/// types, use TryImplicitConversion. If a conversion exists, SCS will
513/// contain the standard conversion sequence required to perform this
514/// conversion and this routine will return true. Otherwise, this
515/// routine will return false and the value of SCS is unspecified.
Mike Stump1eb44332009-09-09 15:08:12 +0000516bool
517Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000518 bool InOverloadResolution,
Mike Stump1eb44332009-09-09 15:08:12 +0000519 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000520 QualType FromType = From->getType();
521
Douglas Gregor60d62c22008-10-31 16:23:19 +0000522 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000523 SCS.setAsIdentityConversion();
Douglas Gregor60d62c22008-10-31 16:23:19 +0000524 SCS.Deprecated = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000525 SCS.IncompatibleObjC = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000526 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor225c41e2008-11-03 19:09:14 +0000527 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000528
Douglas Gregorf9201e02009-02-11 23:02:49 +0000529 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000530 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000531 if (FromType->isRecordType() || ToType->isRecordType()) {
532 if (getLangOptions().CPlusPlus)
533 return false;
534
Mike Stump1eb44332009-09-09 15:08:12 +0000535 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000536 }
537
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000538 // The first conversion can be an lvalue-to-rvalue conversion,
539 // array-to-pointer conversion, or function-to-pointer conversion
540 // (C++ 4p1).
541
Mike Stump1eb44332009-09-09 15:08:12 +0000542 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000543 // An lvalue (3.10) of a non-function, non-array type T can be
544 // converted to an rvalue.
545 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000546 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000547 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor063daf62009-03-13 18:40:31 +0000548 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000549 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000550
551 // If T is a non-class type, the type of the rvalue is the
552 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +0000553 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
554 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000555 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000556 } else if (FromType->isArrayType()) {
557 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000558 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000559
560 // An lvalue or rvalue of type "array of N T" or "array of unknown
561 // bound of T" can be converted to an rvalue of type "pointer to
562 // T" (C++ 4.2p1).
563 FromType = Context.getArrayDecayedType(FromType);
564
565 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
566 // This conversion is deprecated. (C++ D.4).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000567 SCS.Deprecated = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000568
569 // For the purpose of ranking in overload resolution
570 // (13.3.3.1.1), this conversion is considered an
571 // array-to-pointer conversion followed by a qualification
572 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000573 SCS.Second = ICK_Identity;
574 SCS.Third = ICK_Qualification;
575 SCS.ToTypePtr = ToType.getAsOpaquePtr();
576 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000577 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000578 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
579 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000580 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000581
582 // An lvalue of function type T can be converted to an rvalue of
583 // type "pointer to T." The result is a pointer to the
584 // function. (C++ 4.3p1).
585 FromType = Context.getPointerType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000586 } else if (FunctionDecl *Fn
Douglas Gregor43c79c22009-12-09 00:47:37 +0000587 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000588 // Address of overloaded function (C++ [over.over]).
Douglas Gregor904eed32008-11-10 20:40:00 +0000589 SCS.First = ICK_Function_To_Pointer;
590
591 // We were able to resolve the address of the overloaded function,
592 // so we can convert to the type of that function.
593 FromType = Fn->getType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000594 if (ToType->isLValueReferenceType())
595 FromType = Context.getLValueReferenceType(FromType);
596 else if (ToType->isRValueReferenceType())
597 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl33b399a2009-02-04 21:23:32 +0000598 else if (ToType->isMemberPointerType()) {
599 // Resolve address only succeeds if both sides are member pointers,
600 // but it doesn't have to be the same class. See DR 247.
601 // Note that this means that the type of &Derived::fn can be
602 // Ret (Base::*)(Args) if the fn overload actually found is from the
603 // base class, even if it was brought into the derived class via a
604 // using declaration. The standard isn't clear on this issue at all.
605 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
606 FromType = Context.getMemberPointerType(FromType,
607 Context.getTypeDeclType(M->getParent()).getTypePtr());
608 } else
Douglas Gregor904eed32008-11-10 20:40:00 +0000609 FromType = Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000610 } else {
611 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000612 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000613 }
614
615 // The second conversion can be an integral promotion, floating
616 // point promotion, integral conversion, floating point conversion,
617 // floating-integral conversion, pointer conversion,
618 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +0000619 // For overloading in C, this can also be a "compatible-type"
620 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +0000621 bool IncompatibleObjC = false;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000622 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000623 // The unqualified versions of the types are the same: there's no
624 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000625 SCS.Second = ICK_Identity;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000626 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000627 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000628 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000629 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000630 } else if (IsFloatingPointPromotion(FromType, ToType)) {
631 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000632 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000633 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000634 } else if (IsComplexPromotion(FromType, ToType)) {
635 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000636 SCS.Second = ICK_Complex_Promotion;
637 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000638 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000639 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000640 // Integral conversions (C++ 4.7).
641 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000642 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000643 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000644 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
645 // Floating point conversions (C++ 4.8).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000646 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000647 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000648 } else if (FromType->isComplexType() && ToType->isComplexType()) {
649 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000650 SCS.Second = ICK_Complex_Conversion;
651 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000652 } else if ((FromType->isFloatingType() &&
653 ToType->isIntegralType() && (!ToType->isBooleanType() &&
654 !ToType->isEnumeralType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000655 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000656 ToType->isFloatingType())) {
657 // Floating-integral conversions (C++ 4.9).
658 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000659 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000660 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000661 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
662 (ToType->isComplexType() && FromType->isArithmeticType())) {
663 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000664 SCS.Second = ICK_Complex_Real;
665 FromType = ToType.getUnqualifiedType();
Anders Carlsson08972922009-08-28 15:33:32 +0000666 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
667 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000668 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000669 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000670 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregorce940492009-09-25 04:25:58 +0000671 } else if (IsMemberPointerConversion(From, FromType, ToType,
672 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000673 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000674 SCS.Second = ICK_Pointer_Member;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000675 } else if (ToType->isBooleanType() &&
676 (FromType->isArithmeticType() ||
677 FromType->isEnumeralType() ||
Fariborz Jahanian1f7711d2009-12-11 21:23:13 +0000678 FromType->isAnyPointerType() ||
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000679 FromType->isBlockPointerType() ||
680 FromType->isMemberPointerType() ||
681 FromType->isNullPtrType())) {
682 // Boolean conversions (C++ 4.12).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000683 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000684 FromType = Context.BoolTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000685 } else if (!getLangOptions().CPlusPlus &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000686 Context.typesAreCompatible(ToType, FromType)) {
687 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000688 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor43c79c22009-12-09 00:47:37 +0000689 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
690 // Treat a conversion that strips "noreturn" as an identity conversion.
691 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000692 } else {
693 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000694 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000695 }
696
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000697 QualType CanonFrom;
698 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000699 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000700 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000701 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000702 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000703 CanonFrom = Context.getCanonicalType(FromType);
704 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000705 } else {
706 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000707 SCS.Third = ICK_Identity;
708
Mike Stump1eb44332009-09-09 15:08:12 +0000709 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +0000710 // [...] Any difference in top-level cv-qualification is
711 // subsumed by the initialization itself and does not constitute
712 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000713 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000714 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregora4923eb2009-11-16 21:35:15 +0000715 if (CanonFrom.getLocalUnqualifiedType()
716 == CanonTo.getLocalUnqualifiedType() &&
717 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000718 FromType = ToType;
719 CanonFrom = CanonTo;
720 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000721 }
722
723 // If we have not converted the argument type to the parameter type,
724 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000725 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000726 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000727
Douglas Gregor60d62c22008-10-31 16:23:19 +0000728 SCS.ToTypePtr = FromType.getAsOpaquePtr();
729 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000730}
731
732/// IsIntegralPromotion - Determines whether the conversion from the
733/// expression From (whose potentially-adjusted type is FromType) to
734/// ToType is an integral promotion (C++ 4.5). If so, returns true and
735/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000736bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +0000737 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +0000738 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +0000739 if (!To) {
740 return false;
741 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000742
743 // An rvalue of type char, signed char, unsigned char, short int, or
744 // unsigned short int can be converted to an rvalue of type int if
745 // int can represent all the values of the source type; otherwise,
746 // the source rvalue can be converted to an rvalue of type unsigned
747 // int (C++ 4.5p1).
Sebastian Redl07779722008-10-31 14:43:28 +0000748 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000749 if (// We can promote any signed, promotable integer type to an int
750 (FromType->isSignedIntegerType() ||
751 // We can promote any unsigned integer type whose size is
752 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +0000753 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +0000754 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000755 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +0000756 }
757
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000758 return To->getKind() == BuiltinType::UInt;
759 }
760
761 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
762 // can be converted to an rvalue of the first of the following types
763 // that can represent all the values of its underlying type: int,
764 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall842aef82009-12-09 09:09:27 +0000765
766 // We pre-calculate the promotion type for enum types.
767 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
768 if (ToType->isIntegerType())
769 return Context.hasSameUnqualifiedType(ToType,
770 FromEnumType->getDecl()->getPromotionType());
771
772 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000773 // Determine whether the type we're converting from is signed or
774 // unsigned.
775 bool FromIsSigned;
776 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall842aef82009-12-09 09:09:27 +0000777
778 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
779 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000780
781 // The types we'll try to promote to, in the appropriate
782 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +0000783 QualType PromoteTypes[6] = {
784 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000785 Context.LongTy, Context.UnsignedLongTy ,
786 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000787 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +0000788 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000789 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
790 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +0000791 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000792 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
793 // We found the type that we can promote to. If this is the
794 // type we wanted, we have a promotion. Otherwise, no
795 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000796 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000797 }
798 }
799 }
800
801 // An rvalue for an integral bit-field (9.6) can be converted to an
802 // rvalue of type int if int can represent all the values of the
803 // bit-field; otherwise, it can be converted to unsigned int if
804 // unsigned int can represent all the values of the bit-field. If
805 // the bit-field is larger yet, no integral promotion applies to
806 // it. If the bit-field has an enumerated type, it is treated as any
807 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +0000808 // FIXME: We should delay checking of bit-fields until we actually perform the
809 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000810 using llvm::APSInt;
811 if (From)
812 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +0000813 APSInt BitWidth;
Douglas Gregor33bbbc52009-05-02 02:18:30 +0000814 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
815 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
816 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
817 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +0000818
Douglas Gregor86f19402008-12-20 23:49:58 +0000819 // Are we promoting to an int from a bitfield that fits in an int?
820 if (BitWidth < ToSize ||
821 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
822 return To->getKind() == BuiltinType::Int;
823 }
Mike Stump1eb44332009-09-09 15:08:12 +0000824
Douglas Gregor86f19402008-12-20 23:49:58 +0000825 // Are we promoting to an unsigned int from an unsigned bitfield
826 // that fits into an unsigned int?
827 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
828 return To->getKind() == BuiltinType::UInt;
829 }
Mike Stump1eb44332009-09-09 15:08:12 +0000830
Douglas Gregor86f19402008-12-20 23:49:58 +0000831 return false;
Sebastian Redl07779722008-10-31 14:43:28 +0000832 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000833 }
Mike Stump1eb44332009-09-09 15:08:12 +0000834
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000835 // An rvalue of type bool can be converted to an rvalue of type int,
836 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +0000837 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000838 return true;
Sebastian Redl07779722008-10-31 14:43:28 +0000839 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000840
841 return false;
842}
843
844/// IsFloatingPointPromotion - Determines whether the conversion from
845/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
846/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +0000847bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000848 /// An rvalue of type float can be converted to an rvalue of type
849 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +0000850 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
851 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000852 if (FromBuiltin->getKind() == BuiltinType::Float &&
853 ToBuiltin->getKind() == BuiltinType::Double)
854 return true;
855
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000856 // C99 6.3.1.5p1:
857 // When a float is promoted to double or long double, or a
858 // double is promoted to long double [...].
859 if (!getLangOptions().CPlusPlus &&
860 (FromBuiltin->getKind() == BuiltinType::Float ||
861 FromBuiltin->getKind() == BuiltinType::Double) &&
862 (ToBuiltin->getKind() == BuiltinType::LongDouble))
863 return true;
864 }
865
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000866 return false;
867}
868
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000869/// \brief Determine if a conversion is a complex promotion.
870///
871/// A complex promotion is defined as a complex -> complex conversion
872/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000873/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000874bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +0000875 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000876 if (!FromComplex)
877 return false;
878
John McCall183700f2009-09-21 23:43:11 +0000879 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000880 if (!ToComplex)
881 return false;
882
883 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +0000884 ToComplex->getElementType()) ||
885 IsIntegralPromotion(0, FromComplex->getElementType(),
886 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000887}
888
Douglas Gregorcb7de522008-11-26 23:31:11 +0000889/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
890/// the pointer type FromPtr to a pointer to type ToPointee, with the
891/// same type qualifiers as FromPtr has on its pointee type. ToType,
892/// if non-empty, will be a pointer to ToType that may or may not have
893/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +0000894static QualType
895BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +0000896 QualType ToPointee, QualType ToType,
897 ASTContext &Context) {
898 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
899 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +0000900 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +0000901
902 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +0000903 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +0000904 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +0000905 if (!ToType.isNull())
Douglas Gregorcb7de522008-11-26 23:31:11 +0000906 return ToType;
907
908 // Build a pointer to ToPointee. It has the right qualifiers
909 // already.
910 return Context.getPointerType(ToPointee);
911 }
912
913 // Just build a canonical type that has the right qualifiers.
John McCall0953e762009-09-24 19:53:00 +0000914 return Context.getPointerType(
Douglas Gregora4923eb2009-11-16 21:35:15 +0000915 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
916 Quals));
Douglas Gregorcb7de522008-11-26 23:31:11 +0000917}
918
Fariborz Jahanianadcfab12009-12-16 23:13:33 +0000919/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
920/// the FromType, which is an objective-c pointer, to ToType, which may or may
921/// not have the right set of qualifiers.
922static QualType
923BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
924 QualType ToType,
925 ASTContext &Context) {
926 QualType CanonFromType = Context.getCanonicalType(FromType);
927 QualType CanonToType = Context.getCanonicalType(ToType);
928 Qualifiers Quals = CanonFromType.getQualifiers();
929
930 // Exact qualifier match -> return the pointer type we're converting to.
931 if (CanonToType.getLocalQualifiers() == Quals)
932 return ToType;
933
934 // Just build a canonical type that has the right qualifiers.
935 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
936}
937
Mike Stump1eb44332009-09-09 15:08:12 +0000938static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000939 bool InOverloadResolution,
940 ASTContext &Context) {
941 // Handle value-dependent integral null pointer constants correctly.
942 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
943 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
944 Expr->getType()->isIntegralType())
945 return !InOverloadResolution;
946
Douglas Gregorce940492009-09-25 04:25:58 +0000947 return Expr->isNullPointerConstant(Context,
948 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
949 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000950}
Mike Stump1eb44332009-09-09 15:08:12 +0000951
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000952/// IsPointerConversion - Determines whether the conversion of the
953/// expression From, which has the (possibly adjusted) type FromType,
954/// can be converted to the type ToType via a pointer conversion (C++
955/// 4.10). If so, returns true and places the converted type (that
956/// might differ from ToType in its cv-qualifiers at some level) into
957/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000958///
Douglas Gregor7ca09762008-11-27 01:19:21 +0000959/// This routine also supports conversions to and from block pointers
960/// and conversions with Objective-C's 'id', 'id<protocols...>', and
961/// pointers to interfaces. FIXME: Once we've determined the
962/// appropriate overloading rules for Objective-C, we may want to
963/// split the Objective-C checks into a different routine; however,
964/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +0000965/// conversions, so for now they live here. IncompatibleObjC will be
966/// set if the conversion is an allowed Objective-C conversion that
967/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000968bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000969 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +0000970 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +0000971 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +0000972 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +0000973 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
974 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +0000975
Mike Stump1eb44332009-09-09 15:08:12 +0000976 // Conversion from a null pointer constant to any Objective-C pointer type.
977 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000978 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +0000979 ConvertedType = ToType;
980 return true;
981 }
982
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000983 // Blocks: Block pointers can be converted to void*.
984 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000985 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000986 ConvertedType = ToType;
987 return true;
988 }
989 // Blocks: A null pointer constant can be converted to a block
990 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +0000991 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +0000992 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +0000993 ConvertedType = ToType;
994 return true;
995 }
996
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000997 // If the left-hand-side is nullptr_t, the right side can be a null
998 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +0000999 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001000 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001001 ConvertedType = ToType;
1002 return true;
1003 }
1004
Ted Kremenek6217b802009-07-29 21:53:49 +00001005 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001006 if (!ToTypePtr)
1007 return false;
1008
1009 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001010 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001011 ConvertedType = ToType;
1012 return true;
1013 }
Sebastian Redl07779722008-10-31 14:43:28 +00001014
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001015 // Beyond this point, both types need to be pointers
1016 // , including objective-c pointers.
1017 QualType ToPointeeType = ToTypePtr->getPointeeType();
1018 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1019 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1020 ToType, Context);
1021 return true;
1022
1023 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001024 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001025 if (!FromTypePtr)
1026 return false;
1027
1028 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001029
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001030 // An rvalue of type "pointer to cv T," where T is an object type,
1031 // can be converted to an rvalue of type "pointer to cv void" (C++
1032 // 4.10p2).
Douglas Gregorbad0e652009-03-24 20:32:41 +00001033 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001034 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001035 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001036 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001037 return true;
1038 }
1039
Douglas Gregorf9201e02009-02-11 23:02:49 +00001040 // When we're overloading in C, we allow a special kind of pointer
1041 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001042 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001043 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001044 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001045 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001046 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001047 return true;
1048 }
1049
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001050 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001051 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001052 // An rvalue of type "pointer to cv D," where D is a class type,
1053 // can be converted to an rvalue of type "pointer to cv B," where
1054 // B is a base class (clause 10) of D. If B is an inaccessible
1055 // (clause 11) or ambiguous (10.2) base class of D, a program that
1056 // necessitates this conversion is ill-formed. The result of the
1057 // conversion is a pointer to the base class sub-object of the
1058 // derived class object. The null pointer value is converted to
1059 // the null pointer value of the destination type.
1060 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001061 // Note that we do not check for ambiguity or inaccessibility
1062 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001063 if (getLangOptions().CPlusPlus &&
1064 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001065 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001066 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001067 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001068 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001069 ToType, Context);
1070 return true;
1071 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001072
Douglas Gregorc7887512008-12-19 19:13:09 +00001073 return false;
1074}
1075
1076/// isObjCPointerConversion - Determines whether this is an
1077/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1078/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001079bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001080 QualType& ConvertedType,
1081 bool &IncompatibleObjC) {
1082 if (!getLangOptions().ObjC1)
1083 return false;
1084
Steve Naroff14108da2009-07-10 23:34:53 +00001085 // First, we handle all conversions on ObjC object pointer types.
John McCall183700f2009-09-21 23:43:11 +00001086 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001087 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001088 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001089
Steve Naroff14108da2009-07-10 23:34:53 +00001090 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001091 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001092 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001093 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001094 ConvertedType = ToType;
1095 return true;
1096 }
1097 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001098 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001099 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001100 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001101 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001102 ConvertedType = ToType;
1103 return true;
1104 }
1105 // Objective C++: We're able to convert from a pointer to an
1106 // interface to a pointer to a different interface.
1107 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1108 ConvertedType = ToType;
1109 return true;
1110 }
1111
1112 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1113 // Okay: this is some kind of implicit downcast of Objective-C
1114 // interfaces, which is permitted. However, we're going to
1115 // complain about it.
1116 IncompatibleObjC = true;
1117 ConvertedType = FromType;
1118 return true;
1119 }
Mike Stump1eb44332009-09-09 15:08:12 +00001120 }
Steve Naroff14108da2009-07-10 23:34:53 +00001121 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001122 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001123 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001124 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001125 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001126 ToPointeeType = ToBlockPtr->getPointeeType();
1127 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001128 return false;
1129
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001130 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001131 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001132 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001133 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001134 FromPointeeType = FromBlockPtr->getPointeeType();
1135 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001136 return false;
1137
Douglas Gregorc7887512008-12-19 19:13:09 +00001138 // If we have pointers to pointers, recursively check whether this
1139 // is an Objective-C conversion.
1140 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1141 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1142 IncompatibleObjC)) {
1143 // We always complain about this conversion.
1144 IncompatibleObjC = true;
1145 ConvertedType = ToType;
1146 return true;
1147 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001148 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001149 // differences in the argument and result types are in Objective-C
1150 // pointer conversions. If so, we permit the conversion (but
1151 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001152 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001153 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001154 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001155 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001156 if (FromFunctionType && ToFunctionType) {
1157 // If the function types are exactly the same, this isn't an
1158 // Objective-C pointer conversion.
1159 if (Context.getCanonicalType(FromPointeeType)
1160 == Context.getCanonicalType(ToPointeeType))
1161 return false;
1162
1163 // Perform the quick checks that will tell us whether these
1164 // function types are obviously different.
1165 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1166 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1167 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1168 return false;
1169
1170 bool HasObjCConversion = false;
1171 if (Context.getCanonicalType(FromFunctionType->getResultType())
1172 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1173 // Okay, the types match exactly. Nothing to do.
1174 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1175 ToFunctionType->getResultType(),
1176 ConvertedType, IncompatibleObjC)) {
1177 // Okay, we have an Objective-C pointer conversion.
1178 HasObjCConversion = true;
1179 } else {
1180 // Function types are too different. Abort.
1181 return false;
1182 }
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Douglas Gregorc7887512008-12-19 19:13:09 +00001184 // Check argument types.
1185 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1186 ArgIdx != NumArgs; ++ArgIdx) {
1187 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1188 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1189 if (Context.getCanonicalType(FromArgType)
1190 == Context.getCanonicalType(ToArgType)) {
1191 // Okay, the types match exactly. Nothing to do.
1192 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1193 ConvertedType, IncompatibleObjC)) {
1194 // Okay, we have an Objective-C pointer conversion.
1195 HasObjCConversion = true;
1196 } else {
1197 // Argument types are too different. Abort.
1198 return false;
1199 }
1200 }
1201
1202 if (HasObjCConversion) {
1203 // We had an Objective-C conversion. Allow this pointer
1204 // conversion, but complain about it.
1205 ConvertedType = ToType;
1206 IncompatibleObjC = true;
1207 return true;
1208 }
1209 }
1210
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001211 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001212}
1213
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001214/// CheckPointerConversion - Check the pointer conversion from the
1215/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001216/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001217/// conversions for which IsPointerConversion has already returned
1218/// true. It returns true and produces a diagnostic if there was an
1219/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001220bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001221 CastExpr::CastKind &Kind,
1222 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001223 QualType FromType = From->getType();
1224
Ted Kremenek6217b802009-07-29 21:53:49 +00001225 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1226 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001227 QualType FromPointeeType = FromPtrType->getPointeeType(),
1228 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001229
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001230 if (FromPointeeType->isRecordType() &&
1231 ToPointeeType->isRecordType()) {
1232 // We must have a derived-to-base conversion. Check an
1233 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001234 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1235 From->getExprLoc(),
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001236 From->getSourceRange(),
1237 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001238 return true;
1239
1240 // The conversion was successful.
1241 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001242 }
1243 }
Mike Stump1eb44332009-09-09 15:08:12 +00001244 if (const ObjCObjectPointerType *FromPtrType =
John McCall183700f2009-09-21 23:43:11 +00001245 FromType->getAs<ObjCObjectPointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001246 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001247 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001248 // Objective-C++ conversions are always okay.
1249 // FIXME: We should have a different class of conversions for the
1250 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001251 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001252 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001253
Steve Naroff14108da2009-07-10 23:34:53 +00001254 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001255 return false;
1256}
1257
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001258/// IsMemberPointerConversion - Determines whether the conversion of the
1259/// expression From, which has the (possibly adjusted) type FromType, can be
1260/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1261/// If so, returns true and places the converted type (that might differ from
1262/// ToType in its cv-qualifiers at some level) into ConvertedType.
1263bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001264 QualType ToType,
1265 bool InOverloadResolution,
1266 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001267 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001268 if (!ToTypePtr)
1269 return false;
1270
1271 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001272 if (From->isNullPointerConstant(Context,
1273 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1274 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001275 ConvertedType = ToType;
1276 return true;
1277 }
1278
1279 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001280 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001281 if (!FromTypePtr)
1282 return false;
1283
1284 // A pointer to member of B can be converted to a pointer to member of D,
1285 // where D is derived from B (C++ 4.11p2).
1286 QualType FromClass(FromTypePtr->getClass(), 0);
1287 QualType ToClass(ToTypePtr->getClass(), 0);
1288 // FIXME: What happens when these are dependent? Is this function even called?
1289
1290 if (IsDerivedFrom(ToClass, FromClass)) {
1291 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1292 ToClass.getTypePtr());
1293 return true;
1294 }
1295
1296 return false;
1297}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001298
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001299/// CheckMemberPointerConversion - Check the member pointer conversion from the
1300/// expression From to the type ToType. This routine checks for ambiguous or
1301/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1302/// for which IsMemberPointerConversion has already returned true. It returns
1303/// true and produces a diagnostic if there was an error, or returns false
1304/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001305bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001306 CastExpr::CastKind &Kind,
1307 bool IgnoreBaseAccess) {
1308 (void)IgnoreBaseAccess;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001309 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001310 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001311 if (!FromPtrType) {
1312 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001313 assert(From->isNullPointerConstant(Context,
1314 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001315 "Expr must be null pointer constant!");
1316 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001317 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001318 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001319
Ted Kremenek6217b802009-07-29 21:53:49 +00001320 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001321 assert(ToPtrType && "No member pointer cast has a target type "
1322 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001323
Sebastian Redl21593ac2009-01-28 18:33:18 +00001324 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1325 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001326
Sebastian Redl21593ac2009-01-28 18:33:18 +00001327 // FIXME: What about dependent types?
1328 assert(FromClass->isRecordType() && "Pointer into non-class.");
1329 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001330
Douglas Gregora8f32e02009-10-06 17:59:45 +00001331 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1332 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001333 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1334 assert(DerivationOkay &&
1335 "Should not have been called if derivation isn't OK.");
1336 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001337
Sebastian Redl21593ac2009-01-28 18:33:18 +00001338 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1339 getUnqualifiedType())) {
1340 // Derivation is ambiguous. Redo the check to find the exact paths.
1341 Paths.clear();
1342 Paths.setRecordingPaths(true);
1343 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1344 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1345 (void)StillOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001346
Sebastian Redl21593ac2009-01-28 18:33:18 +00001347 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1348 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1349 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1350 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001351 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001352
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001353 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001354 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1355 << FromClass << ToClass << QualType(VBase, 0)
1356 << From->getSourceRange();
1357 return true;
1358 }
1359
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001360 // Must be a base to derived member conversion.
1361 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001362 return false;
1363}
1364
Douglas Gregor98cd5992008-10-21 23:43:52 +00001365/// IsQualificationConversion - Determines whether the conversion from
1366/// an rvalue of type FromType to ToType is a qualification conversion
1367/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001368bool
1369Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001370 FromType = Context.getCanonicalType(FromType);
1371 ToType = Context.getCanonicalType(ToType);
1372
1373 // If FromType and ToType are the same type, this is not a
1374 // qualification conversion.
1375 if (FromType == ToType)
1376 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001377
Douglas Gregor98cd5992008-10-21 23:43:52 +00001378 // (C++ 4.4p4):
1379 // A conversion can add cv-qualifiers at levels other than the first
1380 // in multi-level pointers, subject to the following rules: [...]
1381 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001382 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001383 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001384 // Within each iteration of the loop, we check the qualifiers to
1385 // determine if this still looks like a qualification
1386 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001387 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001388 // until there are no more pointers or pointers-to-members left to
1389 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001390 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001391
1392 // -- for every j > 0, if const is in cv 1,j then const is in cv
1393 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001394 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001395 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001396
Douglas Gregor98cd5992008-10-21 23:43:52 +00001397 // -- if the cv 1,j and cv 2,j are different, then const is in
1398 // every cv for 0 < k < j.
1399 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001400 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001401 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001402
Douglas Gregor98cd5992008-10-21 23:43:52 +00001403 // Keep track of whether all prior cv-qualifiers in the "to" type
1404 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001405 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001406 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001407 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001408
1409 // We are left with FromType and ToType being the pointee types
1410 // after unwrapping the original FromType and ToType the same number
1411 // of types. If we unwrapped any pointers, and if FromType and
1412 // ToType have the same unqualified type (since we checked
1413 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001414 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00001415}
1416
Douglas Gregor734d9862009-01-30 23:27:23 +00001417/// Determines whether there is a user-defined conversion sequence
1418/// (C++ [over.ics.user]) that converts expression From to the type
1419/// ToType. If such a conversion exists, User will contain the
1420/// user-defined conversion sequence that performs such a conversion
1421/// and this routine will return true. Otherwise, this routine returns
1422/// false and User is unspecified.
1423///
1424/// \param AllowConversionFunctions true if the conversion should
1425/// consider conversion functions at all. If false, only constructors
1426/// will be considered.
1427///
1428/// \param AllowExplicit true if the conversion should consider C++0x
1429/// "explicit" conversion functions as well as non-explicit conversion
1430/// functions (C++0x [class.conv.fct]p2).
Sebastian Redle2b68332009-04-12 17:16:29 +00001431///
1432/// \param ForceRValue true if the expression should be treated as an rvalue
1433/// for overload resolution.
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001434/// \param UserCast true if looking for user defined conversion for a static
1435/// cast.
Douglas Gregor20093b42009-12-09 23:02:17 +00001436OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1437 UserDefinedConversionSequence& User,
1438 OverloadCandidateSet& CandidateSet,
1439 bool AllowConversionFunctions,
1440 bool AllowExplicit,
1441 bool ForceRValue,
1442 bool UserCast) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001443 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00001444 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1445 // We're not going to find any constructors.
1446 } else if (CXXRecordDecl *ToRecordDecl
1447 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001448 // C++ [over.match.ctor]p1:
1449 // When objects of class type are direct-initialized (8.5), or
1450 // copy-initialized from an expression of the same or a
1451 // derived class type (8.5), overload resolution selects the
1452 // constructor. [...] For copy-initialization, the candidate
1453 // functions are all the converting constructors (12.3.1) of
1454 // that class. The argument list is the expression-list within
1455 // the parentheses of the initializer.
Douglas Gregor79b680e2009-11-13 18:44:21 +00001456 bool SuppressUserConversions = !UserCast;
1457 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1458 IsDerivedFrom(From->getType(), ToType)) {
1459 SuppressUserConversions = false;
1460 AllowConversionFunctions = false;
1461 }
1462
Mike Stump1eb44332009-09-09 15:08:12 +00001463 DeclarationName ConstructorName
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001464 = Context.DeclarationNames.getCXXConstructorName(
1465 Context.getCanonicalType(ToType).getUnqualifiedType());
1466 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump1eb44332009-09-09 15:08:12 +00001467 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001468 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001469 Con != ConEnd; ++Con) {
Douglas Gregordec06662009-08-21 18:42:58 +00001470 // Find the constructor (which may be a template).
1471 CXXConstructorDecl *Constructor = 0;
1472 FunctionTemplateDecl *ConstructorTmpl
1473 = dyn_cast<FunctionTemplateDecl>(*Con);
1474 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001475 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00001476 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1477 else
1478 Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001479
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00001480 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00001481 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001482 if (ConstructorTmpl)
John McCalld5532b62009-11-23 01:53:49 +00001483 AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
1484 &From, 1, CandidateSet,
Douglas Gregor79b680e2009-11-13 18:44:21 +00001485 SuppressUserConversions, ForceRValue);
Douglas Gregordec06662009-08-21 18:42:58 +00001486 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001487 // Allow one user-defined conversion when user specifies a
1488 // From->ToType conversion via an static cast (c-style, etc).
Douglas Gregordec06662009-08-21 18:42:58 +00001489 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Douglas Gregor79b680e2009-11-13 18:44:21 +00001490 SuppressUserConversions, ForceRValue);
Douglas Gregordec06662009-08-21 18:42:58 +00001491 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001492 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001493 }
1494 }
1495
Douglas Gregor734d9862009-01-30 23:27:23 +00001496 if (!AllowConversionFunctions) {
1497 // Don't allow any conversion functions to enter the overload set.
Mike Stump1eb44332009-09-09 15:08:12 +00001498 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1499 PDiag(0)
Anders Carlssonb7906612009-08-26 23:45:07 +00001500 << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00001501 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00001502 } else if (const RecordType *FromRecordType
Ted Kremenek6217b802009-07-29 21:53:49 +00001503 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001504 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001505 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1506 // Add all of the conversion functions as candidates.
John McCallba135432009-11-21 08:51:07 +00001507 const UnresolvedSet *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00001508 = FromRecordDecl->getVisibleConversionFunctions();
John McCallba135432009-11-21 08:51:07 +00001509 for (UnresolvedSet::iterator I = Conversions->begin(),
1510 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00001511 NamedDecl *D = *I;
1512 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1513 if (isa<UsingShadowDecl>(D))
1514 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1515
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001516 CXXConversionDecl *Conv;
1517 FunctionTemplateDecl *ConvTemplate;
John McCallba135432009-11-21 08:51:07 +00001518 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001519 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1520 else
John McCallba135432009-11-21 08:51:07 +00001521 Conv = dyn_cast<CXXConversionDecl>(*I);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001522
1523 if (AllowExplicit || !Conv->isExplicit()) {
1524 if (ConvTemplate)
John McCall701c89e2009-12-03 04:06:58 +00001525 AddTemplateConversionCandidate(ConvTemplate, ActingContext,
1526 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001527 else
John McCall701c89e2009-12-03 04:06:58 +00001528 AddConversionCandidate(Conv, ActingContext, From, ToType,
1529 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001530 }
1531 }
1532 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001533 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001534
1535 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001536 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001537 case OR_Success:
1538 // Record the standard conversion we used and the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00001539 if (CXXConstructorDecl *Constructor
Douglas Gregor60d62c22008-10-31 16:23:19 +00001540 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1541 // C++ [over.ics.user]p1:
1542 // If the user-defined conversion is specified by a
1543 // constructor (12.3.1), the initial standard conversion
1544 // sequence converts the source type to the type required by
1545 // the argument of the constructor.
1546 //
Douglas Gregor60d62c22008-10-31 16:23:19 +00001547 QualType ThisType = Constructor->getThisType(Context);
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001548 if (Best->Conversions[0].ConversionKind ==
1549 ImplicitConversionSequence::EllipsisConversion)
1550 User.EllipsisConversion = true;
1551 else {
1552 User.Before = Best->Conversions[0].Standard;
1553 User.EllipsisConversion = false;
1554 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001555 User.ConversionFunction = Constructor;
1556 User.After.setAsIdentityConversion();
Mike Stump1eb44332009-09-09 15:08:12 +00001557 User.After.FromTypePtr
Ted Kremenek6217b802009-07-29 21:53:49 +00001558 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor60d62c22008-10-31 16:23:19 +00001559 User.After.ToTypePtr = ToType.getAsOpaquePtr();
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001560 return OR_Success;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001561 } else if (CXXConversionDecl *Conversion
1562 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1563 // C++ [over.ics.user]p1:
1564 //
1565 // [...] If the user-defined conversion is specified by a
1566 // conversion function (12.3.2), the initial standard
1567 // conversion sequence converts the source type to the
1568 // implicit object parameter of the conversion function.
1569 User.Before = Best->Conversions[0].Standard;
1570 User.ConversionFunction = Conversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001571 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001572
1573 // C++ [over.ics.user]p2:
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001574 // The second standard conversion sequence converts the
1575 // result of the user-defined conversion to the target type
1576 // for the sequence. Since an implicit conversion sequence
1577 // is an initialization, the special rules for
1578 // initialization by user-defined conversion apply when
1579 // selecting the best user-defined conversion for a
1580 // user-defined conversion sequence (see 13.3.3 and
1581 // 13.3.3.1).
1582 User.After = Best->FinalConversion;
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001583 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001584 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001585 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001586 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001587 }
Mike Stump1eb44332009-09-09 15:08:12 +00001588
Douglas Gregor60d62c22008-10-31 16:23:19 +00001589 case OR_No_Viable_Function:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001590 return OR_No_Viable_Function;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001591 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001592 // No conversion here! We're done.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001593 return OR_Deleted;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001594
1595 case OR_Ambiguous:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001596 return OR_Ambiguous;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001597 }
1598
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001599 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001600}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001601
1602bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001603Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001604 ImplicitConversionSequence ICS;
1605 OverloadCandidateSet CandidateSet;
1606 OverloadingResult OvResult =
1607 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1608 CandidateSet, true, false, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001609 if (OvResult == OR_Ambiguous)
1610 Diag(From->getSourceRange().getBegin(),
1611 diag::err_typecheck_ambiguous_condition)
1612 << From->getType() << ToType << From->getSourceRange();
1613 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1614 Diag(From->getSourceRange().getBegin(),
1615 diag::err_typecheck_nonviable_condition)
1616 << From->getType() << ToType << From->getSourceRange();
1617 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001618 return false;
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001619 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001620 return true;
1621}
Douglas Gregor60d62c22008-10-31 16:23:19 +00001622
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001623/// CompareImplicitConversionSequences - Compare two implicit
1624/// conversion sequences to determine whether one is better than the
1625/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump1eb44332009-09-09 15:08:12 +00001626ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001627Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1628 const ImplicitConversionSequence& ICS2)
1629{
1630 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1631 // conversion sequences (as defined in 13.3.3.1)
1632 // -- a standard conversion sequence (13.3.3.1.1) is a better
1633 // conversion sequence than a user-defined conversion sequence or
1634 // an ellipsis conversion sequence, and
1635 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1636 // conversion sequence than an ellipsis conversion sequence
1637 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00001638 //
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001639 if (ICS1.ConversionKind < ICS2.ConversionKind)
1640 return ImplicitConversionSequence::Better;
1641 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1642 return ImplicitConversionSequence::Worse;
1643
1644 // Two implicit conversion sequences of the same form are
1645 // indistinguishable conversion sequences unless one of the
1646 // following rules apply: (C++ 13.3.3.2p3):
1647 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1648 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump1eb44332009-09-09 15:08:12 +00001649 else if (ICS1.ConversionKind ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001650 ImplicitConversionSequence::UserDefinedConversion) {
1651 // User-defined conversion sequence U1 is a better conversion
1652 // sequence than another user-defined conversion sequence U2 if
1653 // they contain the same user-defined conversion function or
1654 // constructor and if the second standard conversion sequence of
1655 // U1 is better than the second standard conversion sequence of
1656 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001657 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001658 ICS2.UserDefined.ConversionFunction)
1659 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1660 ICS2.UserDefined.After);
1661 }
1662
1663 return ImplicitConversionSequence::Indistinguishable;
1664}
1665
1666/// CompareStandardConversionSequences - Compare two standard
1667/// conversion sequences to determine whether one is better than the
1668/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00001669ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001670Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1671 const StandardConversionSequence& SCS2)
1672{
1673 // Standard conversion sequence S1 is a better conversion sequence
1674 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1675
1676 // -- S1 is a proper subsequence of S2 (comparing the conversion
1677 // sequences in the canonical form defined by 13.3.3.1.1,
1678 // excluding any Lvalue Transformation; the identity conversion
1679 // sequence is considered to be a subsequence of any
1680 // non-identity conversion sequence) or, if not that,
1681 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1682 // Neither is a proper subsequence of the other. Do nothing.
1683 ;
1684 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1685 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001686 (SCS1.Second == ICK_Identity &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001687 SCS1.Third == ICK_Identity))
1688 // SCS1 is a proper subsequence of SCS2.
1689 return ImplicitConversionSequence::Better;
1690 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1691 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001692 (SCS2.Second == ICK_Identity &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001693 SCS2.Third == ICK_Identity))
1694 // SCS2 is a proper subsequence of SCS1.
1695 return ImplicitConversionSequence::Worse;
1696
1697 // -- the rank of S1 is better than the rank of S2 (by the rules
1698 // defined below), or, if not that,
1699 ImplicitConversionRank Rank1 = SCS1.getRank();
1700 ImplicitConversionRank Rank2 = SCS2.getRank();
1701 if (Rank1 < Rank2)
1702 return ImplicitConversionSequence::Better;
1703 else if (Rank2 < Rank1)
1704 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001705
Douglas Gregor57373262008-10-22 14:17:15 +00001706 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1707 // are indistinguishable unless one of the following rules
1708 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00001709
Douglas Gregor57373262008-10-22 14:17:15 +00001710 // A conversion that is not a conversion of a pointer, or
1711 // pointer to member, to bool is better than another conversion
1712 // that is such a conversion.
1713 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1714 return SCS2.isPointerConversionToBool()
1715 ? ImplicitConversionSequence::Better
1716 : ImplicitConversionSequence::Worse;
1717
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001718 // C++ [over.ics.rank]p4b2:
1719 //
1720 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001721 // conversion of B* to A* is better than conversion of B* to
1722 // void*, and conversion of A* to void* is better than conversion
1723 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00001724 bool SCS1ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001725 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001726 bool SCS2ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001727 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001728 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1729 // Exactly one of the conversion sequences is a conversion to
1730 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001731 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1732 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001733 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1734 // Neither conversion sequence converts to a void pointer; compare
1735 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001736 if (ImplicitConversionSequence::CompareKind DerivedCK
1737 = CompareDerivedToBaseConversions(SCS1, SCS2))
1738 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001739 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1740 // Both conversion sequences are conversions to void
1741 // pointers. Compare the source types to determine if there's an
1742 // inheritance relationship in their sources.
1743 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1744 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1745
1746 // Adjust the types we're converting from via the array-to-pointer
1747 // conversion, if we need to.
1748 if (SCS1.First == ICK_Array_To_Pointer)
1749 FromType1 = Context.getArrayDecayedType(FromType1);
1750 if (SCS2.First == ICK_Array_To_Pointer)
1751 FromType2 = Context.getArrayDecayedType(FromType2);
1752
Douglas Gregor01919692009-12-13 21:37:05 +00001753 QualType FromPointee1
1754 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1755 QualType FromPointee2
1756 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001757
Douglas Gregor01919692009-12-13 21:37:05 +00001758 if (IsDerivedFrom(FromPointee2, FromPointee1))
1759 return ImplicitConversionSequence::Better;
1760 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1761 return ImplicitConversionSequence::Worse;
1762
1763 // Objective-C++: If one interface is more specific than the
1764 // other, it is the better one.
1765 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1766 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1767 if (FromIface1 && FromIface1) {
1768 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1769 return ImplicitConversionSequence::Better;
1770 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1771 return ImplicitConversionSequence::Worse;
1772 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001773 }
Douglas Gregor57373262008-10-22 14:17:15 +00001774
1775 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1776 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00001777 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00001778 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001779 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00001780
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001781 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001782 // C++0x [over.ics.rank]p3b4:
1783 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1784 // implicit object parameter of a non-static member function declared
1785 // without a ref-qualifier, and S1 binds an rvalue reference to an
1786 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00001787 // FIXME: We don't know if we're dealing with the implicit object parameter,
1788 // or if the member function in this case has a ref qualifier.
1789 // (Of course, we don't have ref qualifiers yet.)
1790 if (SCS1.RRefBinding != SCS2.RRefBinding)
1791 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1792 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00001793
1794 // C++ [over.ics.rank]p3b4:
1795 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1796 // which the references refer are the same type except for
1797 // top-level cv-qualifiers, and the type to which the reference
1798 // initialized by S2 refers is more cv-qualified than the type
1799 // to which the reference initialized by S1 refers.
Sebastian Redla9845802009-03-29 15:27:50 +00001800 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1801 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001802 T1 = Context.getCanonicalType(T1);
1803 T2 = Context.getCanonicalType(T2);
Douglas Gregora4923eb2009-11-16 21:35:15 +00001804 if (Context.hasSameUnqualifiedType(T1, T2)) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001805 if (T2.isMoreQualifiedThan(T1))
1806 return ImplicitConversionSequence::Better;
1807 else if (T1.isMoreQualifiedThan(T2))
1808 return ImplicitConversionSequence::Worse;
1809 }
1810 }
Douglas Gregor57373262008-10-22 14:17:15 +00001811
1812 return ImplicitConversionSequence::Indistinguishable;
1813}
1814
1815/// CompareQualificationConversions - Compares two standard conversion
1816/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00001817/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1818ImplicitConversionSequence::CompareKind
Douglas Gregor57373262008-10-22 14:17:15 +00001819Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump1eb44332009-09-09 15:08:12 +00001820 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00001821 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00001822 // -- S1 and S2 differ only in their qualification conversion and
1823 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1824 // cv-qualification signature of type T1 is a proper subset of
1825 // the cv-qualification signature of type T2, and S1 is not the
1826 // deprecated string literal array-to-pointer conversion (4.2).
1827 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1828 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1829 return ImplicitConversionSequence::Indistinguishable;
1830
1831 // FIXME: the example in the standard doesn't use a qualification
1832 // conversion (!)
1833 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1834 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1835 T1 = Context.getCanonicalType(T1);
1836 T2 = Context.getCanonicalType(T2);
1837
1838 // If the types are the same, we won't learn anything by unwrapped
1839 // them.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001840 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00001841 return ImplicitConversionSequence::Indistinguishable;
1842
Mike Stump1eb44332009-09-09 15:08:12 +00001843 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00001844 = ImplicitConversionSequence::Indistinguishable;
1845 while (UnwrapSimilarPointerTypes(T1, T2)) {
1846 // Within each iteration of the loop, we check the qualifiers to
1847 // determine if this still looks like a qualification
1848 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001849 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00001850 // until there are no more pointers or pointers-to-members left
1851 // to unwrap. This essentially mimics what
1852 // IsQualificationConversion does, but here we're checking for a
1853 // strict subset of qualifiers.
1854 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1855 // The qualifiers are the same, so this doesn't tell us anything
1856 // about how the sequences rank.
1857 ;
1858 else if (T2.isMoreQualifiedThan(T1)) {
1859 // T1 has fewer qualifiers, so it could be the better sequence.
1860 if (Result == ImplicitConversionSequence::Worse)
1861 // Neither has qualifiers that are a subset of the other's
1862 // qualifiers.
1863 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001864
Douglas Gregor57373262008-10-22 14:17:15 +00001865 Result = ImplicitConversionSequence::Better;
1866 } else if (T1.isMoreQualifiedThan(T2)) {
1867 // T2 has fewer qualifiers, so it could be the better sequence.
1868 if (Result == ImplicitConversionSequence::Better)
1869 // Neither has qualifiers that are a subset of the other's
1870 // qualifiers.
1871 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00001872
Douglas Gregor57373262008-10-22 14:17:15 +00001873 Result = ImplicitConversionSequence::Worse;
1874 } else {
1875 // Qualifiers are disjoint.
1876 return ImplicitConversionSequence::Indistinguishable;
1877 }
1878
1879 // If the types after this point are equivalent, we're done.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001880 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00001881 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001882 }
1883
Douglas Gregor57373262008-10-22 14:17:15 +00001884 // Check that the winning standard conversion sequence isn't using
1885 // the deprecated string literal array to pointer conversion.
1886 switch (Result) {
1887 case ImplicitConversionSequence::Better:
1888 if (SCS1.Deprecated)
1889 Result = ImplicitConversionSequence::Indistinguishable;
1890 break;
1891
1892 case ImplicitConversionSequence::Indistinguishable:
1893 break;
1894
1895 case ImplicitConversionSequence::Worse:
1896 if (SCS2.Deprecated)
1897 Result = ImplicitConversionSequence::Indistinguishable;
1898 break;
1899 }
1900
1901 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001902}
1903
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001904/// CompareDerivedToBaseConversions - Compares two standard conversion
1905/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00001906/// various kinds of derived-to-base conversions (C++
1907/// [over.ics.rank]p4b3). As part of these checks, we also look at
1908/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001909ImplicitConversionSequence::CompareKind
1910Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1911 const StandardConversionSequence& SCS2) {
1912 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1913 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1914 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1915 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1916
1917 // Adjust the types we're converting from via the array-to-pointer
1918 // conversion, if we need to.
1919 if (SCS1.First == ICK_Array_To_Pointer)
1920 FromType1 = Context.getArrayDecayedType(FromType1);
1921 if (SCS2.First == ICK_Array_To_Pointer)
1922 FromType2 = Context.getArrayDecayedType(FromType2);
1923
1924 // Canonicalize all of the types.
1925 FromType1 = Context.getCanonicalType(FromType1);
1926 ToType1 = Context.getCanonicalType(ToType1);
1927 FromType2 = Context.getCanonicalType(FromType2);
1928 ToType2 = Context.getCanonicalType(ToType2);
1929
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001930 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001931 //
1932 // If class B is derived directly or indirectly from class A and
1933 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001934 //
1935 // For Objective-C, we let A, B, and C also be Objective-C
1936 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001937
1938 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00001939 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00001940 SCS2.Second == ICK_Pointer_Conversion &&
1941 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1942 FromType1->isPointerType() && FromType2->isPointerType() &&
1943 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001944 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00001945 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00001946 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00001947 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001948 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00001949 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001950 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00001951 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001952
John McCall183700f2009-09-21 23:43:11 +00001953 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1954 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1955 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1956 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001957
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001958 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001959 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1960 if (IsDerivedFrom(ToPointee1, ToPointee2))
1961 return ImplicitConversionSequence::Better;
1962 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1963 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00001964
1965 if (ToIface1 && ToIface2) {
1966 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1967 return ImplicitConversionSequence::Better;
1968 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1969 return ImplicitConversionSequence::Worse;
1970 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001971 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001972
1973 // -- conversion of B* to A* is better than conversion of C* to A*,
1974 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1975 if (IsDerivedFrom(FromPointee2, FromPointee1))
1976 return ImplicitConversionSequence::Better;
1977 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1978 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00001979
Douglas Gregorcb7de522008-11-26 23:31:11 +00001980 if (FromIface1 && FromIface2) {
1981 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1982 return ImplicitConversionSequence::Better;
1983 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1984 return ImplicitConversionSequence::Worse;
1985 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001986 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001987 }
1988
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001989 // Compare based on reference bindings.
1990 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1991 SCS1.Second == ICK_Derived_To_Base) {
1992 // -- binding of an expression of type C to a reference of type
1993 // B& is better than binding an expression of type C to a
1994 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00001995 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1996 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001997 if (IsDerivedFrom(ToType1, ToType2))
1998 return ImplicitConversionSequence::Better;
1999 else if (IsDerivedFrom(ToType2, ToType1))
2000 return ImplicitConversionSequence::Worse;
2001 }
2002
Douglas Gregor225c41e2008-11-03 19:09:14 +00002003 // -- binding of an expression of type B to a reference of type
2004 // A& is better than binding an expression of type C to a
2005 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002006 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2007 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002008 if (IsDerivedFrom(FromType2, FromType1))
2009 return ImplicitConversionSequence::Better;
2010 else if (IsDerivedFrom(FromType1, FromType2))
2011 return ImplicitConversionSequence::Worse;
2012 }
2013 }
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002014
2015 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002016 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2017 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2018 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2019 const MemberPointerType * FromMemPointer1 =
2020 FromType1->getAs<MemberPointerType>();
2021 const MemberPointerType * ToMemPointer1 =
2022 ToType1->getAs<MemberPointerType>();
2023 const MemberPointerType * FromMemPointer2 =
2024 FromType2->getAs<MemberPointerType>();
2025 const MemberPointerType * ToMemPointer2 =
2026 ToType2->getAs<MemberPointerType>();
2027 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2028 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2029 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2030 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2031 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2032 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2033 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2034 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002035 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002036 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2037 if (IsDerivedFrom(ToPointee1, ToPointee2))
2038 return ImplicitConversionSequence::Worse;
2039 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2040 return ImplicitConversionSequence::Better;
2041 }
2042 // conversion of B::* to C::* is better than conversion of A::* to C::*
2043 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2044 if (IsDerivedFrom(FromPointee1, FromPointee2))
2045 return ImplicitConversionSequence::Better;
2046 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2047 return ImplicitConversionSequence::Worse;
2048 }
2049 }
2050
Douglas Gregor225c41e2008-11-03 19:09:14 +00002051 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
2052 SCS1.Second == ICK_Derived_To_Base) {
2053 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002054 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2055 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002056 if (IsDerivedFrom(ToType1, ToType2))
2057 return ImplicitConversionSequence::Better;
2058 else if (IsDerivedFrom(ToType2, ToType1))
2059 return ImplicitConversionSequence::Worse;
2060 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002061
Douglas Gregor225c41e2008-11-03 19:09:14 +00002062 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002063 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2064 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002065 if (IsDerivedFrom(FromType2, FromType1))
2066 return ImplicitConversionSequence::Better;
2067 else if (IsDerivedFrom(FromType1, FromType2))
2068 return ImplicitConversionSequence::Worse;
2069 }
2070 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002071
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002072 return ImplicitConversionSequence::Indistinguishable;
2073}
2074
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002075/// TryCopyInitialization - Try to copy-initialize a value of type
2076/// ToType from the expression From. Return the implicit conversion
2077/// sequence required to pass this argument, which may be a bad
2078/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00002079/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redle2b68332009-04-12 17:16:29 +00002080/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2081/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump1eb44332009-09-09 15:08:12 +00002082ImplicitConversionSequence
2083Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002084 bool SuppressUserConversions, bool ForceRValue,
2085 bool InOverloadResolution) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00002086 if (ToType->isReferenceType()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002087 ImplicitConversionSequence ICS;
Mike Stump1eb44332009-09-09 15:08:12 +00002088 CheckReferenceInit(From, ToType,
Douglas Gregor739d8282009-09-23 23:04:10 +00002089 /*FIXME:*/From->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002090 SuppressUserConversions,
2091 /*AllowExplicit=*/false,
2092 ForceRValue,
2093 &ICS);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002094 return ICS;
2095 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002096 return TryImplicitConversion(From, ToType,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002097 SuppressUserConversions,
2098 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00002099 ForceRValue,
2100 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002101 }
2102}
2103
Sebastian Redle2b68332009-04-12 17:16:29 +00002104/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2105/// the expression @p From. Returns true (and emits a diagnostic) if there was
2106/// an error, returns false if the initialization succeeded. Elidable should
2107/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2108/// differently in C++0x for this case.
Mike Stump1eb44332009-09-09 15:08:12 +00002109bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00002110 AssignmentAction Action, bool Elidable) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002111 if (!getLangOptions().CPlusPlus) {
2112 // In C, argument passing is the same as performing an assignment.
2113 QualType FromType = From->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002114
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002115 AssignConvertType ConvTy =
2116 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00002117 if (ConvTy != Compatible &&
2118 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2119 ConvTy = Compatible;
Mike Stump1eb44332009-09-09 15:08:12 +00002120
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002121 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
Douglas Gregor68647482009-12-16 03:45:30 +00002122 FromType, From, Action);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002123 }
Sebastian Redle2b68332009-04-12 17:16:29 +00002124
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002125 if (ToType->isReferenceType())
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002126 return CheckReferenceInit(From, ToType,
Douglas Gregor739d8282009-09-23 23:04:10 +00002127 /*FIXME:*/From->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002128 /*SuppressUserConversions=*/false,
2129 /*AllowExplicit=*/false,
2130 /*ForceRValue=*/false);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002131
Douglas Gregor68647482009-12-16 03:45:30 +00002132 if (!PerformImplicitConversion(From, ToType, Action,
Sebastian Redle2b68332009-04-12 17:16:29 +00002133 /*AllowExplicit=*/false, Elidable))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002134 return false;
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002135 if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
Fariborz Jahanian455acd92009-09-22 19:53:15 +00002136 return Diag(From->getSourceRange().getBegin(),
2137 diag::err_typecheck_convert_incompatible)
Douglas Gregor68647482009-12-16 03:45:30 +00002138 << ToType << From->getType() << Action << From->getSourceRange();
Fariborz Jahanian455acd92009-09-22 19:53:15 +00002139 return true;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002140}
2141
Douglas Gregor96176b32008-11-18 23:14:02 +00002142/// TryObjectArgumentInitialization - Try to initialize the object
2143/// parameter of the given member function (@c Method) from the
2144/// expression @p From.
2145ImplicitConversionSequence
John McCall701c89e2009-12-03 04:06:58 +00002146Sema::TryObjectArgumentInitialization(QualType FromType,
2147 CXXMethodDecl *Method,
2148 CXXRecordDecl *ActingContext) {
2149 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002150 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2151 // const volatile object.
2152 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2153 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2154 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00002155
2156 // Set up the conversion sequence as a "bad" conversion, to allow us
2157 // to exit early.
2158 ImplicitConversionSequence ICS;
2159 ICS.Standard.setAsIdentityConversion();
2160 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2161
2162 // We need to have an object of class type.
Ted Kremenek6217b802009-07-29 21:53:49 +00002163 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00002164 FromType = PT->getPointeeType();
2165
2166 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002167
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002168 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00002169 // where X is the class of which the function is a member
2170 // (C++ [over.match.funcs]p4). However, when finding an implicit
2171 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00002172 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00002173 // (C++ [over.match.funcs]p5). We perform a simplified version of
2174 // reference binding here, that allows class rvalues to bind to
2175 // non-constant references.
2176
2177 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2178 // with the implicit object parameter (C++ [over.match.funcs]p5).
2179 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00002180 if (ImplicitParamType.getCVRQualifiers()
2181 != FromTypeCanon.getLocalCVRQualifiers() &&
Douglas Gregorb1c2ea52009-11-05 00:07:36 +00002182 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon))
Douglas Gregor96176b32008-11-18 23:14:02 +00002183 return ICS;
2184
2185 // Check that we have either the same type or a derived type. It
2186 // affects the conversion rank.
2187 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00002188 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType())
Douglas Gregor96176b32008-11-18 23:14:02 +00002189 ICS.Standard.Second = ICK_Identity;
2190 else if (IsDerivedFrom(FromType, ClassType))
2191 ICS.Standard.Second = ICK_Derived_To_Base;
2192 else
2193 return ICS;
2194
2195 // Success. Mark this as a reference binding.
2196 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2197 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2198 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2199 ICS.Standard.ReferenceBinding = true;
2200 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00002201 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002202 return ICS;
2203}
2204
2205/// PerformObjectArgumentInitialization - Perform initialization of
2206/// the implicit object parameter for the given Method with the given
2207/// expression.
2208bool
2209Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002210 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00002211 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00002212 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002213
Ted Kremenek6217b802009-07-29 21:53:49 +00002214 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002215 FromRecordType = PT->getPointeeType();
2216 DestType = Method->getThisType(Context);
2217 } else {
2218 FromRecordType = From->getType();
2219 DestType = ImplicitParamRecordType;
2220 }
2221
John McCall701c89e2009-12-03 04:06:58 +00002222 // Note that we always use the true parent context when performing
2223 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002224 ImplicitConversionSequence ICS
John McCall701c89e2009-12-03 04:06:58 +00002225 = TryObjectArgumentInitialization(From->getType(), Method,
2226 Method->getParent());
Douglas Gregor96176b32008-11-18 23:14:02 +00002227 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2228 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002229 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00002230 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002231
Douglas Gregor96176b32008-11-18 23:14:02 +00002232 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssona552f7c2009-05-01 18:34:30 +00002233 CheckDerivedToBaseConversion(FromRecordType,
2234 ImplicitParamRecordType,
Douglas Gregor96176b32008-11-18 23:14:02 +00002235 From->getSourceRange().getBegin(),
2236 From->getSourceRange()))
2237 return true;
2238
Mike Stump1eb44332009-09-09 15:08:12 +00002239 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson116b7d92009-08-07 18:45:49 +00002240 /*isLvalue=*/true);
Douglas Gregor96176b32008-11-18 23:14:02 +00002241 return false;
2242}
2243
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002244/// TryContextuallyConvertToBool - Attempt to contextually convert the
2245/// expression From to bool (C++0x [conv]p3).
2246ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump1eb44332009-09-09 15:08:12 +00002247 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002248 // FIXME: Are these flags correct?
2249 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00002250 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00002251 /*ForceRValue=*/false,
2252 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002253}
2254
2255/// PerformContextuallyConvertToBool - Perform a contextual conversion
2256/// of the expression From to bool (C++0x [conv]p3).
2257bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2258 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
Douglas Gregor68647482009-12-16 03:45:30 +00002259 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting))
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002260 return false;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002261
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002262 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002263 return Diag(From->getSourceRange().getBegin(),
2264 diag::err_typecheck_bool_condition)
2265 << From->getType() << From->getSourceRange();
2266 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002267}
2268
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002269/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00002270/// candidate functions, using the given function call arguments. If
2271/// @p SuppressUserConversions, then don't allow user-defined
2272/// conversions via constructors or conversion operators.
Sebastian Redle2b68332009-04-12 17:16:29 +00002273/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2274/// hacky way to implement the overloading rules for elidable copy
2275/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002276///
2277/// \para PartialOverloading true if we are performing "partial" overloading
2278/// based on an incomplete set of function arguments. This feature is used by
2279/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00002280void
2281Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002282 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002283 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00002284 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002285 bool ForceRValue,
2286 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00002287 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002288 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002289 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00002290 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002291 "Use AddConversionCandidate for conversion functions");
Mike Stump1eb44332009-09-09 15:08:12 +00002292 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00002293 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00002294
Douglas Gregor88a35142008-12-22 05:46:06 +00002295 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002296 if (!isa<CXXConstructorDecl>(Method)) {
2297 // If we get here, it's because we're calling a member function
2298 // that is named without a member access expression (e.g.,
2299 // "this->f") that was either written explicitly or created
2300 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00002301 // function, e.g., X::f(). We use an empty type for the implied
2302 // object argument (C++ [over.call.func]p3), and the acting context
2303 // is irrelevant.
2304 AddMethodCandidate(Method, Method->getParent(),
2305 QualType(), Args, NumArgs, CandidateSet,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002306 SuppressUserConversions, ForceRValue);
2307 return;
2308 }
2309 // We treat a constructor like a non-member function, since its object
2310 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00002311 }
2312
Douglas Gregorfd476482009-11-13 23:59:09 +00002313 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00002314 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00002315
Douglas Gregor7edfb692009-11-23 12:27:39 +00002316 // Overload resolution is always an unevaluated context.
2317 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2318
Douglas Gregor66724ea2009-11-14 01:20:54 +00002319 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2320 // C++ [class.copy]p3:
2321 // A member function template is never instantiated to perform the copy
2322 // of a class object to an object of its class type.
2323 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2324 if (NumArgs == 1 &&
2325 Constructor->isCopyConstructorLikeSpecialization() &&
2326 Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2327 return;
2328 }
2329
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002330 // Add this candidate
2331 CandidateSet.push_back(OverloadCandidate());
2332 OverloadCandidate& Candidate = CandidateSet.back();
2333 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00002334 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002335 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002336 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002337
2338 unsigned NumArgsInProto = Proto->getNumArgs();
2339
2340 // (C++ 13.3.2p2): A candidate function having fewer than m
2341 // parameters is viable only if it has an ellipsis in its parameter
2342 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00002343 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2344 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002345 Candidate.Viable = false;
2346 return;
2347 }
2348
2349 // (C++ 13.3.2p2): A candidate function having more than m parameters
2350 // is viable only if the (m+1)st parameter has a default argument
2351 // (8.3.6). For the purposes of overload resolution, the
2352 // parameter list is truncated on the right, so that there are
2353 // exactly m parameters.
2354 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002355 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002356 // Not enough arguments.
2357 Candidate.Viable = false;
2358 return;
2359 }
2360
2361 // Determine the implicit conversion sequences for each of the
2362 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002363 Candidate.Conversions.resize(NumArgs);
2364 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2365 if (ArgIdx < NumArgsInProto) {
2366 // (C++ 13.3.2p3): for F to be a viable function, there shall
2367 // exist for each argument an implicit conversion sequence
2368 // (13.3.3.1) that converts that argument to the corresponding
2369 // parameter of F.
2370 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002371 Candidate.Conversions[ArgIdx]
2372 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002373 SuppressUserConversions, ForceRValue,
2374 /*InOverloadResolution=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00002375 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002376 == ImplicitConversionSequence::BadConversion) {
Fariborz Jahanian99d6c442009-09-28 19:06:58 +00002377 // 13.3.3.1-p10 If several different sequences of conversions exist that
2378 // each convert the argument to the parameter type, the implicit conversion
2379 // sequence associated with the parameter is defined to be the unique conversion
2380 // sequence designated the ambiguous conversion sequence. For the purpose of
2381 // ranking implicit conversion sequences as described in 13.3.3.2, the ambiguous
2382 // conversion sequence is treated as a user-defined sequence that is
2383 // indistinguishable from any other user-defined conversion sequence
Fariborz Jahanian4a6a2b82009-09-29 17:31:54 +00002384 if (!Candidate.Conversions[ArgIdx].ConversionFunctionSet.empty()) {
Fariborz Jahanian99d6c442009-09-28 19:06:58 +00002385 Candidate.Conversions[ArgIdx].ConversionKind =
2386 ImplicitConversionSequence::UserDefinedConversion;
Fariborz Jahanian4a6a2b82009-09-29 17:31:54 +00002387 // Set the conversion function to one of them. As due to ambiguity,
2388 // they carry the same weight and is needed for overload resolution
2389 // later.
2390 Candidate.Conversions[ArgIdx].UserDefined.ConversionFunction =
2391 Candidate.Conversions[ArgIdx].ConversionFunctionSet[0];
2392 }
Fariborz Jahanian99d6c442009-09-28 19:06:58 +00002393 else {
2394 Candidate.Viable = false;
2395 break;
2396 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002397 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002398 } else {
2399 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2400 // argument for which there is no corresponding parameter is
2401 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002402 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002403 = ImplicitConversionSequence::EllipsisConversion;
2404 }
2405 }
2406}
2407
Douglas Gregor063daf62009-03-13 18:40:31 +00002408/// \brief Add all of the function declarations in the given function set to
2409/// the overload canddiate set.
2410void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2411 Expr **Args, unsigned NumArgs,
2412 OverloadCandidateSet& CandidateSet,
2413 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00002414 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor063daf62009-03-13 18:40:31 +00002415 FEnd = Functions.end();
Douglas Gregor364e0212009-06-27 21:05:07 +00002416 F != FEnd; ++F) {
John McCall701c89e2009-12-03 04:06:58 +00002417 // FIXME: using declarations
Douglas Gregor3f396022009-09-28 04:47:19 +00002418 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2419 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2420 AddMethodCandidate(cast<CXXMethodDecl>(FD),
John McCall701c89e2009-12-03 04:06:58 +00002421 cast<CXXMethodDecl>(FD)->getParent(),
2422 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00002423 CandidateSet, SuppressUserConversions);
2424 else
2425 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2426 SuppressUserConversions);
2427 } else {
2428 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2429 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2430 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2431 AddMethodTemplateCandidate(FunTmpl,
John McCall701c89e2009-12-03 04:06:58 +00002432 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00002433 /*FIXME: explicit args */ 0,
John McCall701c89e2009-12-03 04:06:58 +00002434 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00002435 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00002436 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00002437 else
2438 AddTemplateOverloadCandidate(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00002439 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00002440 Args, NumArgs, CandidateSet,
2441 SuppressUserConversions);
2442 }
Douglas Gregor364e0212009-06-27 21:05:07 +00002443 }
Douglas Gregor063daf62009-03-13 18:40:31 +00002444}
2445
John McCall314be4e2009-11-17 07:50:12 +00002446/// AddMethodCandidate - Adds a named decl (which is some kind of
2447/// method) as a method candidate to the given overload set.
John McCall701c89e2009-12-03 04:06:58 +00002448void Sema::AddMethodCandidate(NamedDecl *Decl,
2449 QualType ObjectType,
John McCall314be4e2009-11-17 07:50:12 +00002450 Expr **Args, unsigned NumArgs,
2451 OverloadCandidateSet& CandidateSet,
2452 bool SuppressUserConversions, bool ForceRValue) {
2453
2454 // FIXME: use this
John McCall701c89e2009-12-03 04:06:58 +00002455 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00002456
2457 if (isa<UsingShadowDecl>(Decl))
2458 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2459
2460 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2461 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2462 "Expected a member function template");
John McCall701c89e2009-12-03 04:06:58 +00002463 AddMethodTemplateCandidate(TD, ActingContext, /*ExplicitArgs*/ 0,
2464 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00002465 CandidateSet,
2466 SuppressUserConversions,
2467 ForceRValue);
2468 } else {
John McCall701c89e2009-12-03 04:06:58 +00002469 AddMethodCandidate(cast<CXXMethodDecl>(Decl), ActingContext,
2470 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00002471 CandidateSet, SuppressUserConversions, ForceRValue);
2472 }
2473}
2474
Douglas Gregor96176b32008-11-18 23:14:02 +00002475/// AddMethodCandidate - Adds the given C++ member function to the set
2476/// of candidate functions, using the given function call arguments
2477/// and the object argument (@c Object). For example, in a call
2478/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2479/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2480/// allow user-defined conversions via constructors or conversion
Sebastian Redle2b68332009-04-12 17:16:29 +00002481/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2482/// a slightly hacky way to implement the overloading rules for elidable copy
2483/// initialization in C++0x (C++0x 12.8p15).
Mike Stump1eb44332009-09-09 15:08:12 +00002484void
John McCall701c89e2009-12-03 04:06:58 +00002485Sema::AddMethodCandidate(CXXMethodDecl *Method, CXXRecordDecl *ActingContext,
2486 QualType ObjectType, Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00002487 OverloadCandidateSet& CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00002488 bool SuppressUserConversions, bool ForceRValue) {
2489 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002490 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00002491 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002492 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor96176b32008-11-18 23:14:02 +00002493 "Use AddConversionCandidate for conversion functions");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002494 assert(!isa<CXXConstructorDecl>(Method) &&
2495 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00002496
Douglas Gregor3f396022009-09-28 04:47:19 +00002497 if (!CandidateSet.isNewCandidate(Method))
2498 return;
2499
Douglas Gregor7edfb692009-11-23 12:27:39 +00002500 // Overload resolution is always an unevaluated context.
2501 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2502
Douglas Gregor96176b32008-11-18 23:14:02 +00002503 // Add this candidate
2504 CandidateSet.push_back(OverloadCandidate());
2505 OverloadCandidate& Candidate = CandidateSet.back();
2506 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002507 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002508 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002509
2510 unsigned NumArgsInProto = Proto->getNumArgs();
2511
2512 // (C++ 13.3.2p2): A candidate function having fewer than m
2513 // parameters is viable only if it has an ellipsis in its parameter
2514 // list (8.3.5).
2515 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2516 Candidate.Viable = false;
2517 return;
2518 }
2519
2520 // (C++ 13.3.2p2): A candidate function having more than m parameters
2521 // is viable only if the (m+1)st parameter has a default argument
2522 // (8.3.6). For the purposes of overload resolution, the
2523 // parameter list is truncated on the right, so that there are
2524 // exactly m parameters.
2525 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2526 if (NumArgs < MinRequiredArgs) {
2527 // Not enough arguments.
2528 Candidate.Viable = false;
2529 return;
2530 }
2531
2532 Candidate.Viable = true;
2533 Candidate.Conversions.resize(NumArgs + 1);
2534
John McCall701c89e2009-12-03 04:06:58 +00002535 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00002536 // The implicit object argument is ignored.
2537 Candidate.IgnoreObjectArgument = true;
2538 else {
2539 // Determine the implicit conversion sequence for the object
2540 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00002541 Candidate.Conversions[0]
2542 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
Mike Stump1eb44332009-09-09 15:08:12 +00002543 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor88a35142008-12-22 05:46:06 +00002544 == ImplicitConversionSequence::BadConversion) {
2545 Candidate.Viable = false;
2546 return;
2547 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002548 }
2549
2550 // Determine the implicit conversion sequences for each of the
2551 // arguments.
2552 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2553 if (ArgIdx < NumArgsInProto) {
2554 // (C++ 13.3.2p3): for F to be a viable function, there shall
2555 // exist for each argument an implicit conversion sequence
2556 // (13.3.3.1) that converts that argument to the corresponding
2557 // parameter of F.
2558 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002559 Candidate.Conversions[ArgIdx + 1]
2560 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002561 SuppressUserConversions, ForceRValue,
Anders Carlsson08972922009-08-28 15:33:32 +00002562 /*InOverloadResolution=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00002563 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002564 == ImplicitConversionSequence::BadConversion) {
2565 Candidate.Viable = false;
2566 break;
2567 }
2568 } else {
2569 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2570 // argument for which there is no corresponding parameter is
2571 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002572 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00002573 = ImplicitConversionSequence::EllipsisConversion;
2574 }
2575 }
2576}
2577
Douglas Gregor6b906862009-08-21 00:16:32 +00002578/// \brief Add a C++ member function template as a candidate to the candidate
2579/// set, using template argument deduction to produce an appropriate member
2580/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002581void
Douglas Gregor6b906862009-08-21 00:16:32 +00002582Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall701c89e2009-12-03 04:06:58 +00002583 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00002584 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00002585 QualType ObjectType,
2586 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002587 OverloadCandidateSet& CandidateSet,
2588 bool SuppressUserConversions,
2589 bool ForceRValue) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002590 if (!CandidateSet.isNewCandidate(MethodTmpl))
2591 return;
2592
Douglas Gregor6b906862009-08-21 00:16:32 +00002593 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002594 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00002595 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002596 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00002597 // candidate functions in the usual way.113) A given name can refer to one
2598 // or more function templates and also to a set of overloaded non-template
2599 // functions. In such a case, the candidate functions generated from each
2600 // function template are combined with the set of non-template candidate
2601 // functions.
2602 TemplateDeductionInfo Info(Context);
2603 FunctionDecl *Specialization = 0;
2604 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00002605 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002606 Args, NumArgs, Specialization, Info)) {
2607 // FIXME: Record what happened with template argument deduction, so
2608 // that we can give the user a beautiful diagnostic.
2609 (void)Result;
2610 return;
2611 }
Mike Stump1eb44332009-09-09 15:08:12 +00002612
Douglas Gregor6b906862009-08-21 00:16:32 +00002613 // Add the function template specialization produced by template argument
2614 // deduction as a candidate.
2615 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00002616 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00002617 "Specialization is not a member function?");
John McCall701c89e2009-12-03 04:06:58 +00002618 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), ActingContext,
2619 ObjectType, Args, NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00002620 CandidateSet, SuppressUserConversions, ForceRValue);
2621}
2622
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002623/// \brief Add a C++ function template specialization as a candidate
2624/// in the candidate set, using template argument deduction to produce
2625/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002626void
Douglas Gregore53060f2009-06-25 22:08:12 +00002627Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002628 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002629 Expr **Args, unsigned NumArgs,
2630 OverloadCandidateSet& CandidateSet,
2631 bool SuppressUserConversions,
2632 bool ForceRValue) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002633 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2634 return;
2635
Douglas Gregore53060f2009-06-25 22:08:12 +00002636 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00002637 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00002638 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00002639 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00002640 // candidate functions in the usual way.113) A given name can refer to one
2641 // or more function templates and also to a set of overloaded non-template
2642 // functions. In such a case, the candidate functions generated from each
2643 // function template are combined with the set of non-template candidate
2644 // functions.
2645 TemplateDeductionInfo Info(Context);
2646 FunctionDecl *Specialization = 0;
2647 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00002648 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002649 Args, NumArgs, Specialization, Info)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002650 // FIXME: Record what happened with template argument deduction, so
2651 // that we can give the user a beautiful diagnostic.
John McCall578b69b2009-12-16 08:11:27 +00002652 (void) Result;
2653
2654 CandidateSet.push_back(OverloadCandidate());
2655 OverloadCandidate &Candidate = CandidateSet.back();
2656 Candidate.Function = FunctionTemplate->getTemplatedDecl();
2657 Candidate.Viable = false;
2658 Candidate.IsSurrogate = false;
2659 Candidate.IgnoreObjectArgument = false;
Douglas Gregore53060f2009-06-25 22:08:12 +00002660 return;
2661 }
Mike Stump1eb44332009-09-09 15:08:12 +00002662
Douglas Gregore53060f2009-06-25 22:08:12 +00002663 // Add the function template specialization produced by template argument
2664 // deduction as a candidate.
2665 assert(Specialization && "Missing function template specialization?");
2666 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2667 SuppressUserConversions, ForceRValue);
2668}
Mike Stump1eb44332009-09-09 15:08:12 +00002669
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002670/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00002671/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002672/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00002673/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002674/// (which may or may not be the same type as the type that the
2675/// conversion function produces).
2676void
2677Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall701c89e2009-12-03 04:06:58 +00002678 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002679 Expr *From, QualType ToType,
2680 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002681 assert(!Conversion->getDescribedFunctionTemplate() &&
2682 "Conversion function templates use AddTemplateConversionCandidate");
2683
Douglas Gregor3f396022009-09-28 04:47:19 +00002684 if (!CandidateSet.isNewCandidate(Conversion))
2685 return;
2686
Douglas Gregor7edfb692009-11-23 12:27:39 +00002687 // Overload resolution is always an unevaluated context.
2688 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2689
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002690 // Add this candidate
2691 CandidateSet.push_back(OverloadCandidate());
2692 OverloadCandidate& Candidate = CandidateSet.back();
2693 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002694 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002695 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002696 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump1eb44332009-09-09 15:08:12 +00002697 Candidate.FinalConversion.FromTypePtr
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002698 = Conversion->getConversionType().getAsOpaquePtr();
2699 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2700
Douglas Gregor96176b32008-11-18 23:14:02 +00002701 // Determine the implicit conversion sequence for the implicit
2702 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002703 Candidate.Viable = true;
2704 Candidate.Conversions.resize(1);
John McCall701c89e2009-12-03 04:06:58 +00002705 Candidate.Conversions[0]
2706 = TryObjectArgumentInitialization(From->getType(), Conversion,
2707 ActingContext);
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002708 // Conversion functions to a different type in the base class is visible in
2709 // the derived class. So, a derived to base conversion should not participate
2710 // in overload resolution.
2711 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2712 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump1eb44332009-09-09 15:08:12 +00002713 if (Candidate.Conversions[0].ConversionKind
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002714 == ImplicitConversionSequence::BadConversion) {
2715 Candidate.Viable = false;
2716 return;
2717 }
Fariborz Jahanian3759a032009-10-19 19:18:20 +00002718
2719 // We won't go through a user-define type conversion function to convert a
2720 // derived to base as such conversions are given Conversion Rank. They only
2721 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2722 QualType FromCanon
2723 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2724 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2725 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2726 Candidate.Viable = false;
2727 return;
2728 }
2729
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002730
2731 // To determine what the conversion from the result of calling the
2732 // conversion function to the type we're eventually trying to
2733 // convert to (ToType), we need to synthesize a call to the
2734 // conversion function and attempt copy initialization from it. This
2735 // makes sure that we get the right semantics with respect to
2736 // lvalues/rvalues and the type. Fortunately, we can allocate this
2737 // call on the stack and we don't need its arguments to be
2738 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00002739 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00002740 From->getLocStart());
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002741 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman73c39ab2009-10-20 08:27:19 +00002742 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002743 &ConversionRef, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002744
2745 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00002746 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2747 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00002748 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002749 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00002750 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00002751 ImplicitConversionSequence ICS =
2752 TryCopyInitialization(&Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002753 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002754 /*ForceRValue=*/false,
2755 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002756
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002757 switch (ICS.ConversionKind) {
2758 case ImplicitConversionSequence::StandardConversion:
2759 Candidate.FinalConversion = ICS.Standard;
2760 break;
2761
2762 case ImplicitConversionSequence::BadConversion:
2763 Candidate.Viable = false;
2764 break;
2765
2766 default:
Mike Stump1eb44332009-09-09 15:08:12 +00002767 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002768 "Can only end up with a standard conversion sequence or failure");
2769 }
2770}
2771
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002772/// \brief Adds a conversion function template specialization
2773/// candidate to the overload set, using template argument deduction
2774/// to deduce the template arguments of the conversion function
2775/// template from the type that we are converting to (C++
2776/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00002777void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002778Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall701c89e2009-12-03 04:06:58 +00002779 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002780 Expr *From, QualType ToType,
2781 OverloadCandidateSet &CandidateSet) {
2782 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2783 "Only conversion function templates permitted here");
2784
Douglas Gregor3f396022009-09-28 04:47:19 +00002785 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2786 return;
2787
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002788 TemplateDeductionInfo Info(Context);
2789 CXXConversionDecl *Specialization = 0;
2790 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00002791 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002792 Specialization, Info)) {
2793 // FIXME: Record what happened with template argument deduction, so
2794 // that we can give the user a beautiful diagnostic.
2795 (void)Result;
2796 return;
2797 }
Mike Stump1eb44332009-09-09 15:08:12 +00002798
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002799 // Add the conversion function template specialization produced by
2800 // template argument deduction as a candidate.
2801 assert(Specialization && "Missing function template specialization?");
John McCall701c89e2009-12-03 04:06:58 +00002802 AddConversionCandidate(Specialization, ActingDC, From, ToType, CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002803}
2804
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002805/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2806/// converts the given @c Object to a function pointer via the
2807/// conversion function @c Conversion, and then attempts to call it
2808/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2809/// the type of function that we'll eventually be calling.
2810void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall701c89e2009-12-03 04:06:58 +00002811 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00002812 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00002813 QualType ObjectType,
2814 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002815 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00002816 if (!CandidateSet.isNewCandidate(Conversion))
2817 return;
2818
Douglas Gregor7edfb692009-11-23 12:27:39 +00002819 // Overload resolution is always an unevaluated context.
2820 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2821
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002822 CandidateSet.push_back(OverloadCandidate());
2823 OverloadCandidate& Candidate = CandidateSet.back();
2824 Candidate.Function = 0;
2825 Candidate.Surrogate = Conversion;
2826 Candidate.Viable = true;
2827 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002828 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002829 Candidate.Conversions.resize(NumArgs + 1);
2830
2831 // Determine the implicit conversion sequence for the implicit
2832 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00002833 ImplicitConversionSequence ObjectInit
John McCall701c89e2009-12-03 04:06:58 +00002834 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002835 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2836 Candidate.Viable = false;
2837 return;
2838 }
2839
2840 // The first conversion is actually a user-defined conversion whose
2841 // first conversion is ObjectInit's standard conversion (which is
2842 // effectively a reference binding). Record it as such.
Mike Stump1eb44332009-09-09 15:08:12 +00002843 Candidate.Conversions[0].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002844 = ImplicitConversionSequence::UserDefinedConversion;
2845 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002846 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002847 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00002848 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002849 = Candidate.Conversions[0].UserDefined.Before;
2850 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2851
Mike Stump1eb44332009-09-09 15:08:12 +00002852 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002853 unsigned NumArgsInProto = Proto->getNumArgs();
2854
2855 // (C++ 13.3.2p2): A candidate function having fewer than m
2856 // parameters is viable only if it has an ellipsis in its parameter
2857 // list (8.3.5).
2858 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2859 Candidate.Viable = false;
2860 return;
2861 }
2862
2863 // Function types don't have any default arguments, so just check if
2864 // we have enough arguments.
2865 if (NumArgs < NumArgsInProto) {
2866 // Not enough arguments.
2867 Candidate.Viable = false;
2868 return;
2869 }
2870
2871 // Determine the implicit conversion sequences for each of the
2872 // arguments.
2873 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2874 if (ArgIdx < NumArgsInProto) {
2875 // (C++ 13.3.2p3): for F to be a viable function, there shall
2876 // exist for each argument an implicit conversion sequence
2877 // (13.3.3.1) that converts that argument to the corresponding
2878 // parameter of F.
2879 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00002880 Candidate.Conversions[ArgIdx + 1]
2881 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00002882 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00002883 /*ForceRValue=*/false,
2884 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002885 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002886 == ImplicitConversionSequence::BadConversion) {
2887 Candidate.Viable = false;
2888 break;
2889 }
2890 } else {
2891 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2892 // argument for which there is no corresponding parameter is
2893 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002894 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor106c6eb2008-11-19 22:57:39 +00002895 = ImplicitConversionSequence::EllipsisConversion;
2896 }
2897 }
2898}
2899
Mike Stump390b4cc2009-05-16 07:39:55 +00002900// FIXME: This will eventually be removed, once we've migrated all of the
2901// operator overloading logic over to the scheme used by binary operators, which
2902// works for template instantiation.
Douglas Gregor063daf62009-03-13 18:40:31 +00002903void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002904 SourceLocation OpLoc,
Douglas Gregor96176b32008-11-18 23:14:02 +00002905 Expr **Args, unsigned NumArgs,
Douglas Gregorf680a0f2009-02-04 16:44:47 +00002906 OverloadCandidateSet& CandidateSet,
2907 SourceRange OpRange) {
Douglas Gregor063daf62009-03-13 18:40:31 +00002908 FunctionSet Functions;
2909
2910 QualType T1 = Args[0]->getType();
2911 QualType T2;
2912 if (NumArgs > 1)
2913 T2 = Args[1]->getType();
2914
2915 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002916 if (S)
2917 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Sebastian Redl644be852009-10-23 19:23:15 +00002918 ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00002919 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2920 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregor573d9c32009-10-21 23:19:44 +00002921 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00002922}
2923
2924/// \brief Add overload candidates for overloaded operators that are
2925/// member functions.
2926///
2927/// Add the overloaded operator candidates that are member functions
2928/// for the operator Op that was used in an operator expression such
2929/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2930/// CandidateSet will store the added overload candidates. (C++
2931/// [over.match.oper]).
2932void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2933 SourceLocation OpLoc,
2934 Expr **Args, unsigned NumArgs,
2935 OverloadCandidateSet& CandidateSet,
2936 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00002937 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2938
2939 // C++ [over.match.oper]p3:
2940 // For a unary operator @ with an operand of a type whose
2941 // cv-unqualified version is T1, and for a binary operator @ with
2942 // a left operand of a type whose cv-unqualified version is T1 and
2943 // a right operand of a type whose cv-unqualified version is T2,
2944 // three sets of candidate functions, designated member
2945 // candidates, non-member candidates and built-in candidates, are
2946 // constructed as follows:
2947 QualType T1 = Args[0]->getType();
2948 QualType T2;
2949 if (NumArgs > 1)
2950 T2 = Args[1]->getType();
2951
2952 // -- If T1 is a class type, the set of member candidates is the
2953 // result of the qualified lookup of T1::operator@
2954 // (13.3.1.1.1); otherwise, the set of member candidates is
2955 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00002956 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002957 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00002958 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002959 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002960
John McCalla24dc2e2009-11-17 02:14:36 +00002961 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
2962 LookupQualifiedName(Operators, T1Rec->getDecl());
2963 Operators.suppressDiagnostics();
2964
Mike Stump1eb44332009-09-09 15:08:12 +00002965 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00002966 OperEnd = Operators.end();
2967 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00002968 ++Oper)
John McCall701c89e2009-12-03 04:06:58 +00002969 AddMethodCandidate(*Oper, Args[0]->getType(),
2970 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00002971 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00002972 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002973}
2974
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002975/// AddBuiltinCandidate - Add a candidate for a built-in
2976/// operator. ResultTy and ParamTys are the result and parameter types
2977/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002978/// arguments being passed to the candidate. IsAssignmentOperator
2979/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002980/// operator. NumContextualBoolArguments is the number of arguments
2981/// (at the beginning of the argument list) that will be contextually
2982/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00002983void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002984 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00002985 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002986 bool IsAssignmentOperator,
2987 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00002988 // Overload resolution is always an unevaluated context.
2989 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2990
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002991 // Add this candidate
2992 CandidateSet.push_back(OverloadCandidate());
2993 OverloadCandidate& Candidate = CandidateSet.back();
2994 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00002995 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00002996 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002997 Candidate.BuiltinTypes.ResultTy = ResultTy;
2998 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2999 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3000
3001 // Determine the implicit conversion sequences for each of the
3002 // arguments.
3003 Candidate.Viable = true;
3004 Candidate.Conversions.resize(NumArgs);
3005 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003006 // C++ [over.match.oper]p4:
3007 // For the built-in assignment operators, conversions of the
3008 // left operand are restricted as follows:
3009 // -- no temporaries are introduced to hold the left operand, and
3010 // -- no user-defined conversions are applied to the left
3011 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00003012 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003013 //
3014 // We block these conversions by turning off user-defined
3015 // conversions, since that is the only way that initialization of
3016 // a reference to a non-class type can occur from something that
3017 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003018 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00003019 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003020 "Contextual conversion to bool requires bool type");
3021 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3022 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003023 Candidate.Conversions[ArgIdx]
3024 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00003025 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003026 /*ForceRValue=*/false,
3027 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003028 }
Mike Stump1eb44332009-09-09 15:08:12 +00003029 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor96176b32008-11-18 23:14:02 +00003030 == ImplicitConversionSequence::BadConversion) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003031 Candidate.Viable = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003032 break;
3033 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003034 }
3035}
3036
3037/// BuiltinCandidateTypeSet - A set of types that will be used for the
3038/// candidate operator functions for built-in operators (C++
3039/// [over.built]). The types are separated into pointer types and
3040/// enumeration types.
3041class BuiltinCandidateTypeSet {
3042 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003043 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003044
3045 /// PointerTypes - The set of pointer types that will be used in the
3046 /// built-in candidates.
3047 TypeSet PointerTypes;
3048
Sebastian Redl78eb8742009-04-19 21:53:20 +00003049 /// MemberPointerTypes - The set of member pointer types that will be
3050 /// used in the built-in candidates.
3051 TypeSet MemberPointerTypes;
3052
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003053 /// EnumerationTypes - The set of enumeration types that will be
3054 /// used in the built-in candidates.
3055 TypeSet EnumerationTypes;
3056
Douglas Gregor5842ba92009-08-24 15:23:48 +00003057 /// Sema - The semantic analysis instance where we are building the
3058 /// candidate type set.
3059 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00003060
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003061 /// Context - The AST context in which we will build the type sets.
3062 ASTContext &Context;
3063
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003064 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3065 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00003066 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003067
3068public:
3069 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003070 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003071
Mike Stump1eb44332009-09-09 15:08:12 +00003072 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00003073 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003074
Douglas Gregor573d9c32009-10-21 23:19:44 +00003075 void AddTypesConvertedFrom(QualType Ty,
3076 SourceLocation Loc,
3077 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003078 bool AllowExplicitConversions,
3079 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003080
3081 /// pointer_begin - First pointer type found;
3082 iterator pointer_begin() { return PointerTypes.begin(); }
3083
Sebastian Redl78eb8742009-04-19 21:53:20 +00003084 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003085 iterator pointer_end() { return PointerTypes.end(); }
3086
Sebastian Redl78eb8742009-04-19 21:53:20 +00003087 /// member_pointer_begin - First member pointer type found;
3088 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3089
3090 /// member_pointer_end - Past the last member pointer type found;
3091 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3092
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003093 /// enumeration_begin - First enumeration type found;
3094 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3095
Sebastian Redl78eb8742009-04-19 21:53:20 +00003096 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003097 iterator enumeration_end() { return EnumerationTypes.end(); }
3098};
3099
Sebastian Redl78eb8742009-04-19 21:53:20 +00003100/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003101/// the set of pointer types along with any more-qualified variants of
3102/// that type. For example, if @p Ty is "int const *", this routine
3103/// will add "int const *", "int const volatile *", "int const
3104/// restrict *", and "int const volatile restrict *" to the set of
3105/// pointer types. Returns true if the add of @p Ty itself succeeded,
3106/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003107///
3108/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003109bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00003110BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3111 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00003112
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003113 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003114 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003115 return false;
3116
John McCall0953e762009-09-24 19:53:00 +00003117 const PointerType *PointerTy = Ty->getAs<PointerType>();
3118 assert(PointerTy && "type was not a pointer type!");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003119
John McCall0953e762009-09-24 19:53:00 +00003120 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003121 // Don't add qualified variants of arrays. For one, they're not allowed
3122 // (the qualifier would sink to the element type), and for another, the
3123 // only overload situation where it matters is subscript or pointer +- int,
3124 // and those shouldn't have qualifier variants anyway.
3125 if (PointeeTy->isArrayType())
3126 return true;
John McCall0953e762009-09-24 19:53:00 +00003127 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00003128 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00003129 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003130 bool hasVolatile = VisibleQuals.hasVolatile();
3131 bool hasRestrict = VisibleQuals.hasRestrict();
3132
John McCall0953e762009-09-24 19:53:00 +00003133 // Iterate through all strict supersets of BaseCVR.
3134 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3135 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003136 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3137 // in the types.
3138 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3139 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00003140 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3141 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003142 }
3143
3144 return true;
3145}
3146
Sebastian Redl78eb8742009-04-19 21:53:20 +00003147/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3148/// to the set of pointer types along with any more-qualified variants of
3149/// that type. For example, if @p Ty is "int const *", this routine
3150/// will add "int const *", "int const volatile *", "int const
3151/// restrict *", and "int const volatile restrict *" to the set of
3152/// pointer types. Returns true if the add of @p Ty itself succeeded,
3153/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003154///
3155/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003156bool
3157BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3158 QualType Ty) {
3159 // Insert this type.
3160 if (!MemberPointerTypes.insert(Ty))
3161 return false;
3162
John McCall0953e762009-09-24 19:53:00 +00003163 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3164 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00003165
John McCall0953e762009-09-24 19:53:00 +00003166 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003167 // Don't add qualified variants of arrays. For one, they're not allowed
3168 // (the qualifier would sink to the element type), and for another, the
3169 // only overload situation where it matters is subscript or pointer +- int,
3170 // and those shouldn't have qualifier variants anyway.
3171 if (PointeeTy->isArrayType())
3172 return true;
John McCall0953e762009-09-24 19:53:00 +00003173 const Type *ClassTy = PointerTy->getClass();
3174
3175 // Iterate through all strict supersets of the pointee type's CVR
3176 // qualifiers.
3177 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3178 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3179 if ((CVR | BaseCVR) != CVR) continue;
3180
3181 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3182 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00003183 }
3184
3185 return true;
3186}
3187
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003188/// AddTypesConvertedFrom - Add each of the types to which the type @p
3189/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00003190/// primarily interested in pointer types and enumeration types. We also
3191/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003192/// AllowUserConversions is true if we should look at the conversion
3193/// functions of a class type, and AllowExplicitConversions if we
3194/// should also include the explicit conversion functions of a class
3195/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003196void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003197BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003198 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003199 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003200 bool AllowExplicitConversions,
3201 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003202 // Only deal with canonical types.
3203 Ty = Context.getCanonicalType(Ty);
3204
3205 // Look through reference types; they aren't part of the type of an
3206 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00003207 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003208 Ty = RefTy->getPointeeType();
3209
3210 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003211 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003212
Sebastian Redla65b5512009-11-05 16:36:20 +00003213 // If we're dealing with an array type, decay to the pointer.
3214 if (Ty->isArrayType())
3215 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3216
Ted Kremenek6217b802009-07-29 21:53:49 +00003217 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003218 QualType PointeeTy = PointerTy->getPointeeType();
3219
3220 // Insert our type, and its more-qualified variants, into the set
3221 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003222 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003223 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00003224 } else if (Ty->isMemberPointerType()) {
3225 // Member pointers are far easier, since the pointee can't be converted.
3226 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3227 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003228 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00003229 EnumerationTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003230 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003231 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003232 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003233 // No conversion functions in incomplete types.
3234 return;
3235 }
Mike Stump1eb44332009-09-09 15:08:12 +00003236
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003237 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallba135432009-11-21 08:51:07 +00003238 const UnresolvedSet *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00003239 = ClassDecl->getVisibleConversionFunctions();
John McCallba135432009-11-21 08:51:07 +00003240 for (UnresolvedSet::iterator I = Conversions->begin(),
3241 E = Conversions->end(); I != E; ++I) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003242
Mike Stump1eb44332009-09-09 15:08:12 +00003243 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003244 // about which builtin types we can convert to.
John McCallba135432009-11-21 08:51:07 +00003245 if (isa<FunctionTemplateDecl>(*I))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003246 continue;
3247
John McCallba135432009-11-21 08:51:07 +00003248 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003249 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003250 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003251 VisibleQuals);
3252 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003253 }
3254 }
3255 }
3256}
3257
Douglas Gregor19b7b152009-08-24 13:43:27 +00003258/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3259/// the volatile- and non-volatile-qualified assignment operators for the
3260/// given type to the candidate set.
3261static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3262 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00003263 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003264 unsigned NumArgs,
3265 OverloadCandidateSet &CandidateSet) {
3266 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00003267
Douglas Gregor19b7b152009-08-24 13:43:27 +00003268 // T& operator=(T&, T)
3269 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3270 ParamTypes[1] = T;
3271 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3272 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003273
Douglas Gregor19b7b152009-08-24 13:43:27 +00003274 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3275 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00003276 ParamTypes[0]
3277 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00003278 ParamTypes[1] = T;
3279 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00003280 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003281 }
3282}
Mike Stump1eb44332009-09-09 15:08:12 +00003283
Sebastian Redl9994a342009-10-25 17:03:50 +00003284/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3285/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003286static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3287 Qualifiers VRQuals;
3288 const RecordType *TyRec;
3289 if (const MemberPointerType *RHSMPType =
3290 ArgExpr->getType()->getAs<MemberPointerType>())
3291 TyRec = cast<RecordType>(RHSMPType->getClass());
3292 else
3293 TyRec = ArgExpr->getType()->getAs<RecordType>();
3294 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003295 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003296 VRQuals.addVolatile();
3297 VRQuals.addRestrict();
3298 return VRQuals;
3299 }
3300
3301 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallba135432009-11-21 08:51:07 +00003302 const UnresolvedSet *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00003303 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003304
John McCallba135432009-11-21 08:51:07 +00003305 for (UnresolvedSet::iterator I = Conversions->begin(),
3306 E = Conversions->end(); I != E; ++I) {
3307 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003308 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3309 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3310 CanTy = ResTypeRef->getPointeeType();
3311 // Need to go down the pointer/mempointer chain and add qualifiers
3312 // as see them.
3313 bool done = false;
3314 while (!done) {
3315 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3316 CanTy = ResTypePtr->getPointeeType();
3317 else if (const MemberPointerType *ResTypeMPtr =
3318 CanTy->getAs<MemberPointerType>())
3319 CanTy = ResTypeMPtr->getPointeeType();
3320 else
3321 done = true;
3322 if (CanTy.isVolatileQualified())
3323 VRQuals.addVolatile();
3324 if (CanTy.isRestrictQualified())
3325 VRQuals.addRestrict();
3326 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3327 return VRQuals;
3328 }
3329 }
3330 }
3331 return VRQuals;
3332}
3333
Douglas Gregor74253732008-11-19 15:42:04 +00003334/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3335/// operator overloads to the candidate set (C++ [over.built]), based
3336/// on the operator @p Op and the arguments given. For example, if the
3337/// operator is a binary '+', this routine might add "int
3338/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003339void
Mike Stump1eb44332009-09-09 15:08:12 +00003340Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003341 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00003342 Expr **Args, unsigned NumArgs,
3343 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003344 // The set of "promoted arithmetic types", which are the arithmetic
3345 // types are that preserved by promotion (C++ [over.built]p2). Note
3346 // that the first few of these types are the promoted integral
3347 // types; these types need to be first.
3348 // FIXME: What about complex?
3349 const unsigned FirstIntegralType = 0;
3350 const unsigned LastIntegralType = 13;
Mike Stump1eb44332009-09-09 15:08:12 +00003351 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003352 LastPromotedIntegralType = 13;
3353 const unsigned FirstPromotedArithmeticType = 7,
3354 LastPromotedArithmeticType = 16;
3355 const unsigned NumArithmeticTypes = 16;
3356 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00003357 Context.BoolTy, Context.CharTy, Context.WCharTy,
3358// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003359 Context.SignedCharTy, Context.ShortTy,
3360 Context.UnsignedCharTy, Context.UnsignedShortTy,
3361 Context.IntTy, Context.LongTy, Context.LongLongTy,
3362 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3363 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3364 };
Douglas Gregor652371a2009-10-21 22:01:30 +00003365 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3366 "Invalid first promoted integral type");
3367 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3368 == Context.UnsignedLongLongTy &&
3369 "Invalid last promoted integral type");
3370 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3371 "Invalid first promoted arithmetic type");
3372 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3373 == Context.LongDoubleTy &&
3374 "Invalid last promoted arithmetic type");
3375
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003376 // Find all of the types that the arguments can convert to, but only
3377 // if the operator we're looking at has built-in operator candidates
3378 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003379 Qualifiers VisibleTypeConversionsQuals;
3380 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003381 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3382 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3383
Douglas Gregor5842ba92009-08-24 15:23:48 +00003384 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003385 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3386 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00003387 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003388 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00003389 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003390 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor74253732008-11-19 15:42:04 +00003391 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003392 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregor573d9c32009-10-21 23:19:44 +00003393 OpLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003394 true,
3395 (Op == OO_Exclaim ||
3396 Op == OO_AmpAmp ||
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003397 Op == OO_PipePipe),
3398 VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003399 }
3400
3401 bool isComparison = false;
3402 switch (Op) {
3403 case OO_None:
3404 case NUM_OVERLOADED_OPERATORS:
3405 assert(false && "Expected an overloaded operator");
3406 break;
3407
Douglas Gregor74253732008-11-19 15:42:04 +00003408 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00003409 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00003410 goto UnaryStar;
3411 else
3412 goto BinaryStar;
3413 break;
3414
3415 case OO_Plus: // '+' is either unary or binary
3416 if (NumArgs == 1)
3417 goto UnaryPlus;
3418 else
3419 goto BinaryPlus;
3420 break;
3421
3422 case OO_Minus: // '-' is either unary or binary
3423 if (NumArgs == 1)
3424 goto UnaryMinus;
3425 else
3426 goto BinaryMinus;
3427 break;
3428
3429 case OO_Amp: // '&' is either unary or binary
3430 if (NumArgs == 1)
3431 goto UnaryAmp;
3432 else
3433 goto BinaryAmp;
3434
3435 case OO_PlusPlus:
3436 case OO_MinusMinus:
3437 // C++ [over.built]p3:
3438 //
3439 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3440 // is either volatile or empty, there exist candidate operator
3441 // functions of the form
3442 //
3443 // VQ T& operator++(VQ T&);
3444 // T operator++(VQ T&, int);
3445 //
3446 // C++ [over.built]p4:
3447 //
3448 // For every pair (T, VQ), where T is an arithmetic type other
3449 // than bool, and VQ is either volatile or empty, there exist
3450 // candidate operator functions of the form
3451 //
3452 // VQ T& operator--(VQ T&);
3453 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00003454 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00003455 Arith < NumArithmeticTypes; ++Arith) {
3456 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00003457 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003458 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00003459
3460 // Non-volatile version.
3461 if (NumArgs == 1)
3462 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3463 else
3464 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003465 // heuristic to reduce number of builtin candidates in the set.
3466 // Add volatile version only if there are conversions to a volatile type.
3467 if (VisibleTypeConversionsQuals.hasVolatile()) {
3468 // Volatile version
3469 ParamTypes[0]
3470 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3471 if (NumArgs == 1)
3472 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3473 else
3474 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3475 }
Douglas Gregor74253732008-11-19 15:42:04 +00003476 }
3477
3478 // C++ [over.built]p5:
3479 //
3480 // For every pair (T, VQ), where T is a cv-qualified or
3481 // cv-unqualified object type, and VQ is either volatile or
3482 // empty, there exist candidate operator functions of the form
3483 //
3484 // T*VQ& operator++(T*VQ&);
3485 // T*VQ& operator--(T*VQ&);
3486 // T* operator++(T*VQ&, int);
3487 // T* operator--(T*VQ&, int);
3488 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3489 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3490 // Skip pointer types that aren't pointers to object types.
Ted Kremenek6217b802009-07-29 21:53:49 +00003491 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00003492 continue;
3493
Mike Stump1eb44332009-09-09 15:08:12 +00003494 QualType ParamTypes[2] = {
3495 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00003496 };
Mike Stump1eb44332009-09-09 15:08:12 +00003497
Douglas Gregor74253732008-11-19 15:42:04 +00003498 // Without volatile
3499 if (NumArgs == 1)
3500 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3501 else
3502 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3503
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003504 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3505 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00003506 // With volatile
John McCall0953e762009-09-24 19:53:00 +00003507 ParamTypes[0]
3508 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00003509 if (NumArgs == 1)
3510 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3511 else
3512 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3513 }
3514 }
3515 break;
3516
3517 UnaryStar:
3518 // C++ [over.built]p6:
3519 // For every cv-qualified or cv-unqualified object type T, there
3520 // exist candidate operator functions of the form
3521 //
3522 // T& operator*(T*);
3523 //
3524 // C++ [over.built]p7:
3525 // For every function type T, there exist candidate operator
3526 // functions of the form
3527 // T& operator*(T*);
3528 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3529 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3530 QualType ParamTy = *Ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00003531 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003532 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00003533 &ParamTy, Args, 1, CandidateSet);
3534 }
3535 break;
3536
3537 UnaryPlus:
3538 // C++ [over.built]p8:
3539 // For every type T, there exist candidate operator functions of
3540 // the form
3541 //
3542 // T* operator+(T*);
3543 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3544 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3545 QualType ParamTy = *Ptr;
3546 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3547 }
Mike Stump1eb44332009-09-09 15:08:12 +00003548
Douglas Gregor74253732008-11-19 15:42:04 +00003549 // Fall through
3550
3551 UnaryMinus:
3552 // C++ [over.built]p9:
3553 // For every promoted arithmetic type T, there exist candidate
3554 // operator functions of the form
3555 //
3556 // T operator+(T);
3557 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003558 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00003559 Arith < LastPromotedArithmeticType; ++Arith) {
3560 QualType ArithTy = ArithmeticTypes[Arith];
3561 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3562 }
3563 break;
3564
3565 case OO_Tilde:
3566 // C++ [over.built]p10:
3567 // For every promoted integral type T, there exist candidate
3568 // operator functions of the form
3569 //
3570 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00003571 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00003572 Int < LastPromotedIntegralType; ++Int) {
3573 QualType IntTy = ArithmeticTypes[Int];
3574 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3575 }
3576 break;
3577
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003578 case OO_New:
3579 case OO_Delete:
3580 case OO_Array_New:
3581 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003582 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00003583 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003584 break;
3585
3586 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00003587 UnaryAmp:
3588 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003589 // C++ [over.match.oper]p3:
3590 // -- For the operator ',', the unary operator '&', or the
3591 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003592 break;
3593
Douglas Gregor19b7b152009-08-24 13:43:27 +00003594 case OO_EqualEqual:
3595 case OO_ExclaimEqual:
3596 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00003597 // For every pointer to member type T, there exist candidate operator
3598 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00003599 //
3600 // bool operator==(T,T);
3601 // bool operator!=(T,T);
Mike Stump1eb44332009-09-09 15:08:12 +00003602 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor19b7b152009-08-24 13:43:27 +00003603 MemPtr = CandidateTypes.member_pointer_begin(),
3604 MemPtrEnd = CandidateTypes.member_pointer_end();
3605 MemPtr != MemPtrEnd;
3606 ++MemPtr) {
3607 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3608 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3609 }
Mike Stump1eb44332009-09-09 15:08:12 +00003610
Douglas Gregor19b7b152009-08-24 13:43:27 +00003611 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00003612
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003613 case OO_Less:
3614 case OO_Greater:
3615 case OO_LessEqual:
3616 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003617 // C++ [over.built]p15:
3618 //
3619 // For every pointer or enumeration type T, there exist
3620 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003621 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003622 // bool operator<(T, T);
3623 // bool operator>(T, T);
3624 // bool operator<=(T, T);
3625 // bool operator>=(T, T);
3626 // bool operator==(T, T);
3627 // bool operator!=(T, T);
3628 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3629 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3630 QualType ParamTypes[2] = { *Ptr, *Ptr };
3631 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3632 }
Mike Stump1eb44332009-09-09 15:08:12 +00003633 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003634 = CandidateTypes.enumeration_begin();
3635 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3636 QualType ParamTypes[2] = { *Enum, *Enum };
3637 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3638 }
3639
3640 // Fall through.
3641 isComparison = true;
3642
Douglas Gregor74253732008-11-19 15:42:04 +00003643 BinaryPlus:
3644 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003645 if (!isComparison) {
3646 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3647
3648 // C++ [over.built]p13:
3649 //
3650 // For every cv-qualified or cv-unqualified object type T
3651 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003652 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003653 // T* operator+(T*, ptrdiff_t);
3654 // T& operator[](T*, ptrdiff_t); [BELOW]
3655 // T* operator-(T*, ptrdiff_t);
3656 // T* operator+(ptrdiff_t, T*);
3657 // T& operator[](ptrdiff_t, T*); [BELOW]
3658 //
3659 // C++ [over.built]p14:
3660 //
3661 // For every T, where T is a pointer to object type, there
3662 // exist candidate operator functions of the form
3663 //
3664 // ptrdiff_t operator-(T, T);
Mike Stump1eb44332009-09-09 15:08:12 +00003665 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003666 = CandidateTypes.pointer_begin();
3667 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3668 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3669
3670 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3671 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3672
3673 if (Op == OO_Plus) {
3674 // T* operator+(ptrdiff_t, T*);
3675 ParamTypes[0] = ParamTypes[1];
3676 ParamTypes[1] = *Ptr;
3677 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3678 } else {
3679 // ptrdiff_t operator-(T, T);
3680 ParamTypes[1] = *Ptr;
3681 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3682 Args, 2, CandidateSet);
3683 }
3684 }
3685 }
3686 // Fall through
3687
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003688 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00003689 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003690 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003691 // C++ [over.built]p12:
3692 //
3693 // For every pair of promoted arithmetic types L and R, there
3694 // exist candidate operator functions of the form
3695 //
3696 // LR operator*(L, R);
3697 // LR operator/(L, R);
3698 // LR operator+(L, R);
3699 // LR operator-(L, R);
3700 // bool operator<(L, R);
3701 // bool operator>(L, R);
3702 // bool operator<=(L, R);
3703 // bool operator>=(L, R);
3704 // bool operator==(L, R);
3705 // bool operator!=(L, R);
3706 //
3707 // where LR is the result of the usual arithmetic conversions
3708 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003709 //
3710 // C++ [over.built]p24:
3711 //
3712 // For every pair of promoted arithmetic types L and R, there exist
3713 // candidate operator functions of the form
3714 //
3715 // LR operator?(bool, L, R);
3716 //
3717 // where LR is the result of the usual arithmetic conversions
3718 // between types L and R.
3719 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003720 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003721 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003722 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003723 Right < LastPromotedArithmeticType; ++Right) {
3724 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00003725 QualType Result
3726 = isComparison
3727 ? Context.BoolTy
3728 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003729 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3730 }
3731 }
3732 break;
3733
3734 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00003735 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003736 case OO_Caret:
3737 case OO_Pipe:
3738 case OO_LessLess:
3739 case OO_GreaterGreater:
3740 // C++ [over.built]p17:
3741 //
3742 // For every pair of promoted integral types L and R, there
3743 // exist candidate operator functions of the form
3744 //
3745 // LR operator%(L, R);
3746 // LR operator&(L, R);
3747 // LR operator^(L, R);
3748 // LR operator|(L, R);
3749 // L operator<<(L, R);
3750 // L operator>>(L, R);
3751 //
3752 // where LR is the result of the usual arithmetic conversions
3753 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00003754 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003755 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003756 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003757 Right < LastPromotedIntegralType; ++Right) {
3758 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3759 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3760 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00003761 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003762 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3763 }
3764 }
3765 break;
3766
3767 case OO_Equal:
3768 // C++ [over.built]p20:
3769 //
3770 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00003771 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003772 // empty, there exist candidate operator functions of the form
3773 //
3774 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003775 for (BuiltinCandidateTypeSet::iterator
3776 Enum = CandidateTypes.enumeration_begin(),
3777 EnumEnd = CandidateTypes.enumeration_end();
3778 Enum != EnumEnd; ++Enum)
Mike Stump1eb44332009-09-09 15:08:12 +00003779 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003780 CandidateSet);
3781 for (BuiltinCandidateTypeSet::iterator
3782 MemPtr = CandidateTypes.member_pointer_begin(),
3783 MemPtrEnd = CandidateTypes.member_pointer_end();
3784 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump1eb44332009-09-09 15:08:12 +00003785 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003786 CandidateSet);
3787 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003788
3789 case OO_PlusEqual:
3790 case OO_MinusEqual:
3791 // C++ [over.built]p19:
3792 //
3793 // For every pair (T, VQ), where T is any type and VQ is either
3794 // volatile or empty, there exist candidate operator functions
3795 // of the form
3796 //
3797 // T*VQ& operator=(T*VQ&, T*);
3798 //
3799 // C++ [over.built]p21:
3800 //
3801 // For every pair (T, VQ), where T is a cv-qualified or
3802 // cv-unqualified object type and VQ is either volatile or
3803 // empty, there exist candidate operator functions of the form
3804 //
3805 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3806 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3807 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3808 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3809 QualType ParamTypes[2];
3810 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3811
3812 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003813 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003814 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3815 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003816
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003817 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3818 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00003819 // volatile version
John McCall0953e762009-09-24 19:53:00 +00003820 ParamTypes[0]
3821 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003822 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3823 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00003824 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003825 }
3826 // Fall through.
3827
3828 case OO_StarEqual:
3829 case OO_SlashEqual:
3830 // C++ [over.built]p18:
3831 //
3832 // For every triple (L, VQ, R), where L is an arithmetic type,
3833 // VQ is either volatile or empty, and R is a promoted
3834 // arithmetic type, there exist candidate operator functions of
3835 // the form
3836 //
3837 // VQ L& operator=(VQ L&, R);
3838 // VQ L& operator*=(VQ L&, R);
3839 // VQ L& operator/=(VQ L&, R);
3840 // VQ L& operator+=(VQ L&, R);
3841 // VQ L& operator-=(VQ L&, R);
3842 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003843 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003844 Right < LastPromotedArithmeticType; ++Right) {
3845 QualType ParamTypes[2];
3846 ParamTypes[1] = ArithmeticTypes[Right];
3847
3848 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003849 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003850 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3851 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003852
3853 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00003854 if (VisibleTypeConversionsQuals.hasVolatile()) {
3855 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3856 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3857 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3858 /*IsAssigmentOperator=*/Op == OO_Equal);
3859 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003860 }
3861 }
3862 break;
3863
3864 case OO_PercentEqual:
3865 case OO_LessLessEqual:
3866 case OO_GreaterGreaterEqual:
3867 case OO_AmpEqual:
3868 case OO_CaretEqual:
3869 case OO_PipeEqual:
3870 // C++ [over.built]p22:
3871 //
3872 // For every triple (L, VQ, R), where L is an integral type, VQ
3873 // is either volatile or empty, and R is a promoted integral
3874 // type, there exist candidate operator functions of the form
3875 //
3876 // VQ L& operator%=(VQ L&, R);
3877 // VQ L& operator<<=(VQ L&, R);
3878 // VQ L& operator>>=(VQ L&, R);
3879 // VQ L& operator&=(VQ L&, R);
3880 // VQ L& operator^=(VQ L&, R);
3881 // VQ L& operator|=(VQ L&, R);
3882 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00003883 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003884 Right < LastPromotedIntegralType; ++Right) {
3885 QualType ParamTypes[2];
3886 ParamTypes[1] = ArithmeticTypes[Right];
3887
3888 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003889 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003890 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00003891 if (VisibleTypeConversionsQuals.hasVolatile()) {
3892 // Add this built-in operator as a candidate (VQ is 'volatile').
3893 ParamTypes[0] = ArithmeticTypes[Left];
3894 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3895 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3896 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3897 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003898 }
3899 }
3900 break;
3901
Douglas Gregor74253732008-11-19 15:42:04 +00003902 case OO_Exclaim: {
3903 // C++ [over.operator]p23:
3904 //
3905 // There also exist candidate operator functions of the form
3906 //
Mike Stump1eb44332009-09-09 15:08:12 +00003907 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00003908 // bool operator&&(bool, bool); [BELOW]
3909 // bool operator||(bool, bool); [BELOW]
3910 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003911 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3912 /*IsAssignmentOperator=*/false,
3913 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00003914 break;
3915 }
3916
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003917 case OO_AmpAmp:
3918 case OO_PipePipe: {
3919 // C++ [over.operator]p23:
3920 //
3921 // There also exist candidate operator functions of the form
3922 //
Douglas Gregor74253732008-11-19 15:42:04 +00003923 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003924 // bool operator&&(bool, bool);
3925 // bool operator||(bool, bool);
3926 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003927 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3928 /*IsAssignmentOperator=*/false,
3929 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003930 break;
3931 }
3932
3933 case OO_Subscript:
3934 // C++ [over.built]p13:
3935 //
3936 // For every cv-qualified or cv-unqualified object type T there
3937 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00003938 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003939 // T* operator+(T*, ptrdiff_t); [ABOVE]
3940 // T& operator[](T*, ptrdiff_t);
3941 // T* operator-(T*, ptrdiff_t); [ABOVE]
3942 // T* operator+(ptrdiff_t, T*); [ABOVE]
3943 // T& operator[](ptrdiff_t, T*);
3944 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3945 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3946 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenek6217b802009-07-29 21:53:49 +00003947 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003948 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003949
3950 // T& operator[](T*, ptrdiff_t)
3951 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3952
3953 // T& operator[](ptrdiff_t, T*);
3954 ParamTypes[0] = ParamTypes[1];
3955 ParamTypes[1] = *Ptr;
3956 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3957 }
3958 break;
3959
3960 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003961 // C++ [over.built]p11:
3962 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
3963 // C1 is the same type as C2 or is a derived class of C2, T is an object
3964 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
3965 // there exist candidate operator functions of the form
3966 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
3967 // where CV12 is the union of CV1 and CV2.
3968 {
3969 for (BuiltinCandidateTypeSet::iterator Ptr =
3970 CandidateTypes.pointer_begin();
3971 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3972 QualType C1Ty = (*Ptr);
3973 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00003974 QualifierCollector Q1;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003975 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00003976 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003977 if (!isa<RecordType>(C1))
3978 continue;
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003979 // heuristic to reduce number of builtin candidates in the set.
3980 // Add volatile/restrict version only if there are conversions to a
3981 // volatile/restrict type.
3982 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
3983 continue;
3984 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
3985 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003986 }
3987 for (BuiltinCandidateTypeSet::iterator
3988 MemPtr = CandidateTypes.member_pointer_begin(),
3989 MemPtrEnd = CandidateTypes.member_pointer_end();
3990 MemPtr != MemPtrEnd; ++MemPtr) {
3991 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
3992 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00003993 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00003994 if (C1 != C2 && !IsDerivedFrom(C1, C2))
3995 break;
3996 QualType ParamTypes[2] = { *Ptr, *MemPtr };
3997 // build CV12 T&
3998 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003999 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4000 T.isVolatileQualified())
4001 continue;
4002 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4003 T.isRestrictQualified())
4004 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004005 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004006 QualType ResultTy = Context.getLValueReferenceType(T);
4007 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4008 }
4009 }
4010 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004011 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004012
4013 case OO_Conditional:
4014 // Note that we don't consider the first argument, since it has been
4015 // contextually converted to bool long ago. The candidates below are
4016 // therefore added as binary.
4017 //
4018 // C++ [over.built]p24:
4019 // For every type T, where T is a pointer or pointer-to-member type,
4020 // there exist candidate operator functions of the form
4021 //
4022 // T operator?(bool, T, T);
4023 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004024 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4025 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4026 QualType ParamTypes[2] = { *Ptr, *Ptr };
4027 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4028 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00004029 for (BuiltinCandidateTypeSet::iterator Ptr =
4030 CandidateTypes.member_pointer_begin(),
4031 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4032 QualType ParamTypes[2] = { *Ptr, *Ptr };
4033 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4034 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004035 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004036 }
4037}
4038
Douglas Gregorfa047642009-02-04 00:32:51 +00004039/// \brief Add function candidates found via argument-dependent lookup
4040/// to the set of overloading candidates.
4041///
4042/// This routine performs argument-dependent name lookup based on the
4043/// given function name (which may also be an operator name) and adds
4044/// all of the overload candidates found by ADL to the overload
4045/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00004046void
Douglas Gregorfa047642009-02-04 00:32:51 +00004047Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
4048 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00004049 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004050 OverloadCandidateSet& CandidateSet,
4051 bool PartialOverloading) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004052 FunctionSet Functions;
Douglas Gregorfa047642009-02-04 00:32:51 +00004053
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004054 // FIXME: Should we be trafficking in canonical function decls throughout?
4055
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004056 // Record all of the function candidates that we've already
4057 // added to the overload set, so that we don't add those same
4058 // candidates a second time.
4059 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4060 CandEnd = CandidateSet.end();
4061 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00004062 if (Cand->Function) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004063 Functions.insert(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00004064 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4065 Functions.insert(FunTmpl);
4066 }
Douglas Gregorfa047642009-02-04 00:32:51 +00004067
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004068 // FIXME: Pass in the explicit template arguments?
Sebastian Redl644be852009-10-23 19:23:15 +00004069 ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
Douglas Gregorfa047642009-02-04 00:32:51 +00004070
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004071 // Erase all of the candidates we already knew about.
4072 // FIXME: This is suboptimal. Is there a better way?
4073 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4074 CandEnd = CandidateSet.end();
4075 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00004076 if (Cand->Function) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004077 Functions.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00004078 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4079 Functions.erase(FunTmpl);
4080 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004081
4082 // For each of the ADL candidates we found, add it to the overload
4083 // set.
4084 for (FunctionSet::iterator Func = Functions.begin(),
4085 FuncEnd = Functions.end();
Douglas Gregor364e0212009-06-27 21:05:07 +00004086 Func != FuncEnd; ++Func) {
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004087 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
John McCalld5532b62009-11-23 01:53:49 +00004088 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004089 continue;
4090
4091 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
4092 false, false, PartialOverloading);
4093 } else
Mike Stump1eb44332009-09-09 15:08:12 +00004094 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004095 ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004096 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00004097 }
Douglas Gregorfa047642009-02-04 00:32:51 +00004098}
4099
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004100/// isBetterOverloadCandidate - Determines whether the first overload
4101/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00004102bool
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004103Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump1eb44332009-09-09 15:08:12 +00004104 const OverloadCandidate& Cand2) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004105 // Define viable functions to be better candidates than non-viable
4106 // functions.
4107 if (!Cand2.Viable)
4108 return Cand1.Viable;
4109 else if (!Cand1.Viable)
4110 return false;
4111
Douglas Gregor88a35142008-12-22 05:46:06 +00004112 // C++ [over.match.best]p1:
4113 //
4114 // -- if F is a static member function, ICS1(F) is defined such
4115 // that ICS1(F) is neither better nor worse than ICS1(G) for
4116 // any function G, and, symmetrically, ICS1(G) is neither
4117 // better nor worse than ICS1(F).
4118 unsigned StartArg = 0;
4119 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4120 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004121
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004122 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00004123 // A viable function F1 is defined to be a better function than another
4124 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004125 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004126 unsigned NumArgs = Cand1.Conversions.size();
4127 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4128 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004129 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004130 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4131 Cand2.Conversions[ArgIdx])) {
4132 case ImplicitConversionSequence::Better:
4133 // Cand1 has a better conversion sequence.
4134 HasBetterConversion = true;
4135 break;
4136
4137 case ImplicitConversionSequence::Worse:
4138 // Cand1 can't be better than Cand2.
4139 return false;
4140
4141 case ImplicitConversionSequence::Indistinguishable:
4142 // Do nothing.
4143 break;
4144 }
4145 }
4146
Mike Stump1eb44332009-09-09 15:08:12 +00004147 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004148 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004149 if (HasBetterConversion)
4150 return true;
4151
Mike Stump1eb44332009-09-09 15:08:12 +00004152 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004153 // specialization, or, if not that,
4154 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4155 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4156 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004157
4158 // -- F1 and F2 are function template specializations, and the function
4159 // template for F1 is more specialized than the template for F2
4160 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004161 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00004162 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4163 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004164 if (FunctionTemplateDecl *BetterTemplate
4165 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4166 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor5d7d3752009-09-14 23:02:14 +00004167 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4168 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004169 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004170
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004171 // -- the context is an initialization by user-defined conversion
4172 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4173 // from the return type of F1 to the destination type (i.e.,
4174 // the type of the entity being initialized) is a better
4175 // conversion sequence than the standard conversion sequence
4176 // from the return type of F2 to the destination type.
Mike Stump1eb44332009-09-09 15:08:12 +00004177 if (Cand1.Function && Cand2.Function &&
4178 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004179 isa<CXXConversionDecl>(Cand2.Function)) {
4180 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4181 Cand2.FinalConversion)) {
4182 case ImplicitConversionSequence::Better:
4183 // Cand1 has a better conversion sequence.
4184 return true;
4185
4186 case ImplicitConversionSequence::Worse:
4187 // Cand1 can't be better than Cand2.
4188 return false;
4189
4190 case ImplicitConversionSequence::Indistinguishable:
4191 // Do nothing
4192 break;
4193 }
4194 }
4195
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004196 return false;
4197}
4198
Mike Stump1eb44332009-09-09 15:08:12 +00004199/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00004200/// within an overload candidate set.
4201///
4202/// \param CandidateSet the set of candidate functions.
4203///
4204/// \param Loc the location of the function name (or operator symbol) for
4205/// which overload resolution occurs.
4206///
Mike Stump1eb44332009-09-09 15:08:12 +00004207/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00004208/// function, Best points to the candidate function found.
4209///
4210/// \returns The result of overload resolution.
Douglas Gregor20093b42009-12-09 23:02:17 +00004211OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4212 SourceLocation Loc,
4213 OverloadCandidateSet::iterator& Best) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004214 // Find the best viable function.
4215 Best = CandidateSet.end();
4216 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4217 Cand != CandidateSet.end(); ++Cand) {
4218 if (Cand->Viable) {
4219 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4220 Best = Cand;
4221 }
4222 }
4223
4224 // If we didn't find any viable functions, abort.
4225 if (Best == CandidateSet.end())
4226 return OR_No_Viable_Function;
4227
4228 // Make sure that this function is better than every other viable
4229 // function. If not, we have an ambiguity.
4230 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4231 Cand != CandidateSet.end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00004232 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004233 Cand != Best &&
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004234 !isBetterOverloadCandidate(*Best, *Cand)) {
4235 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004236 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004237 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004238 }
Mike Stump1eb44332009-09-09 15:08:12 +00004239
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004240 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004241 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00004242 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004243 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004244 return OR_Deleted;
4245
Douglas Gregore0762c92009-06-19 23:52:42 +00004246 // C++ [basic.def.odr]p2:
4247 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00004248 // when referred to from a potentially-evaluated expression. [Note: this
4249 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00004250 // (clause 13), user-defined conversions (12.3.2), allocation function for
4251 // placement new (5.3.4), as well as non-default initialization (8.5).
4252 if (Best->Function)
4253 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004254 return OR_Success;
4255}
4256
4257/// PrintOverloadCandidates - When overload resolution fails, prints
4258/// diagnostic messages containing the candidates in the candidate
4259/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump1eb44332009-09-09 15:08:12 +00004260void
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004261Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Fariborz Jahanian16a5eac2009-10-09 00:13:15 +00004262 bool OnlyViable,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004263 const char *Opc,
Fariborz Jahanian16a5eac2009-10-09 00:13:15 +00004264 SourceLocation OpLoc) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004265 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4266 LastCand = CandidateSet.end();
Fariborz Jahanian27687cf2009-10-12 17:51:19 +00004267 bool Reported = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004268 for (; Cand != LastCand; ++Cand) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004269 if (Cand->Viable || !OnlyViable) {
4270 if (Cand->Function) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004271 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004272 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004273 // Deleted or "unavailable" function.
4274 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
4275 << Cand->Function->isDeleted();
Douglas Gregor1fdd89b2009-09-15 20:11:42 +00004276 } else if (FunctionTemplateDecl *FunTmpl
4277 = Cand->Function->getPrimaryTemplate()) {
4278 // Function template specialization
4279 // FIXME: Give a better reason!
4280 Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
4281 << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
4282 *Cand->Function->getTemplateSpecializationArgs());
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004283 } else {
4284 // Normal function
Fariborz Jahanianb1663d02009-09-23 00:58:07 +00004285 bool errReported = false;
4286 if (!Cand->Viable && Cand->Conversions.size() > 0) {
4287 for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
4288 const ImplicitConversionSequence &Conversion =
4289 Cand->Conversions[i];
4290 if ((Conversion.ConversionKind !=
4291 ImplicitConversionSequence::BadConversion) ||
4292 Conversion.ConversionFunctionSet.size() == 0)
4293 continue;
4294 Diag(Cand->Function->getLocation(),
4295 diag::err_ovl_candidate_not_viable) << (i+1);
4296 errReported = true;
4297 for (int j = Conversion.ConversionFunctionSet.size()-1;
4298 j >= 0; j--) {
4299 FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
4300 Diag(Func->getLocation(), diag::err_ovl_candidate);
4301 }
4302 }
4303 }
4304 if (!errReported)
4305 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004306 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004307 } else if (Cand->IsSurrogate) {
Douglas Gregor621b3932008-11-21 02:54:28 +00004308 // Desugar the type of the surrogate down to a function type,
4309 // retaining as many typedefs as possible while still showing
4310 // the function type (and, therefore, its parameter types).
4311 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004312 bool isLValueReference = false;
4313 bool isRValueReference = false;
Douglas Gregor621b3932008-11-21 02:54:28 +00004314 bool isPointer = false;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004315 if (const LValueReferenceType *FnTypeRef =
Ted Kremenek6217b802009-07-29 21:53:49 +00004316 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor621b3932008-11-21 02:54:28 +00004317 FnType = FnTypeRef->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004318 isLValueReference = true;
4319 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenek6217b802009-07-29 21:53:49 +00004320 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004321 FnType = FnTypeRef->getPointeeType();
4322 isRValueReference = true;
Douglas Gregor621b3932008-11-21 02:54:28 +00004323 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004324 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor621b3932008-11-21 02:54:28 +00004325 FnType = FnTypePtr->getPointeeType();
4326 isPointer = true;
4327 }
4328 // Desugar down to a function type.
John McCall183700f2009-09-21 23:43:11 +00004329 FnType = QualType(FnType->getAs<FunctionType>(), 0);
Douglas Gregor621b3932008-11-21 02:54:28 +00004330 // Reconstruct the pointer/reference as appropriate.
4331 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004332 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
4333 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor621b3932008-11-21 02:54:28 +00004334
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004335 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattnerd1625842008-11-24 06:25:27 +00004336 << FnType;
Douglas Gregor33074752009-09-30 21:46:01 +00004337 } else if (OnlyViable) {
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004338 assert(Cand->Conversions.size() <= 2 &&
Fariborz Jahanianad3607d2009-10-09 17:09:58 +00004339 "builtin-binary-operator-not-binary");
Fariborz Jahanian866b2742009-10-16 23:25:02 +00004340 std::string TypeStr("operator");
4341 TypeStr += Opc;
4342 TypeStr += "(";
4343 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4344 if (Cand->Conversions.size() == 1) {
4345 TypeStr += ")";
4346 Diag(OpLoc, diag::err_ovl_builtin_unary_candidate) << TypeStr;
4347 }
4348 else {
4349 TypeStr += ", ";
4350 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4351 TypeStr += ")";
4352 Diag(OpLoc, diag::err_ovl_builtin_binary_candidate) << TypeStr;
4353 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004354 }
Fariborz Jahanian27687cf2009-10-12 17:51:19 +00004355 else if (!Cand->Viable && !Reported) {
4356 // Non-viability might be due to ambiguous user-defined conversions,
4357 // needed for built-in operators. Report them as well, but only once
4358 // as we have typically many built-in candidates.
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00004359 unsigned NoOperands = Cand->Conversions.size();
4360 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
Fariborz Jahanian27687cf2009-10-12 17:51:19 +00004361 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
4362 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion ||
4363 ICS.ConversionFunctionSet.empty())
4364 continue;
4365 if (CXXConversionDecl *Func = dyn_cast<CXXConversionDecl>(
4366 Cand->Conversions[ArgIdx].ConversionFunctionSet[0])) {
4367 QualType FromTy =
4368 QualType(
4369 static_cast<Type*>(ICS.UserDefined.Before.FromTypePtr),0);
4370 Diag(OpLoc,diag::note_ambiguous_type_conversion)
4371 << FromTy << Func->getConversionType();
4372 }
4373 for (unsigned j = 0; j < ICS.ConversionFunctionSet.size(); j++) {
4374 FunctionDecl *Func =
4375 Cand->Conversions[ArgIdx].ConversionFunctionSet[j];
4376 Diag(Func->getLocation(),diag::err_ovl_candidate);
4377 }
4378 }
4379 Reported = true;
4380 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004381 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004382 }
4383}
4384
Douglas Gregor904eed32008-11-10 20:40:00 +00004385/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4386/// an overloaded function (C++ [over.over]), where @p From is an
4387/// expression with overloaded function type and @p ToType is the type
4388/// we're trying to resolve to. For example:
4389///
4390/// @code
4391/// int f(double);
4392/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00004393///
Douglas Gregor904eed32008-11-10 20:40:00 +00004394/// int (*pfd)(double) = f; // selects f(double)
4395/// @endcode
4396///
4397/// This routine returns the resulting FunctionDecl if it could be
4398/// resolved, and NULL otherwise. When @p Complain is true, this
4399/// routine will emit diagnostics if there is an error.
4400FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00004401Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregor904eed32008-11-10 20:40:00 +00004402 bool Complain) {
4403 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00004404 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00004405 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00004406 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004407 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00004408 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00004409 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00004410 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00004411 FunctionType = MemTypePtr->getPointeeType();
4412 IsMember = true;
4413 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004414
4415 // We only look at pointers or references to functions.
Douglas Gregor72e771f2009-07-09 17:16:51 +00004416 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor83314aa2009-07-08 20:55:45 +00004417 if (!FunctionType->isFunctionType())
Douglas Gregor904eed32008-11-10 20:40:00 +00004418 return 0;
4419
4420 // Find the actual overloaded function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00004421
Douglas Gregor904eed32008-11-10 20:40:00 +00004422 // C++ [over.over]p1:
4423 // [...] [Note: any redundant set of parentheses surrounding the
4424 // overloaded function name is ignored (5.1). ]
4425 Expr *OvlExpr = From->IgnoreParens();
4426
4427 // C++ [over.over]p1:
4428 // [...] The overloaded function name can be preceded by the &
4429 // operator.
4430 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4431 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4432 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4433 }
4434
Anders Carlsson70534852009-10-20 22:53:47 +00004435 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00004436 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCallba135432009-11-21 08:51:07 +00004437
4438 llvm::SmallVector<NamedDecl*,8> Fns;
Anders Carlsson70534852009-10-20 22:53:47 +00004439
John McCall129e2df2009-11-30 22:42:35 +00004440 // Look into the overloaded expression.
John McCallf7a1a742009-11-24 19:00:30 +00004441 if (UnresolvedLookupExpr *UL
John McCallba135432009-11-21 08:51:07 +00004442 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4443 Fns.append(UL->decls_begin(), UL->decls_end());
John McCallf7a1a742009-11-24 19:00:30 +00004444 if (UL->hasExplicitTemplateArgs()) {
4445 HasExplicitTemplateArgs = true;
4446 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4447 }
John McCall129e2df2009-11-30 22:42:35 +00004448 } else if (UnresolvedMemberExpr *ME
4449 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4450 Fns.append(ME->decls_begin(), ME->decls_end());
4451 if (ME->hasExplicitTemplateArgs()) {
4452 HasExplicitTemplateArgs = true;
John McCalld5532b62009-11-23 01:53:49 +00004453 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00004454 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00004455 }
Mike Stump1eb44332009-09-09 15:08:12 +00004456
John McCallba135432009-11-21 08:51:07 +00004457 // If we didn't actually find anything, we're done.
4458 if (Fns.empty())
4459 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004460
Douglas Gregor904eed32008-11-10 20:40:00 +00004461 // Look through all of the overloaded functions, searching for one
4462 // whose type matches exactly.
Douglas Gregor00aeb522009-07-08 23:33:52 +00004463 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004464 bool FoundNonTemplateFunction = false;
John McCallba135432009-11-21 08:51:07 +00004465 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4466 E = Fns.end(); I != E; ++I) {
Douglas Gregor904eed32008-11-10 20:40:00 +00004467 // C++ [over.over]p3:
4468 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00004469 // targets of type "pointer-to-function" or "reference-to-function."
4470 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00004471 // type "pointer-to-member-function."
4472 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00004473
Mike Stump1eb44332009-09-09 15:08:12 +00004474 if (FunctionTemplateDecl *FunctionTemplate
John McCallba135432009-11-21 08:51:07 +00004475 = dyn_cast<FunctionTemplateDecl>(*I)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004476 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00004477 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004478 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00004479 // static when converting to member pointer.
4480 if (Method->isStatic() == IsMember)
4481 continue;
4482 } else if (IsMember)
4483 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00004484
Douglas Gregor00aeb522009-07-08 23:33:52 +00004485 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004486 // If the name is a function template, template argument deduction is
4487 // done (14.8.2.2), and if the argument deduction succeeds, the
4488 // resulting template argument list is used to generate a single
4489 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00004490 // overloaded functions considered.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004491 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor83314aa2009-07-08 20:55:45 +00004492 FunctionDecl *Specialization = 0;
4493 TemplateDeductionInfo Info(Context);
4494 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00004495 = DeduceTemplateArguments(FunctionTemplate,
4496 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
Douglas Gregor83314aa2009-07-08 20:55:45 +00004497 FunctionType, Specialization, Info)) {
4498 // FIXME: make a note of the failed deduction for diagnostics.
4499 (void)Result;
4500 } else {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004501 // FIXME: If the match isn't exact, shouldn't we just drop this as
4502 // a candidate? Find a testcase before changing the code.
Mike Stump1eb44332009-09-09 15:08:12 +00004503 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00004504 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor00aeb522009-07-08 23:33:52 +00004505 Matches.insert(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00004506 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor83314aa2009-07-08 20:55:45 +00004507 }
John McCallba135432009-11-21 08:51:07 +00004508
4509 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00004510 }
Mike Stump1eb44332009-09-09 15:08:12 +00004511
John McCallba135432009-11-21 08:51:07 +00004512 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00004513 // Skip non-static functions when converting to pointer, and static
4514 // when converting to member pointer.
4515 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00004516 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00004517
4518 // If we have explicit template arguments, skip non-templates.
4519 if (HasExplicitTemplateArgs)
4520 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004521 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00004522 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00004523
John McCallba135432009-11-21 08:51:07 +00004524 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*I)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00004525 QualType ResultTy;
4526 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
4527 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
4528 ResultTy)) {
John McCallba135432009-11-21 08:51:07 +00004529 Matches.insert(cast<FunctionDecl>(FunDecl->getCanonicalDecl()));
Douglas Gregor00aeb522009-07-08 23:33:52 +00004530 FoundNonTemplateFunction = true;
4531 }
Mike Stump1eb44332009-09-09 15:08:12 +00004532 }
Douglas Gregor904eed32008-11-10 20:40:00 +00004533 }
4534
Douglas Gregor00aeb522009-07-08 23:33:52 +00004535 // If there were 0 or 1 matches, we're done.
4536 if (Matches.empty())
4537 return 0;
Sebastian Redl07ab2022009-10-17 21:12:09 +00004538 else if (Matches.size() == 1) {
4539 FunctionDecl *Result = *Matches.begin();
4540 MarkDeclarationReferenced(From->getLocStart(), Result);
4541 return Result;
4542 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00004543
4544 // C++ [over.over]p4:
4545 // If more than one function is selected, [...]
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004546 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregor312a2022009-09-26 03:56:17 +00004547 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004548 // [...] and any given function template specialization F1 is
4549 // eliminated if the set contains a second function template
4550 // specialization whose function template is more specialized
4551 // than the function template of F1 according to the partial
4552 // ordering rules of 14.5.5.2.
4553
4554 // The algorithm specified above is quadratic. We instead use a
4555 // two-pass algorithm (similar to the one used to identify the
4556 // best viable function in an overload set) that identifies the
4557 // best function template (if it exists).
Sebastian Redl07ab2022009-10-17 21:12:09 +00004558 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
Douglas Gregor312a2022009-09-26 03:56:17 +00004559 Matches.end());
Sebastian Redl07ab2022009-10-17 21:12:09 +00004560 FunctionDecl *Result =
4561 getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4562 TPOC_Other, From->getLocStart(),
4563 PDiag(),
4564 PDiag(diag::err_addr_ovl_ambiguous)
4565 << TemplateMatches[0]->getDeclName(),
4566 PDiag(diag::err_ovl_template_candidate));
4567 MarkDeclarationReferenced(From->getLocStart(), Result);
4568 return Result;
Douglas Gregor00aeb522009-07-08 23:33:52 +00004569 }
Mike Stump1eb44332009-09-09 15:08:12 +00004570
Douglas Gregor312a2022009-09-26 03:56:17 +00004571 // [...] any function template specializations in the set are
4572 // eliminated if the set also contains a non-template function, [...]
4573 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4574 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4575 if ((*M)->getPrimaryTemplate() == 0)
4576 RemainingMatches.push_back(*M);
4577
Mike Stump1eb44332009-09-09 15:08:12 +00004578 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00004579 // selected function.
Sebastian Redl07ab2022009-10-17 21:12:09 +00004580 if (RemainingMatches.size() == 1) {
4581 FunctionDecl *Result = RemainingMatches.front();
4582 MarkDeclarationReferenced(From->getLocStart(), Result);
4583 return Result;
4584 }
Mike Stump1eb44332009-09-09 15:08:12 +00004585
Douglas Gregor00aeb522009-07-08 23:33:52 +00004586 // FIXME: We should probably return the same thing that BestViableFunction
4587 // returns (even if we issue the diagnostics here).
4588 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4589 << RemainingMatches[0]->getDeclName();
4590 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4591 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregor904eed32008-11-10 20:40:00 +00004592 return 0;
4593}
4594
Douglas Gregor4b52e252009-12-21 23:17:24 +00004595/// \brief Given an expression that refers to an overloaded function, try to
4596/// resolve that overloaded function expression down to a single function.
4597///
4598/// This routine can only resolve template-ids that refer to a single function
4599/// template, where that template-id refers to a single template whose template
4600/// arguments are either provided by the template-id or have defaults,
4601/// as described in C++0x [temp.arg.explicit]p3.
4602FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
4603 // C++ [over.over]p1:
4604 // [...] [Note: any redundant set of parentheses surrounding the
4605 // overloaded function name is ignored (5.1). ]
4606 Expr *OvlExpr = From->IgnoreParens();
4607
4608 // C++ [over.over]p1:
4609 // [...] The overloaded function name can be preceded by the &
4610 // operator.
4611 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4612 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4613 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4614 }
4615
4616 bool HasExplicitTemplateArgs = false;
4617 TemplateArgumentListInfo ExplicitTemplateArgs;
4618
4619 llvm::SmallVector<NamedDecl*,8> Fns;
4620
4621 // Look into the overloaded expression.
4622 if (UnresolvedLookupExpr *UL
4623 = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4624 Fns.append(UL->decls_begin(), UL->decls_end());
4625 if (UL->hasExplicitTemplateArgs()) {
4626 HasExplicitTemplateArgs = true;
4627 UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4628 }
4629 } else if (UnresolvedMemberExpr *ME
4630 = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4631 Fns.append(ME->decls_begin(), ME->decls_end());
4632 if (ME->hasExplicitTemplateArgs()) {
4633 HasExplicitTemplateArgs = true;
4634 ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4635 }
4636 }
4637
4638 // If we didn't actually find any template-ids, we're done.
4639 if (Fns.empty() || !HasExplicitTemplateArgs)
4640 return 0;
4641
4642 // Look through all of the overloaded functions, searching for one
4643 // whose type matches exactly.
4644 FunctionDecl *Matched = 0;
4645 for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4646 E = Fns.end(); I != E; ++I) {
4647 // C++0x [temp.arg.explicit]p3:
4648 // [...] In contexts where deduction is done and fails, or in contexts
4649 // where deduction is not done, if a template argument list is
4650 // specified and it, along with any default template arguments,
4651 // identifies a single function template specialization, then the
4652 // template-id is an lvalue for the function template specialization.
4653 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
4654
4655 // C++ [over.over]p2:
4656 // If the name is a function template, template argument deduction is
4657 // done (14.8.2.2), and if the argument deduction succeeds, the
4658 // resulting template argument list is used to generate a single
4659 // function template specialization, which is added to the set of
4660 // overloaded functions considered.
4661 // FIXME: We don't really want to build the specialization here, do we?
4662 FunctionDecl *Specialization = 0;
4663 TemplateDeductionInfo Info(Context);
4664 if (TemplateDeductionResult Result
4665 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
4666 Specialization, Info)) {
4667 // FIXME: make a note of the failed deduction for diagnostics.
4668 (void)Result;
4669 continue;
4670 }
4671
4672 // Multiple matches; we can't resolve to a single declaration.
4673 if (Matched)
4674 return 0;
4675
4676 Matched = Specialization;
4677 }
4678
4679 return Matched;
4680}
4681
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004682/// \brief Add a single candidate to the overload set.
4683static void AddOverloadedCallCandidate(Sema &S,
John McCallba135432009-11-21 08:51:07 +00004684 NamedDecl *Callee,
John McCalld5532b62009-11-23 01:53:49 +00004685 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004686 Expr **Args, unsigned NumArgs,
4687 OverloadCandidateSet &CandidateSet,
4688 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00004689 if (isa<UsingShadowDecl>(Callee))
4690 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
4691
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004692 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00004693 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004694 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4695 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004696 return;
John McCallba135432009-11-21 08:51:07 +00004697 }
4698
4699 if (FunctionTemplateDecl *FuncTemplate
4700 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00004701 S.AddTemplateOverloadCandidate(FuncTemplate, ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00004702 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00004703 return;
4704 }
4705
4706 assert(false && "unhandled case in overloaded call candidate");
4707
4708 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004709}
4710
4711/// \brief Add the overload candidates named by callee and/or found by argument
4712/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00004713void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004714 Expr **Args, unsigned NumArgs,
4715 OverloadCandidateSet &CandidateSet,
4716 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00004717
4718#ifndef NDEBUG
4719 // Verify that ArgumentDependentLookup is consistent with the rules
4720 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004721 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004722 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4723 // and let Y be the lookup set produced by argument dependent
4724 // lookup (defined as follows). If X contains
4725 //
4726 // -- a declaration of a class member, or
4727 //
4728 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00004729 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004730 //
4731 // -- a declaration that is neither a function or a function
4732 // template
4733 //
4734 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00004735
John McCall3b4294e2009-12-16 12:17:52 +00004736 if (ULE->requiresADL()) {
4737 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
4738 E = ULE->decls_end(); I != E; ++I) {
4739 assert(!(*I)->getDeclContext()->isRecord());
4740 assert(isa<UsingShadowDecl>(*I) ||
4741 !(*I)->getDeclContext()->isFunctionOrMethod());
4742 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00004743 }
4744 }
4745#endif
4746
John McCall3b4294e2009-12-16 12:17:52 +00004747 // It would be nice to avoid this copy.
4748 TemplateArgumentListInfo TABuffer;
4749 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
4750 if (ULE->hasExplicitTemplateArgs()) {
4751 ULE->copyTemplateArgumentsInto(TABuffer);
4752 ExplicitTemplateArgs = &TABuffer;
4753 }
4754
4755 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
4756 E = ULE->decls_end(); I != E; ++I)
John McCalld5532b62009-11-23 01:53:49 +00004757 AddOverloadedCallCandidate(*this, *I, ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00004758 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004759 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00004760
John McCall3b4294e2009-12-16 12:17:52 +00004761 if (ULE->requiresADL())
4762 AddArgumentDependentLookupCandidates(ULE->getName(), Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004763 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004764 CandidateSet,
4765 PartialOverloading);
4766}
John McCall578b69b2009-12-16 08:11:27 +00004767
John McCall3b4294e2009-12-16 12:17:52 +00004768static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
4769 Expr **Args, unsigned NumArgs) {
4770 Fn->Destroy(SemaRef.Context);
4771 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4772 Args[Arg]->Destroy(SemaRef.Context);
4773 return SemaRef.ExprError();
4774}
4775
John McCall578b69b2009-12-16 08:11:27 +00004776/// Attempts to recover from a call where no functions were found.
4777///
4778/// Returns true if new candidates were found.
John McCall3b4294e2009-12-16 12:17:52 +00004779static Sema::OwningExprResult
4780BuildRecoveryCallExpr(Sema &SemaRef, Expr *Fn,
4781 UnresolvedLookupExpr *ULE,
4782 SourceLocation LParenLoc,
4783 Expr **Args, unsigned NumArgs,
4784 SourceLocation *CommaLocs,
4785 SourceLocation RParenLoc) {
John McCall578b69b2009-12-16 08:11:27 +00004786
4787 CXXScopeSpec SS;
4788 if (ULE->getQualifier()) {
4789 SS.setScopeRep(ULE->getQualifier());
4790 SS.setRange(ULE->getQualifierRange());
4791 }
4792
John McCall3b4294e2009-12-16 12:17:52 +00004793 TemplateArgumentListInfo TABuffer;
4794 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
4795 if (ULE->hasExplicitTemplateArgs()) {
4796 ULE->copyTemplateArgumentsInto(TABuffer);
4797 ExplicitTemplateArgs = &TABuffer;
4798 }
4799
John McCall578b69b2009-12-16 08:11:27 +00004800 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
4801 Sema::LookupOrdinaryName);
4802 if (SemaRef.DiagnoseEmptyLookup(SS, R))
John McCall3b4294e2009-12-16 12:17:52 +00004803 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCall578b69b2009-12-16 08:11:27 +00004804
John McCall3b4294e2009-12-16 12:17:52 +00004805 assert(!R.empty() && "lookup results empty despite recovery");
4806
4807 // Build an implicit member call if appropriate. Just drop the
4808 // casts and such from the call, we don't really care.
4809 Sema::OwningExprResult NewFn = SemaRef.ExprError();
4810 if ((*R.begin())->isCXXClassMember())
4811 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
4812 else if (ExplicitTemplateArgs)
4813 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
4814 else
4815 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
4816
4817 if (NewFn.isInvalid())
4818 return Destroy(SemaRef, Fn, Args, NumArgs);
4819
4820 Fn->Destroy(SemaRef.Context);
4821
4822 // This shouldn't cause an infinite loop because we're giving it
4823 // an expression with non-empty lookup results, which should never
4824 // end up here.
4825 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
4826 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
4827 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00004828}
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004829
Douglas Gregorf6b89692008-11-26 05:54:23 +00004830/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00004831/// (which eventually refers to the declaration Func) and the call
4832/// arguments Args/NumArgs, attempt to resolve the function call down
4833/// to a specific function. If overload resolution succeeds, returns
4834/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00004835/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00004836/// arguments and Fn, and returns NULL.
John McCall3b4294e2009-12-16 12:17:52 +00004837Sema::OwningExprResult
4838Sema::BuildOverloadedCallExpr(Expr *Fn, UnresolvedLookupExpr *ULE,
4839 SourceLocation LParenLoc,
4840 Expr **Args, unsigned NumArgs,
4841 SourceLocation *CommaLocs,
4842 SourceLocation RParenLoc) {
4843#ifndef NDEBUG
4844 if (ULE->requiresADL()) {
4845 // To do ADL, we must have found an unqualified name.
4846 assert(!ULE->getQualifier() && "qualified name with ADL");
4847
4848 // We don't perform ADL for implicit declarations of builtins.
4849 // Verify that this was correctly set up.
4850 FunctionDecl *F;
4851 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
4852 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
4853 F->getBuiltinID() && F->isImplicit())
4854 assert(0 && "performing ADL for builtin");
4855
4856 // We don't perform ADL in C.
4857 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
4858 }
4859#endif
4860
Douglas Gregorf6b89692008-11-26 05:54:23 +00004861 OverloadCandidateSet CandidateSet;
Douglas Gregor17330012009-02-04 15:01:18 +00004862
John McCall3b4294e2009-12-16 12:17:52 +00004863 // Add the functions denoted by the callee to the set of candidate
4864 // functions, including those from argument-dependent lookup.
4865 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00004866
4867 // If we found nothing, try to recover.
4868 // AddRecoveryCallCandidates diagnoses the error itself, so we just
4869 // bailout out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00004870 if (CandidateSet.empty())
4871 return BuildRecoveryCallExpr(*this, Fn, ULE, LParenLoc, Args, NumArgs,
4872 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00004873
Douglas Gregorf6b89692008-11-26 05:54:23 +00004874 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004875 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00004876 case OR_Success: {
4877 FunctionDecl *FDecl = Best->Function;
4878 Fn = FixOverloadedFunctionReference(Fn, FDecl);
4879 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
4880 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00004881
4882 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00004883 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00004884 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00004885 << ULE->getName() << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00004886 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4887 break;
4888
4889 case OR_Ambiguous:
4890 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00004891 << ULE->getName() << Fn->getSourceRange();
Douglas Gregorf6b89692008-11-26 05:54:23 +00004892 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4893 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004894
4895 case OR_Deleted:
4896 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4897 << Best->Function->isDeleted()
John McCall3b4294e2009-12-16 12:17:52 +00004898 << ULE->getName()
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004899 << Fn->getSourceRange();
4900 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4901 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00004902 }
4903
4904 // Overload resolution failed. Destroy all of the subexpressions and
4905 // return NULL.
4906 Fn->Destroy(Context);
4907 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4908 Args[Arg]->Destroy(Context);
John McCall3b4294e2009-12-16 12:17:52 +00004909 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00004910}
4911
John McCall7453ed42009-11-22 00:44:51 +00004912static bool IsOverloaded(const Sema::FunctionSet &Functions) {
4913 return Functions.size() > 1 ||
4914 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
4915}
4916
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004917/// \brief Create a unary operation that may resolve to an overloaded
4918/// operator.
4919///
4920/// \param OpLoc The location of the operator itself (e.g., '*').
4921///
4922/// \param OpcIn The UnaryOperator::Opcode that describes this
4923/// operator.
4924///
4925/// \param Functions The set of non-member functions that will be
4926/// considered by overload resolution. The caller needs to build this
4927/// set based on the context using, e.g.,
4928/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4929/// set should not contain any member functions; those will be added
4930/// by CreateOverloadedUnaryOp().
4931///
4932/// \param input The input argument.
4933Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4934 unsigned OpcIn,
4935 FunctionSet &Functions,
Mike Stump1eb44332009-09-09 15:08:12 +00004936 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004937 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4938 Expr *Input = (Expr *)input.get();
4939
4940 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4941 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4942 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4943
4944 Expr *Args[2] = { Input, 0 };
4945 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004946
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004947 // For post-increment and post-decrement, add the implicit '0' as
4948 // the second argument, so that we know this is a post-increment or
4949 // post-decrement.
4950 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4951 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump1eb44332009-09-09 15:08:12 +00004952 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004953 SourceLocation());
4954 NumArgs = 2;
4955 }
4956
4957 if (Input->isTypeDependent()) {
John McCallba135432009-11-21 08:51:07 +00004958 UnresolvedLookupExpr *Fn
John McCallf7a1a742009-11-24 19:00:30 +00004959 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
4960 0, SourceRange(), OpName, OpLoc,
John McCall7453ed42009-11-22 00:44:51 +00004961 /*ADL*/ true, IsOverloaded(Functions));
Mike Stump1eb44332009-09-09 15:08:12 +00004962 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004963 FuncEnd = Functions.end();
4964 Func != FuncEnd; ++Func)
John McCallba135432009-11-21 08:51:07 +00004965 Fn->addDecl(*Func);
Mike Stump1eb44332009-09-09 15:08:12 +00004966
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004967 input.release();
4968 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4969 &Args[0], NumArgs,
4970 Context.DependentTy,
4971 OpLoc));
4972 }
4973
4974 // Build an empty overload set.
4975 OverloadCandidateSet CandidateSet;
4976
4977 // Add the candidates from the given function set.
4978 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4979
4980 // Add operator candidates that are member functions.
4981 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4982
4983 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00004984 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004985
4986 // Perform overload resolution.
4987 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00004988 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004989 case OR_Success: {
4990 // We found a built-in operator or an overloaded operator.
4991 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00004992
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004993 if (FnDecl) {
4994 // We matched an overloaded operator. Build a call to that
4995 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00004996
Douglas Gregorbc736fc2009-03-13 23:49:33 +00004997 // Convert the arguments.
4998 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4999 if (PerformObjectArgumentInitialization(Input, Method))
5000 return ExprError();
5001 } else {
5002 // Convert the arguments.
5003 if (PerformCopyInitialization(Input,
5004 FnDecl->getParamDecl(0)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +00005005 AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005006 return ExprError();
5007 }
5008
5009 // Determine the result type
Anders Carlsson26a2a072009-10-13 21:19:37 +00005010 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00005011
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005012 // Build the actual expression node.
5013 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5014 SourceLocation());
5015 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00005016
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005017 input.release();
Eli Friedman4c3b8962009-11-18 03:58:17 +00005018 Args[0] = Input;
Anders Carlsson26a2a072009-10-13 21:19:37 +00005019 ExprOwningPtr<CallExpr> TheCall(this,
5020 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman4c3b8962009-11-18 03:58:17 +00005021 Args, NumArgs, ResultTy, OpLoc));
Anders Carlsson26a2a072009-10-13 21:19:37 +00005022
5023 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5024 FnDecl))
5025 return ExprError();
5026
5027 return MaybeBindToTemporary(TheCall.release());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005028 } else {
5029 // We matched a built-in operator. Convert the arguments, then
5030 // break out so that we will build the appropriate built-in
5031 // operator node.
5032 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00005033 Best->Conversions[0], AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005034 return ExprError();
5035
5036 break;
5037 }
5038 }
5039
5040 case OR_No_Viable_Function:
5041 // No viable function; fall through to handling this as a
5042 // built-in operator, which will produce an error message for us.
5043 break;
5044
5045 case OR_Ambiguous:
5046 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5047 << UnaryOperator::getOpcodeStr(Opc)
5048 << Input->getSourceRange();
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005049 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5050 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005051 return ExprError();
5052
5053 case OR_Deleted:
5054 Diag(OpLoc, diag::err_ovl_deleted_oper)
5055 << Best->Function->isDeleted()
5056 << UnaryOperator::getOpcodeStr(Opc)
5057 << Input->getSourceRange();
5058 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5059 return ExprError();
5060 }
5061
5062 // Either we found no viable overloaded operator or we matched a
5063 // built-in operator. In either case, fall through to trying to
5064 // build a built-in operation.
5065 input.release();
5066 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5067}
5068
Douglas Gregor063daf62009-03-13 18:40:31 +00005069/// \brief Create a binary operation that may resolve to an overloaded
5070/// operator.
5071///
5072/// \param OpLoc The location of the operator itself (e.g., '+').
5073///
5074/// \param OpcIn The BinaryOperator::Opcode that describes this
5075/// operator.
5076///
5077/// \param Functions The set of non-member functions that will be
5078/// considered by overload resolution. The caller needs to build this
5079/// set based on the context using, e.g.,
5080/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5081/// set should not contain any member functions; those will be added
5082/// by CreateOverloadedBinOp().
5083///
5084/// \param LHS Left-hand argument.
5085/// \param RHS Right-hand argument.
Mike Stump1eb44332009-09-09 15:08:12 +00005086Sema::OwningExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00005087Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005088 unsigned OpcIn,
Douglas Gregor063daf62009-03-13 18:40:31 +00005089 FunctionSet &Functions,
5090 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00005091 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005092 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00005093
5094 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5095 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5096 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5097
5098 // If either side is type-dependent, create an appropriate dependent
5099 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005100 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00005101 if (Functions.empty()) {
5102 // If there are no functions to store, just build a dependent
5103 // BinaryOperator or CompoundAssignment.
5104 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
5105 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
5106 Context.DependentTy, OpLoc));
5107
5108 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
5109 Context.DependentTy,
5110 Context.DependentTy,
5111 Context.DependentTy,
5112 OpLoc));
5113 }
5114
John McCallba135432009-11-21 08:51:07 +00005115 UnresolvedLookupExpr *Fn
John McCallf7a1a742009-11-24 19:00:30 +00005116 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5117 0, SourceRange(), OpName, OpLoc,
John McCall7453ed42009-11-22 00:44:51 +00005118 /* ADL */ true, IsOverloaded(Functions));
John McCallba135432009-11-21 08:51:07 +00005119
Mike Stump1eb44332009-09-09 15:08:12 +00005120 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor063daf62009-03-13 18:40:31 +00005121 FuncEnd = Functions.end();
5122 Func != FuncEnd; ++Func)
John McCallba135432009-11-21 08:51:07 +00005123 Fn->addDecl(*Func);
Mike Stump1eb44332009-09-09 15:08:12 +00005124
Douglas Gregor063daf62009-03-13 18:40:31 +00005125 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00005126 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00005127 Context.DependentTy,
5128 OpLoc));
5129 }
5130
5131 // If this is the .* operator, which is not overloadable, just
5132 // create a built-in binary operator.
5133 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005134 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00005135
Sebastian Redl275c2b42009-11-18 23:10:33 +00005136 // If this is the assignment operator, we only perform overload resolution
5137 // if the left-hand side is a class or enumeration type. This is actually
5138 // a hack. The standard requires that we do overload resolution between the
5139 // various built-in candidates, but as DR507 points out, this can lead to
5140 // problems. So we do it this way, which pretty much follows what GCC does.
5141 // Note that we go the traditional code path for compound assignment forms.
5142 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005143 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00005144
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005145 // Build an empty overload set.
5146 OverloadCandidateSet CandidateSet;
Douglas Gregor063daf62009-03-13 18:40:31 +00005147
5148 // Add the candidates from the given function set.
5149 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
5150
5151 // Add operator candidates that are member functions.
5152 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
5153
5154 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00005155 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00005156
5157 // Perform overload resolution.
5158 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005159 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005160 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00005161 // We found a built-in operator or an overloaded operator.
5162 FunctionDecl *FnDecl = Best->Function;
5163
5164 if (FnDecl) {
5165 // We matched an overloaded operator. Build a call to that
5166 // operator.
5167
5168 // Convert the arguments.
5169 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005170 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5171 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +00005172 AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00005173 return ExprError();
5174 } else {
5175 // Convert the arguments.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005176 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +00005177 AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005178 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +00005179 AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00005180 return ExprError();
5181 }
5182
5183 // Determine the result type
5184 QualType ResultTy
John McCall183700f2009-09-21 23:43:11 +00005185 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor063daf62009-03-13 18:40:31 +00005186 ResultTy = ResultTy.getNonReferenceType();
5187
5188 // Build the actual expression node.
5189 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00005190 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00005191 UsualUnaryConversions(FnExpr);
5192
Anders Carlsson15ea3782009-10-13 22:43:21 +00005193 ExprOwningPtr<CXXOperatorCallExpr>
5194 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
5195 Args, 2, ResultTy,
5196 OpLoc));
5197
5198 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5199 FnDecl))
5200 return ExprError();
5201
5202 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor063daf62009-03-13 18:40:31 +00005203 } else {
5204 // We matched a built-in operator. Convert the arguments, then
5205 // break out so that we will build the appropriate built-in
5206 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005207 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00005208 Best->Conversions[0], AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005209 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00005210 Best->Conversions[1], AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00005211 return ExprError();
5212
5213 break;
5214 }
5215 }
5216
Douglas Gregor33074752009-09-30 21:46:01 +00005217 case OR_No_Viable_Function: {
5218 // C++ [over.match.oper]p9:
5219 // If the operator is the operator , [...] and there are no
5220 // viable functions, then the operator is assumed to be the
5221 // built-in operator and interpreted according to clause 5.
5222 if (Opc == BinaryOperator::Comma)
5223 break;
5224
Sebastian Redl8593c782009-05-21 11:50:50 +00005225 // For class as left operand for assignment or compound assigment operator
5226 // do not fall through to handling in built-in, but report that no overloaded
5227 // assignment operator found
Douglas Gregor33074752009-09-30 21:46:01 +00005228 OwningExprResult Result = ExprError();
5229 if (Args[0]->getType()->isRecordType() &&
5230 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00005231 Diag(OpLoc, diag::err_ovl_no_viable_oper)
5232 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005233 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00005234 } else {
5235 // No viable function; try to create a built-in operation, which will
5236 // produce an error. Then, show the non-viable candidates.
5237 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00005238 }
Douglas Gregor33074752009-09-30 21:46:01 +00005239 assert(Result.isInvalid() &&
5240 "C++ binary operator overloading is missing candidates!");
5241 if (Result.isInvalid())
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005242 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5243 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00005244 return move(Result);
5245 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005246
5247 case OR_Ambiguous:
5248 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
5249 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005250 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005251 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5252 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00005253 return ExprError();
5254
5255 case OR_Deleted:
5256 Diag(OpLoc, diag::err_ovl_deleted_oper)
5257 << Best->Function->isDeleted()
5258 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005259 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor063daf62009-03-13 18:40:31 +00005260 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5261 return ExprError();
5262 }
5263
Douglas Gregor33074752009-09-30 21:46:01 +00005264 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00005265 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00005266}
5267
Sebastian Redlf322ed62009-10-29 20:17:01 +00005268Action::OwningExprResult
5269Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5270 SourceLocation RLoc,
5271 ExprArg Base, ExprArg Idx) {
5272 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5273 static_cast<Expr*>(Idx.get()) };
5274 DeclarationName OpName =
5275 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5276
5277 // If either side is type-dependent, create an appropriate dependent
5278 // expression.
5279 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5280
John McCallba135432009-11-21 08:51:07 +00005281 UnresolvedLookupExpr *Fn
John McCallf7a1a742009-11-24 19:00:30 +00005282 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5283 0, SourceRange(), OpName, LLoc,
John McCall7453ed42009-11-22 00:44:51 +00005284 /*ADL*/ true, /*Overloaded*/ false);
John McCallf7a1a742009-11-24 19:00:30 +00005285 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00005286
5287 Base.release();
5288 Idx.release();
5289 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5290 Args, 2,
5291 Context.DependentTy,
5292 RLoc));
5293 }
5294
5295 // Build an empty overload set.
5296 OverloadCandidateSet CandidateSet;
5297
5298 // Subscript can only be overloaded as a member function.
5299
5300 // Add operator candidates that are member functions.
5301 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5302
5303 // Add builtin operator candidates.
5304 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5305
5306 // Perform overload resolution.
5307 OverloadCandidateSet::iterator Best;
5308 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5309 case OR_Success: {
5310 // We found a built-in operator or an overloaded operator.
5311 FunctionDecl *FnDecl = Best->Function;
5312
5313 if (FnDecl) {
5314 // We matched an overloaded operator. Build a call to that
5315 // operator.
5316
5317 // Convert the arguments.
5318 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5319 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5320 PerformCopyInitialization(Args[1],
5321 FnDecl->getParamDecl(0)->getType(),
Douglas Gregor68647482009-12-16 03:45:30 +00005322 AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00005323 return ExprError();
5324
5325 // Determine the result type
5326 QualType ResultTy
5327 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5328 ResultTy = ResultTy.getNonReferenceType();
5329
5330 // Build the actual expression node.
5331 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5332 LLoc);
5333 UsualUnaryConversions(FnExpr);
5334
5335 Base.release();
5336 Idx.release();
5337 ExprOwningPtr<CXXOperatorCallExpr>
5338 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5339 FnExpr, Args, 2,
5340 ResultTy, RLoc));
5341
5342 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5343 FnDecl))
5344 return ExprError();
5345
5346 return MaybeBindToTemporary(TheCall.release());
5347 } else {
5348 // We matched a built-in operator. Convert the arguments, then
5349 // break out so that we will build the appropriate built-in
5350 // operator node.
5351 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00005352 Best->Conversions[0], AA_Passing) ||
Sebastian Redlf322ed62009-10-29 20:17:01 +00005353 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00005354 Best->Conversions[1], AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00005355 return ExprError();
5356
5357 break;
5358 }
5359 }
5360
5361 case OR_No_Viable_Function: {
5362 // No viable function; try to create a built-in operation, which will
5363 // produce an error. Then, show the non-viable candidates.
5364 OwningExprResult Result =
5365 CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
5366 assert(Result.isInvalid() &&
5367 "C++ subscript operator overloading is missing candidates!");
5368 if (Result.isInvalid())
5369 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5370 "[]", LLoc);
5371 return move(Result);
5372 }
5373
5374 case OR_Ambiguous:
5375 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5376 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5377 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5378 "[]", LLoc);
5379 return ExprError();
5380
5381 case OR_Deleted:
5382 Diag(LLoc, diag::err_ovl_deleted_oper)
5383 << Best->Function->isDeleted() << "[]"
5384 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5385 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5386 return ExprError();
5387 }
5388
5389 // We matched a built-in operator; build it.
5390 Base.release();
5391 Idx.release();
5392 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5393 Owned(Args[1]), RLoc);
5394}
5395
Douglas Gregor88a35142008-12-22 05:46:06 +00005396/// BuildCallToMemberFunction - Build a call to a member
5397/// function. MemExpr is the expression that refers to the member
5398/// function (and includes the object parameter), Args/NumArgs are the
5399/// arguments to the function call (not including the object
5400/// parameter). The caller needs to validate that the member
5401/// expression refers to a member function or an overloaded member
5402/// function.
John McCallaa81e162009-12-01 22:10:20 +00005403Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00005404Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5405 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor88a35142008-12-22 05:46:06 +00005406 unsigned NumArgs, SourceLocation *CommaLocs,
5407 SourceLocation RParenLoc) {
5408 // Dig out the member expression. This holds both the object
5409 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00005410 Expr *NakedMemExpr = MemExprE->IgnoreParens();
5411
John McCall129e2df2009-11-30 22:42:35 +00005412 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00005413 CXXMethodDecl *Method = 0;
John McCall129e2df2009-11-30 22:42:35 +00005414 if (isa<MemberExpr>(NakedMemExpr)) {
5415 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00005416 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5417 } else {
5418 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
John McCallaa81e162009-12-01 22:10:20 +00005419
John McCall701c89e2009-12-03 04:06:58 +00005420 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00005421
Douglas Gregor88a35142008-12-22 05:46:06 +00005422 // Add overload candidates
5423 OverloadCandidateSet CandidateSet;
Mike Stump1eb44332009-09-09 15:08:12 +00005424
John McCallaa81e162009-12-01 22:10:20 +00005425 // FIXME: avoid copy.
5426 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5427 if (UnresExpr->hasExplicitTemplateArgs()) {
5428 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5429 TemplateArgs = &TemplateArgsBuffer;
5430 }
5431
John McCall129e2df2009-11-30 22:42:35 +00005432 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
5433 E = UnresExpr->decls_end(); I != E; ++I) {
5434
John McCall701c89e2009-12-03 04:06:58 +00005435 NamedDecl *Func = *I;
5436 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
5437 if (isa<UsingShadowDecl>(Func))
5438 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
5439
John McCall129e2df2009-11-30 22:42:35 +00005440 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005441 // If explicit template arguments were provided, we can't call a
5442 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00005443 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005444 continue;
5445
John McCall701c89e2009-12-03 04:06:58 +00005446 AddMethodCandidate(Method, ActingDC, ObjectType, Args, NumArgs,
5447 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00005448 } else {
John McCall129e2df2009-11-30 22:42:35 +00005449 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall701c89e2009-12-03 04:06:58 +00005450 ActingDC, TemplateArgs,
5451 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00005452 CandidateSet,
5453 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00005454 }
Douglas Gregordec06662009-08-21 18:42:58 +00005455 }
Mike Stump1eb44332009-09-09 15:08:12 +00005456
John McCall129e2df2009-11-30 22:42:35 +00005457 DeclarationName DeclName = UnresExpr->getMemberName();
5458
Douglas Gregor88a35142008-12-22 05:46:06 +00005459 OverloadCandidateSet::iterator Best;
John McCall129e2df2009-11-30 22:42:35 +00005460 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005461 case OR_Success:
5462 Method = cast<CXXMethodDecl>(Best->Function);
5463 break;
5464
5465 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00005466 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00005467 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00005468 << DeclName << MemExprE->getSourceRange();
Douglas Gregor88a35142008-12-22 05:46:06 +00005469 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5470 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00005471 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00005472
5473 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00005474 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00005475 << DeclName << MemExprE->getSourceRange();
Douglas Gregor88a35142008-12-22 05:46:06 +00005476 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5477 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00005478 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005479
5480 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00005481 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005482 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00005483 << DeclName << MemExprE->getSourceRange();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005484 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5485 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00005486 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00005487 }
5488
Douglas Gregor699ee522009-11-20 19:42:02 +00005489 MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
John McCallaa81e162009-12-01 22:10:20 +00005490
John McCallaa81e162009-12-01 22:10:20 +00005491 // If overload resolution picked a static member, build a
5492 // non-member call based on that function.
5493 if (Method->isStatic()) {
5494 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
5495 Args, NumArgs, RParenLoc);
5496 }
5497
John McCall129e2df2009-11-30 22:42:35 +00005498 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00005499 }
5500
5501 assert(Method && "Member call to something that isn't a method?");
Mike Stump1eb44332009-09-09 15:08:12 +00005502 ExprOwningPtr<CXXMemberCallExpr>
John McCallaa81e162009-12-01 22:10:20 +00005503 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump1eb44332009-09-09 15:08:12 +00005504 NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00005505 Method->getResultType().getNonReferenceType(),
5506 RParenLoc));
5507
Anders Carlssoneed3e692009-10-10 00:06:20 +00005508 // Check for a valid return type.
5509 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5510 TheCall.get(), Method))
John McCallaa81e162009-12-01 22:10:20 +00005511 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00005512
Douglas Gregor88a35142008-12-22 05:46:06 +00005513 // Convert the object argument (for a non-static member function call).
John McCallaa81e162009-12-01 22:10:20 +00005514 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00005515 if (!Method->isStatic() &&
Douglas Gregor88a35142008-12-22 05:46:06 +00005516 PerformObjectArgumentInitialization(ObjectArg, Method))
John McCallaa81e162009-12-01 22:10:20 +00005517 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00005518 MemExpr->setBase(ObjectArg);
5519
5520 // Convert the rest of the arguments
Douglas Gregor72564e72009-02-26 23:50:07 +00005521 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00005522 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00005523 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00005524 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00005525
Anders Carlssond406bf02009-08-16 01:56:34 +00005526 if (CheckFunctionCall(Method, TheCall.get()))
John McCallaa81e162009-12-01 22:10:20 +00005527 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00005528
John McCallaa81e162009-12-01 22:10:20 +00005529 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor88a35142008-12-22 05:46:06 +00005530}
5531
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005532/// BuildCallToObjectOfClassType - Build a call to an object of class
5533/// type (C++ [over.call.object]), which can end up invoking an
5534/// overloaded function call operator (@c operator()) or performing a
5535/// user-defined conversion on the object argument.
Mike Stump1eb44332009-09-09 15:08:12 +00005536Sema::ExprResult
5537Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00005538 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005539 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00005540 SourceLocation *CommaLocs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005541 SourceLocation RParenLoc) {
5542 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00005543 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005544
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005545 // C++ [over.call.object]p1:
5546 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00005547 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005548 // candidate functions includes at least the function call
5549 // operators of T. The function call operators of T are obtained by
5550 // ordinary lookup of the name operator() in the context of
5551 // (E).operator().
5552 OverloadCandidateSet CandidateSet;
Douglas Gregor44b43212008-12-11 16:49:14 +00005553 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00005554
5555 if (RequireCompleteType(LParenLoc, Object->getType(),
5556 PartialDiagnostic(diag::err_incomplete_object_call)
5557 << Object->getSourceRange()))
5558 return true;
5559
John McCalla24dc2e2009-11-17 02:14:36 +00005560 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
5561 LookupQualifiedName(R, Record->getDecl());
5562 R.suppressDiagnostics();
5563
Douglas Gregor593564b2009-11-15 07:48:03 +00005564 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00005565 Oper != OperEnd; ++Oper) {
John McCall701c89e2009-12-03 04:06:58 +00005566 AddMethodCandidate(*Oper, Object->getType(), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00005567 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00005568 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00005569
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005570 // C++ [over.call.object]p2:
5571 // In addition, for each conversion function declared in T of the
5572 // form
5573 //
5574 // operator conversion-type-id () cv-qualifier;
5575 //
5576 // where cv-qualifier is the same cv-qualification as, or a
5577 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00005578 // denotes the type "pointer to function of (P1,...,Pn) returning
5579 // R", or the type "reference to pointer to function of
5580 // (P1,...,Pn) returning R", or the type "reference to function
5581 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005582 // is also considered as a candidate function. Similarly,
5583 // surrogate call functions are added to the set of candidate
5584 // functions for each conversion function declared in an
5585 // accessible base class provided the function is not hidden
5586 // within T by another intervening declaration.
Douglas Gregor4a27d702009-10-21 06:18:39 +00005587 // FIXME: Look in base classes for more conversion operators!
John McCallba135432009-11-21 08:51:07 +00005588 const UnresolvedSet *Conversions
Douglas Gregor4a27d702009-10-21 06:18:39 +00005589 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
John McCallba135432009-11-21 08:51:07 +00005590 for (UnresolvedSet::iterator I = Conversions->begin(),
5591 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00005592 NamedDecl *D = *I;
5593 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5594 if (isa<UsingShadowDecl>(D))
5595 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5596
Douglas Gregor4a27d702009-10-21 06:18:39 +00005597 // Skip over templated conversion functions; they aren't
5598 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00005599 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00005600 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005601
John McCall701c89e2009-12-03 04:06:58 +00005602 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00005603
Douglas Gregor4a27d702009-10-21 06:18:39 +00005604 // Strip the reference type (if any) and then the pointer type (if
5605 // any) to get down to what might be a function type.
5606 QualType ConvType = Conv->getConversionType().getNonReferenceType();
5607 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5608 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005609
Douglas Gregor4a27d702009-10-21 06:18:39 +00005610 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall701c89e2009-12-03 04:06:58 +00005611 AddSurrogateCandidate(Conv, ActingContext, Proto,
5612 Object->getType(), Args, NumArgs,
5613 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005614 }
Mike Stump1eb44332009-09-09 15:08:12 +00005615
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005616 // Perform overload resolution.
5617 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005618 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005619 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005620 // Overload resolution succeeded; we'll build the appropriate call
5621 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005622 break;
5623
5624 case OR_No_Viable_Function:
Mike Stump1eb44332009-09-09 15:08:12 +00005625 Diag(Object->getSourceRange().getBegin(),
Sebastian Redle4c452c2008-11-22 13:44:36 +00005626 diag::err_ovl_no_viable_object_call)
Chris Lattner4330d652009-02-17 07:29:20 +00005627 << Object->getType() << Object->getSourceRange();
Sebastian Redle4c452c2008-11-22 13:44:36 +00005628 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005629 break;
5630
5631 case OR_Ambiguous:
5632 Diag(Object->getSourceRange().getBegin(),
5633 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00005634 << Object->getType() << Object->getSourceRange();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005635 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5636 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005637
5638 case OR_Deleted:
5639 Diag(Object->getSourceRange().getBegin(),
5640 diag::err_ovl_deleted_object_call)
5641 << Best->Function->isDeleted()
5642 << Object->getType() << Object->getSourceRange();
5643 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5644 break;
Mike Stump1eb44332009-09-09 15:08:12 +00005645 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005646
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005647 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005648 // We had an error; delete all of the subexpressions and return
5649 // the error.
Ted Kremenek8189cde2009-02-07 01:47:29 +00005650 Object->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005651 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek8189cde2009-02-07 01:47:29 +00005652 Args[ArgIdx]->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005653 return true;
5654 }
5655
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005656 if (Best->Function == 0) {
5657 // Since there is no function declaration, this is one of the
5658 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00005659 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005660 = cast<CXXConversionDecl>(
5661 Best->Conversions[0].UserDefined.ConversionFunction);
5662
5663 // We selected one of the surrogate functions that converts the
5664 // object parameter to a function pointer. Perform the conversion
5665 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00005666
5667 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00005668 // and then call it.
Eli Friedmanc8c771e2009-12-09 04:52:43 +00005669 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00005670
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00005671 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00005672 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
5673 CommaLocs, RParenLoc).release();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005674 }
5675
5676 // We found an overloaded operator(). Build a CXXOperatorCallExpr
5677 // that calls this method, using Object for the implicit object
5678 // parameter and passing along the remaining arguments.
5679 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00005680 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005681
5682 unsigned NumArgsInProto = Proto->getNumArgs();
5683 unsigned NumArgsToCheck = NumArgs;
5684
5685 // Build the full argument list for the method call (the
5686 // implicit object parameter is placed at the beginning of the
5687 // list).
5688 Expr **MethodArgs;
5689 if (NumArgs < NumArgsInProto) {
5690 NumArgsToCheck = NumArgsInProto;
5691 MethodArgs = new Expr*[NumArgsInProto + 1];
5692 } else {
5693 MethodArgs = new Expr*[NumArgs + 1];
5694 }
5695 MethodArgs[0] = Object;
5696 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5697 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00005698
5699 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00005700 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005701 UsualUnaryConversions(NewFn);
5702
5703 // Once we've built TheCall, all of the expressions are properly
5704 // owned.
5705 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00005706 ExprOwningPtr<CXXOperatorCallExpr>
5707 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor063daf62009-03-13 18:40:31 +00005708 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00005709 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005710 delete [] MethodArgs;
5711
Anders Carlsson07d68f12009-10-13 21:49:31 +00005712 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
5713 Method))
5714 return true;
5715
Douglas Gregor518fda12009-01-13 05:10:00 +00005716 // We may have default arguments. If so, we need to allocate more
5717 // slots in the call for them.
5718 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00005719 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00005720 else if (NumArgs > NumArgsInProto)
5721 NumArgsToCheck = NumArgsInProto;
5722
Chris Lattner312531a2009-04-12 08:11:20 +00005723 bool IsError = false;
5724
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005725 // Initialize the implicit object parameter.
Chris Lattner312531a2009-04-12 08:11:20 +00005726 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005727 TheCall->setArg(0, Object);
5728
Chris Lattner312531a2009-04-12 08:11:20 +00005729
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005730 // Check the argument types.
5731 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005732 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00005733 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005734 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00005735
Douglas Gregor518fda12009-01-13 05:10:00 +00005736 // Pass the argument.
5737 QualType ProtoArgType = Proto->getArgType(i);
Douglas Gregor68647482009-12-16 03:45:30 +00005738 IsError |= PerformCopyInitialization(Arg, ProtoArgType, AA_Passing);
Douglas Gregor518fda12009-01-13 05:10:00 +00005739 } else {
Douglas Gregord47c47d2009-11-09 19:27:57 +00005740 OwningExprResult DefArg
5741 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
5742 if (DefArg.isInvalid()) {
5743 IsError = true;
5744 break;
5745 }
5746
5747 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00005748 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005749
5750 TheCall->setArg(i + 1, Arg);
5751 }
5752
5753 // If this is a variadic call, handle args passed through "...".
5754 if (Proto->isVariadic()) {
5755 // Promote the arguments (C99 6.5.2.2p7).
5756 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
5757 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00005758 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005759 TheCall->setArg(i + 1, Arg);
5760 }
5761 }
5762
Chris Lattner312531a2009-04-12 08:11:20 +00005763 if (IsError) return true;
5764
Anders Carlssond406bf02009-08-16 01:56:34 +00005765 if (CheckFunctionCall(Method, TheCall.get()))
5766 return true;
5767
Anders Carlssona303f9e2009-08-16 03:53:54 +00005768 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00005769}
5770
Douglas Gregor8ba10742008-11-20 16:27:02 +00005771/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00005772/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00005773/// @c Member is the name of the member we're trying to find.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005774Sema::OwningExprResult
5775Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
5776 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor8ba10742008-11-20 16:27:02 +00005777 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00005778
Douglas Gregor8ba10742008-11-20 16:27:02 +00005779 // C++ [over.ref]p1:
5780 //
5781 // [...] An expression x->m is interpreted as (x.operator->())->m
5782 // for a class object x of type T if T::operator->() exists and if
5783 // the operator is selected as the best match function by the
5784 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00005785 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
5786 OverloadCandidateSet CandidateSet;
Ted Kremenek6217b802009-07-29 21:53:49 +00005787 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005788
Eli Friedmanf43fb722009-11-18 01:28:03 +00005789 if (RequireCompleteType(Base->getLocStart(), Base->getType(),
5790 PDiag(diag::err_typecheck_incomplete_tag)
5791 << Base->getSourceRange()))
5792 return ExprError();
5793
John McCalla24dc2e2009-11-17 02:14:36 +00005794 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
5795 LookupQualifiedName(R, BaseRecord->getDecl());
5796 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00005797
5798 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00005799 Oper != OperEnd; ++Oper) {
5800 NamedDecl *D = *Oper;
5801 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5802 if (isa<UsingShadowDecl>(D))
5803 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5804
5805 AddMethodCandidate(cast<CXXMethodDecl>(D), ActingContext,
5806 Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00005807 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00005808 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00005809
5810 // Perform overload resolution.
5811 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00005812 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00005813 case OR_Success:
5814 // Overload resolution succeeded; we'll build the call below.
5815 break;
5816
5817 case OR_No_Viable_Function:
5818 if (CandidateSet.empty())
5819 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005820 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005821 else
5822 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005823 << "operator->" << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005824 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005825 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005826
5827 case OR_Ambiguous:
5828 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00005829 << "->" << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005830 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005831 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005832
5833 case OR_Deleted:
5834 Diag(OpLoc, diag::err_ovl_deleted_oper)
5835 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00005836 << "->" << Base->getSourceRange();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005837 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005838 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005839 }
5840
5841 // Convert the object parameter.
5842 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregorfc195ef2008-11-21 03:04:22 +00005843 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005844 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00005845
5846 // No concerns about early exits now.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00005847 BaseIn.release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00005848
5849 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00005850 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5851 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00005852 UsualUnaryConversions(FnExpr);
Anders Carlsson15ea3782009-10-13 22:43:21 +00005853
5854 QualType ResultTy = Method->getResultType().getNonReferenceType();
5855 ExprOwningPtr<CXXOperatorCallExpr>
5856 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
5857 &Base, 1, ResultTy, OpLoc));
5858
5859 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
5860 Method))
5861 return ExprError();
5862 return move(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00005863}
5864
Douglas Gregor904eed32008-11-10 20:40:00 +00005865/// FixOverloadedFunctionReference - E is an expression that refers to
5866/// a C++ overloaded function (possibly with some parentheses and
5867/// perhaps a '&' around it). We have resolved the overloaded function
5868/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00005869/// refer (possibly indirectly) to Fn. Returns the new expr.
5870Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005871 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Douglas Gregor699ee522009-11-20 19:42:02 +00005872 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
5873 if (SubExpr == PE->getSubExpr())
5874 return PE->Retain();
5875
5876 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
5877 }
5878
5879 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5880 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00005881 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00005882 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00005883 "Implicit cast type cannot be determined from overload");
Douglas Gregor699ee522009-11-20 19:42:02 +00005884 if (SubExpr == ICE->getSubExpr())
5885 return ICE->Retain();
5886
5887 return new (Context) ImplicitCastExpr(ICE->getType(),
5888 ICE->getCastKind(),
5889 SubExpr,
5890 ICE->isLvalueCast());
5891 }
5892
5893 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump1eb44332009-09-09 15:08:12 +00005894 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00005895 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00005896 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5897 if (Method->isStatic()) {
5898 // Do nothing: static member functions aren't any different
5899 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00005900 } else {
John McCallf7a1a742009-11-24 19:00:30 +00005901 // Fix the sub expression, which really has to be an
5902 // UnresolvedLookupExpr holding an overloaded member function
5903 // or template.
John McCallba135432009-11-21 08:51:07 +00005904 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5905 if (SubExpr == UnOp->getSubExpr())
5906 return UnOp->Retain();
Douglas Gregor699ee522009-11-20 19:42:02 +00005907
John McCallba135432009-11-21 08:51:07 +00005908 assert(isa<DeclRefExpr>(SubExpr)
5909 && "fixed to something other than a decl ref");
5910 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
5911 && "fixed to a member ref with no nested name qualifier");
5912
5913 // We have taken the address of a pointer to member
5914 // function. Perform the computation here so that we get the
5915 // appropriate pointer to member type.
5916 QualType ClassType
5917 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
5918 QualType MemPtrType
5919 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
5920
5921 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
5922 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00005923 }
5924 }
Douglas Gregor699ee522009-11-20 19:42:02 +00005925 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5926 if (SubExpr == UnOp->getSubExpr())
5927 return UnOp->Retain();
Anders Carlsson96ad5332009-10-21 17:16:23 +00005928
Douglas Gregor699ee522009-11-20 19:42:02 +00005929 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
5930 Context.getPointerType(SubExpr->getType()),
5931 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00005932 }
John McCallba135432009-11-21 08:51:07 +00005933
5934 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00005935 // FIXME: avoid copy.
5936 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00005937 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00005938 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
5939 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00005940 }
5941
John McCallba135432009-11-21 08:51:07 +00005942 return DeclRefExpr::Create(Context,
5943 ULE->getQualifier(),
5944 ULE->getQualifierRange(),
5945 Fn,
5946 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00005947 Fn->getType(),
5948 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00005949 }
5950
John McCall129e2df2009-11-30 22:42:35 +00005951 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00005952 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00005953 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5954 if (MemExpr->hasExplicitTemplateArgs()) {
5955 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5956 TemplateArgs = &TemplateArgsBuffer;
5957 }
John McCalld5532b62009-11-23 01:53:49 +00005958
John McCallaa81e162009-12-01 22:10:20 +00005959 Expr *Base;
5960
5961 // If we're filling in
5962 if (MemExpr->isImplicitAccess()) {
5963 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
5964 return DeclRefExpr::Create(Context,
5965 MemExpr->getQualifier(),
5966 MemExpr->getQualifierRange(),
5967 Fn,
5968 MemExpr->getMemberLoc(),
5969 Fn->getType(),
5970 TemplateArgs);
5971 } else
5972 Base = new (Context) CXXThisExpr(SourceLocation(),
5973 MemExpr->getBaseType());
5974 } else
5975 Base = MemExpr->getBase()->Retain();
5976
5977 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00005978 MemExpr->isArrow(),
5979 MemExpr->getQualifier(),
5980 MemExpr->getQualifierRange(),
5981 Fn,
John McCalld5532b62009-11-23 01:53:49 +00005982 MemExpr->getMemberLoc(),
John McCallaa81e162009-12-01 22:10:20 +00005983 TemplateArgs,
Douglas Gregor699ee522009-11-20 19:42:02 +00005984 Fn->getType());
5985 }
5986
Douglas Gregor699ee522009-11-20 19:42:02 +00005987 assert(false && "Invalid reference to overloaded function");
5988 return E->Retain();
Douglas Gregor904eed32008-11-10 20:40:00 +00005989}
5990
Douglas Gregor20093b42009-12-09 23:02:17 +00005991Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
5992 FunctionDecl *Fn) {
5993 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Fn));
5994}
5995
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005996} // end namespace clang